-module (quickstart_app).
-export ([start/2, stop/0, do/1]).
-include_lib ("nitrogen/include/wf.hrl").
-define(PORT, 8000).

start(_, _) ->
    inets:start(),
    {ok, Pid} = inets:start(httpd, [
        {port, ?PORT},
        {server_name, "nitrogen"},
        {server_root, "."},
        {document_root, "./static"},
        {modules, [?MODULE]},
        {mime_types, [{"css", "text/css"}, {"js", "text/javascript"}, {"html", "text/html"}]}
    ]),
    link(Pid),
    {ok, Pid}.

stop() ->
    httpd:stop_service({any, ?PORT}),
    ok.

do(Info) ->
    RequestBridge = simple_bridge:make_request(inets_request_bridge, Info),
    ResponseBridge = simple_bridge:make_response(inets_response_bridge, Info),
    nitrogen:init_request(RequestBridge, ResponseBridge),

    %% Uncomment for basic authentication...
    nitrogen:handler(http_basic_auth_security_handler, basic_auth_callback_mod),

    nitrogen:run().

Comment out basic auth by default.

-module (quickstart_app).
-export ([start/2, stop/0, do/1]).
-include_lib ("nitrogen/include/wf.hrl").
-define(PORT, 8000).

start(_, _) ->
    inets:start(),
    {ok, Pid} = inets:start(httpd, [
        {port, ?PORT},
        {server_name, "nitrogen"},
        {server_root, "."},
        {document_root, "./static"},
        {modules, [?MODULE]},
        {mime_types, [{"css", "text/css"}, {"js", "text/javascript"}, {"html", "text/html"}]}
    ]),
    link(Pid),
    {ok, Pid}.

stop() ->
    httpd:stop_service({any, ?PORT}),
    ok.

do(Info) ->
    RequestBridge = simple_bridge:make_request(inets_request_bridge, Info),
    ResponseBridge = simple_bridge:make_response(inets_response_bridge, Info),
    nitrogen:init_request(RequestBridge, ResponseBridge),

    %% Uncomment for basic authentication...
    %% nitrogen:handler(http_basic_auth_security_handler, basic_auth_callback_mod),

    nitrogen:run().


%% -------------------------------------------------------------------
%%
%% Copyright (c) 2007-2010 Basho Technologies, Inc.  All Rights Reserved.
%%
%% -------------------------------------------------------------------

-module(lucene_parser).
-export([parse/3]).
-include("lucene_parser.hrl").

%% @doc Parse a given query string into a query graph. The query graph
%% consists of a nested set of Erlang records found in lucene_parser.hrl.
parse(DefaultIndex, DefaultField, QueryString) when is_list(DefaultIndex) andalso is_list(DefaultField) andalso is_list(QueryString) ->
    case lucene_scan:string(QueryString) of
        {ok, Tokens, 1} ->
            case lucene_parse:parse(Tokens) of
                {ok, QueryGraph} ->
                    %% Success case.
                    QueryGraph1 = #scope { index=DefaultIndex, field=DefaultField, ops=QueryGraph },
                    {ok, QueryGraph1};
                {error, {_, lucene_parse, String}} ->
                    %% Syntax error.
                    {error, {lucene_parse, lists:flatten(String)}};
                {error, Error} ->
                    %% Other parsing error.
                    {error, Error}
            end;
        {error, Error} ->
            %% Scanning error.
            {error, Error}
    end.

Add error handling clause to catch error triplets returned from lucene_scan.

%% -------------------------------------------------------------------
%%
%% Copyright (c) 2007-2010 Basho Technologies, Inc.  All Rights Reserved.
%%
%% -------------------------------------------------------------------

-module(lucene_parser).
-export([parse/3]).
-include("lucene_parser.hrl").

%% @doc Parse a given query string into a query graph. The query graph
%% consists of a nested set of Erlang records found in lucene_parser.hrl.
parse(DefaultIndex, DefaultField, QueryString) when is_list(DefaultIndex) andalso is_list(DefaultField) andalso is_list(QueryString) ->
    case lucene_scan:string(QueryString) of
        {ok, Tokens, 1} ->
            case lucene_parse:parse(Tokens) of
                {ok, QueryGraph} ->
                    %% Success case.
                    QueryGraph1 = #scope { index=DefaultIndex, field=DefaultField, ops=QueryGraph },
                    {ok, QueryGraph1};
                {error, {_, lucene_parse, String}} ->
                    %% Syntax error.
                    {error, {lucene_parse, lists:flatten(String)}};
                {error, Error} ->
                    %% Other parsing error.
                    {error, Error}
            end;
        {error, Error} ->
            %% Scanning error.
            {error, Error};
        {error, Error, _} ->
            %% Scanning error.
            {error, Error}
    end.


%% Feel free to use, reuse and abuse the code in this file.

%% @doc GET echo handler.
-module(toppage_handler).

-export([init/2]).

init(Req, Opts) ->
	Method = cowboy_req:method(Req),
	#{echo := Echo} = cowboy_req:match_qs([echo], Req),
	Req2 = echo(Method, Echo, Req),
	{ok, Req2, Opts}.

echo(<<"GET">>, undefined, Req) ->
	cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);
echo(<<"GET">>, Echo, Req) ->
	cowboy_req:reply(200, #{
		<<"content-type">> => <<"text/plain; charset=utf-8">>
	}, Echo, Req);
echo(_, _, Req) ->
	%% Method not allowed.
	cowboy_req:reply(405, Req).

Fix small issue in echo_get example

%% Feel free to use, reuse and abuse the code in this file.

%% @doc GET echo handler.
-module(toppage_handler).

-export([init/2]).

init(Req, Opts) ->
	Method = cowboy_req:method(Req),
	#{echo := Echo} = cowboy_req:match_qs([echo], Req),
	echo(Method, Echo, Req),
	{ok, Req, Opts}.

echo(<<"GET">>, undefined, Req) ->
	cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);
echo(<<"GET">>, Echo, Req) ->
	cowboy_req:reply(200, #{
		<<"content-type">> => <<"text/plain; charset=utf-8">>
	}, Echo, Req);
echo(_, _, Req) ->
	%% Method not allowed.
	cowboy_req:reply(405, Req).


%% @copyright Geoff Cant
%% @author Geoff Cant <nem@erlang.geek.nz>
%% @version {@vsn}, {@date} {@time}
%% @doc Logplex Shell functions
%% @end
-module(logplex).

-include("logplex_channel.hrl").

-export([serialize_channel/1
         ,deserialize_channel/1
        ]).

serialize_channel(ChannelId) when is_integer(ChannelId) ->
    {logplex_channel:lookup(ChannelId),
     logplex_token:lookup_by_channel(ChannelId),
     logplex_drain:lookup_by_channel(ChannelId)}.

deserialize_channel({Chan,
                     Tokens,
                     Drains}) ->
    {logplex_channel:store(Chan),
     [ logplex_token:store(Token)
       || Token <- Tokens ],
     [ logplex_drain:store(Drain)
       || Drain <- Drains ]}.

Remove unnecessary channel header file.

%% @copyright Geoff Cant
%% @author Geoff Cant <nem@erlang.geek.nz>
%% @version {@vsn}, {@date} {@time}
%% @doc Logplex Shell functions
%% @end
-module(logplex).

-export([serialize_channel/1
         ,deserialize_channel/1
        ]).

serialize_channel(ChannelId) when is_integer(ChannelId) ->
    {logplex_channel:lookup(ChannelId),
     logplex_token:lookup_by_channel(ChannelId),
     logplex_drain:lookup_by_channel(ChannelId)}.

deserialize_channel({Chan,
                     Tokens,
                     Drains}) ->
    {logplex_channel:store(Chan),
     [ logplex_token:store(Token)
       || Token <- Tokens ],
     [ logplex_drain:store(Drain)
       || Drain <- Drains ]}.


f(UpgradeNode).
UpgradeNode = fun () ->
  io:format(whereis(user), "at=upgrade_start cur_vsn=36~n", []),
  l(logplex_tcpsyslog_drain),
  l(logplex_tcpsyslog2_drain),
  l(logplex_drain),
  l(logplex_api),
  l(logplex_drain_buffer),
  l(logplex_drain_stats),
  l(logplex_sup),
  l(logplex_syslog_utils),
  l(logplex_tcpsyslog_drain),
  l(logplex_tcpsyslog2_drain),

  Drains = supervisor:which_children(logplex_drain_sup),

  [ try
        case logplex_drain:lookup(Id) of
            {drain,Id,Ch,Tok,
             _,Host,Port,true} ->
                logplex_drain:stop(Id),
                {Id, logplex_drain:start(tcpsyslog2, Id,
                                         [Ch, Id, Tok, Host, Port])};
            _ ->
                {ignored, Id}
        end
    catch
        Class:Err -> {Id, Class, Err}
    end
    ||
      {Id, Pid, _, _} <- Drains],

  io:format(whereis(user), "at=upgrade_end cur_vsn=37~n", []),
  length(Drains)
end.

Set updated git branch on upgrade completion.

f(UpgradeNode).
UpgradeNode = fun () ->
  io:format(whereis(user), "at=upgrade_start cur_vsn=36~n", []),
  l(logplex_tcpsyslog_drain),
  l(logplex_tcpsyslog2_drain),
  l(logplex_drain),
  l(logplex_api),
  l(logplex_drain_buffer),
  l(logplex_drain_stats),
  l(logplex_sup),
  l(logplex_syslog_utils),
  l(logplex_tcpsyslog_drain),
  l(logplex_tcpsyslog2_drain),

  Drains = supervisor:which_children(logplex_drain_sup),

  [ try
        case logplex_drain:lookup(Id) of
            {drain,Id,Ch,Tok,
             _,Host,Port,true} ->
                logplex_drain:stop(Id),
                {Id, logplex_drain:start(tcpsyslog2, Id,
                                         [Ch, Id, Tok, Host, Port])};
            _ ->
                {ignored, Id}
        end
    catch
        Class:Err -> {Id, Class, Err}
    end
    ||
      {Id, Pid, _, _} <- Drains],

  io:format(whereis(user), "at=upgrade_end cur_vsn=37~n", []),
  application:set_env(logplex, git_branch, "v37"),
  length(Drains)
end.


%% -------------------------------------------------------------------
%%
%% Copyright (c) 2007-2011 Basho Technologies, Inc.  All Rights Reserved.
%%
%% -------------------------------------------------------------------

%% @doc Convenience functions for setting up the riak_moss HTTP interface.

-module(riak_moss_web).

-export([dispatch_table/0]).

dispatch_table() ->
    case application:get_env(riak_moss, auth_bypass) of
        {ok, AuthBypass} ->
            ok;
        undefined ->
            AuthBypass = false
    end,
    StatsProps = stats_props(AuthBypass),

    [
     {[], riak_moss_wm_service, [{auth_bypass, AuthBypass}]},
     {["RiakCS", '*'], riak_cs_wm_stats, StatsProps},
     {["stats"], riak_cs_wm_stats, StatsProps},
     {["user"], riak_moss_wm_user, []},
     {["usage", '*'], riak_moss_wm_usage, [{auth_bypass, AuthBypass}]},
     {[bucket], riak_moss_wm_bucket, [{auth_bypass, AuthBypass}]},
     {[bucket, '*'], riak_moss_wm_key, [{auth_bypass, AuthBypass}]}
    ].

stats_props(AuthBypass) ->
    [{auth_bypass, AuthBypass}].

Change admin URI prefix from /RiakCS -> /riak-cs

%% -------------------------------------------------------------------
%%
%% Copyright (c) 2007-2011 Basho Technologies, Inc.  All Rights Reserved.
%%
%% -------------------------------------------------------------------

%% @doc Convenience functions for setting up the riak_moss HTTP interface.

-module(riak_moss_web).

-export([dispatch_table/0]).

dispatch_table() ->
    case application:get_env(riak_moss, auth_bypass) of
        {ok, AuthBypass} ->
            ok;
        undefined ->
            AuthBypass = false
    end,
    StatsProps = stats_props(AuthBypass),

    [
     {[], riak_moss_wm_service, [{auth_bypass, AuthBypass}]},
     {["riak-cs", '*'], riak_cs_wm_stats, StatsProps},
     {["stats"], riak_cs_wm_stats, StatsProps},
     {["user"], riak_moss_wm_user, []},
     {["usage", '*'], riak_moss_wm_usage, [{auth_bypass, AuthBypass}]},
     {[bucket], riak_moss_wm_bucket, [{auth_bypass, AuthBypass}]},
     {[bucket, '*'], riak_moss_wm_key, [{auth_bypass, AuthBypass}]}
    ].

stats_props(AuthBypass) ->
    [{auth_bypass, AuthBypass}].


