You have to change restart strategy to something like RestartStrategy = {one_for_one, 10, 1}, because 0, 1 means that app can't be restarted at all....
I know abs is an atom, not a function. [...] Why does it work when the module name is used? The documentation explains that (slightly reorganized): ExprM:ExprF(Expr1,...,ExprN) each of ExprM and ExprF must be an atom or an expression that evaluates to an atom. The function is said to...
Erlang only describes program communication through the ports, and not code execution. While you have one point of serialization and all the communication goes through one actor, it doesn't mean that you cannot distribute work in general. You can parallel your C program as you wish even with the single...
architecture,erlang,docker,elixir,microservices
This is a very open question but I will try to illustrate why Elixir/Erlang may be the best platform out there for developing distributed systems (regardless if you are working with microservices). First, let's start with some background. The Erlang VM and its standard library were designed upfront for building...
You can use code:is_module_native/1: 1> code:is_module_native(lists). false ...
1) Yep - this is a good scheme. An improvement you can make is to increment the load of a remote node every time you balance load to another node. This is like keeping an estimate for remote node load and stops you from sending all load to one node...
For reliability reasons every statement in erlang must have some return value. In this code your if statement has no return value when X and Y both are nonzero. So your code should change to this: test(X, Y) -> if X == 0 -> -1; Y == 0 -> -2;...
Use := instead of => #{ born := B } = Henry8. source: http://erlang.org/doc/reference_manual/expressions.html#id79796...
The whole point of gen_server:call/2,3 is to wrap into a function call the passing of a message into a gen_server process and the reception of its reply. If you want to deal only with messages, don't use gen_server:call/2,3 but rather have the caller invoke gen_server:cast/2 and include the caller pid...
concurrency,process,erlang,messages
Erlang processes are cheap. You're free (and encouraged) to use more than however many cores you have. There might be an upper limit to what is practical for your problem (loading 1TB of data in one process per line is asking a bit for much, depending on line size)....
Its because Erlang reads your source files like latin1 by default, but on newer versions of erlang you can set your files to use unicode. %% coding: utf-8 -module(test). -compile(export_all). test() -> COMMAND = "touch ჟანიweł", os:cmd(COMMAND). and then compiling and executing the module works fine rorra-air:~ > erl Erlang/OTP...
design-patterns,concurrency,erlang
The function is indeed concurrent, as you are spawning new processes to walk the subtrees. You might want to alter tree:walk/1 so that it returns the atom ok in the case of a successful walk (I also switch out io:format/1 with erlang:display so that values are printed on separate lines):...
how to handle low_entropy exception of crypto:strong_rand_bytes(N)? Handle it by not getting into the bad state in the first place. You avoid it by seeding the generator. You should explicitly seed the generator on startup. This avoids some of the problems with calling RAND_poll. For some of the problems,...
Support for arbitrary keys in map patterns is already available in "Erlang 18 (release candidate 2)". $ erl Erlang/OTP 18 [RELEASE CANDIDATE 2] [erts-7.0] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] Eshell V7.0 (abort with ^G) 1> Pid = self(). <0.33.0> 2> #{Pid => 1}. #{<0.33.0> => 1} ...
There are many problems in the code you propose. First, there is only one case in the if statement so if A+B+C is different from N it will crash (try with main(20)). in the find_triple function you assign 4 time the variable Acc, remember than variable are not mutable in...
-noshell syntax is erl -noshell -s Module Function Arguments where Arguments is a list of atoms. So you have to get 'fac' argument from list and convert it to integer. This -module(factorial). -export([fac/1]). fac([N]) -> X = fac(list_to_integer(atom_to_list(N))), io:format("~p~n", [X]); fac(0) -> 1; fac(N) -> N * fac(N-1). works >>>...
The pattern [p1 | p2] matches a non-empty list, whose head matches the pattern p1 and whose tail matches the pattern p2. So since the pattern _ matches anything, [_ | _] matches any non-empty list. _ by itself on the other hand matches anything, including the empty list....
You can use function xml:get_path_s, asking it to descend into the element called received to get the attribute called id: > xml:get_path_s(Packet, [{elem, "received"}, {attr, "id"}]). "018A12FB-0718-4304-87FD-430C59EDB4F9" ...
As far as I know, you cannot build a guard with a call to get the substring from a string, so instead of using a Erlang Match Specification you would have to iterate over all the records and filter the ones that you need. -module(tuples). -compile(export_all). -record(group, {group_id, group_name, group_type,...
This seems like a bug either in the documentation or the code. If the code that invokes the driver start function finds that the function returns ERL_DRV_ERROR_ERRNO, it takes the error number from errno, not erl_errno (this is true as of otp master commit dc35ae6c, anyway, which is roughly Erlang...
Found the answer here: http://erlang.org/doc/reference_manual/typespec.html I had to use the ';' change this: -spec update(pid(), tuple(tuple(), integer(), atom()), tuple(atom(), atom())) -> tuple(tuple(), integer(), atom()). -spec update(pid(), tuple(tuple(), atom(), atom()), tuple(integer(), atom())) -> tuple(tuple(), atom(), atom()). -spec update(pid(), tuple(tuple(), atom(), atom()), tuple(atom())) -> tuple(tuple(), atom(), atom()). into this: -spec update(pid(), tuple(tuple(),...
a list is a recursive construction of the form L=[Head|Tail] where Head is any valid erlang term and Tail should be a list (if it is something else L is called an improper list, out of the scope of this discussion). Saying that L is passed as a reference means...
The version number is stored in the .app file. In the original source code look for boss.app.src. On GitHub it can be viewed here: https://github.com/ChicagoBoss/ChicagoBoss/blob/v0.8.14/src/boss.app.src The relevant line is: {vsn, "0.8.14"}, If Chicago Boss is already compiled and running you can still find the version by looking for a file...
Like @José mentioned the proc fs is special since the file contents are generated on the fly. If you look at the file sizes in /proc you'll see that they have size 0. I believe this is why the read function fails to return anything, the file is empty! The...
You might want to read about this issue in the Erlang efficiency guide, since there it says that building the list via | and then reversing the result is more efficient than using the appending ++ operator. If you want to know the performance difference, use timer:tc: 1> timer:tc(fun() ->...
The errors you get are not exactly SQL or MongooseIM specific errors. They are erroneous uses of io_lib:format/2 or a similar string formatting function. This error: 2015-03-09 16:37:11.598 [debug] <0.763.0>@mod_zeropush:count_msg:102 FORMAT ERROR: "Count = ~s" [{selected,[<<"count">>],[{<<"5">>}]}] relates to: ?DEBUG("Count = ~s", [Count]) But Count is neither a string, nor a...
You are not comparing the right values. From erlang:process_info {heap_size, Size} Size is the size in words of youngest heap generation of the process. This generation currently include the stack of the process. This information is highly implementation dependent, and may change if the implementation change. recon_alloc:memory(allocated_types) is in bytes...
The global registry is for registering processes. So when you call: :global.register_name(:my_node, self) You are registering the current process (given by self) globally. There is no node name registering because their names are already available globally. So the last snippet in your post is the correct way of doing so....
android,sockets,ssl,erlang,ejabberd
Here is how you can go about it. I work on the sandbox environment and after a bit of patching, i could make it work. Follow the patching done here: http://erlang.org/pipermail/erlang-questions/2015-June/084868.html You would be required to make changes in ssl_cipher.erl and ssl_handshake.erl files. These 2 files are a part of...
ruby-on-rails,ruby,erlang,cowboy
RubyOnRails as with all frameworks can call out tertiary processes on the server either directly through: ` <command> ` or indirectly though ActiveJob (or some background task alternative) Erlang/Beam/OTP, etc.. can be leveraged though this mechanism...
The simplest way would probably be for child1 and child2 to be registered under local aliases. You can do that while starting your GenServer by passing the name option: defmodule Child1 do use GenServer def start_link do GenServer.start_link(__MODULE__, [], name: __MODULE__) end end In this case a process backed by...
You can extract a list of attributes of the JSON object using pattern matching and then find a value by a key in the resulting list: {Attrs} = jiffy:decode(<<"{\"foo\": \"bar\"}">>), FooValue = proplists:get_value(<<"foo">>, Attrs). ...
Take a look at this code: -module(test). -export([add/1]). -record(adder, {value=6}). add(X) -> #adder{value = X + #adder.value}. If you compile this in your shell, any call to "add(3)" will result in "{adder,5}" and not in "{adder, 9}". Take a look: Eshell V6.4 (abort with ^G) 1> c(test). {ok,test} 2> test:add(3)....
I guess that you want to do Packet_Type = xml:get_tag_attr_s("type", XML), not Packet_Type = xml:get_tag_attr_s("type", Packet)
Looks like it was just a timezone issue :) Since I was working with javascript timestamps the default timezone of the javscript time stamp is my localtimzone which is "IST". Now internally when qdate sees an integer in qdate:to_date(Timestamp). it automatically selects a UTC timezone for it. Relevant code on...
I had the same issue when experimenting with the Aerospike binding. The problem is that the .so file is assumed to be in the current working directory. I made a small change to aerospike.erl so it's located correctly independent of the path. Replace ok = erlang:load_nif("./aerospike_nif", 0). in init() with...
Calling application:load(App) (after stopping and unloading) will reload the .app file but not the modules. As the documentation says: "Note that the function does not load the actual Erlang object code." If you were to do an upgrade using releases, you would ship an .appup file that specified which modules...
A typical approach to packaging such systems is an OTP release. You can use exrm for that. If for some reasons, you still want to use escript, you can just call :timer.sleep(:infinity) after you start all the applications and processes....
I won't attempt to answer completely your broader question about the "best practices" of adding scripting. It seems to me that choosing between "hook-based" solution (in which you define hook implementations by name convention and they are automatically recognized) and "explicit api" solution (in which you use functions predefinied in...
The problem is that url() is specified as a binary() but you pass in [byte()] (strings) in there. You need to change the type specification of url() to something like iodata() instead, or to restrict your input by converting it to a binary first.
Erlang's processes are not like general processes. In erlang contexes are much smaller and so contex switching time for erlang processes is not as much as general ones. This code show you how erlang message passing is fast: module.erl: -module(module). -export([messager1/0, messager2/0]). messager1() -> receive {_, 1000} -> io:format("Goodby~n"); {X,...
It reads a "packet" from a byte stream, where the "packet length" is 16 bits (assuming 8-bit chars), stuffing the bytes read into a buffer (that has to be large enough to accommodate the read bytes) and returns the number of bytes actually read. First, we read two bytes from...
The simplest solution would be to create a barrier by keeping a counter in cve_receive so you can keep track of how many worker processes that have completed. Something like: %% First Spawn N work processes ... %% Then receive N messages. cve_receive(N). ... cve_receive(N) -> receive Msg -> io:fwrite("~s~n",...
Rebar is gradually being replaced by rebar3, which provides more deterministic builds and conflict resolution, packages (integrating with hex.pm), and so on. As one of the current rebar and rebar3 maintainers, I'd recommend rebar3....
timer,erlang,periodic-task,periodic-processing
I think you need something like this: start_timer() -> gen_server:start_link({local, clock}, ?MODULE, [], []). ...
You can always use erlang NIFs (http://erlang.org/doc/tutorial/nif.html) to wrap an external library
There are no nightly builds. As far as I know, the tests should be passing on your machine. Perhaps something is misconfigured? Pull requests are on GitHub: https://github.com/erlang/otp/pulls and there is an erlang-bugs mailing list: http://erlang.org/mailman/listinfo/erlang-bugs. Here is a wiki page on Erlang bug reports: https://github.com/erlang/otp/wiki/Bug-reports ...
erlang,elixir,arity,pattern-guards
Currently it is not possible to introspect this information without looking at the source.
functional-programming,erlang,elixir
You need to wrap the for expression in parentheses like the Erlang code. def combination(n, [x|xs]) do (for y <- combination(n - 1, xs), do: [x|y]) ++ combination(n, xs) end Demo: iex(1)> defmodule Foo do ...(1)> def combination(0, _), do: [[]] ...(1)> def combination(_, []), do: [] ...(1)> def combination(n,...
While startnig erl sends all logs to standard output. Only after the kernel application comes up you can use error_logger to redirect to file or any other custom log handler. The errors which occur even before kernel application is started (For example in your case) you cannot log it to...
To expand on my comment about boolean blindness, I don't just mean using another type isomorphic to 2, but rather, using the right type to encode the reason your recursive function cares about which iteration it is. Compare your code to the following version which is I'd say cleaner and...
It's not just the file module that tags errors with an error atom; rather, this is a very common Erlang practice. The benefit is that any code wanting to check for an error without bothering with the reason can just match {error, _Reason} and take an appropriate action, whereas if...
python,ruby,haskell,floating-point,erlang
This happens because all the languages are using the same numerical representation for non-integer numbers: IEEE 754 floating point numbers with, most likely, the same level of precision. (Either 32-bit "floats" or 64-bit "doubles", depending on how your system and languages are configured.) Floating point numbers are the default choice...
The problem is that you expect mnesia:select/4, which is documented as: select(Tab, MatchSpec, NObjects, Lock) -> transaction abort | {[Object],Cont} | '$end_of_table' to get you the NObjects limit, being NObjects in your example 10,000. But the same documentation also says: For efficiency the NObjects is a recommendation only and the...
Erlang module and C program communicate via stdin and stdout by sending byte stream(sequence of bytes). Creating a port with Port = open_port({spawn, ExtPrg}, [{packet, N}]). (valid values for N are 1,2,4) tells erlang that the packets sent will be in this format : N bytes : data length of...
There are various ways to do this. Think about where you want to store the value: Erlang doesn't have "static variables" like C, so the function itself cannot remember the value. You could pass the current record as an argument to add_new_num, and get the updated record from its return...
function,variables,if-statement,functional-programming,erlang
Because expressions should be separated by ,, not ;: Val=cal(Arg1), if ... ; is the separator for if/case/receive and function clauses....
The .app file (in ebin/) is the file necessary by the Erlang VM to load OTP applications. It must contain fields such as the dependencies of the application, the modules it contains, the version, and so on. Particularly, the list of modules for the application is tedious to maintain, but...
Yes, since the release version R17 - somewhere early 2014 - Erlang supports maps. You can read all about it at http://learnyousomeerlang.com/maps. You should go for the latest release, being 17.5.
c,multithreading,lua,erlang,ffi
If you can make the Lua code — or more accurately, its underlying native code — cooperate with the Erlang VM, you have a few choices. Consider one of the most important functions of the Erlang VM: managing the execution of a (potentially large number of) Erlang's lightweight processes across...
algorithm,erlang,dynamic-programming,combinatorics,lis
Your current implementation of lis/1 function is O(n), I don't see any reasons to doubt. But there is some problem. You implementation doesn't actually calculate valid LIS. Try lis(lists:reverse([1,2,3,4,1,2])) for error example. Longest increasing sequense is [1,2,3,4], right? But your algorith returns 6 as result. First error in your algorithm...
exception,error-handling,exception-handling,erlang,ejabberd
Seems the reason is an exception happens in mochijson2:decode/1. The function doesn't return a error as a tuple, instead the process crashes. There isn't enough information to tell what exactly the reason is. However I guess that the data format of Ccode might be wrong. You can handle exception using...
Distributed systems programming is hard. It's hard to understand. It's hard to implement correctly. The source code for riak_core can be very hard to understand at first. Here are some resources that helped me better understand riak_core: Where to Start with Riak Core (specifically, Try Try Try by Ryan Zezeski)...
You need to add :eredis to your app_list function, so that it is packaged with the release, that goes for the rest of your dependencies as well.
There are a number of problems with this code. Did you compile it? First, an easy problem: your io:fwrite/2 calls need to have their arguments to be printed passed in a list, not as individual terms, so this: io:fwrite("~p\n", oid) is wrong. It should be: io:fwrite("~p\n", [oid]) But there's little...
The project has finished a week ago. The main ideas behind SD Erlang are reducing the number of connections Erlang nodes maintain while keeping transitivity and common namespace for groups of nodes. Benchmarks that we used (Orbit, Ant Colony Optimization (ACO), and Instant Messenger) showed very promising results. Unfortunately, we...
Unfortunately there's no easy way to do this. Those messages are emitted unconditionally via io:format calls from within the mnesia source code, and the mnesia functions don't provide any options to control whether the messages are emitted or not.
android,erlang,xmpp,ejabberd,user-presence
Scenario 1: When I swipe-right the app (kill the app), the user goes offline on the server immediately. Its status is changed to offline at that very instant. In above case your Android xmpp client is sending presence as unavailable before closing your Android application, maybe your Android XMPP...
The reason is simple: map hasn't been fully implemented yet. Take a look at: http://learnyousomeerlang.com/maps Also, you might think of alternative implementations, using the stuff that's already possible with maps: count_characters(Str) -> count_characters(Str, #{}). count_characters([H|T], Map) -> N = maps:get(H, Map, 0), count_characters(T, maps:put(H, N + 1, Map)); count_characters([], Map)...
What you have is close to a good solution, but it can be improved. There's no need to dig out the first key and value to use an the initial value for the fold, since you can just pass an artificial value instead and make your fold function deal with...
functional-programming,erlang,pattern-matching
Although Attic's approach is correct, there is a straightforward solution (including trimming of leading spaces): first_word_bin(Bin) -> first_word_bin(ltrim(Bin), <<>>). first_word_bin(<<>>, Acc) -> Acc; first_word_bin(<<$\s, _/binary>>, Acc) -> Acc; first_word_bin(<<X, Bin/binary>>, Acc) -> first_word_bin(Bin, <<Acc/binary, X>>). ltrim(<<$\s, Bin/binary>>) -> ltrim(Bin); ltrim(Bin) -> Bin. ...
mnesia:dirty_read does a rpc call even if the table is local. Also it checks for the current activity context and maintains it even for dirty lookups. This will result in the extra time required for the lookup. In your case (where there is only one node with local mnesia), direct...
First of, you need to add the directory containing your beam with the argument -pa Dir1 Dir2 .... It will add the directory to the erlang path and you will be able to type somequery:fbquery(Arg1,Arg2) in your shell. Then, you can use the argument -s module function [args..] to launch...
arrays,function,erlang,arguments
Like Hynek Vychodil says in his answer, there is no built-in array type in Erlang. Arrays do exist, in a sense, as you can get something that behaves like an (immutable) array using the array module. In Erlang, an expression that begins with an opening bracket, such as [1, 2,...
I'm going to use œ as the example unicode character in the examples below: <<197,147>> = <<"œ"/utf8>>. [197,147] = binary_to_list(<<"œ"/utf8>>). <<195,133,194,147>> = unicode:characters_to_binary(binary_to_list(<<"œ"/utf8>>), utf8). Prior to R17, the default encoding of latin1 is what allowed this to work in conjunction with binary_to_list/1. The new default is unicode. The list [197,147]...
Ah, here we go: -module(test). -export([run/0]). test() -> io:format("toasters", []). bagel() -> fun test/0. % <- This is what I needed to change. run() -> (bagel())(). I was looking here for an answer, and they didn't explicitly state it, but the example near the top gave me the hint just...
process,erlang,send,alarm,spawn
Me as a novice useful to write more code, so I suggest such an option: setalarm(T,Message)-> S = spawn(sotest,second,[]), Pid = spawn(sotest,first,[S,T,Message]). first(Pid,T,Message) -> receive after T -> Pid ! Message end. second() -> receive Message -> io:format("The message is ~p~n",[Message]) end. ...
You can delete a directory via console command using os:cmd, though it's a rough approach. For unix-like OS it will be: os:cmd("rm -Rf " ++ DirPath). If you want to delete a non-empty directory using appropriate erlang functions you have to do it recursively. The following example from here shows...
Message receiving is an atomic operation. If you are interested how it is done, read the source code of VM. If I simplify it, the sending process is doing those steps: Allocate a target memory space in the sending process (it's called environment). Copy the message to that memory space...
You can use the modules erl_scan and erl_parse, as in this answer. Since erl_scan:string requires a string, not a binary, you have to convert the value with binary_to_list first: > {ok, Scanned, _} = erl_scan:string(binary_to_list(<<"{1,2}">>)). {ok,[{'{',1},{integer,1,1},{',',1},{integer,1,2},{'}',1}],1} Then, you'd use erl_parse:parse_term to get the actual term. However, this function expects the...
excerpt from http://docs.basho.com/riak/latest/dev/advanced/bucket-types/#Managing-Bucket-Types-Through-the-Command-Line: Bucket types are created, updated, activated, and more through the riak-admin bucket-type interface. Below is a full list of available sub-commands: Command Action Form create create or modify a bucket type create <type> <json> before activation activate activate a bucket type activate <type> list list all currently...
All function parameter definitions are patterns, and #state{lsock = LSock} = State is one pattern that binds State to the whole term passed as a function call argument, and at the same time asserts that it is a record state and binds State#state.lsock to LSock. In your shell examples, A...
You can use a simple network-capable client such as netcat (/usr/bin/nc on my system) to send whatever form of request you like. For example, the following connects to a web server listening on localhost port 8000 and sends a GET request where the path is a URL (note that the...
xml,file,formatting,erlang,output
That's because the runtime is unsure whether your terminal can display non-ASCII unicode. All strings are just lists of integers, and all binaries are just long strings of bits split into bytes of 8-bits. So the numbers you are seeing is the data you want to see, just the raw...
The problem is with the reduce phase. The map phase is spread around the cluster and executed by many vnodes that forward the map phase result to the node that will be running the reduce. Since these are not expect to arrive simultaneously, the reduce phase function may be run...
There's nothing wrong here; rather, these are just warnings that the rebar build tool issues when it starts to build a system but hasn't yet retrieved and built the project dependencies. The warnings won't occur again once rebar downloads and builds them.
You could do a :global.sync() before :global.whereis_name(id)
From the following link http://www.erlang.org/doc/man/unicode.html Other Unicode encodings than integers representing codepoints or UTF-8 in binaries are referred to as "external encodings". The ISO-latin-1 encoding is in binaries and lists referred to as latin1-encoding. It is recommended to only use external encodings for communication with external entities where this is...
I guess you meant this: ["FF","AC","01"] => <<255,172,1>>. You can use list_to_integer/2 function. It takes number base as second argument. Hexs = ["FF","AC","01"], Ints = [list_to_integer(Hex, 16) || Hex <- Hexs], %% [255,172,1] Binary = list_to_binary(Ints). %% <<255,172,1>> ...
windows,memory,erlang,erlang-shell
It is not terminating because you are creating a new non-empty list in every case: [Anything] is always a non-empty list, even if that list contains an empty list as its only member ([[]] is a non-empty list of one member). A proper list terminates like this: [ Something |...
The reason for this is that you set a trap_exit flag to true which means this process will get {'EXIT', FromPid, Reason} message instead of being killed. Just remove process_flag(trap_exit, true) or in case of receiving this type of message, kill it. You can read about it here....
string,erlang,string-concatenation
If {\"message\":\"tttfdfdfdfdddtt\",\"customid\":\"454dddfdfdfd\"} is a string you just need to convert it to binary with erlang:list_to_binary/1...