-module(oauth1_storage).

-include_lib("oauth1_module_abbreviations.hrl").

-export_type(
    [ error/0
    ]).

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

-type error() ::
      not_found
    | {io_error, any()}
    .

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

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

-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).

-spec lookup_storage_module() ->
    atom().
lookup_storage_module() ->
    ?config:get(storage_module).

Fix incorrect function reference in the storage module.

-module(oauth1_storage).

-include_lib("oauth1_module_abbreviations.hrl").

-export_type(
    [ error/0
    ]).

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

-type error() ::
      not_found
    | {io_error, any()}
    .

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

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

-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:get(Bucket, Key).

-spec lookup_storage_module() ->
    atom().
lookup_storage_module() ->
    ?config:get(storage_module).


-module(doko_node_tbl_man).

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

-define(PAUSE, 10).

-record(state, {table}).

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

init() ->
    Table = ets:new(index_conf, [set,protected,{heir,self(),[]}]),
    reset(Table).

start_link() ->
    Pid = spawn(?MODULE, init, []),
    {ok,Pid}.

%%----------------------------------------------------------------------------
%% Internal functions
%%----------------------------------------------------------------------------

reset(Table) ->
    case whereis(doko_node) of
        undefined ->
            timer:sleep(?PAUSE),
            reset(Table);
        TableUser ->
            %% link to table user
            true = link(TableUser),
            %% trap exits
            process_flag(trap_exit, true),
            %% give table away
            ets:give_away(Table, TableUser, []),
            %% enter loop
            loop(#state{})
    end.

loop(State) ->
    receive
        {'ETS-TRANSFER',Table,_,_} ->
            loop(State#state{table = Table});
        {'EXIT',_,killed} ->
            reset(State#state.table);
        _Msg ->
            loop(State)
    end.

%% Local variables:
%% mode: erlang
%% fill-column: 78
%% coding: latin-1
%% End:

Make table manager shutdown cleanly

-module(doko_node_tbl_man).

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

-define(PAUSE, 10).
-define(USER, doko_node).

-record(state, {table}).

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

init() ->
    Table = ets:new(index_conf, [set,protected,{heir,self(),[]}]),
    reset(Table).

start_link() ->
    Pid = spawn(?MODULE, init, []),
    {ok,Pid}.

%%----------------------------------------------------------------------------
%% Internal functions
%%----------------------------------------------------------------------------

reset(Table) ->
    case whereis(?USER) of
        undefined ->
            timer:sleep(?PAUSE),
            reset(Table);
        TableUser ->
            %% link to table user
            true = link(TableUser),
            %% trap exits
            process_flag(trap_exit, true),
            %% give table away
            ets:give_away(Table, TableUser, []),
            %% enter loop
            loop(#state{})
    end.

loop(State) ->
    receive
        {'ETS-TRANSFER',Table,_,_} ->
            loop(State#state{table = Table});
        {'EXIT',_,killed} ->
            reset(State#state.table);
        {'EXIT',_,shutdown} ->
            unlink(whereis(?USER)),
            exit(shutdown);
        _ ->
            loop(State)
    end.

%% Local variables:
%% mode: erlang
%% fill-column: 78
%% coding: latin-1
%% 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.

-include("include/amazon_s3.hrl").
-include("include/shorthand.hrl").
-include("include/test.hrl").
-include("include/types.hrl").

Fix headers so they work with flymake also

%% @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.

-include("amazon_s3.hrl").
-include("shorthand.hrl").
-include("test.hrl").
-include("types.hrl").


%% Copyright (c) 2012-2013, Aetrion LLC
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

%% @doc Convenience API to start erl-dns directly.
-module(erldns).

-export([start/0]).

-spec start() -> any().
start() ->
  inets:start(),
  crypto:start(),
  ssl:start(),
  lager:start(),
  folsom:start(),
  application:start(ranch),
  application:start(cowboy),
  application:start(hottub),
  lager:debug("Starting erldns app"),
  application:start(erldns).

Switch how folsom is started.

%% Copyright (c) 2012-2013, Aetrion LLC
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

%% @doc Convenience API to start erl-dns directly.
-module(erldns).

-export([start/0]).

-spec start() -> any().
start() ->
  inets:start(),
  crypto:start(),
  ssl:start(),
  lager:start(),
  application:start(folsom),
  application:start(ranch),
  application:start(cowboy),
  application:start(hottub),
  application:start(erldns).


% 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.

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

-record(collector, {
    db_name=nil,
    query_args,
    callback,
    counters,
    buffer_size,
    blocked = [],
    total_rows = 0,
    offset = 0,
    rows = [],
    skip,
    limit,
    keys,
    os_proc,
    reducer,
    lang,
    sorted,
    user_acc
}).

-record(stream_acc, {
    workers,
    start_fun,
    replacements
}).

-record(view_row, {key, id, value, doc, worker}).
-record(change, {key, id, value, deleted=false, doc, worker}).

Add collation to view result collector record

% 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.

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

-record(collector, {
    db_name=nil,
    query_args,
    callback,
    counters,
    buffer_size,
    blocked = [],
    total_rows = 0,
    offset = 0,
    rows = [],
    skip,
    limit,
    keys,
    os_proc,
    reducer,
    collation,
    lang,
    sorted,
    user_acc
}).

-record(stream_acc, {
    workers,
    start_fun,
    replacements
}).

-record(view_row, {key, id, value, doc, worker}).
-record(change, {key, id, value, deleted=false, doc, worker}).


-type callback_mod() :: atom.
-type callback_args() :: any().
-type callback() :: {callback_mod(), callback_args()}.

-type path() :: binary().
-type args() :: binary().
-type version() :: {0,9} | {1,0} | {1,1}.
-type header() :: {Key::binary(), Value::binary() | string()}.
-type headers() :: [header()].
-type body() :: binary() | iolist().
-type response() :: iolist().

-type response_code() :: 200 | 404 | 500.
-type connection_token_atom() :: keep_alive | close.

-define(l2i(L), list_to_integer(L)).
-define(i2l(I), integer_to_list(I)).
-define(b2i(I), list_to_integer(binary_to_list(I))).

-type timestamp() :: {integer(), integer(), integer()}.

-record(state, {socket,
                acceptors = 0,
                open_reqs = 0,
                callback :: callback()
}).

-record(req, {
          method :: 'GET' | 'HEAD' | 'POST' | 'PUT',
          path :: [binary()],
          args,
          raw_path :: binary(),
          version,
          headers :: headers(),
          body :: body(),
          pid :: pid(),
          peer :: inet:ip_address()
}).

Use same http methods as erlang:decode_packet(http_bin, ..., ...).

-type callback_mod() :: atom.
-type callback_args() :: any().
-type callback() :: {callback_mod(), callback_args()}.

-type path() :: binary().
-type args() :: binary().
-type version() :: {0,9} | {1,0} | {1,1}.
-type header() :: {Key::binary(), Value::binary() | string()}.
-type headers() :: [header()].
-type body() :: binary() | iolist().
-type response() :: iolist().

-type response_code() :: 200 | 404 | 500.
-type connection_token_atom() :: keep_alive | close.

-define(l2i(L), list_to_integer(L)).
-define(i2l(I), integer_to_list(I)).
-define(b2i(I), list_to_integer(binary_to_list(I))).

-type timestamp() :: {integer(), integer(), integer()}.

-record(state, {socket,
                acceptors = 0,
                open_reqs = 0,
                callback :: callback()
}).

-record(req, {
          method :: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' |
                    'PUT' | 'DELETE' | 'TRACE',
          path :: [binary()],
          args,
          raw_path :: binary(),
          version,
          headers :: headers(),
          body :: body(),
          pid :: pid(),
          peer :: inet:ip_address()
}).


-define(PRINT(Var), io:format("DEBUG: ~p:~p - ~p~n~n ~p~n~n", [?MODULE, ?LINE, ??Var, Var])).

-define(BUCKET, <<"saturn_leaf">>).

-define(PROXY_MASTER, saturn_proxy_vnode_master).
-define(PROXY_SERVICE, saturn_proxy).
-define(SIMPLE_MASTER, saturn_simple_backend_vnode_master).
-define(SIMPLE_SERVICE, saturn_simple_backend).

-define(GROUPSFILE, "data/manager/groups_file_simple.saturn").
-define(TREEFILE, "data/manager/tree_file_simple.saturn").
-define(TREEFILE_TEST, "../include/tree_file_test.saturn").
-define(GROUPSFILE_TEST, "../include/groups_file_test.saturn").

-define(BACKEND, simple_backend).
-define(BACKEND_CONNECTOR, simple_backend_connector).

-define(MYIDPREFIX, {prefix, myid_prefix}).
-define(MYIDKEY, myid_key).

-define(HEARTBEAT_FREQ, 1000).

Add label record and payloads

-define(PRINT(Var), io:format("DEBUG: ~p:~p - ~p~n~n ~p~n~n", [?MODULE, ?LINE, ??Var, Var])).

-define(BUCKET, <<"saturn_leaf">>).

-define(PROXY_MASTER, saturn_proxy_vnode_master).
-define(PROXY_SERVICE, saturn_proxy).
-define(SIMPLE_MASTER, saturn_simple_backend_vnode_master).
-define(SIMPLE_SERVICE, saturn_simple_backend).

-define(GROUPSFILE, "data/manager/groups_file_simple.saturn").
-define(TREEFILE, "data/manager/tree_file_simple.saturn").
-define(TREEFILE_TEST, "../include/tree_file_test.saturn").
-define(GROUPSFILE_TEST, "../include/groups_file_test.saturn").

-define(BACKEND, simple_backend).
-define(BACKEND_CONNECTOR, simple_backend_connector).

-define(MYIDPREFIX, {prefix, myid_prefix}).
-define(MYIDKEY, myid_key).

-define(HEARTBEAT_FREQ, 1000).

-record(label, {operation :: remote_read | update | remote_reply,
                key,
                timestamp :: non_neg_integer(),
                node,
                sender :: non_neg_integer(),
                payload}).

-record(payload_reply, {to :: all | non_neg_integer(),
                        client,
                        value
                       }).

-record(payload_remote, {to :: all | non_neg_integer(),
                         key_source,
                         client
                        }).


-module(selection_mechanisms).
-export([roulette_wheel_fn/1]).

%% Assigns slots to the different phenotypes based on their fitness values
assign_slots(Plist) ->
    assign_slots(Plist, 0, []).

assign_slots([{indiv, I, fitness, F} | T], N, Acc) ->
    With_slots = {indiv, I, fitness, F, slots, [N, N+F]},
    assign_slots(T, N + F, [With_slots | Acc]);
assign_slots([], N, Acc) ->
    {plist, Acc, total, N - 1}.

in_interval_fn(V) ->
    fun ({indiv, _, fitness, _, slots, [Lower, Upper]}) ->
            (Lower =< V) and (V < Upper)
    end.

%% Returns a zero-arity function returning the individual who won the current
%% roulette. Multiple runs may return the same individual.
roulette_wheel_fn(Plist) ->
    {plist, Slotted, total, N} = assign_slots(Plist),
    fun () ->
            Val = random:uniform(N),
            {indiv, I,
             fitness, _,
             slots, _} = utils:ffilter(Slotted, in_interval_fn(Val)),
            I
    end.

Fix off-by-one error in roulette wheel.

-module(selection_mechanisms).
-export([roulette_wheel_fn/1]).

%% Assigns slots to the different phenotypes based on their fitness values
assign_slots(Plist) ->
    assign_slots(Plist, 0, []).

assign_slots([{indiv, I, fitness, F} | T], N, Acc) ->
    With_slots = {indiv, I, fitness, F, slots, [N, N+F]},
    assign_slots(T, N + F, [With_slots | Acc]);
assign_slots([], N, Acc) ->
    {plist, Acc, total, N}.

in_interval_fn(V) ->
    fun ({indiv, _, fitness, _, slots, [Lower, Upper]}) ->
            (Lower < V) and (V =< Upper)
    end.

%% Returns a zero-arity function returning the individual who won a single
%% roulette run. Multiple runs may return the same individual.
roulette_wheel_fn(Plist) ->
    {plist, Slotted, total, N} = assign_slots(Plist),
    fun () ->
            Val = random:uniform(N),
            {indiv, I,
             fitness, _,
             slots, _} = utils:ffilter(Slotted, in_interval_fn(Val)),
            I
    end.


-module(pre_client_hooks).

-include("log.hrl").
-include("pre_client.hrl").

-export([register_hooks/0, client_login_hook/2]).

%% ------------------------------------------------------------------
%% API Function Definitions
%% ------------------------------------------------------------------

register_hooks() ->
	?debug("Registering client hooks."),
	pre_hooks:add_hook(client_logged_in, ?MODULE, client_login_hook, undefined, [node()]).

%% ------------------------------------------------------------------

client_login_hook(undefined, ClientRecord) ->
	?debug("Client logged in: ~p", [ClientRecord]),
	#client_info{connection = Connection} = ClientRecord,
	LevelUrl = <<"scenes/cnk.json">>,
	LoadLevel = {struct, [
		{type, <<"setZone">>},
		{level, LevelUrl}
	]},
	pre_client_connection:send(Connection, ssl, event, level, LoadLevel),
	{ok, undefined}.

Send the setZone message over TCP instead of SSL.

-module(pre_client_hooks).

-include("log.hrl").
-include("pre_client.hrl").

-export([register_hooks/0, client_login_hook/2]).

%% ------------------------------------------------------------------
%% API Function Definitions
%% ------------------------------------------------------------------

register_hooks() ->
	?debug("Registering client hooks."),
	pre_hooks:add_hook(client_logged_in, ?MODULE, client_login_hook, undefined, [node()]).

%% ------------------------------------------------------------------

client_login_hook(undefined, ClientRecord) ->
	?debug("Client logged in: ~p", [ClientRecord]),
	#client_info{connection = Connection} = ClientRecord,
	LevelUrl = <<"scenes/cnk.json">>,
	LoadLevel = {struct, [
		{type, <<"setZone">>},
		{level, LevelUrl}
	]},
	pre_client_connection:send(Connection, tcp, event, level, LoadLevel),
	{ok, undefined}.


-record(zone, {
    name :: dns:dname(),
    version :: binary(),
    authority = [] :: [dns:rr()],
    record_count = 0 :: non_neg_integer(),
    records = [] :: [dns:rr()],
    records_by_name :: [dns:rr()],
    records_by_type :: [dns:rr()]
  }).

-record(authorities, {
    owner_name,
    ttl,
    class,
    name_server,
    email_addr,
    serial_num,
    refresh,
    retry,
    expiry,
    nxdomain
}).

Add slot for key signing key and zone signing key.

-record(zone, {
    name :: dns:dname(),
    version :: binary(),
    authority = [] :: [dns:rr()],
    record_count = 0 :: non_neg_integer(),
    records = [] :: [dns:rr()],
    records_by_name :: [dns:rr()],
    records_by_type :: [dns:rr()],
    key_signing_key :: crypto:rsa_private(),
    zone_signing_key :: crypto:rsa_private()
  }).

-record(authorities, {
    owner_name,
    ttl,
    class,
    name_server,
    email_addr,
    serial_num,
    refresh,
    retry,
    expiry,
    nxdomain
}).


%%%----------------------------------------------------------------------
%%% Copyright (c) 2012, Alkis Gotovos <el3ctrologos@hotmail.com>,
%%%                     Maria Christakis <mchrista@softlab.ntua.gr>
%%%                 and Kostis Sagonas <kostis@cs.ntua.gr>.
%%% All rights reserved.
%%%
%%% This file is distributed under the Simplified BSD License.
%%% Details can be found in the LICENSE file.
%%%----------------------------------------------------------------------
%%% Authors     : Tsitsimpis Ilias <iliastsi@hotmail.com>
%%% Description : Interface to extract scenarios from our tests
%%%----------------------------------------------------------------------

-module(scenarios).

-export([extract/1]).

extract(Files) ->
    S1 = lists:map(fun extractOne/1, Files),
    S2 = lists:flatten(S1),
    lists:foreach(fun(S) -> io:format("~p\n", [S]) end, S2).

extractOne(File) ->
    Module = list_to_atom(filename:basename(File, ".erl")),
    %% Get the scenarios for one module
    Scenarios = apply(Module, scenarios, []),
    %% Put module name to it
    FunMap =
        fun(Scenario) ->
                case Scenario of
                    {Fun, Preb} ->
                        {Module, Fun, Preb, full};
                    {Fun, Preb, Flag} when Flag=:=full; Flag=:=dpor ->
                        {Module, Fun, Preb, Flag}
                end
        end,
    lists:map(FunMap, Scenarios).

Fix a bug with extract_scenario output

%%%----------------------------------------------------------------------
%%% Copyright (c) 2012, Alkis Gotovos <el3ctrologos@hotmail.com>,
%%%                     Maria Christakis <mchrista@softlab.ntua.gr>
%%%                 and Kostis Sagonas <kostis@cs.ntua.gr>.
%%% All rights reserved.
%%%
%%% This file is distributed under the Simplified BSD License.
%%% Details can be found in the LICENSE file.
%%%----------------------------------------------------------------------
%%% Authors     : Tsitsimpis Ilias <iliastsi@hotmail.com>
%%% Description : Interface to extract scenarios from our tests
%%%----------------------------------------------------------------------

-module(scenarios).

-export([extract/1]).

extract(Files) ->
    S1 = lists:map(fun extractOne/1, Files),
    S2 = lists:flatten(S1),
    lists:foreach(fun(S) -> io:format("~w\n", [S]) end, S2).

extractOne(File) ->
    Module = list_to_atom(filename:basename(File, ".erl")),
    %% Get the scenarios for one module
    Scenarios = apply(Module, scenarios, []),
    %% Put module name to it
    FunMap =
        fun(Scenario) ->
                case Scenario of
                    {Fun, Preb} ->
                        {Module, Fun, Preb, full};
                    {Fun, Preb, Flag} when Flag=:=full; Flag=:=dpor ->
                        {Module, Fun, Preb, Flag}
                end
        end,
    lists:map(FunMap, Scenarios).


-module(boss_cache).
-export([start/0, start/1]).
-export([stop/0]).
-export([get/2, set/4, delete/2]).

-define(POOLNAME, boss_cache_pool).

start() ->
    Adapter = boss_cache_adapter_memcached_bin,
    start([{adapter, Adapter}, {cache_servers, [{"127.0.0.1", 11211, 1}]}]).

start(Options) ->
    Adapter = proplists:get_value(adapter, Options, boss_cache_adapter_memcached_bin),
    Adapter:start(Options),
    boss_cache_sup:start_link(Options).

stop() ->
    ok.

set(Prefix, Key, Val, TTL) ->
    boss_pool:call(?POOLNAME, {set, Prefix, Key, Val, TTL}).

get(Prefix, Key) ->
    boss_pool:call(?POOLNAME, {get, Prefix, Key}).

delete(Prefix, Key) ->
    boss_pool:call(?POOLNAME, {delete, Prefix, Key}).

Fix cache adapter name bug

-module(boss_cache).
-export([start/0, start/1]).
-export([stop/0]).
-export([get/2, set/4, delete/2]).

-define(POOLNAME, boss_cache_pool).

start() ->
    Adapter = boss_cache_adapter_memcached_bin,
    start([{adapter, Adapter}, {cache_servers, [{"127.0.0.1", 11211, 1}]}]).

start(Options) ->
    AdapterName = proplists:get_value(adapter, Options, memcached_bin),
    Adapter = list_to_atom(lists:concat(["boss_cache_adapter_", AdapterName])),
    Adapter:start(Options),
    boss_cache_sup:start_link(Options).

stop() ->
    ok.

set(Prefix, Key, Val, TTL) ->
    boss_pool:call(?POOLNAME, {set, Prefix, Key, Val, TTL}).

get(Prefix, Key) ->
    boss_pool:call(?POOLNAME, {get, Prefix, Key}).

delete(Prefix, Key) ->
    boss_pool:call(?POOLNAME, {delete, Prefix, Key}).


-module(eventsource_emitter).
-behaviour(cowboy_loop_handler).

-export([init/3]).
-export([info/3]).
-export([terminate/3]).

-record(state, {}).

init({_Any, http}, Req, _Opts) ->
    timer:send_after(0, {message, [":ok", "\n\n"]}),
    Headers = [
        {<<"content-type">>, <<"text/event-stream">>},
        {<<"cache-control">>, <<"no-cache">>},
        {<<"connection">>, <<"keep-alive">>}
    ],
    {ok, Req2} = cowboy_req:chunked_reply(200, Headers, Req),
    {loop, Req2, #state{}, hibernate}.

info(shutdown, Req, State) ->
    {ok, Req, State};

info({message, Msg}, Req, State) ->
    ok = cowboy_req:chunk(Msg, Req),
    timer:send_after(1000, {message, ["data: ", id(), "\n\n"]}),
    {loop, Req, State, hibernate}.

terminate(_Reason, _Req, _State) ->
    ok.

id() ->
    {Mega, Sec, _Micro} = os:timestamp(),
    Id = ((Mega * 1000000 + Sec) * 1000),
    integer_to_list(Id).

Create a non-rounded timestamp in microseconds.

-module(eventsource_emitter).
-behaviour(cowboy_loop_handler).

-export([init/3]).
-export([info/3]).
-export([terminate/3]).

-record(state, {}).

init({_Any, http}, Req, _Opts) ->
    timer:send_after(0, {message, [":ok", "\n\n"]}),
    Headers = [
        {<<"content-type">>, <<"text/event-stream">>},
        {<<"cache-control">>, <<"no-cache">>},
        {<<"connection">>, <<"keep-alive">>}
    ],
    {ok, Req2} = cowboy_req:chunked_reply(200, Headers, Req),
    {loop, Req2, #state{}, hibernate}.

info(shutdown, Req, State) ->
    {ok, Req, State};

info({message, Msg}, Req, State) ->
    ok = cowboy_req:chunk(Msg, Req),
    timer:send_after(1000, {message, ["data: ", id(), "\n\n"]}),
    {loop, Req, State, hibernate}.

terminate(_Reason, _Req, _State) ->
    ok.

id() ->
    {Mega, Sec, Micro} = os:timestamp(),
    Id = round((((Mega * 1000000) + Sec) * 1000) + (Micro / 1000)),
    integer_to_list(Id).


-define(DEPS_PATH, filename:join([mad_utils:home(), ".otp", "deps"])).
-define(COMPILE_OPTS(Inc, Ebin), [{i, Inc}, {outdir, Ebin}]).

Add 'report' option to compile options

-define(DEPS_PATH, filename:join([mad_utils:home(), ".otp", "deps"])).
-define(COMPILE_OPTS(Inc, Ebin), [report, {i, Inc}, {outdir, Ebin}]).


%%%'   HEADER
%%% @author {{author_name}} <{{author_email}}>
%%% @copyright {{copyright_year}} {{author_name}}
%%% @doc Nitrogen action: {{description}}
%%% @end
-module({{app_name}}_{{name}}_action).
-author('{{author_name}} <{{author_email}}>').

-include_lib("nitrogen_core/include/wf.hrl").
-export([render_action/1]).

%% TODO: Make sure to add record definition to your app's header file.

%%%.
%%%'   NITROGEN CALLBACKS

%% @hidden
render_action(Record) ->
  Target = Record#{{name}}_action.target,
  % TODO change script below to something you want JS to do.
  Script = "toString()",
  [wf:f("objs('~s').", [Target], Script)].

%%%.
%%%'   PRIVATE FUNCTIONS

%% TODO: Add private functions for element module here.

%%%.
%%% vim: set filetype=erlang tabstop=2 foldmarker=%%%',%%%. foldmethod=marker:

Fix typo in Nitrogen action template

%%%'   HEADER
%%% @author {{author_name}} <{{author_email}}>
%%% @copyright {{copyright_year}} {{author_name}}
%%% @doc Nitrogen action: {{description}}
%%% @end
-module({{app_name}}_{{name}}_action).
-author('{{author_name}} <{{author_email}}>').

-include_lib("nitrogen_core/include/wf.hrl").
-export([render_action/1]).

%% TODO: Make sure to add record definition to your app's header file.

%%%.
%%%'   NITROGEN CALLBACKS

%% @hidden
render_action(Record) ->
  Target = Record#{{name}}_action.target,
  % TODO change script below to something you want JS to do.
  Script = "toString()",
  [wf:f("objs('~s').", [Target]), Script].

%%%.
%%%'   PRIVATE FUNCTIONS

%% TODO: Add private functions for element module here.

%%%.
%%% vim: set filetype=erlang tabstop=2 foldmarker=%%%',%%%. foldmethod=marker:


-module(mtws_app).

-behaviour(application).

%% Application callbacks
-export([
  start/0,
  start/2,
  stop/1
]).

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, _StartArgs) ->
  nitrogen_sup:start_link(),
  mtws_sup:start_link().

%% TODO: remove this
start() ->
  [application:start(A) || A <- [gproc, riakc, metalkia_riak, metalkia_web_site, exmpp, metalkia_xmpp]].

stop(_State) ->
    ok.


-module(floppystore).

-export([confirm/0]).

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

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

confirm() ->
    Nodes = rt:build_clusters([3]),
    lager:info("Nodes: ~p", [Nodes]),
    ok.

Return pass from the test.

-module(floppystore).

-export([confirm/0]).

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

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

confirm() ->
    Nodes = rt:build_clusters([3]),
    lager:info("Nodes: ~p", [Nodes]),
    pass.


-module(exometer_function).

-behaviour(exometer_entry).

-export([new/3,
	 update/4,
	 reset/3,
	 setopts/4,
	 get_value/3,
	 sample/3,
	 delete/3,
	 reset/3,
	 setopts/4]).

-export([empty/0]).

new(_Name, function, Opts) ->
    case lists:keyfind(type_arg, 1, Opts) of
	{_, {function, M, F}} ->
	    {ok, {M, F}};
	false ->
	    {ok, {?MODULE, empty}}
    end.

get_value(_, function, {M, F}) ->
    M:F().

update(_, _, _, _) ->
    {error, unsupported}.

sample(_, _, _) ->
    {error, unsupported}.

reset(_, _, _) ->
    {error, unsupported}.

setopts(_,_, _, _) ->
    {error, unsupported}.

delete(_, _, _) ->
    ok.

reset(_, _, _) ->
    {error, unsupported}.

setopts(_, _, _, _) ->
    {error, unsupported}.

empty() ->
    [].

Duplicate code from merge fixed

-module(exometer_function).

-behaviour(exometer_entry).

-export([new/3,
	 update/4,
	 reset/3,
	 get_value/3,
	 sample/3,
	 delete/3,
	 setopts/4]).

-export([empty/0]).

new(_Name, function, Opts) ->
    case lists:keyfind(type_arg, 1, Opts) of
	{_, {function, M, F}} ->
	    {ok, {M, F}};
	false ->
	    {ok, {?MODULE, empty}}
    end.

get_value(_, function, {M, F}) ->
    M:F().

update(_, _, _, _) ->
    {error, unsupported}.

sample(_, _, _) ->
    {error, unsupported}.

reset(_, _, _) ->
    {error, unsupported}.

setopts(_,_, _, _) ->
    {error, unsupported}.

delete(_, _, _) ->
    ok.

empty() ->
    [].


-module (erlrc_boot_test).

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

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

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

notify (Item) ->
  gen_server:cast (?MODULE, { notify, erlang:now(), Item }).

%
% gen_server callbacks
%

dump () ->
  gen_server:call (?MODULE, dump).

init ([ ]) ->
  { ok, [ ] }.

handle_call (dump, _From, State) ->
  { reply, State, State };
handle_call (_Request, _From, State) ->
  { noreply, State }.

handle_cast ({ notify, Time, Item }, State) ->
  { noreply, [ { Time, Item } | State ] };
handle_cast (_Request, State) ->
  { noreply, State }.

handle_info (_Msg, State) ->
  { noreply, State }.

terminate (_Reason, _State) ->
  ok.

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

Replace now() with os:timestamp() to silence deprecation warning.

-module (erlrc_boot_test).

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

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

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

notify (Item) ->
  gen_server:cast (?MODULE, { notify, os:timestamp(), Item }).

%
% gen_server callbacks
%

dump () ->
  gen_server:call (?MODULE, dump).

init ([ ]) ->
  { ok, [ ] }.

handle_call (dump, _From, State) ->
  { reply, State, State };
handle_call (_Request, _From, State) ->
  { noreply, State }.

handle_cast ({ notify, Time, Item }, State) ->
  { noreply, [ { Time, Item } | State ] };
handle_cast (_Request, State) ->
  { noreply, State }.

handle_info (_Msg, State) ->
  { noreply, State }.

terminate (_Reason, _State) ->
  ok.

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


-module(http_simple_handler).

-include_lib("mixer/include/mixer.hrl").
-mixin([
        {http_base_handler,
         [
          init/2,
          content_types_accepted/2,
          content_types_provided/2,
          resource_exists/2
         ]}
       ]).

-export([ allowed_methods/2
        , handle_head/2
        , handle_get/2
        , handle_post/2
        , delete_resource/2
        ]).

%% cowboy
allowed_methods(Req, State) ->
  Methods =[ <<"GET">>
           , <<"POST">>
           , <<"HEAD">>
           , <<"OPTIONS">>
           , <<"DELETE">>
           , <<"PATCH">>
           , <<"PUT">>
           ],
  {Methods, Req, State}.

%% internal

handle_head(Req, State) ->
  {<<>>, Req, State}.

handle_get(Req, State) ->
  %% Force cowboy to send more than one TCP packet by making
  %% the body big enough
  Body = lists:duplicate(1000, <<"I'm simple!">>),
  {Body, Req, State}.

handle_post(Req, State) ->
  {ok, Data, Req1} = cowboy_req:body(Req),
  Method = cowboy_req:method(Req1),
  Body = [Method, <<": ">>, Data],
  Req2 = cowboy_req:set_resp_body(Body, Req1),
  {true, Req2, State}.

delete_resource(Req, State) ->
  {true, Req, State}.

Fix few more tests but correctly reading cowboy_req body

-module(http_simple_handler).

-include_lib("mixer/include/mixer.hrl").
-mixin([
        {http_base_handler,
         [
          init/2,
          content_types_accepted/2,
          content_types_provided/2,
          resource_exists/2
         ]}
       ]).

-export([ allowed_methods/2
        , handle_head/2
        , handle_get/2
        , handle_post/2
        , delete_resource/2
        ]).

%% cowboy
allowed_methods(Req, State) ->
  Methods =[ <<"GET">>
           , <<"POST">>
           , <<"HEAD">>
           , <<"OPTIONS">>
           , <<"DELETE">>
           , <<"PATCH">>
           , <<"PUT">>
           ],
  {Methods, Req, State}.

%% internal

handle_head(Req, State) ->
  {<<>>, Req, State}.

handle_get(Req, State) ->
  %% Force cowboy to send more than one TCP packet by making
  %% the body big enough
  Body = lists:duplicate(1000, <<"I'm simple!">>),
  {Body, Req, State}.

handle_post(Req, State) ->
  {ok, Data, Req1} = cowboy_req:read_body(Req),
  Method = cowboy_req:method(Req1),
  Body = [Method, <<": ">>, Data],
  Req2 = cowboy_req:set_resp_body(Body, Req1),
  {true, Req2, State}.

delete_resource(Req, State) ->
  {true, Req, State}.


-record(config, { dir,
                  opts }).

-record(global_state, { working_dir }).

-define(FAIL, throw({error, failed})).

-define(ABORT(Str, Args), ?ERROR(Str, Args), halt(1)).

-define(CONSOLE(Str, Args), io:format(Str, Args)).

-define(DEBUG(Str, Args), rebar_log:log(debug, Str, Args)).
-define(INFO(Str, Args), rebar_log:log(info, Str, Args)).
-define(WARN(Str, Args), rebar_log:log(warn, Str, Args)).
-define(ERROR(Str, Args), rebar_log:log(error, Str, Args)).

-define(FMT(Str, Args), lists:flatten(io_lib:format(Str, Args))).

Use init:stop/1 over halt/1 to ensure all I/O gets a chance to flush

-record(config, { dir,
                  opts }).

-record(global_state, { working_dir }).

-define(FAIL, throw({error, failed})).

-define(ABORT(Str, Args), ?ERROR(Str, Args), init:stop(1)).

-define(CONSOLE(Str, Args), io:format(Str, Args)).

-define(DEBUG(Str, Args), rebar_log:log(debug, Str, Args)).
-define(INFO(Str, Args), rebar_log:log(info, Str, Args)).
-define(WARN(Str, Args), rebar_log:log(warn, Str, Args)).
-define(ERROR(Str, Args), rebar_log:log(error, Str, Args)).

-define(FMT(Str, Args), lists:flatten(io_lib:format(Str, Args))).


-module(mumq_app).

-behaviour(application).

-export([start/2,
         stop/1]).

start(_StartType, _StartArgs) ->
    error_logger:info_report([{"muMQ", "application started"}]),
    mumq_subs:init(),
    mumq_sup:start_link().

stop(_State) ->
    mumq_subs:terminate(),
    error_logger:info_report([{"muMQ", "application stopped"}]).

Remove calls to the OTP logger

-module(mumq_app).

-behaviour(application).

-export([start/2,
         stop/1]).

start(_StartType, _StartArgs) ->
    mumq_subs:init(),
    mumq_sup:start_link().

stop(_State) ->
    mumq_subs:terminate().


%%  Top supervisor for etcdc
%%
%% ----------------------------------------------------------------------------

-module(etcdc_sup).

-copyright("Christoffer Vikström <chvi77@gmail.com>").

-export([start_link/0]).

-export([init/1]).

-behaviour(supervisor).

%% ----------------------------------------------------------------------------

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

%% ----------------------------------------------------------------------------

init(no_arg) ->
    WatchSup = child(etcdc_watch_sup, etcdc_watch_sup, supervisor, []),
    StreamSup = child(etcdc_stream_sup, etcdc_stream_sup, supervisor, []),
    TTLSup = child(etcdc_ttl_sup, etcdc_ttl_sup, supervisor, []),
    Strategy = {one_for_one, 1, 10},
    {ok, {Strategy, [WatchSup, StreamSup, TTLSup]}}.

%% ----------------------------------------------------------------------------

child(Name, Mod, Type, Args) ->
    {Name, {Mod, start_link, Args}, permanent, 3000, Type, [Mod]}.

Fix startup bug (trying to start etcdc_stream_sup)


-module(main).
-export([start/1]).
-import(conversions, [bitstr_to_list/1, list_to_bitstr/1]).

start([Name]) ->
    random:seed(now()),
    Geno = (one_max:random_genotype_fn([20]))(),
    io:format("~w~nHello ~s!~n", [Geno, Name]).

%% (1) choose a genetic representation
%% (2) build a population
%% (3) design a fitness function
%% (4) choose a selection operator
%% (5) choose a recombination operator
%% (6) choose a mutation operator
%% (7) devise a data analysis procedure.

Add function which fetches module fns.

-module(main).
-export([start/1]).
-import(conversions, [bitstr_to_list/1, list_to_bitstr/1]).

start([Name]) ->
    random:seed(now()),
    Geno = (one_max:random_genotype_fn([20]))(),
    io:format("~w~nHello ~s!~n", [Geno, Name]).

fetch_fns(Module, Opts) ->
    Rand_gtype = Module:random_genotype_fn(Opts),
    PtoG = Module:phenotype_to_genotype_fn(Opts),
    GtoP = Module:genotype_to_phenotype_fn(Opts),
    Fitness = Module:fitness_fn(Opts),
    Crossfn = Module:crossover_fn(Opts),
    Mutfn = Module:mutation_fn(Opts),
    {rand, Rand_gtype, p_to_g, PtoG, g_to_p, GtoP,
     fitness, Fitness, cross, Crossfn, mut, Mutfn}.

%% (1) choose a genetic representation
%% (2) build a population
%% (3) design a fitness function
%% (4) choose a selection operator
%% (5) choose a recombination operator
%% (6) choose a mutation operator
%% (7) devise a data analysis procedure.


%% -------------------------------------------------------------------
%%
%% Copyright (c) 2011 Basho Technologies, Inc.
%%
%% This file is provided 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(riak_control_app).

-behaviour(application).

%% Application callbacks
-export([start/2, stop/1]).

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, _StartArgs) ->
    case riak_control_sup:start_link() of
        {error, Reason} ->
            {error, Reason};
        {ok, Pid} ->
            riak_core_capability:register({riak_control, member_info_version},
                                          [v0, v1],
                                          v0),
            {ok, Pid}
    end.

stop(_State) ->
    ok.

Resolve incorrect capability negotation order.

%% -------------------------------------------------------------------
%%
%% Copyright (c) 2011 Basho Technologies, Inc.
%%
%% This file is provided 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(riak_control_app).

-behaviour(application).

%% Application callbacks
-export([start/2, stop/1]).

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, _StartArgs) ->
    case riak_control_sup:start_link() of
        {error, Reason} ->
            {error, Reason};
        {ok, Pid} ->
            riak_core_capability:register({riak_control, member_info_version},
                                          [v1, v0],
                                          v0),
            {ok, Pid}
    end.

stop(_State) ->
    ok.


-module(erl_reader).
-behaviour(gen_server).

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

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

-record(state, {feeds=[]}).

start() ->
    application:start(?MODULE).

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

init([]) ->
    process_flag(trap_exit, true),
    io:format("~p starting~n", [?MODULE]),
    {ok, #state{}}.

handle_call({add, Uri}, _From, #state{feeds=F}) ->
    {reply, ok, #state{feeds=[Uri|F]}};

handle_call(_, _From, State) ->
    {reply, ok, State}.

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Msg, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    io:format("~p stopping~n", [?MODULE]),
    ok.

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

add_feed(Uri) ->
    gen_server:call(?MODULE, {add, Uri}).

Handle errors when parsing feed

-module(erl_reader).
-behaviour(gen_server).

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

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

-record(state, {feeds=[]}).

start() ->
    application:start(?MODULE).

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

init([]) ->
    process_flag(trap_exit, true),
    io:format("~p starting~n", [?MODULE]),
    {ok, #state{}}.

handle_call({add, Uri}, _From, State = #state{feeds=F}) ->
    try atomizer:parse_url(Uri) of
        unknown ->
            {reply, bad_feed, State};
        _Feed ->
            {reply, ok, #state{feeds=[Uri|F]}}
    catch
        throw:Reason -> {reply, Reason, State}
    end;

handle_call(_, _From, State) ->
    {reply, ok, State}.

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Msg, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    io:format("~p stopping~n", [?MODULE]),
    ok.

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

add_feed(Uri) ->
    gen_server:call(?MODULE, {add, Uri}).


-module(print_num).
-export([print_all/1, print_odd/1]).

print_range(I, Bound) when I =< Bound ->
	io:format('~B~n', [I]),
	print_range(I + 1, Bound);
print_range(_, _) -> true.

print_all(N) ->
	print_range(1, N).

print_odd_range(I, Bound) when I =< Bound ->
	case (I rem 2) =/= 0 of
		true -> io:format('~B~n', [I]);
		_ -> true
	end,
	print_odd_range(I + 1, Bound);
print_odd_range(_, _) -> true.
print_odd(N) ->
	print_odd_range(1, N).

Print functions return ok instead true

-module(print_num).
-export([print_all/1, print_odd/1]).

print_range(I, Bound) when I =< Bound ->
	io:format('~B~n', [I]),
	print_range(I + 1, Bound);
print_range(_, _) -> ok.

print_all(N) ->
	print_range(1, N).

print_odd_range(I, Bound) when I =< Bound ->
	case (I rem 2) =/= 0 of
		true -> io:format('~B~n', [I]);
		_ -> true
	end,
	print_odd_range(I + 1, Bound);
print_odd_range(_, _) -> ok.
print_odd(N) ->
	print_odd_range(1, N).


-module(floppy).

-include("floppy.hrl").

-export([append/2, read/2]).

%% Public API

%% @doc The append/2 function adds an operation to the log of the CRDT
%%      object stored at some key.
append(Key, {OpParam, Actor}) ->
    Payload = #payload{key=Key, op_param=OpParam, actor=Actor},
    case floppy_rep_vnode:append(Key, Payload) of
        {ok, Result} ->
            {ok, Result};
        {error, Reason} ->
            {error, Reason}
    end.

%% @doc The read/2 function returns the current value for the CRDT
%%      object stored at some key.
read(Key, Type) ->
    case floppy_rep_vnode:read(Key) of
        {ok, Ops} ->
            Init = materializer:create_snapshot(Type),
            Snapshot = materializer:update_snapshot(Key, Type, Init, Ops),
            Type:value(Snapshot);
        {error, Reason} ->
            {error, Reason}
    end.

Update return value of read operation.

-module(floppy).

-include("floppy.hrl").

-export([append/2, read/2]).

%% Public API

%% @doc The append/2 function adds an operation to the log of the CRDT
%%      object stored at some key.
append(Key, {OpParam, Actor}) ->
    Payload = #payload{key=Key, op_param=OpParam, actor=Actor},
    case floppy_rep_vnode:append(Key, Payload) of
        {ok, Result} ->
            {ok, Result};
        {error, Reason} ->
            {error, Reason}
    end.

%% @doc The read/2 function returns the current value for the CRDT
%%      object stored at some key.
read(Key, Type) ->
    case floppy_rep_vnode:read(Key) of
        {ok, Ops} ->
            Init = materializer:create_snapshot(Type),
            Snapshot = materializer:update_snapshot(Key, Type, Init, Ops),
            {ok, Type:value(Snapshot)};
        {error, Reason} ->
            {error, Reason}
    end.


-module(dna).
-export([to_rna/1]).

to_rna(Strand) ->
  lists:map(fun transcribe_to_rna/1, Strand).

transcribe_to_rna($G) ->
     $C;
transcribe_to_rna($C) ->
     $G;
transcribe_to_rna($T) ->
     $A;
transcribe_to_rna($A) ->
     $U.

Use the same module name in sample and tests

-module(rna_transcription).
-export([to_rna/1]).

to_rna(Strand) ->
  lists:map(fun transcribe_to_rna/1, Strand).

transcribe_to_rna($G) ->
     $C;
transcribe_to_rna($C) ->
     $G;
transcribe_to_rna($T) ->
     $A;
transcribe_to_rna($A) ->
     $U.


-module(eep48_redundant).

-export_type([t_only_attr/0,
	      t_only_tag/0,
	      t_redundant/0]).

-type t_only_attr() :: any().
%% Type `t_only_attr' defined with an attribute.

%% @type t_only_tag() = any().
%% Type `t_only_tag' defined with a tag.

-type t_redundant() :: any().
%% Type `t_redundant' defined with an attribute, redundant with a tag.

%% @type t_redundant() = any().
%% Type `t_redundant' defined with a tag, redundant with an attribute.

-spec f_redundant_spec() -> atom().
%% @doc Function with a redundant spec.
%% @spec f_redundant_spec() -> tag()
f_redundant_spec() -> ok.

-spec f_only_attr() -> atom().
%% @doc Function with only a spec attribute.
f_only_attr() -> ok.

%% @spec f_only_tag() -> atom()
%% @doc Function with only a spec tag.
f_only_tag() -> ok.

Add a fixture of a spec prefix with a module name

-module(eep48_redundant).

-export_type([t_only_attr/0,
	      t_only_tag/0,
	      t_redundant/0]).

-type t_only_attr() :: any().
%% Type `t_only_attr' defined with an attribute.

%% @type t_only_tag() = any().
%% Type `t_only_tag' defined with a tag.

-type t_redundant() :: any().
%% Type `t_redundant' defined with an attribute, redundant with a tag.

%% @type t_redundant() = any().
%% Type `t_redundant' defined with a tag, redundant with an attribute.

-spec f_redundant_spec() -> atom().
%% @doc Function with a redundant spec.
%% @spec f_redundant_spec() -> tag()
f_redundant_spec() -> ok.

-spec f_only_attr() -> atom().
%% @doc Function with only a spec attribute.
f_only_attr() -> ok.

%% @spec f_only_tag() -> atom()
%% @doc Function with only a spec tag.
f_only_tag() -> ok.

-spec eep48_redundant:f_prefixed_spec() -> any().
f_prefixed_spec() -> ok.


-module(mzb_api_metrics).

-export([get_metrics/5,
         extract_metric_names/1]).

get_metrics(UserName, DirNode, Host, RemoteScriptPath, RemoteEnvPath) ->
    [Res] = mzb_subprocess:remote_cmd(
              UserName,
              [Host],
              io_lib:format("~s/mzbench/bin/metric_names.escript", [mzb_api_paths:node_deployment_path()]),
              [DirNode, RemoteScriptPath, RemoteEnvPath], mzb_api_app:default_logger(), []),
    try
        jiffy:decode(Res, [return_maps])
    catch
        C:E ->
            ST = erlang:get_stacktrace(),
            lager:error("Failed to parse metrics names cause of ~p~nOutput: ~p~nStacktrace: ~p", [E, Res, ST]),
            erlang:raise(C,E,ST)
    end.

extract_metric_names(#{<<"groups">>:= Groups} = _Metrics) ->
    [Name || #{<<"graphs">>:= Graphs} <- Groups, #{<<"metrics">>:= Metrics} <- Graphs, #{<<"name">>:= Name} <- Metrics].

Fix function_clause on handling of empty list of metrics

-module(mzb_api_metrics).

-export([get_metrics/5,
         extract_metric_names/1]).

get_metrics(UserName, DirNode, Host, RemoteScriptPath, RemoteEnvPath) ->
    [Res] = mzb_subprocess:remote_cmd(
              UserName,
              [Host],
              io_lib:format("~s/mzbench/bin/metric_names.escript", [mzb_api_paths:node_deployment_path()]),
              [DirNode, RemoteScriptPath, RemoteEnvPath], mzb_api_app:default_logger(), []),
    try
        jiffy:decode(Res, [return_maps])
    catch
        C:E ->
            ST = erlang:get_stacktrace(),
            lager:error("Failed to parse metrics names cause of ~p~nOutput: ~p~nStacktrace: ~p", [E, Res, ST]),
            erlang:raise(C,E,ST)
    end.

extract_metric_names(#{<<"groups">>:= Groups} = _Metrics) ->
    [Name || #{<<"graphs">>:= Graphs} <- Groups, #{<<"metrics">>:= Metrics} <- Graphs, #{<<"name">>:= Name} <- Metrics];
extract_metric_names(#{}) ->
    [].


%%% @author Andreas Pauley
%%% Created : 20 Sep 2013 by Andreas Pauley

-module(rsa_id_number_tests).

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

-export([test/0]).

all() ->
  [proper_spec_test].

-define(DEFAULT_OPTS, [{numtests,250},{to_file, user}]).

-spec test() -> ok.
test() ->
  Bools = [?MODULE:Test() || Test <- all()],
  true = lists:all(fun(Bool) -> Bool end, Bools).

-spec proper_spec_test() -> true.
proper_spec_test() ->
  _MFAs = [] = proper:check_specs(rsa_id_number, ?DEFAULT_OPTS),
  true.

Add failing test to see how travis picks it up

%%% @author Andreas Pauley
%%% Created : 20 Sep 2013 by Andreas Pauley

-module(rsa_id_number_tests).

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

-export([test/0]).

all() ->
  [proper_spec_test,
   id_length_test].

-define(DEFAULT_OPTS, [{numtests,250},{to_file, user}]).

-spec test() -> ok.
test() ->
  Bools = [?MODULE:Test() || Test <- all()],
  true = lists:all(fun(Bool) -> Bool end, Bools).

-spec proper_spec_test() -> true.
proper_spec_test() ->
  _MFAs = [] = proper:check_specs(rsa_id_number, ?DEFAULT_OPTS),
  true.

-spec id_length_test() -> true.
id_length_test() ->
  ok = print_env(),
  {error, invalid_length} = rsa_id_number:parse_str(""),
  true.

print_env() ->
  Envs = os:getenv(),
  [io:format("~p~n", [Env]) || Env <- Envs],
  Envs.


-module(bolingbroke_updates_handler).
-export([init/3, info/3, terminate/3]).

-define(DEFAULT_INTERVAL_MS, 10000).

init(_Type, Req, _Opts) ->
    Headers = [{<<"content-type">>, <<"text/event-stream">>}],
    {ok, Req2} = cowboy_req:chunked_reply(200, Headers, Req),

    self() ! update,

    State = undefined,
    {loop, Req2, State}.

info(update, Req, State) ->
    {Qs, Req2} = cowboy_req:qs(Req),
    Patterns = [binary_to_list(P) || P <- binary:split(Qs, <<"&">>, [global])],
    JSON = bolingbroke_query:create_json(Patterns),
    Chunk = ["data: ", JSON, "\r\n",
             "\r\n"],
    ok = cowboy_req:chunk(Chunk, Req),

    IntervalMs = application:get_env(bolingbroke, update_interval_ms, ?DEFAULT_INTERVAL_MS),
    erlang:send_after(IntervalMs, self(), update),

    {loop, Req2, State}.

terminate(_Reason, _Req, _State) ->
    ok.

Fix everything that broke with cowboy 2.x

-module(bolingbroke_updates_handler).
-export([init/2, info/3, terminate/3]).

-define(DEFAULT_INTERVAL_MS, 10000).

init(Req0, _Opts) ->
    Headers = #{<<"content-type">> => <<"text/event-stream">>},
    Req = cowboy_req:stream_reply(200, Headers, Req0),

    self() ! update,

    State = undefined,
    {cowboy_loop, Req, State}.

info(update, Req, State) ->
    Qs = cowboy_req:qs(Req),
    Patterns = [binary_to_list(P) || P <- binary:split(Qs, <<"&">>, [global])],
    JSON = bolingbroke_query:create_json(Patterns),
    ok = cowboy_req:stream_events(#{ id => next_id(), data => JSON }, nofin, Req),

    IntervalMs = application:get_env(bolingbroke, update_interval_ms, ?DEFAULT_INTERVAL_MS),
    erlang:send_after(IntervalMs, self(), update),
    {ok, Req, State}.

terminate(_Reason, _Req, _State) ->
    ok.

next_id() ->
    integer_to_list(erlang:unique_integer([positive, monotonic]), 16).


-module(action_api).
-author('Maxim Sokhatsky').
-include_lib("n2o/include/wf.hrl").
-compile(export_all).

render_action(Record) ->
    Name = Record#api.name,
    Data = "utf8_toByteArray(JSON.stringify(data))",
    PostbackScript = wf_event:new(Name, "document", Record#api.delegate, api_event, Data, []),
    wf:f("~s = function(data) {",  [Name]) ++ PostbackScript ++ "};".

Convert PostbackScript to list from binary before concatination.

-module(action_api).
-author('Maxim Sokhatsky').
-include_lib("n2o/include/wf.hrl").
-compile(export_all).

render_action(Record) ->
    Name = Record#api.name,
    Data = "utf8_toByteArray(JSON.stringify(data))",
    PostbackScript = wf_event:new(Name, "document", Record#api.delegate, api_event, Data, []),
    wf:f("~s = function(data) {",  [Name]) ++ binary_to_list(PostbackScript) ++ "};".


%% @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.
%%

-type histogram() :: [{atom(), non_neg_integer()}].
-type map() :: [[atom(), ...], ...].
-type moves() :: [{non_neg_integer(), atom(), atom()}].

-define(LOG(Fun, Format, Args),
        error_logger:Fun("~s:~s:~B: " 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)).

Make it so we can use non-literal strings for log macros

%% @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.
%%

-type histogram() :: [{atom(), non_neg_integer()}].
-type map() :: [[atom(), ...], ...].
-type moves() :: [{non_neg_integer(), atom(), atom()}].

-define(LOG(Fun, Format, Args),
        error_logger:Fun("~s:~s:~B: " ++ 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)).


% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2010 Rusty Klophaus
% See MIT-LICENSE for licensing information.

-module (element_table).
-include_lib ("wf.hrl").
-compile(export_all).

reflect() -> record_info(fields, table).

render_element(Record) ->

    Header = case Record#table.header of
      [] -> "";
      _ -> wf_tags:emit_tag(thead, Record#table.header, [])
    end,

    Footer = case Record#table.footer of
      [] -> "";
      _ -> wf_tags:emit_tag(tfoot, Record#table.footer, [])
    end,

    Body = wf_tags:emit_tag(tbody, Record#table.rows, []),
    Content = [Header, Footer, Body ],

    wf_tags:emit_tag( table, Content, [
        {id, Record#table.html_id},
        {border, 0},
        {cellpadding, 0},
        {cellspacing, 0},
        {class, [table, Record#table.class]},
        {style, Record#table.style}
    ]).

Remove cellspacing=0 and cellpadding=0 from table

% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2010 Rusty Klophaus
% See MIT-LICENSE for licensing information.

-module (element_table).
-include_lib ("wf.hrl").
-compile(export_all).

reflect() -> record_info(fields, table).

render_element(Record) ->

    Header = case Record#table.header of
      [] -> "";
      _ -> wf_tags:emit_tag(thead, Record#table.header, [])
    end,

    Footer = case Record#table.footer of
      [] -> "";
      _ -> wf_tags:emit_tag(tfoot, Record#table.footer, [])
    end,

    Body = wf_tags:emit_tag(tbody, Record#table.rows, []),
    Content = [Header, Footer, Body ],

    wf_tags:emit_tag( table, Content, [
        {id, Record#table.html_id},
        {border, 0},
        {class, [table, Record#table.class]},
        {style, Record#table.style}
    ]).


% 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(chttpd_test_util).

-export([start_couch/0, start_couch/1, stop_couch/0, stop_couch/1]).

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

start_couch() ->
    start_couch(?CONFIG_CHAIN).

start_couch(IniFiles) ->
    ok = application:set_env(config, ini_files, IniFiles),
    ok = lager:start(),
    ok = test_util:start_applications([inets, ibrowse, ssl, config, couch, chttpd]),
    ok.

stop_couch() ->
    ok = application:stop(couch),
    ok = application:stop(lager),
    ok = application:stop(goldrush),
    ok = application:stop(config),
    ok = application:stop(ssl),
    ok = application:stop(ibrowse),
    ok = application:stop(inets),
    ok = application:stop(chttpd),
    ok.

stop_couch(_) ->
    stop_couch().

Fix chttpd tests using new test_util:start_applications protocol

% 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(chttpd_test_util).

-export([start_couch/0, start_couch/1, stop_couch/1]).

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

start_couch() ->
    start_couch(?CONFIG_CHAIN).

start_couch(IniFiles) ->
    ok = application:set_env(config, ini_files, IniFiles),
    ok = lager:start(),
    test_util:start_applications([inets, ibrowse, ssl, config, couch, chttpd]).

stop_couch(Ctx) ->
    test_util:stop_couch(Ctx).


-module(docsh_SUITE).
-compile(export_all).

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

-define(TESTED, example).

-define(eq(Expected, Actual), ?assertEqual(Expected, Actual)).

all() ->
    [edoc_example_has_helpers,
     recon_has_helpers].

%%
%% Tests
%%

edoc_example_has_helpers(C) ->
    h0(C, edoc_example),
    h2(C, edoc_example).

recon_has_helpers(C) ->
    h0(C, recon),
    h2(C, recon).

%%
%% Helpers
%%

h0(_, Module) ->
    code:ensure_loaded(Module),
    ?eq(true, erlang:function_exported(Module, h, 0)),
    ?eq(ok, Module:h()).

h2(_, Module) ->
    code:ensure_loaded(Module),
    ?eq(true, erlang:function_exported(Module, h, 2)),
    {Fun, Arity} = hd(recon:module_info(exports) -- [{h,0}, {h,2}]),
    ?eq(ok, Module:h(Fun, Arity)).

Fix hardcoded module name in test

-module(docsh_SUITE).
-compile(export_all).

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

-define(TESTED, example).

-define(eq(Expected, Actual), ?assertEqual(Expected, Actual)).

all() ->
    [edoc_example_has_helpers,
     recon_has_helpers].

%%
%% Tests
%%

edoc_example_has_helpers(C) ->
    h0(C, edoc_example),
    h2(C, edoc_example).

recon_has_helpers(C) ->
    h0(C, recon),
    h2(C, recon).

%%
%% Helpers
%%

h0(_, Module) ->
    code:ensure_loaded(Module),
    ?eq(true, erlang:function_exported(Module, h, 0)),
    ?eq(ok, Module:h()).

h2(_, Module) ->
    code:ensure_loaded(Module),
    ?eq(true, erlang:function_exported(Module, h, 2)),
    {Fun, Arity} = hd(Module:module_info(exports) -- [{h,0}, {h,2}]),
    ?eq(ok, Module:h(Fun, Arity)).


-module(memebot_tests).

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

memebot_test_() ->
    {timeout, 60, ?_assert(run_props())}.

run_props() ->
    case proper:module(?MODULE, [long_result, {to_file, user}]) of
	[] ->
	    true;
	Result ->
	    ?debugFmt("~p~n", [Result]),
	    false
    end.

g_opts() ->
    ?LET({Top, Bottom}, {non_empty(binary()), non_empty(binary())},
	 [{top, Top}, {bottom, Bottom}]).

prop_generate() ->
    ?FORALL(Opts, g_opts(),
	    begin
		case memebot:generate(Opts) of
		    {ok, _Meme} ->
			true;
		    {error, _Error} ->
			false
		end
	    end).

Return error, rather than false

-module(memebot_tests).

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

memebot_test_() ->
    {timeout, 60, ?_assert(run_props())}.

run_props() ->
    case proper:module(?MODULE, [long_result, {to_file, user}]) of
	[] ->
	    true;
	Result ->
	    ?debugFmt("~p~n", [Result]),
	    false
    end.

g_opts() ->
    ?LET({Top, Bottom}, {non_empty(binary()), non_empty(binary())},
	 [{top, Top}, {bottom, Bottom}]).

prop_generate() ->
    ?FORALL(Opts, g_opts(),
	    begin
		case memebot:generate(Opts) of
		    {ok, _Meme} ->
			true;
		    {error, Error} ->
			{error, Error}
		end
	    end).


f(ChildPids).
ChildPids = fun (Sup) ->
              [ element(2, R) || R <- supervisor:which_children(Sup) ]
            end.

f(UpgradeNode).
UpgradeNode = fun () ->
  io:format(whereis(user), "at=upgrade_start~n", []),

  Proxies = ChildPids(tcp_proxy_sup),
  lists:map(fun sys:suspend/1, Proxies),
  l(tcp_proxy),
  [ sys:change_code(P, tcp_proxy, v33, undefined) || P <- Proxies ],
  lists:map(fun sys:resume/1, Proxies),

  Drains = [Pid ||
               {Pid, tcp_syslog} <- gproc:lookup_local_properties(drain_type)],
  lists:map(fun sys:suspend/1, Drains),
  l(logplex_tcpsyslog_drain),
  [ sys:change_code(P, logplex_tcpsyslog_drain,
                    v33, undefined) || P <- Drains ],
  lists:map(fun sys:resume/1, Drains),

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

Add version tags to upgrade messages.

f(ChildPids).
ChildPids = fun (Sup) ->
              [ element(2, R) || R <- supervisor:which_children(Sup) ]
            end.

f(UpgradeNode).
UpgradeNode = fun () ->
  io:format(whereis(user), "at=upgrade_start cur_vsn=33~n", []),

  Proxies = ChildPids(tcp_proxy_sup),
  lists:map(fun sys:suspend/1, Proxies),
  l(tcp_proxy),
  [ sys:change_code(P, tcp_proxy, v33, undefined) || P <- Proxies ],
  lists:map(fun sys:resume/1, Proxies),

  Drains = [Pid ||
               {Pid, tcp_syslog} <- gproc:lookup_local_properties(drain_type)],
  lists:map(fun sys:suspend/1, Drains),
  l(logplex_tcpsyslog_drain),
  [ sys:change_code(P, logplex_tcpsyslog_drain,
                    v33, undefined) || P <- Drains ],
  lists:map(fun sys:resume/1, Drains),

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


%%%-------------------------------------------------------------------
%%% @author Krzysztof Trzepla
%%% @copyright (C) 2014 ACK CYFRONET AGH
%%% This software is released under the MIT license
%%% cited in 'LICENSE.txt'.
%%% @end
%%%-------------------------------------------------------------------
%%% @doc OZ definition of user record.
%%% @end
%%%-------------------------------------------------------------------

-ifndef(OZ_USERS_HRL).
-define(OZ_USERS_HRL, 1).

%% user_details record contains following fields:
%% * id   - unique user ID assigned by OZ
%% * name - username
-record(user_details, {
    id :: binary(),
    name :: binary(),
    connected_accounts :: proplists:proplist(),
    alias :: string() | integer() | binary(),
    email_list :: [binary()]
}).

%% user_spaces record contains following fields:
%% * ids     - list of IDs of user's Spaces
%% * default - id of default user's Space
-record(user_spaces, {
    ids :: [binary()],
    default :: binary()
}).

-endif.

Update type of connected_accounts info

%%%-------------------------------------------------------------------
%%% @author Krzysztof Trzepla
%%% @copyright (C) 2014 ACK CYFRONET AGH
%%% This software is released under the MIT license
%%% cited in 'LICENSE.txt'.
%%% @end
%%%-------------------------------------------------------------------
%%% @doc OZ definition of user record.
%%% @end
%%%-------------------------------------------------------------------

-ifndef(OZ_USERS_HRL).
-define(OZ_USERS_HRL, 1).

%% user_details record contains following fields:
%% * id   - unique user ID assigned by OZ
%% * name - username
%% * connected_accounts - list of proplists with info about connected oauth accounts,
%% contains data provided by oauth: provider_id, user_id, login, name, email_list
%% * alias - onedata user alias
%% * email_list - list of connected emails
-record(user_details, {
    id :: binary(),
    name :: binary(),
    connected_accounts :: [proplists:proplist()],
    alias :: string() | integer() | binary(),
    email_list :: [binary()]
}).

%% user_spaces record contains following fields:
%% * ids     - list of IDs of user's Spaces
%% * default - id of default user's Space
-record(user_spaces, {
    ids :: [binary()],
    default :: binary()
}).

-endif.


%% -*- erlang-indent-level: 4;indent-tabs-mode: nil; fill-column: 92 -*-
%% ex: ts=4 sw=4 et
%%% @author Mark Anderson <mark@opscode.com>
%%% @copyright Copyright 2012-2012 Opscode Inc.
%%% @doc
%%% Mux-demux for commands to clients and responses from clients
%%% @end

Add basic structure of command switch code

%% -*- erlang-indent-level: 4;indent-tabs-mode: nil; fill-column: 92 -*-
%% ex: ts=4 sw=4 et
%%% @author Mark Anderson <mark@opscode.com>
%%% @copyright Copyright 2012-2012 Opscode Inc.
%%% @doc
%%% Mux-demux for commands to clients and responses from clients
%%% @end

-module(pushy_command_switch).
-behaviour(gen_server).
-define(SERVER, ?MODULE).

%% ------------------------------------------------------------------
%% API Function Exports
%% ------------------------------------------------------------------

-export([start_link/1]).

%% ------------------------------------------------------------------
%% gen_server Function Exports
%% ------------------------------------------------------------------

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

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

-record(state,
        {command_sock}).

%% ------------------------------------------------------------------
%% API Function Definitions
%% ------------------------------------------------------------------

start_link(Ctx) ->
    gen_server:start_link({local, ?SERVER}, ?MODULE, [Ctx], []).

%% ------------------------------------------------------------------
%% gen_server Function Definitions
%% ------------------------------------------------------------------

init([Ctx]) ->
    CommandAddress = pushy_util:make_zmq_socket_addr(command_port),

    error_logger:info_msg("Starting command mux listening on ~s~n.", [CommandAddress]),

    {ok, CommandSock} = erlzmq:socket(Ctx, [pull, {active, true}]),
    ok = erlzmq:bind(CommandSock, CommandAddress),
    State = #state{command_sock = CommandSock},
    {ok, State}.

handle_call(_Request, _From, State) ->
    {reply, ok, State}.

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info({zmq, _CommandSock, Header, [rcvmore]},
    #state{command_sock=_CommandSocket}=State) ->

    Body = pushy_util:read_body(),
    case catch pushy_util:do_authenticate_message(Header, Body) of
        ok ->

        {no_authn, bad_sig} ->
            error_logger:error_msg("Command message failed verification: header=~s~n", [Header])
    end,

    {noreply, State};
handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

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

%% ------------------------------------------------------------------
%% Internal Function Definitions
%% ------------------------------------------------------------------


%% @license The FreeBSD License
%% @copyright 2012 Wooga GmbH

-module (ebloomd_app).
-compile ([export_all]).

-behaviour (application).
-export ([start/2, stop/1]).

% Callback starting the backend.
start(_StartType, _StartArgs) ->
    % Start ranch as well.
    application:start(ranch),
    ebloomd_sup:start_link().

% Just `ok`.
stop(_State) -> ok.

Stop ranch when stopping ebloomd

%% @license The FreeBSD License
%% @copyright 2012 Wooga GmbH

-module (ebloomd_app).
-compile ([export_all]).

-behaviour (application).
-export ([start/2, stop/1]).

% Callback starting the backend.
start(_StartType, _StartArgs) ->
    % Start ranch as well.
    application:start(ranch),
    ebloomd_sup:start_link().

% Just `ok`.
stop(_State) ->
    application:stop(ranch),
    ok.


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

new_test() ->
    ?assertEqual([], erlcfg_interp:new()).

eval_val_with_empty_interp_test() ->
    Interp = erlcfg_interp:new(),
    Expected = {Interp, foo},
    ?assertEqual(Expected, erlcfg_interp:eval(Interp, {val, foo, nil})).

eval_val_with_nonempty_interp_test() ->
    Interp = [{foo, bar}, {bar, baz}],
    Expected = {Interp, 5},
    ?assertEqual(Expected, erlcfg_interp:eval(Interp, {val, 5, nil})).

eval_set_test()  ->
    Interp = erlcfg_interp:new(),
    Expected = {[{foo, bar}], bar},
    ?assertEqual(Expected, erlcfg_interp:eval(Interp, {set, foo, bar})).

eval_set_no_parent_test()  ->
    Interp = erlcfg_interp:new(),
    {Interp1, bar} = erlcfg_interp:eval(Interp, {set, foo, bar}),
    Expected = {not_found, foo.foo},
    ?assertThrow(Expected, erlcfg_interp:eval(Interp1, {set, foo.foo.bar, bar})).

Update erlcfg_interp unittests, to work properly again

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

new_test() ->
    ?assertEqual({c, '', []}, erlcfg_interp:new()).

eval_val_with_empty_interp_test() ->
    Interp = erlcfg_interp:new(),
    Expected = {Interp, foo},
    ?assertEqual(Expected, erlcfg_interp:eval(Interp, {val, foo, nil})).

eval_val_with_nonempty_interp_test() ->
    Interp = {c, '', [{d, foo, bar}, {d, bar, baz}]},
    Expected = {Interp, 5},
    ?assertEqual(Expected, erlcfg_interp:eval(Interp, {val, 5, nil})).

eval_set_test()  ->
    Interp = erlcfg_interp:new(),
    Expected = {{c, '', [{d, foo, bar}]}, bar},
    ?assertEqual(Expected, erlcfg_interp:eval(Interp, {set, foo, bar})).

eval_set_no_parent_test()  ->
    Interp = erlcfg_interp:new(),
    {Interp1, bar} = erlcfg_interp:eval(Interp, {set, foo, bar}),
    Expected = {not_found, foo.foo},
    ?assertThrow(Expected, erlcfg_interp:eval(Interp1, {set, foo.foo.bar, bar})).


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

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

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).

init(_Transport, Req, []) ->
	{ok, Req, undefined}.

handle(Req, State) ->
	{Method, Req2} = cowboy_req:method(Req),
	HasBody = cowboy_req:has_body(Req2),
	{ok, Req3} = maybe_echo(Method, HasBody, Req2),
	{ok, Req3, State}.

maybe_echo(<<"POST">>, true, Req) ->
	{ok, PostVals, Req2} = cowboy_req:body_qs(Req),
	Echo = proplists:get_value(<<"echo">>, PostVals),
	echo(Echo, Req2);
maybe_echo(<<"POST">>, false, Req) ->
	cowboy_req:reply(400, [], <<"Missing body.">>, Req);
maybe_echo(_, _, Req) ->
	%% Method not allowed.
	cowboy_req:reply(405, Req).

echo(undefined, Req) ->
	cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);
echo(Echo, Req) ->
	cowboy_req:reply(200,
		[{<<"content-encoding">>, <<"utf-8">>}], Echo, Req).

terminate(_Reason, _Req, _State) ->
	ok.

Fix wrong header sent in echo_post example

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

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

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).

init(_Transport, Req, []) ->
	{ok, Req, undefined}.

handle(Req, State) ->
	{Method, Req2} = cowboy_req:method(Req),
	HasBody = cowboy_req:has_body(Req2),
	{ok, Req3} = maybe_echo(Method, HasBody, Req2),
	{ok, Req3, State}.

maybe_echo(<<"POST">>, true, Req) ->
	{ok, PostVals, Req2} = cowboy_req:body_qs(Req),
	Echo = proplists:get_value(<<"echo">>, PostVals),
	echo(Echo, Req2);
maybe_echo(<<"POST">>, false, Req) ->
	cowboy_req:reply(400, [], <<"Missing body.">>, Req);
maybe_echo(_, _, Req) ->
	%% Method not allowed.
	cowboy_req:reply(405, Req).

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

terminate(_Reason, _Req, _State) ->
	ok.


%% @author Driebit <info@driebit.nl>
%% @copyright 2015

-module(mod_ginger_base).
-author("Driebit <info@driebit.nl>").

-mod_title("Ginger Base").
-mod_description("Ginger Base").
-mod_prio(250).

Add custom actions to newcomment postback

%% @author Driebit <info@driebit.nl>
%% @copyright 2015

-module(mod_ginger_base).
-author("Driebit <info@driebit.nl>").

-mod_title("Ginger Base").
-mod_description("Ginger Base").
-mod_prio(250).

-export([event/2]).

-include("zotonic.hrl").

%% @doc Handle the submit event of a new comment
event(#submit{message={newcomment, Args}, form=FormId}, Context) ->
    ExtraActions = proplists:get_all_values(action, Args),
    {id, Id} = proplists:lookup(id, Args),
    case z_auth:is_auth(Context) of
        false ->
            Name = z_context:get_q_validated("name", Context),
            Email = z_context:get_q_validated("mail", Context);
        true ->
            Name = "",
            Email = ""
    end,
    Message = z_context:get_q_validated("message", Context),
    Is_visible = case m_config:get_value(comments, moderate, Context) of <<"1">> -> false; _Else -> true end,
    case m_comment:insert(Id, Name, Email, Message, Is_visible, Context) of
        {ok, CommentId} ->
            CommentsListElt = proplists:get_value(comments_list, Args, "comments-list"),
            CommentTemplate = proplists:get_value(comment_template, Args, "_comments_comment.tpl"),
            Comment = m_comment:get(CommentId, Context),
            Props = [
                {id, Id},
                {comment, Comment},
                {creator, m_rsc:p(Id, creator_id, Context)},
                {hidden, true}
            ],
            Html = z_template:render(CommentTemplate, Props, Context),
            Context1 = z_render:insert_bottom(CommentsListElt, Html, Context),
            Context2 = case Is_visible of
			   true ->
             AllActions = lists:merge([
					      {set_value, [{selector, "#"++FormId++" textarea[name=\"message\"]"}, {value, ""}]},
					      {set_value, [{selector, "#"++FormId++" input[name=\"message\"]"}, {value, ""}]},
					      {fade_in, [{target, "comment-"++integer_to_list(CommentId)}]}
					     ], ExtraActions),
			       z_render:wire(AllActions, Context1);
			   false ->
			       Context1
		       end,
            case z_convert:to_bool(proplists:get_value(do_redirect, Args, true)) of
                true -> z_render:wire({redirect, [{location, "#comment-"++integer_to_list(CommentId)}]}, Context2);
                false -> Context2
            end;
        {error, _} ->
            Context
    end.


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

-module (mas).
-export ([start/3]).
-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(pos_integer(), sim_params(), [tuple()]) -> [agent()].
start(Time, SP, Options) ->
    ConfigRecord = mas_config:proplist_to_record(Options),
    io:format("### ConfigRecord: ~p~n", [ConfigRecord]),
    Model = ConfigRecord#config.model,
    Model:start(Time, SP, ConfigRecord).

Print config in one line.

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

-module (mas).
-export ([start/3]).
-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(pos_integer(), sim_params(), [tuple()]) -> [agent()].
start(Time, SP, Options) ->
    ConfigRecord = mas_config:proplist_to_record(Options),
    io:format("### ConfigRecord: ~w~n", [ConfigRecord]),
    Model = ConfigRecord#config.model,
    Model:start(Time, SP, ConfigRecord).


%%%-------------------------------------------------------------------
%%% @author Kalin
%%% @copyright (C) 2017, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 01. Apr 2017 8:13 PM
%%%-------------------------------------------------------------------
-module(iotlb_stats_json).
-author("Kalin").

%% API
-export([encode_stats/1, stats/1]).

encode_stats(LBStats) ->
  Map = stats(LBStats),
  jsone:encode(Map).

stats(LBStats) ->
  lists:map(fun node_stats/1,LBStats).

node_stats({Node,Brokers}) ->
  #{node => Node, brokers => lists:map(fun broker_stats/1, Brokers)}.

broker_stats({Broker,BStats}) ->
  #{broker => broker(Broker), stats => BStats}.

broker({Host,Port}) ->
  #{host => host(Host), port => Port}.

host(Name) when is_atom(Name); is_binary(Name); is_list(Name) -> Name;
host(IP = {_B1,_B2,_B3,_B4}) -> inet:ntoa(IP);
host(IP = {_B1,_B2,_B3,_B4,_B5,_B6,_B7,_B8}) -> inet:ntoa(IP).

Fix for String (non-binary) host names

%%%-------------------------------------------------------------------
%%% @author Kalin
%%% @copyright (C) 2017, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 01. Apr 2017 8:13 PM
%%%-------------------------------------------------------------------
-module(iotlb_stats_json).
-author("Kalin").

%% API
-export([encode_stats/1, stats/1]).

encode_stats(LBStats) ->
  Map = stats(LBStats),
  jsone:encode(Map).

stats(LBStats) ->
  lists:map(fun node_stats/1,LBStats).

node_stats({Node,Brokers}) ->
  #{node => Node, brokers => lists:map(fun broker_stats/1, Brokers)}.

broker_stats({Broker,BStats}) ->
  #{broker => broker(Broker), stats => BStats}.

broker({Host,Port}) ->
  #{host => host(Host), port => Port}.

host(Name) when is_atom(Name); is_binary(Name) -> Name;
host(Name) when is_list(Name) -> list_to_binary(Name);
host(IP = {_B1,_B2,_B3,_B4}) -> list_to_binary(inet:ntoa(IP));
host(IP = {_B1,_B2,_B3,_B4,_B5,_B6,_B7,_B8}) -> inet:ntoa(IP).


%% vim: ts=4 sw=4 et
-module(nitrogen_main_handler).
-export([
    run/0,
    ws_init/0
]).

handlers() ->
    %% Put any custom handlers here
    %% See http://nitrogenproject.com/doc/handlers.html
    %% Example:
    %%
    %%   wf_handler:set_handler(MySecurityHandler, HandlerConfig),
    %%
    ok.

ws_init() ->
    handlers().

run() ->
    handlers(),
    wf_core:run().

Use debug crash handler by default

%% vim: ts=4 sw=4 et
-module(nitrogen_main_handler).
-export([
    run/0,
    ws_init/0
]).

handlers() ->
    %% Put any custom handlers here
    %% See http://nitrogenproject.com/doc/handlers.html
    %% Example:
    %%
    %%   nitrogen:handler(MySecurityHandler, HandlerConfig),
    %%
    %%
    %% The following enables the debug_crash_handler for development. If you
    %% wish to use the default_crash_handler, which just spits out "Internal
    %% Server Error", comment or delete this next line.
    nitrogen:handler(debug_crash_handler, []),
    ok.

ws_init() ->
    handlers().

run() ->
    handlers(),
    wf_core:run().


%% -*- erlang-indent-level: 4;indent-tabs-mode: nil; fill-column: 92 -*-
%% ex: ts=4 sw=4 et
%% @copyright 2011-2012 Opscode Inc.

-module(pushysim_app).

-behaviour(application).

%% Application callbacks
-export([start/2, stop/1]).

%-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
%-endif.

-include("pushysim.hrl").

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, _StartArgs) ->
    error_logger:info_msg("Pushy Client Simulator starting.~n"),
    IoProcesses = pushy_util:get_env(pushysim, zmq_io_processes, fun is_integer/1),
    case erlzmq:context(IoProcesses) of
        {ok, Ctx} ->
            case pushysim_sup:start_link(#client_state{ctx=Ctx}) of
                {ok, Pid} -> {ok, Pid, Ctx};
                Error -> Error
            end;
        Error ->
            Error
    end.

stop(Ctx) ->
    erlzmq:term(Ctx, 5000).

Add default for zmq_io_processes env

%% -*- erlang-indent-level: 4;indent-tabs-mode: nil; fill-column: 92 -*-
%% ex: ts=4 sw=4 et
%% @copyright 2011-2012 Opscode Inc.

-module(pushysim_app).

-behaviour(application).

%% Application callbacks
-export([start/2, stop/1]).

%-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
%-endif.

-include("pushysim.hrl").

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, _StartArgs) ->
    error_logger:info_msg("Pushy Client Simulator starting.~n"),
    IoProcesses = pushy_util:get_env(pushysim, zmq_io_processes, 1, fun is_integer/1),
    case erlzmq:context(IoProcesses) of
        {ok, Ctx} ->
            case pushysim_sup:start_link(#client_state{ctx=Ctx}) of
                {ok, Pid} -> {ok, Pid, Ctx};
                Error -> Error
            end;
        Error ->
            Error
    end.

stop(Ctx) ->
    erlzmq:term(Ctx, 5000).


%% @author Arjan Scherpenisse <arjan@scherpenisse.net>
%% @copyright 2009 Arjan Scherpenisse

%% Copyright 2009 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(action_admin_zlink).
-include("zotonic.hrl").
-export([render_action/4]).

render_action(_TriggerId, _TargetId, Args, Context) ->
    Id   = z_convert:to_integer(proplists:get_value(id, Args, "")),
    Title = m_rsc:p(Id, title, Context),
    Url = m_rsc:p(Id, page_url, Context),
	Script = [<<"window.z_zlink(\"">>,z_utils:js_escape(Url),<<"\",\"">>, z_utils:js_escape(Title),<<"\");">>],
	{Script, Context}.

Use translation lookup in internal link action.

%% @author Arjan Scherpenisse <arjan@scherpenisse.net>
%% @copyright 2009 Arjan Scherpenisse

%% Copyright 2009 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(action_admin_zlink).
-include("zotonic.hrl").
-export([render_action/4]).

render_action(_TriggerId, _TargetId, Args, Context) ->
    Id   = z_convert:to_integer(proplists:get_value(id, Args, "")),
    Title = z_trans:lookup_fallback(m_rsc:p(Id, title, Context), Context),
    Url = m_rsc:p(Id, page_url, Context),
	Script = [<<"window.z_zlink(\"">>,z_utils:js_escape(Url),<<"\",\"">>, z_utils:js_escape(Title),<<"\");">>],
	{Script, Context}.


%%-----------------------------------------------------------------------------
%% Test that tests overloaded contratcs.
%% In December 2008 it works as far as intersection types are concerned (test1)
%% However, it does NOT work as far as type variables are concerned (test2)
%%-----------------------------------------------------------------------------
-module(overloaded1).
-export([test1/0, test2/0, foo/2]).

test1() ->
  {ok, gazonk} = foo({a,b,1}, atom_to_list(gazonk)),
  ok.

test2() ->
  {ok, gazonk} = foo(baz, []),
  ok.

-type mod() :: atom().

-spec foo(ATM, list()) -> {'ok', ATM} | {'error', _} when is_subtype(ATM, mod())
       ; (MFA, list()) -> {'ok', MFA} | {'error', _} when is_subtype(MFA, mfa()).

foo(F, _) when is_atom(F) ->
  case atom_to_list(F) of
      [42|_] -> {ok, F};
      _Other -> {error, mod:bar(F)}
  end;
foo({M,F,A}, _) ->
  case A =:= 0 of
    false -> {ok, {M,F,A}};
    true -> {error, M}
  end.

Use the modern version of is_subtype

%%-----------------------------------------------------------------------------
%% Test that tests overloaded contracts.
%% In December 2008 it works as far as intersection types are concerned (test1)
%% However, it does NOT work as far as type variables are concerned (test2)
%%-----------------------------------------------------------------------------
-module(overloaded1).
-export([test1/0, test2/0, foo/2]).

test1() ->
  {ok, gazonk} = foo({a,b,1}, atom_to_list(gazonk)),
  ok.

test2() ->
  {ok, gazonk} = foo(baz, []),
  ok.

-type mod() :: atom().

-spec foo(ATM, list()) -> {'ok', ATM} | {'error', _} when ATM :: mod()
       ; (MFA, list()) -> {'ok', MFA} | {'error', _} when MFA :: mfa().

foo(F, _) when is_atom(F) ->
  case atom_to_list(F) of
    [42|_] -> {ok, F};
    _Other -> {error, some_mod:some_function()}
  end;
foo({M,F,A}, _) ->
  case A =:= 0 of
    false -> {ok, {M,F,A}};
    true -> {error, M}
  end.


-module(eval_shim).
-export([exprs/2]).

exprs(Expressions, Bindings) ->
  % Convert the values of the current bindings back to their Reia form
  Bindings2 = [{Var, reia_erl:e2r(Val)} || {Var, Val} <- Bindings],

  % Call erl_eval
  {value, Value, NewBindings} = erl_eval:exprs(Expressions, Bindings2, {value, fun local_function/2}),

  % Wrap the resulting binding in {tuple, {...}} to prevent clobbering of
  % variable names like 'tuple', 'list', etc.
  {value, Value, [{tuple, {Var, Val}} || {Var, Val} <- NewBindings]}.

local_function(Name, [Args, Block]) ->
  case Name of
    'puts' ->
      ['Main':puts({Arg}, Block) || Arg <- list_to_tuple(Args)];
    _ ->
      'Main':Name(Args, Block)
  end.

Fix special cased puts supoort for local_function

-module(eval_shim).
-export([exprs/2]).

exprs(Expressions, Bindings) ->
  % Convert the values of the current bindings back to their Reia form
  Bindings2 = [{Var, reia_erl:e2r(Val)} || {Var, Val} <- Bindings],

  % Call erl_eval
  {value, Value, NewBindings} = erl_eval:exprs(Expressions, Bindings2, {value, fun local_function/2}),

  % Wrap the resulting binding in {tuple, {...}} to prevent clobbering of
  % variable names like 'tuple', 'list', etc.
  {value, Value, [{tuple, {Var, Val}} || {Var, Val} <- NewBindings]}.

local_function(Name, [Args, Block]) ->
  case Name of
    'puts' ->
      ['Main':puts({Arg}, Block) || Arg <- tuple_to_list(Args)];
    _ ->
      'Main':Name(Args, Block)
  end.


-module(config_listener).

-behaviour(gen_event).

%% Public interface
-export([start/1]).

-export([behaviour_info/1]).

%% Required gen_event interface
-export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2,
    code_change/3]).

behaviour_info(callbacks) ->
    [{handle_config_change/4}];
behaviour_info(_) ->
    undefined.

start(Module) ->
    gen_event:add_sup_handler(config_event, {?MODULE, Module}, [Module]).

init(Module) ->
    {ok, Module}.

handle_event({config_change, Sec, Key, Value, Persist}, Module) ->
    Module:handle_config_change(Sec, Key, Value, Persist).

handle_call(_Request, Module) ->
    {ok, ignored, St}.

handle_info(_Info, Module) ->
    {ok, St}.

terminate(_Reason, Module) ->
    ok.

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

Enable the listener to carry some state

-module(config_listener).

-behaviour(gen_event).

%% Public interface
-export([start/2]).

-export([behaviour_info/1]).

%% Required gen_event interface
-export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2,
    code_change/3]).

behaviour_info(callbacks) ->
    [{handle_config_change,5}];
behaviour_info(_) ->
    undefined.

start(Module, State) ->
    gen_event:add_sup_handler(config_event, {?MODULE, Module}, {Module, State}).

init({Module, State}) ->
    {ok, {Module, State}}.

handle_event({config_change, Sec, Key, Value, Persist}, {Module, State}) ->
    case Module:handle_config_change(Sec, Key, Value, Persist, State) of
        {ok, NewState} ->
            {ok, {Module, NewState}};
        remove_handler ->
            remove_handler
    end.

handle_call(_Request, Module) ->
    {ok, ignored, St}.

handle_info(_Info, Module) ->
    {ok, St}.

terminate(_Reason, Module) ->
    ok.

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


-module(fail_macro_module_names).

-export([
         module_name/0,
         function_name/0,
         no_errors/0,
         build_binary/0
        ]).

-define(FUNCTION_NAME, function_name).
-define(BINARY, "bla").
-define(function_name, function_name).
-define(module_name, ?MODULE).

module_name() ->
    ?MODULE:function_name(),
    ?module_name:?function_name().

function_name() ->
    module:?FUNCTION_NAME(params),
    module:?FUNCTION_NAME (params),
    lists:?MODULE().

build_binary() ->
    Bin = <<?BINARY:32>>,
    <<Bin, ?BINARY:1, "prefix">>.

no_errors() ->
    ?LINE.

Add valid binary matching tests

-module(fail_macro_module_names).

-export([
         module_name/0,
         function_name/0,
         no_errors/0,
         build_binary/0
        ]).

-define(FUNCTION_NAME, function_name).
-define(BINARY, "bla").
-define(BINARY_SIZE, 3).
-define(function_name, function_name).
-define(module_name, ?MODULE).

module_name() ->
    ?MODULE:function_name(),
    ?module_name:?function_name().

function_name() ->
    module:?FUNCTION_NAME(params),
    module:?FUNCTION_NAME (params),
    lists:?MODULE().

build_binary() ->
    Bin = <<?BINARY:32>>,
    _Bin2 = <<Bin:?BINARY_SIZE/binary>>,
    _Bin3 = <<?BINARY:?BINARY_SIZE>>,
    BinSize = ?BINARY_SIZE,
    _Bin4 = <<?BINARY:BinSize>>,
    <<Bin, ?BINARY:1, "prefix">>.

no_errors() ->
    ?LINE.


-module(epo_po_template).
-author("evgeny").

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

erl() ->
	{ok, [
<<"%% -*- coding: utf-8 -*-
-module(template).
-compile(nowarn_unused_vars).
-compile(nowarn_unused_function).
-compile(nowarn_unused_record).

-record(porec2, {msgstr, msgstr_n = {}, n_max}).
-export([get_record/2, get_idx/2]).
">>
	,
<<"get_idx(N, <<Locale2:2/binary, $_, _/binary>>) ->
	get_idx(N, Locale2);
get_idx(_, _) ->
	0.

get_record(Key, Locale) ->
	case Key of">>
	,
<<"		_ -> undefined
	end.

to_integer(true) -> to_integer(1);
to_integer(false) -> to_integer(0);
to_integer(N) when is_integer(N) -> N.

to_boolean(true) -> true;
to_boolean(false) -> false;
to_boolean(N) when N > 0 -> to_boolean(true);
to_boolean(N) when N == 0 -> to_boolean(false).
	">>]}.

Add ignore_xref to generated translation module.

-module(epo_po_template).
-author("evgeny").

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

erl() ->
	{ok, [
<<"%% -*- coding: utf-8 -*-
-module(template).
-compile(nowarn_unused_vars).
-compile(nowarn_unused_function).
-compile(nowarn_unused_record).

-record(porec2, {msgstr, msgstr_n = {}, n_max}).
-export([get_record/2, get_idx/2]).
-ignore_xref([get_record/2, get_idx/2]).
">>
	,
<<"get_idx(N, <<Locale2:2/binary, $_, _/binary>>) ->
	get_idx(N, Locale2);
get_idx(_, _) ->
	0.

get_record(Key, Locale) ->
	case Key of">>
	,
<<"		_ -> undefined
	end.

to_integer(true) -> to_integer(1);
to_integer(false) -> to_integer(0);
to_integer(N) when is_integer(N) -> N.

to_boolean(true) -> true;
to_boolean(false) -> false;
to_boolean(N) when N > 0 -> to_boolean(true);
to_boolean(N) when N == 0 -> to_boolean(false).
	">>]}.


%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%

-ifdef(line_trace).
-line_trace(true).
-define(line,
	put(test_server_loc,{?MODULE,?LINE}),
	io:format(lists:concat([?MODULE,",",integer_to_list(?LINE),": ~p"]),
		  [erlang:now()]),).
-else.
-define(line,put(test_server_loc,{?MODULE,?LINE}),).
-endif.
-define(t,test_server).
-define(config,test_server:lookup_config).

Make the ?line macro be empty; we're running out of code size in JVM class spec.

%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2009. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%

-ifdef(line_trace).
-line_trace(true).
-define(line,
	put(test_server_loc,{?MODULE,?LINE}),
	io:format(lists:concat([?MODULE,",",integer_to_list(?LINE),": ~p"]),
		  [erlang:now()]),).
-else.
%-define(line,put(test_server_loc,{?MODULE,?LINE}),).
-define(line,).
-endif.
-define(t,test_server).
-define(config,test_server:lookup_config).


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

-module(riak_moss_lfs_utils).

-export([object_or_manifest/1,
         remove_chunk/2,
         still_waiting/1]).

%% @doc Returns whether or not
%%      a value is a normal object,
%%      or a manifest document
object_or_manifest(_Value) ->
    ok.

%% @doc Remove a chunk from the
%%      chunks field of State
remove_chunk(_State, _Chunk) ->
    ok.

%% @doc Return true or false
%%      depending on whether
%%      we're still waiting
%%      to accumulate more chunks
still_waiting(_State) ->
    ok.

Include hrl in utils, rename func to show bool return value

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

-module(riak_moss_lfs_utils).

-include("riak_moss.hrl").

-export([object_or_manifest/1,
         remove_chunk/2,
         still_waiting/1]).

%% @doc Returns whether or not
%%      a value is a normal object,
%%      or a manifest document
is_manifest(Value) ->
    is_record(Value, lfs_manifest).

%% @doc Remove a chunk from the
%%      chunks field of State
remove_chunk(_State, _Chunk) ->
    ok.

%% @doc Return true or false
%%      depending on whether
%%      we're still waiting
%%      to accumulate more chunks
still_waiting(_State) ->
    ok.