-define(PARAM_CALLBACK         , <<"oauth_callback">>).
-define(PARAM_CONSUMER_KEY     , <<"oauth_consumer_key">>).
-define(PARAM_NONCE            , <<"oauth_nonce">>).
-define(PARAM_REALM            , <<"realm">>).
-define(PARAM_SIGNATURE        , <<"oauth_signature">>).
-define(PARAM_SIGNATURE_METHOD , <<"oauth_signature_method">>).
-define(PARAM_TIMESTAMP        , <<"oauth_timestamp">>).
-define(PARAM_TOKEN            , <<"oauth_token">>).
-define(PARAM_TOKEN_SECRET     , <<"oauth_token_secret">>).
-define(PARAM_VERIFIER         , <<"oauth_verifier">>).
-define(PARAM_VERSION          , <<"oauth_version">>).

Define name macro for parameter: "oauth_callback_confirmed"

-define(PARAM_CALLBACK         , <<"oauth_callback">>).
-define(PARAM_CALLBACK_CONFIRMED , <<"oauth_callback_confirmed">>).
-define(PARAM_CONSUMER_KEY     , <<"oauth_consumer_key">>).
-define(PARAM_NONCE            , <<"oauth_nonce">>).
-define(PARAM_REALM            , <<"realm">>).
-define(PARAM_SIGNATURE        , <<"oauth_signature">>).
-define(PARAM_SIGNATURE_METHOD , <<"oauth_signature_method">>).
-define(PARAM_TIMESTAMP        , <<"oauth_timestamp">>).
-define(PARAM_TOKEN            , <<"oauth_token">>).
-define(PARAM_TOKEN_SECRET     , <<"oauth_token_secret">>).
-define(PARAM_VERIFIER         , <<"oauth_verifier">>).
-define(PARAM_VERSION          , <<"oauth_version">>).


%%%
%%% Copyright (c) 2015 The Celo Authors. All rights reserved.
%%% Use of this source code is governed by a BSD-style
%%% license that can be found in the LICENSE file.
%%%
%%% ----------------------------------------------------------------------------
%%% @author Alexander Færøy <ahf@0x90.dk>
%%% @doc The Celo Core Utilities API.
%%% @end
%%% ----------------------------------------------------------------------------
-module(celo_core_utilities).

%% API.
-export([expand_tilde/1,
         home_dir/0
        ]).

-spec expand_tilde(Path :: file:filename()) -> file:filename().
expand_tilde(Path) ->
    binary_to_list(iolist_to_binary(re:replace(Path, "~", home_dir()))).

-spec home_dir() -> file:filename().
home_dir() ->
    case os:getenv("HOME") of
        false ->
            [];

        Homedir ->
            Homedir
    end.

Add utilities for working with hex encoded data.

%%%
%%% Copyright (c) 2015 The Celo Authors. All rights reserved.
%%% Use of this source code is governed by a BSD-style
%%% license that can be found in the LICENSE file.
%%%
%%% ----------------------------------------------------------------------------
%%% @author Alexander Færøy <ahf@0x90.dk>
%%% @doc The Celo Core Utilities API.
%%% @end
%%% ----------------------------------------------------------------------------
-module(celo_core_utilities).

%% API.
-export([expand_tilde/1,
         home_dir/0,
         hex_to_binary/1,
         binary_to_hex/1
        ]).

-spec expand_tilde(Path :: file:filename()) -> file:filename().
expand_tilde(Path) ->
    binary_to_list(iolist_to_binary(re:replace(Path, "~", home_dir()))).

-spec home_dir() -> file:filename().
home_dir() ->
    case os:getenv("HOME") of
        false ->
            [];

        Homedir ->
            Homedir
    end.

%% @doc Convert hex to binary.
-spec hex_to_binary(Data :: binary()) -> binary();
                   (Data :: string()) -> binary().
hex_to_binary([A, B | Rest]) ->
    <<(list_to_integer([A, B], 16)), (hex_to_binary(Rest))/binary>>;

hex_to_binary([A]) ->
    <<(list_to_integer([A], 16))>>;

hex_to_binary([]) ->
    <<>>;

hex_to_binary(Data) when is_binary(Data) ->
    hex_to_binary(binary_to_list(Data)).

%% @doc Convert binary data to hex.
-spec binary_to_hex(Data :: binary()) -> binary();
                   (Data :: string()) -> binary().
binary_to_hex(Data) when is_binary(Data) ->
    list_to_binary(lists:flatten([integer_to_list(X, 16) || <<X:4/integer>> <= Data]));

binary_to_hex(Data) when is_list(Data) ->
    binary_to_hex(list_to_binary(Data)).


%% -------------------------------------------------------------------
%%
%% Copyright (c) 2007-2011 Basho Technologies, Inc.  All Rights Reserved.
%%
%% -------------------------------------------------------------------

-module(basho_bench_driver_moss).

-export([new/1,
         run/4]).

-include("basho_bench.hrl").

-record(state, { client_id }).

-spec new(integer()) -> {ok, term()}.
new(ID) ->
    application:start(ibrowse),
    {ok, #state{client_id=ID}}.

-spec run(atom(), fun(), fun(), term()) -> {ok, term()}.
run(_Operation, _KeyGen, _ValueGen, State) ->
    {ok, State}.

Add connect and disconnect funcs from Riak http driver

%% -------------------------------------------------------------------
%%
%% Copyright (c) 2007-2011 Basho Technologies, Inc.  All Rights Reserved.
%%
%% -------------------------------------------------------------------

-module(basho_bench_driver_moss).

-export([new/1,
         run/4]).

-include("basho_bench.hrl").

-record(url, {host, port}).
-record(state, { client_id }).

%% ====================================================================
%% API
%% ====================================================================

-spec new(integer()) -> {ok, term()}.
new(ID) ->
    application:start(ibrowse),
    {ok, #state{client_id=ID}}.

-spec run(atom(), fun(), fun(), term()) -> {ok, term()}.
run(_Operation, _KeyGen, _ValueGen, State) ->
    {ok, State}.

%% ====================================================================
%% Internal functions
%% ====================================================================

%% This is ripped from basho_bench_driver_http_raw.erl
connect(Url) ->
    case erlang:get({ibrowse_pid, Url#url.host}) of
        undefined ->
            {ok, Pid} = ibrowse_http_client:start({Url#url.host, Url#url.port}),
            erlang:put({ibrowse_pid, Url#url.host}, Pid),
            Pid;
        Pid ->
            case is_process_alive(Pid) of
                true ->
                    Pid;
                false ->
                    erlang:erase({ibrowse_pid, Url#url.host}),
                    connect(Url)
            end
    end.

%% This is ripped from basho_bench_driver_http_raw.erl
disconnect(Url) ->
    case erlang:get({ibrowse_pid, Url#url.host}) of
        undefined ->
            ok;
        OldPid ->
            catch(ibrowse_http_client:stop(OldPid))
    end,
    erlang:erase({ibrowse_pid, Url#url.host}),
    ok.


-module(beamjs_mod_sys).
-export([exports/0]).
-include_lib("erlv8/include/erlv8.hrl").

exports() ->
	[{"print", fun print/3}].

print(_Script, #erlv8_fun_invocation{} = _Invocation, Expr) ->
	io:format("~p",[Expr]),
	undefined.

Make sys.print() use v8's detail string for the object it is printing

-module(beamjs_mod_sys).
-export([exports/0]).
-include_lib("erlv8/include/erlv8.hrl").

exports() ->
	[{"print", fun print/3}].

print(Script, #erlv8_fun_invocation{} = _Invocation, Expr) ->
	io:format("~s",[erlv8_script:to_detail_string(Script,Expr)]),
	undefined.


%% @doc This module starts the mas framework with given environment, model and parameters

-module (mas).
-export ([start/5]).
-export_type([agent/0,
              agent/1,
              sim_params/0,
              sim_params/1,
              agent_behaviour/0,
              agent_behaviour/1]).

-include ("mas.hrl").

-type agent(Any) :: Any.
-type agent() :: agent(any()).

-type sim_params(Any) :: Any.
-type sim_params() :: sim_params(any()).

-type agent_behaviour(Any) :: Any.
-type agent_behaviour() :: agent_behaviour(any()).

-spec start(atom(), model(), pos_integer(), sim_params(), [tuple()]) -> [agent()].
start(Module, Model, Time, SP, Options) ->
    ConfigFile = filename:join(mas_misc_util:get_config_dir(), "mas.config"),
    {ok, ConfigFromFile} = file:consult(ConfigFile),
    ConfigWithEnv = [{agent_env,Module}|ConfigFromFile],
    OverwrittenConfig = mas_misc_util:overwrite_options(Options, ConfigWithEnv),
    ConfigRecord = mas_config:proplist_to_record(OverwrittenConfig),
    Model:start(Time, SP, ConfigRecord).

Stop using file for configuation.

%% @doc This module starts the mas framework with given environment, model and parameters

-module (mas).
-export ([start/5]).
-export_type([agent/0,
              agent/1,
              sim_params/0,
              sim_params/1,
              agent_behaviour/0,
              agent_behaviour/1]).

-include ("mas.hrl").

-type agent(Any) :: Any.
-type agent() :: agent(any()).

-type sim_params(Any) :: Any.
-type sim_params() :: sim_params(any()).

-type agent_behaviour(Any) :: Any.
-type agent_behaviour() :: agent_behaviour(any()).

-spec start(atom(), model(), pos_integer(), sim_params(), [tuple()]) -> [agent()].
start(Module, Model, Time, SP, Options) ->
    ConfigRecord = mas_config:proplist_to_record([{agent_env, Module} | Options]),
    io:format(">>ConfigRecord: ~p~n", [ConfigRecord]),
    Model:start(Time, SP, ConfigRecord).


%% -------------------------------------------------------------------
%%
%% Copyright (c) 2007-2012 Basho Technologies, Inc.  All Rights Reserved.
%%
%% -------------------------------------------------------------------

-module(bucket_bouncer_server_sup).

-behaviour(supervisor).

%% API
-export([start_link/0]).

%% Supervisor callbacks
-export([init/1]).

%% ===================================================================
%% API functions
%% ===================================================================

%% @doc API for starting the supervisor.
-spec start_link() -> {ok, pid()} | ignore | {error, term()}.
start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

%% ===================================================================
%% Supervisor callbacks
%% ===================================================================

%% @doc Initialize this supervisor. This is a `one_for_one',
%%      whose child spec is for starting a `bucket_bouncer_server' process.
-spec init([]) -> {ok, {{supervisor:strategy(),
                         pos_integer(),
                         pos_integer()},
                        [supervisor:child_spec()]}}.
init([]) ->
    RestartStrategy = one_for_one,
    MaxRestarts = 1000,
    MaxSecondsBetweenRestarts = 3600,

    SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},

    Restart = temporary,
    Shutdown = 2000,
    Type = worker,

    ServerSpec = {undefined,
                  {bucket_bouncer_server, start_link, []},
                  Restart, Shutdown, Type, [bucket_bouncer_server]},

    {ok, {SupFlags, [ServerSpec]}}.

Change the server restart strategy to permanent.

%% -------------------------------------------------------------------
%%
%% Copyright (c) 2007-2012 Basho Technologies, Inc.  All Rights Reserved.
%%
%% -------------------------------------------------------------------

-module(bucket_bouncer_server_sup).

-behaviour(supervisor).

%% API
-export([start_link/0]).

%% Supervisor callbacks
-export([init/1]).

%% ===================================================================
%% API functions
%% ===================================================================

%% @doc API for starting the supervisor.
-spec start_link() -> {ok, pid()} | ignore | {error, term()}.
start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

%% ===================================================================
%% Supervisor callbacks
%% ===================================================================

%% @doc Initialize this supervisor. This is a `one_for_one',
%%      whose child spec is for starting a `bucket_bouncer_server' process.
-spec init([]) -> {ok, {{supervisor:strategy(),
                         pos_integer(),
                         pos_integer()},
                        [supervisor:child_spec()]}}.
init([]) ->
    RestartStrategy = one_for_one,
    MaxRestarts = 1000,
    MaxSecondsBetweenRestarts = 3600,

    SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},

    Restart = permanent,
    Shutdown = 2000,
    Type = worker,

    ServerSpec = {undefined,
                  {bucket_bouncer_server, start_link, []},
                  Restart, Shutdown, Type, [bucket_bouncer_server]},

    {ok, {SupFlags, [ServerSpec]}}.


-module(erlcfg_data, [Node]).
-export([
        raw/0,
        get/1,
        get/2
    ]).

raw() ->
    Node.

get(Key, Default) ->
    case THIS:get(Key) of
        {error, _Reason} ->
            Default;
        Value ->
            Value
    end.

get(Key) ->
    case erlcfg_node:get(Node, Key) of
        {not_found, MissingNode} ->
            {error, {not_found, MissingNode}};
        {value, Value} ->
            Value
    end.

Implement erlcfg:ensure_get/1 which crashes when key is not found

-module(erlcfg_data, [Node]).
-export([
        raw/0,
        get/1,
        get/2,
        ensure_get/1
    ]).

raw() ->
    Node.

get(Key, Default) ->
    case THIS:get(Key) of
        {error, _Reason} ->
            Default;
        Value ->
            Value
    end.

get(Key) ->
    case erlcfg_node:get(Node, Key) of
        {not_found, MissingNode} ->
            {error, {not_found, MissingNode}};
        {value, Value} ->
            Value
    end.

ensure_get(Key) ->
    case THIS:get(Key) of
        {error, Reason} ->
            throw(Reason);
        Value ->
            Value
    end.


%%%-------------------------------------------------------------------
%%% File : similar_data.hrl
%%% Author : Nicolas R Dufour <nrdufour@gmail.com>
%%% Created : 2009/05/19
%%% Description :
%%%     Basic record containing the simulation data.
%%%
%%% Copyright 2009 Nicolas R Dufour <nrdufour@gmail.com>
%%%
%%% This software is licensed as described in the file LICENSE, which
%%% you should have received as part of this distribution.
%%%-------------------------------------------------------------------

-record(sm_data,
	{

	%%% {EvTree; R;E;Current; RealTime; SList; Trace}

	%% Events to be scheduled
	events = [],
	%% Resources list
	resources = [],
	%% Alive processes in the simulation
	processes = [],
	%% Active processes in the simulation
	actives = [],
	%% Simulation time
	time = 0,
	%% Properties
	props = [],
	%% Activate the traces or not
	trace = false

	}
).

%%%

Add a record to carry a singular event.

%%%-------------------------------------------------------------------
%%% File : similar_data.hrl
%%% Author : Nicolas R Dufour <nrdufour@gmail.com>
%%% Created : 2009/05/19
%%% Description :
%%%     Basic record containing the simulation data.
%%%
%%% Copyright 2009 Nicolas R Dufour <nrdufour@gmail.com>
%%%
%%% This software is licensed as described in the file LICENSE, which
%%% you should have received as part of this distribution.
%%%-------------------------------------------------------------------

-record(sm_data,
	{

	%%% {EvTree; R;E;Current; RealTime; SList; Trace}

	%% Events to be scheduled
	events = [],
	%% Resources list
	resources = [],
	%% Alive processes in the simulation
	processes = [],
	%% Active processes in the simulation
	actives = [],
	%% Simulation time
	time = 0,
	%% Properties
	props = [],
	%% Activate the traces or not
	trace = false

	}
).

-record(sm_event,
	{
		%% Event timestamp
		time = 0,
		%% Processes to wake up at that timestamp
		procs = []
	}
).

%%%


-module(iota_api_checks_tests).

-include_lib("eunit/include/eunit.hrl").

internal_consistency_test_() ->
  EmptyResults = iota_result:new(foo),
  ExpectedWarning = iota_errors:emit_warning(EmptyResults,
                                             foo, {api, unrestricted_api}),
  [ ?_assertMatch(ExpectedWarning,
                  iota_api_checks:internal_consistency({foo, [{is_api, true},
                                                             {api, all}]},
                                                       EmptyResults
                                                      )),
    ?_assertMatch(EmptyResults,
                  iota_api_checks:internal_consistency({foo, [{is_api, true},
                                                              {api, [foo]}]},
                                                       EmptyResults
                                                      )),
    ?_assertMatch(EmptyResults,
                  iota_api_checks:internal_consistency({foo, [{is_api, false},
                                                              {api, []}]},
                                                       EmptyResults
                                                      ))
  ].

Fix call to iota_result:new in unit test

-module(iota_api_checks_tests).

-include_lib("eunit/include/eunit.hrl").

internal_consistency_test_() ->
  EmptyResults = iota_result:new(),
  ExpectedWarning = iota_errors:emit_warning(EmptyResults,
                                             foo, {api, unrestricted_api}),
  [ ?_assertMatch(ExpectedWarning,
                  iota_api_checks:internal_consistency({foo, [{is_api, true},
                                                             {api, all}]},
                                                       EmptyResults
                                                      )),
    ?_assertMatch(EmptyResults,
                  iota_api_checks:internal_consistency({foo, [{is_api, true},
                                                              {api, [foo]}]},
                                                       EmptyResults
                                                      )),
    ?_assertMatch(EmptyResults,
                  iota_api_checks:internal_consistency({foo, [{is_api, false},
                                                              {api, []}]},
                                                       EmptyResults
                                                      ))
  ].


%% @doc Supervise coord fsm.
-module(floppy_coord_sup).
-behavior(supervisor).

-export([start_fsm/1,
         start_link/0]).
-export([init/1]).

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

start_fsm(Args) ->
    supervisor:start_child(?MODULE, Args).

init([]) ->
    Worker = {floppy_coord_fsm,
              {floppy_coord_fsm, start_link, []},
              transient, 5000, worker, [floppy_coord_fsm]},
    {ok, {{simple_one_for_one, 5, 10}, [Worker]}}.

Add documentation for coordinator FSM.

%% @doc Supervisor for the coordinator FSMs.
%%

-module(floppy_coord_sup).

-behavior(supervisor).

-export([start_fsm/1,
         start_link/0]).

-export([init/1]).

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

start_fsm(Args) ->
    supervisor:start_child(?MODULE, Args).

init([]) ->
    Worker = {floppy_coord_fsm,
              {floppy_coord_fsm, start_link, []},
              transient, 5000, worker, [floppy_coord_fsm]},
    {ok, {{simple_one_for_one, 5, 10}, [Worker]}}.


-module(ginger_config).
-author("Driebit <tech@driebit.nl").

-export([
    install_config/1
]).

-include_lib("zotonic.hrl").

%% @doc Set preferred default config (but don't overwrite if already set)
-spec install_config(#context{}) -> ok.
install_config(Context) ->
    lists:foreach(
        fun({Mod, Key, Value}) ->
            m_config:get(Mod, Key, Context),
            case m_config:get(Mod, Key, Context) of
                undefined ->
                    m_config:set_value(Mod, Key, Value, Context);
                _ ->
                    noop
            end
        end,
        get_config()
    ),
    ok.

%% @doc Get default Ginger config parameters
-spec get_config() -> list().
get_config() ->
    [
        {mod_l10n, timezone, <<"Europe/Berlin">>},
        {mod_l10n, timezone_is_fixed, true}
    ].

Set Dutch as default site language

-module(ginger_config).
-author("Driebit <tech@driebit.nl").

-export([
    install_config/1
]).

-include_lib("zotonic.hrl").

%% @doc Set preferred default config (but don't overwrite if already set)
-spec install_config(#context{}) -> ok.
install_config(Context) ->
    lists:foreach(
        fun({Mod, Key, Value}) ->
            m_config:get(Mod, Key, Context),
            case m_config:get(Mod, Key, Context) of
                undefined ->
                    m_config:set_value(Mod, Key, Value, Context);
                _ ->
                    noop
            end
        end,
        get_config()
    ),
    ok.

%% @doc Get default Ginger config parameters
-spec get_config() -> list().
get_config() ->
    [
        {i18n, language, nl},
        {mod_l10n, timezone, <<"Europe/Berlin">>},
        {mod_l10n, timezone_is_fixed, true}
    ].


-module(teles_data_manager_sup).
-behaviour(supervisor).
-export([start_link/1, init/1, start_agents/2]).

start_link(NumAgents) ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, [NumAgents]).

init([NumAgents]) ->
    Manager = {data_manager, {teles_data_manager, start_link, [NumAgents]},
            permanent, 5000, worker, dynamic},

    % Start no agents, as they are added dynamically
    % when needed
    {ok, {{one_for_one, 10, 10}, [Manager]}}.

% Starts a number of agents
start_agents(Num, Space) ->
    start_agents(Num, Space, []).

start_agents(0, _, Results) -> Results;
start_agents(Num, Space, Results) ->
    AgentSpec = {{agent, Space, Num},
                {teles_data_agent, start_link, [Num, Space]},
                temporary, 5000, worker, dynamic},

    % Start the child
    Res = case supervisor:start_child(?MODULE, AgentSpec) of
        {ok, Pid} -> {new, Pid};
        {error, {already_started, Pid}} -> {exists, Pid};
        {error, _} -> error
    end,
    start_agents(Num - 1, Space, [Res | Results]).

Split start_agents into 2, so you can start a single agent

-module(teles_data_manager_sup).
-behaviour(supervisor).
-export([start_link/1, init/1, start_agents/2, start_agent/2]).

start_link(NumAgents) ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, [NumAgents]).

init([NumAgents]) ->
    Manager = {data_manager, {teles_data_manager, start_link, [NumAgents]},
            permanent, 5000, worker, dynamic},

    % Start no agents, as they are added dynamically
    % when needed
    {ok, {{one_for_one, 10, 10}, [Manager]}}.

% Starts a number of agents
start_agents(Num, Space) ->
    start_agents(Num, Space, []).

start_agents(0, _, Results) -> Results;
start_agents(Num, Space, Results) ->
    Res = start_agent(Num, Space),
    start_agents(Num - 1, Space, [Res | Results]).

% Starts a single agent
start_agent(Num, Space) ->
    AgentSpec = {{agent, Space, Num},
                {teles_data_agent, start_link, [Num, Space]},
                temporary, 5000, worker, dynamic},

    case supervisor:start_child(?MODULE, AgentSpec) of
        {ok, Pid} -> {new, Pid};
        {error, {already_started, Pid}} -> {exists, Pid};
        {error, _} -> error
    end.


-module(rna_transcription_tests).

-define(TESTED_MODULE, (sut(rna_transcription))).
-define(TEST_VERSION, 1).
-include("exercism.hrl").

transcribes_cytidine_unchanged_test() ->
  ?assertEqual("C", ?TESTED_MODULE:to_rna("G")).

transcribes_guanosine_unchanged_test() ->
  ?assertEqual("G", ?TESTED_MODULE:to_rna("C")).

transcribes_adenosine_unchanged_test() ->
  ?assertEqual("A", ?TESTED_MODULE:to_rna("T")).

transcribes_thymidine_to_uracil_test() ->
  ?assertEqual("U", ?TESTED_MODULE:to_rna("A")).

transcribes_all_occurences_test() ->
  ?assertEqual(
     "UGCACCAGAAUU",
     ?TESTED_MODULE:to_rna("ACGTGGTCTTAA")
    ).

Change the name of tests

-module(rna_transcription_tests).

-define(TESTED_MODULE, (sut(rna_transcription))).
-define(TEST_VERSION, 1).
-include("exercism.hrl").

transcribes_cytidine_to_guanosine_test() ->
  ?assertEqual("C", ?TESTED_MODULE:to_rna("G")).

transcribes_guanosine_to_cytidine_test() ->
  ?assertEqual("G", ?TESTED_MODULE:to_rna("C")).

transcribes_adenosine_to_thymidine_test() ->
  ?assertEqual("A", ?TESTED_MODULE:to_rna("T")).

transcribes_thymidine_to_uracil_test() ->
  ?assertEqual("U", ?TESTED_MODULE:to_rna("A")).

transcribes_all_occurences_test() ->
  ?assertEqual(
     "UGCACCAGAAUU",
     ?TESTED_MODULE:to_rna("ACGTGGTCTTAA")
    ).


%%% -*- erlang-indent-level:4; indent-tabs-mode: nil -*-
%%%-------------------------------------------------------------------
%%% @copyright (C) 2018, Aeternity Anstalt
%%% @doc Test Sophia language compiler.
%%%
%%% @end
%%%-------------------------------------------------------------------

-module(aeso_compiler_tests).

-include_lib("eunit/include/eunit.hrl").

%% simple_compile_test_() -> ok.
%%  Very simply test compile the given contracts. Only basic checks
%%  are made on the output, just that it is a binary which indicates
%%  that the compilation worked.

simple_compile_test_() ->
    {setup,
     fun () -> ok end,                          %Setup
     fun (_) -> ok end,                         %Cleanup
     [ {"Testing the " ++ ContractName ++ " contract",
        fun() ->
                ContractString = aeso_test_utils:read_contract(ContractName),
                ?assertMatch(Code when is_binary(Code),
                                       aeso_compiler:from_string(ContractString, []))

        end} ||
         ContractName <- compilable_contracts() ]}.

%% compilable_contracts() -> [ContractName].
%%  The currently compilable contracts.

compilable_contracts() ->
    ["complex_types",
     "counter",
     "dutch_auction",
     "environment",
     "factorial",
     "fundme",
     "identity",
     "maps",
     "remote_call",
     "simple",
     "simple_storage",
     "spend_test",
     "stack",
     "test"
    ].

Add oracles.aes test Sophia contract among compilation unit tests

%%% -*- erlang-indent-level:4; indent-tabs-mode: nil -*-
%%%-------------------------------------------------------------------
%%% @copyright (C) 2018, Aeternity Anstalt
%%% @doc Test Sophia language compiler.
%%%
%%% @end
%%%-------------------------------------------------------------------

-module(aeso_compiler_tests).

-include_lib("eunit/include/eunit.hrl").

%% simple_compile_test_() -> ok.
%%  Very simply test compile the given contracts. Only basic checks
%%  are made on the output, just that it is a binary which indicates
%%  that the compilation worked.

simple_compile_test_() ->
    {setup,
     fun () -> ok end,                          %Setup
     fun (_) -> ok end,                         %Cleanup
     [ {"Testing the " ++ ContractName ++ " contract",
        fun() ->
                ContractString = aeso_test_utils:read_contract(ContractName),
                ?assertMatch(Code when is_binary(Code),
                                       aeso_compiler:from_string(ContractString, []))

        end} ||
         ContractName <- compilable_contracts() ]}.

%% compilable_contracts() -> [ContractName].
%%  The currently compilable contracts.

compilable_contracts() ->
    ["complex_types",
     "counter",
     "dutch_auction",
     "environment",
     "factorial",
     "fundme",
     "identity",
     "maps",
     "oracles",
     "remote_call",
     "simple",
     "simple_storage",
     "spend_test",
     "stack",
     "test"
    ].


%% @doc RDF searches through linked data
%% @author David de Boer <david@driebit.nl>
-module(ginger_rdf_search).

-export([
    search_query/2
]).

-include_lib("zotonic.hrl").
-include_lib("../include/rdf.hrl").

%% @doc Search in linked data sources and return results as sets of RDF triples
-spec search_query(#search_query{}, list()) -> list().
search_query(#search_query{search = {rdf, _Args}, offsetlimit = _OffsetLimit} = Query, Context) ->
    %% Look up all sources and combine the results

    %% @todo Enable users to configure this config value on an admin GUI page.
    Source = m_config:get_value(mod_ginger_rdf, source, Context),
    z_notifier:first(#rdf_search{source = Source, query = Query}, Context);
search_query(#search_query{}, _Context) ->
    undefined.

Fix Unknown search query {rdf, ...}

%% @doc RDF searches through linked data
%% @author David de Boer <david@driebit.nl>
-module(ginger_rdf_search).

-export([
    search_query/2
]).

-include_lib("zotonic.hrl").
-include_lib("../include/rdf.hrl").

%% @doc Search in linked data sources and return results as sets of RDF triples
-spec search_query(#search_query{}, list()) -> list().
search_query(#search_query{search = {rdf, _Args}, offsetlimit = _OffsetLimit} = Query, Context) ->
    %% Look up all sources and combine the results

    %% @todo Enable users to configure this config value on an admin GUI page.
    Source = m_config:get_value(mod_ginger_rdf, source, Context),
    case z_notifier:first(#rdf_search{source = Source, query = Query}, Context) of
        undefined ->
            [];
        Result ->
            Result
    end;
search_query(#search_query{}, _Context) ->
    undefined.


%%%-------------------------------------------------------------------
%%% File    : node_controller.erl
%%% Author  : Ari Lerner
%%% Description :
%%%
%%% Created :  Fri Nov 13 11:43:49 PST 2009
%%%-------------------------------------------------------------------

-module (nodes_controller).
-include ("router.hrl").
-include ("http.hrl").
-export ([get/1, post/2, put/2, delete/2]).

get(_) ->
  {struct, [
    {"routers", [format_nodes(fun node_manager:get_routers/0)]},
    {"nodes", format_nodes(fun node_manager:get_nodes/0)}
    ]
  }.

format_nodes(F) ->
  lists:append(
    lists:map(fun(#node{name = Name, host = Host} = _Node) ->
      {struct, ?BINIFY([
        {"name", Name},
        {"host", Host}
      ])}
    end, lists:map(fun(N) -> node_manager:dump(N) end, F())
  )).

post(_Path, _Data) -> "unhandled".
put(_Path, _Data) -> "unhandled".
delete(_Path, _Data) -> "unhandled".

Structure nodes json response (TODO: update this)

%%%-------------------------------------------------------------------
%%% File    : node_controller.erl
%%% Author  : Ari Lerner
%%% Description :
%%%
%%% Created :  Fri Nov 13 11:43:49 PST 2009
%%%-------------------------------------------------------------------

-module (nodes_controller).
-include ("router.hrl").
-include ("http.hrl").
-export ([get/1, post/2, put/2, delete/2]).

get(_) ->
  {struct, [
    {"routers", [format_nodes(fun node_manager:get_routers/0)]},
    {"nodes", format_nodes(fun node_manager:get_nodes/0)}
    ]
  }.

format_nodes(F) ->
  Nodes = lists:append(
    lists:map(fun(#node{name = Name, host = Host} = _Node) ->
      ?BINIFY([
        {"name", Name},
        {"host", Host}
      ])
    end, lists:map(fun(N) -> node_manager:dump(N) end, F())
  )),
  {struct, Nodes}.

post(_Path, _Data) -> "unhandled".
put(_Path, _Data) -> "unhandled".
delete(_Path, _Data) -> "unhandled".


Add simple proto_handler that prints all messages to stdout

-module(echo).
-behaviour(gen_server).
-behaviour(proto_handler).

-export([start/2, send_msg/2]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

-record(state, {parent, name}).

start(Config, Parent) ->
	gen_server:start_link(echo, {Config, Parent}, []).

send_msg(Pid, Msg) ->
	gen_server:cast(Pid, Msg).

init({Name, Parent}) ->
	io:format("~s:Starting echo handler with pid ~p~n", [Name, self()]),
	{ok, #state{parent=Parent,name=Name}}.

handle_call(Request, Parent, #state{parent=Parent} = State) ->
	io:format("~s:Sync request: ~p~n", [State#state.name, Request]),
	{noreply, State};

handle_call(Request, From, State) ->
	io:format("~s:Sync request from ~p: ~p~n", [State#state.name, From, Request]),
	{noreply, State}.

handle_cast(Request, State) ->
	io:format("~s:Async request: ~p~n", [State#state.name, Request]),
	{noreply, State}.

handle_info(Info, State) ->
	io:format("~s:Info received: ~p~n", [State#state.name, Info]),
	{noreply, State}.

terminate(Reason, State) ->
	io:format("~s:Shutting down with reason: ~p~n", [State#state.name, Reason]).

code_change(_, State, _) ->
	{ok, State}.


Split - split a list into two sub-lists with elementes distributed

-module(split2).
-include_lib("eunit/include/eunit.hrl").
-export([split/1]).

split_even_list_test() ->
    ?assertEqual({[1,2], [3,4]}, split([1,2,3,4])).
split_odd_list_test() ->
    ?assertEqual({[a], [b,c]}, split([a,b,c])).
split_empty_list_test() ->
    ?assertEqual({[],[]}, split([])).
split_one_elm_list_test() ->
    ?assertEqual({[], [a]}, split([a])).
split_8_elm_list_test() ->
    ?assertEqual({[1,2,3,4],[5,6,7,8]}, split([1,2,3,4,5,6,7,8])).
split_9_elm_list_test() ->
    ?assertEqual({[0,1,2,3],[4,5,6,7,8]}, split([0,1,2,3,4,5,6,7,8])).

reverse_test() ->
    ?assertEqual([4,3,2,1], reverse([1,2,3,4])).
reverse_odd_list_test() ->
    ?assertEqual([a,b,c], reverse([c,b,a])).
reverse_empty_list_test() ->
    ?assertEqual([],reverse([])).

split(L) -> split(L, L, []).
split([], L1, L2) -> {reverse(L2), L1};
split([_], L1, L2) -> {reverse(L2), L1};
split([_,_|TT], [H|T], L2) -> split(TT, T, [H|L2]).
%% L2/L1 flipped because we do want [1,2,3] to split into {[1] , [2,3]}

reverse(L) -> reverse(L, []).
reverse([], L) -> L;
reverse([H|T], L) -> reverse(T, [H|L]).


Add a UDP roundtrip encoding eunit test for enet_codec.


-module(wilcog_path_tree).
-export([build_tree/1, build_tree/2]).

build_tree(Path)->
  NewTree = gb_trees:empty(),
  PathProperties = [{"path", Path}],
  RootTree = gb_trees:enter(Path, PathProperties, NewTree),
  build_tree(Path, RootTree).

build_tree(Path, Tree)->
  {ok, Items} = file:list_dir_all(Path),

  ItemMapper = fun(Item)->
    ParentProps = gb_trees:get(Path, Tree),
    ParentPath = proplists:get_value("path", ParentProps),
    ItemPath = filename:absname_join(ParentPath, Item),
    LastModifiedAt = filelib:last_modified(ItemPath),
    ItemProperties = [
      {"path", ItemPath}
    ],

    case filelib:is_dir(ItemPath) of
      true ->
        erlang:display("Dir"),
        erlang:display(ItemPath),
        UpdatedTree = gb_trees:enter(ItemPath, ItemProperties, Tree),
        build_tree(ItemPath, UpdatedTree);
      _ ->
        erlang:display("File"),
        erlang:display(ItemPath),
        gb_trees:enter(ItemPath, [{"modified_at", LastModifiedAt} | ItemProperties], Tree)
    end
  end,
  lists:map(ItemMapper, Items).


Add map manager module. (not implemented anything!)

%%
%% em_map.erl
%%
%% Easymmo map manager (users can be located in one map.)

-module(npc_pool).
-include_lib("amqp_client.hrl").

-export([start_link/3]).
-export([terminate/2]).
-export([init/1]).
-export([handle_info/2]).

start_link(ServerIp, ToClientEx, FromClientEx) ->
	gen_server:start_link({local, ?MODULE}, ?MODULE, [ServerIp, ToClientEx, FromClientEx], []).

init(Args) ->
    [ServerIp, ToClientEx, FromClientEx] = Args,
	{ok, bidir_mq:init_topic(ServerIp, ToClientEx, FromClientEx, [<<"move.#">>])}.

%%
%% APIs
%%

%% gen_server behaviour %%
terminate(_Reason, State) ->
	bidir_mq:shutdown_by_state(State),
	ok.

%% just after setup, this message will arrive.
handle_info(#'basic.consume_ok'{}, State) ->
	{noreply, State};

%% while subscribing, message will be delivered by #amqp_msg
handle_info( {#'basic.deliver'{routing_key = _RoutingKey}, #amqp_msg{payload = Body}} , State) ->
	{_ServerIp, ToClientEx, _FromClientEx, {_Connection, ChTC, _ChFC}} = State,
	BinMsg = <<"info: Hello, this is move_srv!">>,
	amqp_channel:cast(ChTC,
		#'basic.publish'{exchange = ToClientEx, routing_key = <<"move.id.99999">> },
		#amqp_msg{payload = BinMsg}),
	{noreply, State}.


Add skeleton for list-of-manifest manipulation module


f(UpgradeNode).
UpgradeNode = fun () ->
  case logplex_app:config(git_branch) of
      "v58" ->
          io:format(whereis(user), "at=upgrade_start cur_vsn=58~n", []);
      "v59" ->
          io:format(whereis(user),
                    "at=upgrade type=retry cur_vsn=58 old_vsn=59~n", []);
      Else ->
          io:format(whereis(user),
                    "at=upgrade_start old_vsn=~p abort=wrong_version", [tl(Else)]),
          erlang:error({wrong_version, Else})
  end,

  %% Stateless

  l(logplex_http_drain),
  l(logplex_tcpsyslog_drain),
  l(logplex_drain),

  io:format(whereis(user), "at=upgrade_end cur_vsn=59~n", []),
  application:set_env(logplex, git_branch, "v59"),
  ok
end.

f(NodeVersions).
NodeVersions = fun () ->
                       lists:keysort(3,
                           [ {N,
                              element(2, rpc:call(N, application, get_env, [logplex, git_branch])),
                              rpc:call(N, os, getenv, ["INSTANCE_NAME"])}
                             || N <- [node() | nodes()] ])
               end.

f(NodesAt).
NodesAt = fun (Vsn) ->
                  [ N || {N, V, _} <- NodeVersions(), V =:= Vsn ]
          end.

f(RollingUpgrade).
RollingUpgrade = fun (Nodes) ->
  lists:foldl(fun (N, {good, Upgraded}) ->
    case rpc:call(N, erlang, apply, [ UpgradeNode, [] ]) of
      ok ->
        {good, [N | Upgraded]};
      Else ->
        {{bad, N, Else}, Upgraded}
    end;
    (N, {_, _} = Acc) -> Acc
    end,
    {good, []},
    Nodes)
end.


-module(aebytecode_SUITE).

%% common_test exports
-export([ all/0 ]).

%% test case exports
-export([ roundtrip_identy/1 ]).

-include_lib("common_test/include/ct.hrl").

all() ->
    [ roundtrip_identy ].

roundtrip_identy(_Cfg) ->
    CodeDir = code:lib_dir(aebytecode, test),
    FileName = filename:join(CodeDir, "asm_code/identity.aesm"),
    Code = aeb_asm:file(FileName, []),
    ct:log("Code ~p:~n~s~n", [FileName, aeb_disassemble:format(Code, fun io:format/2)]),
    ok.


-module(chloe_session_test).

-include_lib("eunit/include/eunit.hrl").

send_to_browser_test() ->
    {ok, MockPid} = gen_server_mock:new(),
    gen_server_mock:expect_cast(MockPid, fun({send, "some test data"}, State) ->
                {ok, State}
        end),

    {ok, SessionPid} = chloe_session:start_link(MockPid),
    chloe_session:send_to_browser(SessionPid, "some test data"),
    gen_server_mock:assert_expectations(MockPid).


-module(optimised).
-export([sum/1]).

maximumSum(N, M) ->
  N div M.

% Could be rewritten to SUM's but for functional programming I think it's same ))
list(Count, X)->
  [ N * X || N <- lists:seq(1, maximumSum(Count - 1, X)) ].

sum(Count) ->
  lists:sum(lists:umerge(list(Count, 3), list(Count, 5))).


%% @copyright 2012 Opscode, Inc. All Rights Reserved
%% @author Tim Dysinger <timd@opscode.com>
%%
%% Licensed to the Apache Software Foundation (ASF) under one or more
%% contributor license agreements.  See the NOTICE file distributed
%% with this work for additional information regarding copyright
%% ownership.  The ASF licenses this file to you under the Apache
%% License, Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License.  You may obtain a copy of
%% the License at http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
%% implied.  See the License for the specific language governing
%% permissions and limitations under the License.

-module(bookshelf_fs).
-include("bookshelf.hrl").
-export([
         bucket_list/1,
         bucket_exists/2,
         bucket_create/2,
         bucket_delete/2
        ]).

%% ===================================================================
%% Bucket functions
%% ===================================================================

bucket_list(Dir) ->
    {ok, Files} = file:list_dir(Dir), %% crash if no access to base dir
    lists:map(fun(P) -> %% crash if no access to any bucket dir
                      {ok, #file_info{ctime=Date}} =
                          file:read_file_info(P, [{time, universal}]),
                      #bucket{ name=filename:basename(P),
                               date=iso8601:format(Date) }
              end,
              lists:filter(fun filelib:is_dir/1,
                           lists:map(fun(F) ->
                                             filename:join(Dir, F)
                                     end,
                                     Files))).

bucket_exists(Dir, Bucket) ->
    filelib:is_dir(filename:join(Dir, Bucket)).

bucket_create(Dir, Bucket) ->
    file:make_dir(filename:join(Dir, Bucket)).

bucket_delete(Dir, Bucket) ->
    file:del_dir(filename:join(Dir, Bucket)).


Add test that will unload nif, this should make gcov save it's result

-module(unload_test).
-export([unload_test/0]).

unload_test() ->
    code:delete(fast_yaml),
    code:purge(fast_yaml),
    code:load_file(fast_yaml).


-module(torrent_piecemap).
-behaviour(gen_server).

-export([start_link/1, init/1, handle_call/3, handle_cast/2, code_change/3, handle_info/2]).
-export([terminate/2]).

start_link(Amount) ->
    gen_server:start_link(torrent_piecemap, Amount, []).

init(NumberOfPieces) ->
    PieceTable = initialize_piece_table(NumberOfPieces),
    random:seed(erlang:now(), erlang:now()+1, erlang:now()-1),
    {ok, PieceTable}.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

handle_info(Info, State) ->
    error_logger:info_report([{'INFO', Info}, {'State', State}]),
    {noreply, State}.

terminate(shutdown, _Piecemap) ->
    ok.

initialize_piece_table(Amount) ->
    Table = ets:new(piece_table, []),
    populate_table(Table, Amount).

populate_table(Table, 0) ->
    Table;
populate_table(Table, N) ->
    ets:insert(Table, {N, unclaimed}),
    populate_table(Table, N-1).

handle_call({request_piece, PiecesPeerHas}, Who, PieceTable) ->
    case find_appropriate_piece(PieceTable, Who, PiecesPeerHas) of
	{ok, P} ->
	    {reply, {piece_to_get, P}};
	none_applies ->
	    {reply, no_pieces_are_interesting}
    end.

handle_cast({peer_got_piece, _PieceNum}, PieceTable) ->
    {noreply, PieceTable}. %% This can later be used for rarest first selection

find_appropriate_piece(PieceTable, Who, PiecesPeerHas) ->
    case find_eligible_pieces(PiecesPeerHas, PieceTable) of
	{ok, Pieces} ->
	    P = pick_random(Pieces),
	    mark_as_requested(PieceTable, P, Who),
	    {ok, P};
	none ->
	    none_applies
    end.

mark_as_requested(PieceTable, PNum, Who) ->
    ets:insert(PieceTable, {PNum, Who}).

find_eligible_pieces(PiecesPeerHas, PieceTable) ->
    Unclaimed = sets:from_list(ets:select(PieceTable, [{{'$1', unclaimed}, [], ['$1']}])),
    Eligible = sets:intersection(Unclaimed, PiecesPeerHas),
    EligibleSize = sets:size(Eligible),
    if
	EligibleSize > 0 ->
	    {ok, Eligible};
	true ->
	    none
    end.

pick_random(PieceSet) ->
    Size = sets:size(PieceSet),
    lists:nth(random:uniform(Size), sets:to_list(PieceSet)).


Add tests for design document validations

% Licensed under the Apache License, Version 2.0 (the "License"); you may not
% use this file except in compliance with the License. You may obtain a copy of
% the License at
%
%   http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
% License for the specific language governing permissions and limitations under
% the License.

-module(couch_mrview_ddoc_validation_tests).

-include_lib("couch/include/couch_eunit.hrl").
-include_lib("couch/include/couch_db.hrl").

setup() ->
    {ok, Db} = couch_mrview_test_util:init_db(?tempdb(), map),
    Db.

teardown(Db) ->
    couch_db:close(Db),
    couch_server:delete(Db#db.name, [?ADMIN_CTX]),
    ok.

ddoc_validation_test_() ->
    {
        "ddoc validation tests",
        {
            setup,
            fun test_util:start_couch/0, fun test_util:stop_couch/1,
            {
                foreach,
                fun setup/0, fun teardown/1,
                [
                    fun should_reject_invalid_js_map/1,
                    fun should_reject_invalid_js_reduce/1,
                    fun should_reject_invalid_builtin_reduce/1
                ]
            }
        }
    }.

should_reject_invalid_js_map(Db) ->
    Doc = couch_doc:from_json_obj({[
        {<<"_id">>, <<"_design/should_reject_invalid_js_map">>},
        {<<"views">>, {[
            {<<"foo">>, {[
                {<<"map">>, <<"function(doc) }{">>}
            ]}}
        ]}}
    ]}),
    ?_assertThrow({compilation_error, _}, couch_db:update_doc(Db, Doc, [])).

should_reject_invalid_js_reduce(Db) ->
    Doc = couch_doc:from_json_obj({[
        {<<"_id">>, <<"_design/should_reject_invalid_js_reduce">>},
        {<<"views">>, {[
            {<<"foo">>, {[
                {<<"map">>, <<"function(doc) { emit(null); }">>},
                {<<"reduce">>, <<"function(k, v, r) }{}">>}
            ]}}
        ]}}
    ]}),
    ?_assertThrow({compilation_error, _}, couch_db:update_doc(Db, Doc, [])).

should_reject_invalid_builtin_reduce(Db) ->
    Doc = couch_doc:from_json_obj({[
        {<<"_id">>, <<"_design/should_reject_invalid_builtin_reduce">>},
        {<<"views">>, {[
            {<<"foo">>, {[
                {<<"map">>, <<"function(doc) { emit(null); }">>},
                {<<"reduce">>, <<"_foobar">>}
            ]}}
        ]}}
    ]}),
    ?_assertThrow({invalid_design_doc, _}, couch_db:update_doc(Db, Doc, [])).


-module(derflow_riak_kv_integration).
-author("Christopher Meiklejohn <cmeiklejohn@basho.com>").

-export([postcommit_log_object/1]).

%% @doc Trigger a log message when postcommit hook is triggered.
postcommit_log_object(Object) ->
    lager:info("Postcommit hook triggered for ~p", [Object]).


-module(append_test).

-export([confirm/0]).

-include_lib("eunit/include/eunit.hrl").

-define(HARNESS, (rt_config:get(rt_harness))).

confirm() ->
    [Nodes] = rt:build_clusters([1]),

    lager:info("Waiting for ring to converge."),
    rt:wait_until_ring_converged(Nodes),

    Node = hd(Nodes),

    WriteResult = rpc:call(Node,
                           floppy, append,
                           [key, {increment, ucl}]),
    ?assertMatch({ok, _}, WriteResult),

    pass.


%%% This file is part of the RayActor Lighting Software.
%%%
%%% RayActor is free software: you can redistribute it and/or modify it under
%%% the terms of the GNU Affero General Public License as published by the Free
%%% Software Foundation, either version 3 of the License, or (at your option)
%%% any later version.
%%%
%%% RayActor is distributed in the hope that it will be useful, but WITHOUT ANY
%%% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
%%% FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
%%% more details.
%%%
%%% You should have received a copy of the GNU Affero General Public License
%%% along with Rayactor. If not, see <http://www.gnu.org/licenses/>.
%%%
-module(rayactor_color).

-export([new/1, new/3, set/3, to_binary/1, blend/3]).

-record(color, {red :: red(), green :: green(), blue :: blue()}).

-type red() :: byte().
-type green() :: byte().
-type blue() :: byte().
-type channel() :: red() | green() | blue().
-type color() :: #color{}.

-export_type([color/0, channel/0, red/0, green/0, blue/0]).

-spec new(red() | float(), green() | float(), blue() | float()) -> color().

new(Red, Green, Blue) ->
    #color{red = round(Red), green = round(Green), blue = round(Blue)}.

-spec new(non_neg_integer() | binary()) -> color().

new(IntVal) when is_integer(IntVal) -> new(<<IntVal:24>>);
new(<<Red:8, Green:8, Blue:8>>) -> new(Red, Green, Blue).

-spec set(color(), red | green | blue, channel()) -> color().

set(C, red,   Val) -> C#color{red   = Val};
set(C, green, Val) -> C#color{green = Val};
set(C, blue,  Val) -> C#color{blue  = Val}.

-spec to_binary(color()) -> binary().

to_binary(C) -> <<(C#color.red):8, (C#color.green):8, (C#color.blue):8>>.

-spec blend(color(), color(), Weight :: float()) -> color().

blend(C1, C2, Weight) ->
    R = C1#color.red   * (1.0 - Weight) + C2#color.red   * Weight,
    G = C1#color.green * (1.0 - Weight) + C2#color.green * Weight,
    B = C1#color.blue  * (1.0 - Weight) + C2#color.blue  * Weight,
    new(R, G, B).


f(UpgradeNode).
UpgradeNode = fun () ->
  case logplex_app:config(git_branch) of
      "v64" ->
          io:format(whereis(user), "at=upgrade_start cur_vsn=64~n", []);
      "v65" ->
          io:format(whereis(user),
                    "at=upgrade type=retry cur_vsn=64 old_vsn=65~n", []);
      Else ->
          io:format(whereis(user),
                    "at=upgrade_start old_vsn=~p abort=wrong_version", [tl(Else)]),
          erlang:error({wrong_version, Else})
  end,

  %% stateless, internal
  l(logplex_logs_rest),
  l(logplex_tcpsyslog_drain),

  io:format(whereis(user), "at=upgrade_end cur_vsn=65~n", []),
  application:set_env(logplex, git_branch, "v65"),
  ok
end.

f(NodeVersions).
NodeVersions = fun () ->
                       lists:keysort(3,
                           [ {N,
                              element(2, rpc:call(N, application, get_env, [logplex, git_branch])),
                              rpc:call(N, os, getenv, ["INSTANCE_NAME"])}
                             || N <- [node() | nodes()] ])
               end.

f(NodesAt).
NodesAt = fun (Vsn) ->
                  [ N || {N, V, _} <- NodeVersions(), V =:= Vsn ]
          end.

f(RollingUpgrade).
RollingUpgrade = fun (Nodes) ->
  lists:foldl(fun (N, {good, Upgraded}) ->
    case rpc:call(N, erlang, apply, [ UpgradeNode, [] ]) of
      ok ->
        {good, [N | Upgraded]};
      Else ->
        {{bad, N, Else}, Upgraded}
    end;
    (N, {_, _} = Acc) -> Acc
    end,
    {good, []},
    Nodes)
end.


Add test for Erlson parser for Erlang shell

%%  Copyright (c) 2011 Anton Lavrik, http://github.com/alavrik
%%
%%  Permission is hereby granted, free of charge, to any person obtaining
%%  a copy of this software and associated documentation files (the
%%  "Software"), to deal in the Software without restriction, including
%%  without limitation the rights to use, copy, modify, merge, publish,
%%  distribute, sublicense, and/or sell copies of the Software, and to
%%  permit persons to whom the Software is furnished to do so, subject to
%%  the following conditions:
%%
%%  The above copyright notice and this permission notice shall be
%%  included in all copies or substantial portions of the Software.
%%
%%  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
%%  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
%%  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
%%  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
%%  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
%%  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
%%  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-module(erlson_shell_test).
%-compile(export_all).

-include_lib("eunit/include/eunit.hrl").

compile_test() ->
    % load a different version of erl_parse.beam that contains in-place Erlson
    % transformations
    erlson:init(),
    ErlParsePath = code:which(erl_parse),

    %?debugFmt("AAAAAAAAAAA: erl_parse.beam: ~s~n", [ErlParsePath]),
    ?assert(string:str(ErlParsePath, "erl_parse_shell.beam") =/= 0),

    % now, compile a test file using a different parser
    Res = compile:file("erlson_tests.erl"),

    %?debugFmt("AAAAAAAAAAA: erlson_shell compilation: ~p~n", [Res]),
    ?assertEqual(element(1, Res), ok),

    ok.


Add migration for metrics storage reengineering

#!/usr/bin/env escript

main([BenchDir]) ->
    MetricsFile = filename:join(BenchDir, "metrics.txt"),
    OutputFilePattern = filename:join(BenchDir, "metrics_~s.txt"),
    case file:open(MetricsFile, [raw, binary, read]) of
        {ok, H} ->
            _ = parse_file(H, OutputFilePattern, _State = #{}),
            ok = file:close(H),
            ok = file:delete(MetricsFile);
        {error, enoent} -> ok;
        {error, Reason} ->
            io:format("Can't read metrics file: ~s with reason: ~p", [MetricsFile, Reason]),
            erlang:error({file_read_error, MetricsFile, Reason})
    end,

    StatusFile = filename:join(BenchDir, "status"),
    case file:consult(StatusFile) of
        {ok, [Status]} ->
            NewStatusContent = io_lib:format("~p.", [migrate(Status)]),
            ok = file:write_file(StatusFile, NewStatusContent);
        {error, enoent} -> ok;
        {error, Reason2} ->
            io:format("Can't read status file: ~s with reason: ~p", [StatusFile, Reason2]),
            erlang:error({file_read_error, StatusFile, Reason2})
    end.

parse_file(H, OutputFile, State) ->
    case file:read_line(H) of
        {ok, D} ->
            [TS, M, V] = binary:split(D, <<"\t">>, [global]),
            case maps:find(M, State) of
                {ok, Output} ->
                    ok = file:write(Output, <<TS/binary, "\t", V/binary>>),
                    parse_file(H, OutputFile, State);
                error ->
                    F = lists:flatten(io_lib:format(OutputFile, [re:replace(M, "\\W", "_", [global, {return, list}])])),
                    {ok, Output} = file:open(F, [raw, binary, write]),
                    ok = file:write(Output, <<TS/binary, "\t", V/binary>>),
                    parse_file(H, OutputFile, maps:put(M, Output, State))
            end;
        eof ->
            _ = [ file:close(O) || {_, O} <- maps:to_list(State)],
            #{};
        {error, Error} ->
            io:format("Failed to read from metrics file: ~p",[Error]),
            erlang:error({read_metrics_error, Error})
    end.

migrate(Status = #{config:= Config}) ->
    Status#{config => Config#{metrics_file => "metrics_~s.txt"}};
migrate(Status = #{}) ->
    Status.


-module(floppy_log).

-export([confirm/0]).

-include_lib("eunit/include/eunit.hrl").

-define(HARNESS, (rt_config:get(rt_harness))).

confirm() ->
    mult_writes_one_read().

mult_writes_one_read() ->
    N = 3,
    ListIds = [random:uniform(N) || _ <- lists:seq(1, 10)],
    [Nodes] = rt:build_clusters([N]),

    F = fun(Elem, Acc) ->
            Node = lists:nth(Elem, Nodes),
            lager:info("Sending append to Node ~w~n",[Node]),
              WriteResult = rpc:call(Node, floppy, append, [abc, {increment, 4}]),
              ?assertMatch({ok, _}, WriteResult),
            Acc + 1
    end,

    Total = lists:foldl(F, 0, ListIds),
    FirstNode = hd(Nodes),
    lager:info("Sending read to Node ~w~n",[FirstNode]),
    ReadResult = rpc:call(FirstNode, floppy, read, [abc, riak_dt_gcounter]),
    ?assertEqual(Total, ReadResult),
    pass.


Introduce main --application-- module of the daemon, rudimentary for the moment.

%
% src/erlang/lib/dnsresolvd.erl
% =============================================================================
% DNS Resolver Daemon (dnsresolvd). Version 0.1
% =============================================================================
% A daemon that performs DNS lookups for the given hostname
% passed in an HTTP request, with the focus on its implementation
% using various programming languages. (Cowboy-boosted impl.)
% =============================================================================
% Copyright (C) 2017-2018 Radislav (Radicchio) Golubtsov
%
% (See the LICENSE file at the top of the source tree.)
%

%% @doc The main --application-- module of the daemon.
-module(dnsresolvd).

-export([start/2]).

%% @doc Starts up the daemon.<br />
%%      It has to be the application module callback, but used directly
%%      from the startup script of the daemon.
%%
%% @param Args A list containing the server port number to listen on
%%             as the first element.
%%
%% @returns The tuple containing the PID of the top supervisor process
%%          and the state of the running application (or an empty list).
start(_, Args) ->
    {Port_number, Daemon_name, Log} = Args,

%   {ok, _} = application:ensure_all_started(cowboy).
    ok.

% vim:set nu et ts=4 sw=4:


Implement client callback management abstraction.

-module(oauth1_callback).

-export_type(
    [ t/0
    ]).

-export(
    [ cons/2
    , set_token_and_verifier/3
    , get_uri/1
    , store/1
    , fetch/1
    ]).

-record(t,
    { token :: oauth1_credentials:id(tmp)
    , uri   :: oauth1_uri:t()
    }).

-opaque t() ::
    #t{}.

-define(STORAGE_BUCKET_NAME, <<"oauth1-callback">>).

-spec cons(oauth1_credentials:id(tmp), oauth1_uri:t()) ->
    t().
cons({tmp, <<Token/binary>>}, Uri) ->
    #t
    { token = Token
    , uri   = Uri
    }.

-spec get_uri(t()) ->
    oauth1_uri:t().
get_uri(#t{uri=URI}) ->
    URI.

-spec set_token_and_verifier(t(), Token, Verifier) ->
    t()
    when Token    :: oauth1_credentials:id(tmp)
       , Verifier :: oauth1_verifier:t()
       .
set_token_and_verifier( #t{uri=Uri1}=T
                      , {tmp, <<Token/binary>>}
                      , <<Verifier/binary>>
                      ) ->
    QueryParams =
        [ {<<"oauth_token">>    , Token}
        , {<<"oauth_verifier">> , Verifier}
        ],
    Uri2 = oauth1_uri:set_query(Uri1, QueryParams),
    T#t{uri=Uri2}.

-spec store(t()) ->
    hope_result:t(ok, oauth1_storage:error()).
store(#t{token = <<Token/binary>>, uri=Uri}) ->
    Key   = Token,
    Value = oauth1_uri:to_bin(Uri),
    oauth1_storage:put(?STORAGE_BUCKET_NAME, Key, Value).

-spec fetch(binary()) ->
    hope_result:t(t(), oauth1_storage:error()).
fetch(<<Token/binary>>) ->
    case oauth1_storage:get()
    of  {error, _}=Error ->
            Error
    ;   {ok, UriBin} ->
            {ok, Uri} = oauth1_uri:of_bin(UriBin),
            T = #t
                { token = Token
                , uri   = Uri
                },
            {ok, T}
    end.


Create initial skeleton for dk_yaws_server unit tests

%%%------------------------------------------------------------------------------
%%% @copyright (c) 2011, DuoMark International, Inc.  All rights reserved
%%% @author Jay Nelson <jay@duomark.com>
%%% @doc
%%%   Verify that dk_yaws_server instantiates and operates properly.
%%% @since v0.1.1
%%% @end
%%%------------------------------------------------------------------------------
-module(dk_yaws_server_tests).
-copyright("(c) 2011, DuoMark International, Inc.  All rights reserved").
-author(jayn).

-export([
         check_start/1
        ]).

-include_lib("eunit/include/eunit.hrl").

-define(TM, dk_yaws_server).

start() -> fun() -> ?TM:start_link() end.
stop() ->  fun({ok, _P1}) -> ok end.

%% @doc Start the server and verify the children.
start_test_() ->
    {setup, start(), stop(),
     {with, [fun check_start/1]}
    }.

check_start({ok, P1}) when is_pid(P1) ->
    ?assert(is_process_alive(P1)).


%% -------------------------------------------------------------------
%%
%% Copyright (c) 2007-2011 Basho Technologies, Inc.  All Rights Reserved.
%%
%% -------------------------------------------------------------------

-module(riak_moss_wm_key_test).

-export([key_test_/0]).

-include("riak_moss.hrl").
-include_lib("webmachine/include/webmachine.hrl").
-include_lib("eunit/include/eunit.hrl").

key_test_() ->
    {setup,
     fun riak_moss_wm_test_utils:setup/0,
     fun riak_moss_wm_test_utils:teardown/1,
     [fun create_object/0]}.

create_object() ->
    ok.

Add failing key resource test

%% -------------------------------------------------------------------
%%
%% Copyright (c) 2007-2011 Basho Technologies, Inc.  All Rights Reserved.
%%
%% -------------------------------------------------------------------

-module(riak_moss_wm_key_test).

-export([key_test_/0]).

-include("riak_moss.hrl").
-include_lib("webmachine/include/webmachine.hrl").
-include_lib("eunit/include/eunit.hrl").

key_test_() ->
    {setup,
     fun riak_moss_wm_test_utils:setup/0,
     fun riak_moss_wm_test_utils:teardown/1,
     [fun get_object/0]}.

create_object() ->
    ok.

get_object() ->
    %% We use this instead of setting
    %% path info the wm_reqdata because
    %% riak_moss_wm_utils:ensure_doc uses
    %% it.
    Ctx= #key_context{bucket="keytest", key="foo"},
    RD = #wm_reqdata{},

    {Object, _, _} = riak_moss_wm_key:produce_body(RD, Ctx),
    ?assertEqual(<<>>, Object).


Add check modules' version is lastest for node

% input: none
%
% op: check module is last
%
% e.g.: ./erl_expect -sname ejabberd@ebs-ali-beijing-5 common/check_module_version_last.erl
%       true | false

echo(off),

MLs = [MPath || {_Name, MPath} <- code:all_loaded(), is_list(MPath)],
MLMs =lists:filter(fun(Val) -> string:str(Val, "message_store") =/= 0 end, MLs),
Fun = fun(H) -> {ok, {_MName, Md5_beam}} = beam_lib:md5(H), BeamF = string:substr(H, string:rstr(H, "/") + 1), Mod = string:sub_string(BeamF, 1, string:rstr(BeamF, ".") -1), Md5_modu = (erlang:list_to_atom(Mod)):module_info(md5), Md5_beam /= Md5_modu end,
List = lists:filter(Fun, MLMs),
case List == [] of
    true ->
	io:format("true~n", []);
    _ ->
	io:format("false~n", [])
end,
ok.


Add phase_2_prep_migration that darklaunches orgs for containers / groups.

-module(mover_phase_2_prep_migration_callback).

-export([
	  migration_init/0,
         migration_type/0,
         supervisor/0,
         migration_start_worker_args/2,
         error_halts_migration/0,
         reconfigure_object/2,
	  migration_action/2,
	  next_object/0
         ]).

-include("mover.hrl").
-include_lib("moser/include/moser.hrl").

migration_init() ->
    % make sure we aren't in dry_run because otherwise
    % we can't set redis value
    false = envy:get(mover, dry_run, boolean),

    % initialize a transient queue with all orgs, we will fail in migration_action
    % if the org has already been phase_2 migrated as it has an entry in the state table
    AcctInfo = moser_acct_processor:open_account(),
    AllOrgs = moser_acct_processor:all_orgs(AcctInfo),
    OrgNames = [ OrgName || #org_info{org_name=OrgName} <- AllOrgs],
    mover_transient_migration_queue:initialize_queue(?MODULE, OrgNames).

migration_start_worker_args(Object, AcctInfo) ->
    [Object, AcctInfo].

migration_action(OrgName, AcctInfo) ->
    OrgInfo = moser_acct_processor:expand_org_info(#org_info{org_name = OrgName, account_info = AcctInfo}),
    OrgId = OrgInfo#org_info.org_id,

    case moser_state_tracker:insert_one_org(OrgInfo, mover_phase_2_migration_callback:migration_type()) of
	% org did not have phase_2_migration set in state table,
        % darklaunch it and set phase_2_migration to holding
	ok ->
	    mover_org_darklaunch:org_to_couch(OrgName, ?PHASE_2_MIGRATION_COMPONENTS),
	    moser_state_tracker:force_org_to_state(OrgName, mover_phase_2_migration_callback:migration_type(), <<"holding">>),
	    ok;
	% org already exited for phase_2_migration in state table, do nothing
	{error, {error, error, <<"23505">>, _Msg, _Detail}} ->
	    lager:warning([{org_name,OrgName}, {org_id, OrgId}], "org already exists, ignoring"),
	    ok;
	{error, Reason} ->
            lager:error([{org_name,OrgName}, {org_id, OrgId}],
                        "stopping - failed to capture state because: ~p", [Reason])
    end.

next_object() ->
    mover_transient_migration_queue:next(?MODULE).

migration_type() ->
    <<"phase_2_migration_prep">>.

supervisor() ->
    mover_transient_worker_sup.

error_halts_migration() ->
    true.

reconfigure_object(_ObjectId, _AcctInfo) ->
    no_op.


Test case for the native erlang call problem.

-module(transaction_SUITE).

-include_lib("common_test/include/ct.hrl").

-export([
  all/0,
  init_per_suite/1,
  end_per_suite/1
  ]).

-export([
  no_txn/1
  ]).

all() ->
  [no_txn].

init_per_suite(Config) ->
  erlang_v8:start(),
  Vm = ev8:new_vm(),
  C1 = ev8:new_context(Vm),
  C2 = ev8:new_context(Vm),
  [{vm, Vm}, {c1, C1}, {c2, C2} | Config].

end_per_suite(Config) ->
  erlang_v8:stop(),
  Config.

% Illustrates the issue with not running your code in a transaction
no_txn(Config) ->
  C1 = ?config(c1, Config),
  C2 = ?config(c2, Config),

  Obj = ev8:run_script(C1, <<"new Object">>),
  ev8:set(C1, Obj, <<"longFun">>, fun() ->
        timer:sleep(1000), <<"long">> end),
  ev8:set(C1, Obj, <<"shortFun">>, fun() ->
        timer:sleep(300), <<"short">> end),

  LongFun = ev8:get(C1, Obj, <<"longFun">>),
  ShortFun = ev8:get(C1, Obj, <<"shortFun">>),

  Self = self(),
  spawn(fun() ->
        Result = ev8:call(C1, ShortFun, []),
        Self ! {short, Result}
    end),
  spawn(fun() ->
        Result = ev8:call(C2, LongFun, []),
        Self ! {long, Result}
    end),

  ok = receive
    {long, <<"short">>} -> ok;
    {long, _} -> {error, wrong_return}
  end,

  ok = receive
    {short, <<"long">>} -> ok;
    {short, _} -> {error, wrong_return}
  end,

  ok.


Add a script which allows running of any example.

#!/usr/bin/env escript
%%! -noinput -pa ../cecho/_build/default/lib/cecho/ebin +A 50

%% Read the LICENSE file
-include_lib("cecho/include/cecho.hrl").
main(["countdown"]) ->
  cecho_example:countdown();
main(["simple"]) ->
  cecho_example:simple();
main(["colors"]) ->
  cecho_example:colors();
main(["input"]) ->
  cecho_example:input();
main(["cursmove"]) ->
  cecho_example:cursmove();
main(["helloworld"]) ->
  cecho_example:helloworld();
main(_) ->
  io:format("Usage: ./examples.escript <example>\n"),
  io:format("\n"),
  io:format("where <example> is one of\n"),
  io:format("\n"),
  io:format("    countdown - Simple countdown which shows\n"),
  io:format("                how to print, move and get\n"),
  io:format("                coordinates\n"),
  io:format("\n"),
  io:format("    simple - Simple example to show usage\n"),
  io:format("\n"),
  io:format("    colors - Fun with colors\n"),
  io:format("\n"),
  io:format("    input - Prints a number continuously as another\n"),
  io:format("            io thread is waiting for keyinput\n"),
  io:format("\n"),
  io:format("    cursmove - move the '@' around the screen with the\n"),
  io:format("               arrow keys. 'q' to quit.\n"),
  io:format("\n"),
  io:format("    helloworld - bounce 'Hello World!' around the screen\n").


Add a small library for a dmx() data type

%%% This file is part of the RayActor Lighting Software.
%%%
%%% RayActor is free software: you can redistribute it and/or modify it under
%%% the terms of the GNU Affero General Public License as published by the Free
%%% Software Foundation, either version 3 of the License, or (at your option)
%%% any later version.
%%%
%%% RayActor is distributed in the hope that it will be useful, but WITHOUT ANY
%%% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
%%% FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
%%% more details.
%%%
%%% You should have received a copy of the GNU Affero General Public License
%%% along with Rayactor. If not, see <http://www.gnu.org/licenses/>.
%%%
-module(rayactor_dmx).

-export([new/0, set/3]).
-export_type([dmx/0]).

-type dmx() :: binary().
-type channel() :: integer().

-spec new() -> dmx().

new() -> binary:copy(<<0>>, 512).

-spec set(integer(), channel(), dmx()) -> dmx().

set(Pos, Chan, Data) ->
    <<Left:Pos/binary, _:8, Right/binary>> = Data,
    <<Left:Pos/binary, Chan:8, Right/binary>>.


Add /api/base/media_upload API access point, for uploading files.

%% @author Arjan Scherpenisse <arjan@scherpenisse.net>
%% @copyright 2012 Arjan Scherpenisse <arjan@scherpenisse.net>
%% Date: 2012-02-12

%% @doc Upload media items. Pass in the "file" argument for the actual file.

%% Copyright 2012 Arjan Scherpenisse
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%     http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.

-module(service_base_media_upload).
-author("Arjan Scherpenisse <arjan@scherpenisse.net>").

-svc_title("Upload media items.").
-svc_needauth(true).

-export([process_post/2]).

-include_lib("zotonic.hrl").

process_post(_ReqData, Context) ->
    Upload = #upload{} = z_context:get_q("file", Context),

    Props
        = lists:flatten(
            lists:map(
              fun(Prop) ->
                      Value = z_context:get_q(atom_to_list(Prop), Context, <<>>),
                      case z_utils:is_empty(Value) of
                          false -> [{Prop, Value}];
                          true -> []
                      end
              end,
              [title, summary, body, chapeau, subtitle, website, page_path]
             )
           ),

    case m_media:insert_file(Upload, Props, Context) of
        {ok, Id} ->
            Id;
        {error, R} ->
            {error, R, <<>>}
    end.


Introduce a bare-bones Janitorial process.

-module(etorrent_fs_janitor).

-behaviour(gen_server).

-export([start_link/0, fs_collect/0]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
         terminate/2, code_change/3]).

-define(HIGH, 128).
-define(LOW, 100).
-define(SERVER, ?MODULE).

-record(state, { high, low }).

%% Start a new janitor.
start_link() ->
    gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).

fs_collect() ->
    gen_server:cast(?SERVER, fs_collect).

collect_filesystem_processes() ->
    todo.

create_tab() ->
    ets:new(?MODULE, [public, named_table]).

%% =======================================================================

init([]) ->
    create_tab(),
    process_flag(trap_exit, true),
    H = case application:get_env(etorrent, fs_watermark_high) of
                {ok, HVal} -> HVal;
                undefined -> ?HIGH
        end,
    L = case application:get_env(etorrent, fs_watermark_low) of
                {ok, LVal} -> LVal;
                undefined -> ?LOW
        end,
    {ok, #state { high = H, low = L}}.

handle_cast(fs_collect, S) ->
    collect_filesystem_processes(),
    {noreply, S};
handle_cast(Other, S) ->
    error_logger:error_report([unknown_msg, Other]),
    {noreply, S}.

handle_call(Other, _From, S) ->
    error_logger:error_report([unknown_msg, Other]),
    {noreply, S}.

handle_info(_Info, S) ->
    {noreply, S}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.


-module(pushysim_services).

-export([create_client/2]).

-include_lib("public_key/include/public_key.hrl").

%% Create a client in erchef and return {ok, PrivateKey} otherwise
%% an error tuple
-spec create_client(OrgName :: binary(),
                    NodeName :: binary()) -> {ok, rsa_private_key()} | {error, binary()}.
create_client(OrgName, NodeName) ->
    {ok, CreatorKey} = chef_keyring:get_key(creator),
    {ok, CreatorName} = application:get_env(pushysim, creator_name),
    Body = make_body(NodeName),
    Headers = chef_authn:sign_request(CreatorKey, Body,
                                      CreatorName, <<"POST">>,
                                      now, path(OrgName)),
    FullHeaders= [{"Accept", "application/json"} | Headers],
    Url = url(OrgName),
    case ibrowse:send_req(Url, FullHeaders, post, Body) of
        {ok, "404", _ResponseHeaders, _ResponseBody} ->
            not_found;
        {ok, Code, ResponseHeaders, ResponseBody} ->
            ok = check_http_response(Code, ResponseHeaders, ResponseBody),
            parse_json_response(ResponseBody);
        {error, Reason} ->
            throw({error, Reason})
    end.

url(OrgName) ->
    {ok, ErchefHost} = application:get_env(pushysim, erchef_root_url),
    ErchefHost ++ path(OrgName).

path(OrgName) ->
    "/organizations/" ++ binary_to_list(OrgName) ++ "/clients".

make_body(NodeName) ->
    Json = {[{<<"name">>,NodeName},
             {<<"client_name">>,NodeName},
             {<<"admin">>, false}
            ]},
    jiffy:encode(Json).

%% @doc extract the private_key from the json structure.
%%
parse_json_response(Body) ->
    try
        EJson = jiffy:decode(Body),
        lager:info(EJson),
        ej:get({<<"private_key">>}, EJson)
    catch
        throw:{error, _} ->
            throw({error, invalid_json})
    end.

%% @doc Check the code of the HTTP response and throw error if non-2XX
%%
check_http_response(Code, Headers, Body) ->
    case Code of
        "2" ++ _Digits ->
            ok;
        "3" ++ _Digits ->
            throw({error, {redirection, {Code, Headers, Body}}});
        "4" ++ _Digits ->
            throw({error, {client_error, {Code, Headers, Body}}});
        "5" ++ _Digits ->
            throw({error, {server_error, {Code, Headers, Body}}})
    end.


%% @copyright 2012 Opscode, Inc. All Rights Reserved
%% @author Tim Dysinger <timd@opscode.com>
%%
%% Licensed to the Apache Software Foundation (ASF) under one or more
%% contributor license agreements.  See the NOTICE file distributed
%% with this work for additional information regarding copyright
%% ownership.  The ASF licenses this file to you under the Apache
%% License, Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License.  You may obtain a copy of
%% the License at http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
%% implied.  See the License for the specific language governing
%% permissions and limitations under the License.

-module(bookshelf_fs_tests).
-include("bookshelf.hrl").

%% ===================================================================
%%                         Bucket functions
%% ===================================================================

bookshelf_fs_test_() ->
    [{"should be able to create, list & delete buckets",
      fun() ->
              {Ma, Se, Mi} = erlang:now(),
              Bucket = list_to_binary(io_lib:format("~p~p~p", [Ma,Se,Mi])),
              Dir = filename:join("/tmp", Bucket),
              file:make_dir(Dir),
              Buckets = ["lol", "cat", "walrus", "bukkit"],
              lists:foreach(
                fun(B) ->
                        ?assertEqual(ok, bookshelf_fs:bucket_create(Dir, B)),
                        ?assert(bookshelf_fs:bucket_exists(Dir, B))
                end,
                Buckets),
              ?assertEqual(ok, bookshelf_fs:bucket_delete(Dir, "cat")),
              Pass2 = bookshelf_fs:bucket_list(Dir),
              ?assertEqual(3, length(Pass2)),
              ?assertNot(bookshelf_fs:bucket_exists(Dir, "cat"))
      end
     }].


-module(create_tables).

-export([ init_tables/0,
          insert_user/3, insert_project/2 ]).

-record(user, { id, name }).
-record(project, { title, description }).
-record(contributor, { user_id, project_title }).

init_tables() ->
    mnesia:create_table(user, [{attributes, record_info(fields, user)}]),
    mnesia:create_table(project, [{attributes, record_info(fields, project)}]),
    mnesia:create_table(contributor, [{type, bag}, {attributes, record_info(fields, contributor)}]).

insert_user(Id, Name, ProjectTitles) when ProjectTitles =/= [] ->
    User = #user{id = Id, name = Name},
    Fun = fun() ->
        mnesia:write(User),
        lists:foreach(
            fun(Title) ->
                [ #project{title = Title} ] = mnesia:read(project, Title),
                mnesia:write(#contributor{user_id = Id, project_title = Title})
            end,
            ProjectTitles)
    end,
    mnesia:transaction(Fun).

insert_project(Title, Description) ->
    mnesia:dirty_write(#project{title = Title, description = Description}).


%% @author Northscale <info@northscale.com>
%% @copyright 2010 NorthScale, Inc.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%      http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% @doc Macros used all over the place.
%%

-define(LOG(Fun, Format, Args),
        error_logger:Fun("~p:~p:~p: " Format "~n",
                         [node(), ?MODULE, ?LINE] ++ Args)).

-define(log_info(Format, Args), ?LOG(info_msg, Format, Args)).
-define(log_warning(Format, Args), ?LOG(warning_msg, Format, Args)).
-define(log_error(Format, Args), ?LOG(error_msg, Format, Args)).


%% NOTE: Coordinate ?DTRACE_TAG_KEY with riak_core_dtrace.erl
-define(DTRACE_TAG_KEY, '**DTRACE*TAG*KEY**').

%% Erlang tracing-related funnel functions for DTrace/SystemTap.  When
%% using Redbug or other Erlang tracing framework, trace these
%% functions.  Include these here to avoid copy/pasting to every
%% module.

dtrace(_BKey, Category, Ints, Strings) ->
    riak_core_dtrace:dtrace(Category, Ints, Strings).

%% Internal functions, not so interesting for Erlang tracing.

dtrace_int(Category, Ints, Strings) ->
    dtrace(get(?DTRACE_TAG_KEY), Category, Ints, Strings).


-module(oauth1_storage_SUITE).

%% Callbacks
-export(
    [ all/0
    , groups/0
    ]).

%% Tests
-export(
    [ t_put_and_get/1
    , t_get_not_found_in_new_bucket/1
    , t_get_not_found_in_existing_bucket/1
    ]).

-define(GROUP, oauth1_storage).

%%=============================================================================
%% Callbacks
%%=============================================================================

all() ->
    [{group, ?GROUP}].

groups() ->
    Tests =
        [ t_put_and_get
        , t_get_not_found_in_new_bucket
        , t_get_not_found_in_existing_bucket
        ],
    Properties = [],
    [ {?GROUP, Properties, Tests}
    ].

%%=============================================================================
%% Tests
%%=============================================================================

t_put_and_get(_Cfg) ->
    Bucket = <<"foo">>,
    Key    = <<"bar">>,
    Value  = <<"baz">>,
    {ok, ok}    = oauth1_storage:put(Bucket, Key, Value),
    {ok, Value} = oauth1_storage:get(Bucket, Key).

t_get_not_found_in_new_bucket(_Cfg) ->
    Bucket = <<"foo">>,
    Key    = <<"bar">>,
    {error, not_found} = oauth1_storage:get(Bucket, Key).

t_get_not_found_in_existing_bucket(_Cfg) ->
    Bucket = <<"foo">>,
    Key1   = <<"bar">>,
    Key2   = <<"baz">>,
    % The first put to a bucket, is expected to create it if it does not exist.
    {ok, ok}           = oauth1_storage:put(Bucket, Key1, <<"qux">>),
    {error, not_found} = oauth1_storage:get(Bucket, Key2).


#!/usr/bin/env escript
-include("../deps/of_protocol/include/of_protocol.hrl").
-include("../deps/of_protocol/include/ofp_v4.hrl").

%% LINCX controller script for cc master.
main(_) ->
    %% get root lincx dir by removing last two entries of script path
    LincxDir = filename:join(lists:reverse(tl(tl(lists:reverse(
        filename:split(filename:absname(escript:script_name()))))))),
    code:add_path(filename:join(LincxDir,"deps/of_protocol/ebin")),

    {ok, Sock} = gen_tcp:connect("192.168.1.100",6653,[binary, {packet, raw},{reuseaddr, true}]),

    message(Sock, #ofp_hello{}),

    message(Sock, flow_mod(1,2)),
    message(Sock, flow_mod(2,1)),

    io:format("LINCX configured\n").

flow_mod(InPort, OutPort) ->
    Fields = [
        #ofp_field{name = in_port,value = <<InPort:32>>}
    ],

    Instruction = #ofp_instruction_apply_actions{
        actions = [#ofp_action_output{port = OutPort}]
    },

    #ofp_flow_mod{
        table_id = 0,
        command = add,
        match = #ofp_match{fields = Fields},
        instructions = [Instruction]
    }.

message(Sock, Body) ->
    {ok, Bin} =
        of_protocol:encode(#ofp_message{
            version = 4,
            xid = random:uniform(1 bsl 32 - 1),
            body = Body
        }),
    ok = gen_tcp:send(Sock, Bin).


Add non-ICE examples in a newly-created 'extra' folder

%% See LICENSE for licensing information.
%% -*- coding: utf-8 -*-
-module(thaw_examples_tests).

%% Examples written in Erlang rather than ICE.
%%
%% They are written as tests for convenience.

-include_lib("eunit/include/eunit.hrl").

%% API.

-export([fib_seq/1]).
-export([fib_par/1]).
-export([spawn_n/2, join/1]). %% Functions exported for internals of fib_par/1

fib_seq(0) ->
  0;
fib_seq(1) ->
  1;
fib_seq(N) ->
  fib_seq(N - 2) + fib_seq(N - 1).

fib_par(0) ->
  0;
fib_par(1) ->
  1;
fib_par(N) ->
  MFA2 = [?MODULE, fib_par, [N - 2]],
  MFA1 = [?MODULE, fib_par, [N - 1]],
  Pids = ?MODULE:spawn_n(self(), [MFA2, MFA1]),
  [N2, N1] = ?MODULE:join(Pids),
  N2 + N1.

%% API internals.

spawn_n(PPid, MFAs) ->
  lists:map(
    fun([M,F,A]) ->
        spawn(fun() -> PPid ! {self(), apply(M,F,A)} end)
    end,
    MFAs).

join(Pids) ->
  lists:map(fun(Pid) -> receive {Pid, RV} -> RV end end, Pids).

%% API tests.

fib_seq_test() ->
  ?assertEqual(
     [0,1,1,2,3,5,13,55],
     lists:map(fun ?MODULE:fib_seq/1, [0,1,2,3,4,5,7,10])).

fib_par_test() ->
  ?assertEqual(
     [0,1,1,2,3,5,13,55],
     lists:map(fun ?MODULE:fib_par/1, [0,1,2,3,4,5,7,10])).

%% Tests' internals.

%% End of Module.


-module('Tuple').
-export([call/4]).

call(Tuple, to_s, _Args, _Block) ->
  List = tuple_to_list(Tuple),
  lists:flatten(["(", string:join([convert(Elem) || Elem <- List], ","), ")"]).

convert(Value) -> reia_dispatch:call(Value, to_s, [], nil).

Support for retrieving members of tuples

-module('Tuple').
-export([call/4]).

call(Tuple, '[]', {Index}, _Block) ->
  element(Index + 1, Tuple);

call(Tuple, to_s, _Args, _Block) ->
  List = tuple_to_list(Tuple),
  lists:flatten(["(", string:join([convert(Elem) || Elem <- List], ","), ")"]).

convert(Value) -> reia_dispatch:call(Value, to_s, [], nil).


Define a generic k/v storage abstraction.

-module(oauth1_storage).

-export_type(
    [ error/0
    ]).

-export(
    [ put/3
    , get/2
    ]).

-type error() :: not_found
               | io_error
               .
-callback put(binary(), binary(), binary()) ->
    hope_result:t(ok, error()).

-callback get(binary(), binary()) ->
    hope_result:t(binary(), error()).

-define(not_implemented, error(not_implemented)).

-spec put(binary(), binary(), binary()) -> hope_result:t(ok, error()).
put(Bucket, Key, Value) ->
    StorageModule = lookup_storage_module(),
    StorageModule:put(Bucket, Key, Value).

-spec get(binary(), binary()) -> hope_result:t(binary(), error()).
get(Bucket, Key) ->
    StorageModule = lookup_storage_module(),
    StorageModule:put(Bucket, Key).

lookup_storage_module() ->
    {ok, StorageModule} = application:get_env(oauth1, storage_module),
    StorageModule.


-module('1498504778_gin_index').

-export([upgrade/1, downgrade/1]).
-behaviour(sql_migration).

upgrade(Pool) ->
    {ok, _, _} = pgapp:squery(Pool, "CREATE EXTENSION IF NOT EXISTS btree_gin"),
    {ok, _, _} =
        pgapp:squery(
          Pool,
          "DROP INDEX metrics_dimensions_idx"),
    {ok, _, _} =
        pgapp:squery(
          Pool,
          "CREATE INDEX ON metrics USING GIN (collection, dimensions)"),
    ok.

downgrade(Pool) ->
    {ok, _, _} =
        pgapp:squery(
          Pool,
          "CREATE INDEX ON metrics USING GIST (dimensions)"),
    ok.


Swap adjacents starting from the first index upto the end of the input string -- String O Permute

-module(string_o_permute).
-include_lib("eunit/include/eunit.hrl").
-export([main/0]).
-import(swap, [swap_adjacent/1]).

main() ->
    {ok, [T]} = io:fread("", "~d"),
    PL = run_test_cases_on(T, []),
    display(PL),
    true.

run_test_cases_on(0, PL) ->
    PL;
run_test_cases_on(Countdown, PL) ->
    {ok, [L]} = io:fread("", "~ts"),
    run_test_cases_on(Countdown-1, lists:append(PL, [swap:swap_adjacent(L)])).

display([]) ->
    ok;
display([H|T]) ->
    display(H, T).

display(X, []) ->
    io:fwrite("~s~n", [X]);
display(X, [H|T]) ->
    io:fwrite("~s~n", [X]),
    display(H, T).

string_o_premute_test_() ->
    {"swap adjacent for 'abcdpqrs' must yield in 'badcqpsr'", ?_assertEqual("badcqpsr", swap:swap_adjacent("abcdpqrs")) }.

string_o_premute_za_test_() ->
    {"swap adjacent for 'za' must yield in 'az'", ?_assertEqual("az", swap:swap_adjacent("za")) }.


-module(reia_annotator).
-export([annotate/1]).
-include("reia_nodes.hrl").

% Internal state of the annotator
-record(state, {scope=normal, bindings=dict:new()}).

annotate(Node) ->
  {Node2, _State} = reia_syntax:mapfold_subtrees(
    fun annotate/2,
    #state{},
    Node
  ),
  Node2.

% Match expressions mutate variables on the LHS
annotate(#match{} = Node, State) ->
  {Right, State2} = reia_syntax:mapfold_subtrees(
    fun annotate/2,
    State,
    Node#match.right
  ),

  {Left, State3} = reia_syntax:mapfold_subtrees(
    fun annotate/2,
    State2#state{scope=match},
    Node#match.left
  ),

  Node2  = Node#match{left=Left, right=Right},
  State4 = State3#state{scope=State#state.scope},
  {Node2, State4};

annotate(Node, State) ->
  io:format("annotating: ~p~n", [Node]),
  {Node, State}.

Update bindings dict when match expressions are encountered

-module(reia_annotator).
-export([annotate/1]).
-include("reia_nodes.hrl").

% Internal state of the annotator
-record(state, {scope=normal, bindings=dict:new()}).

annotate(Node) ->
  {Node2, _State} = reia_syntax:mapfold_subtrees(
    fun annotate/2,
    #state{},
    Node
  ),
  Node2.

% Walk the LHS of a match expression in match scope
annotate(#match{} = Node, State) ->
  {Right, State2} = reia_syntax:mapfold_subtrees(
    fun annotate/2,
    State,
    Node#match.right
  ),

  {Left, State3} = reia_syntax:mapfold_subtrees(
    fun annotate/2,
    State2#state{scope=match},
    Node#match.left
  ),

  Node2  = Node#match{left=Left, right=Right},
  State4 = State3#state{scope=State#state.scope},
  {Node2, State4};

% Variables are (re)bound while in match scope
annotate(#identifier{name=Name} = Node, #state{scope=match} = State) ->
  NewBindings = case dict:find(Name, State#state.bindings) of
    {ok, Version} -> dict:store(Name, Version + 1);
    error         -> dict:store(Name, 0)
  end,
  {Node, State#state{bindings=NewBindings}};

annotate(Node, State) ->
  io:format("annotating: ~p~n", [Node]),
  {Node, State}.


-module(robot_trigger).

-behavior(gen_event).

% API
-export([register/0]).

% Callbacks
-export([init/1]).
-export([handle_event/2]).
-export([handle_call/2]).
-export([handle_info/2]).
-export([code_change/3]).
-export([terminate/2]).

%--- API -----------------------------------------------------------------------

register() ->
    message("registering..."),
    gen_event:add_handler(grisp_gpio_events, ?MODULE, undefined).

%--- Callbacks -----------------------------------------------------------------

init(_Args) ->
    grisp_led:flash(2, blue, 100),
    message("registered"),
    {ok, undefined}.

handle_event({jumper_1, true}, State) ->
    message("jumper triggered"),
    spawn(fun() ->
        run_robot()
    end),
    {ok, State};
handle_event(Event, State) ->
    io:format("ROBOT: ignoring ~p~n", [Event]),
    {ok, State}.

handle_call(Request, _State) -> error({unknown_request, Request}).

handle_info(_Info, State) -> {ok, State}.

code_change(_OldVsn, State, _Extra) -> State.

terminate(_Arg, _State) ->
    message("terminated"),
    undefined.

%--- Internal ------------------------------------------------------------------

run_robot() ->
    message("starting..."),
    grisp_led:flash(2, green, 100),
    timer:sleep(2000),
    grisp_led:color(2, green),
    robot:start(),
    command(forward, 50),
    command(backward, 50),
    timer:sleep(2000),
    command(left, 50),
    command(right, 50),
    command(left, 50),
    timer:sleep(1000),
    command(forward, 200),
    command(right, 55),
    command(forward, 200),
    command(right, 55),
    command(forward, 200),
    command(right, 55),
    command(forward, 200),
    command(left, 200),
    message("done").

command(Command, Time) ->
    message(atom_to_list(Command)),
    robot:Command(Time),
    timer:sleep(100).

message(Message) -> io:format("ROBOT: ~s~n", [Message]).