hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
list
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
list
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
list
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
93babe14f00a1c766bab971fd2b306d244529d5a
878
ex
Elixir
lib/nostrum/struct/embed/field.ex
jos-b/nostrum
baf5c9de9f17c3bd99c5c06a454e03cc448aad1c
[ "MIT" ]
2
2020-03-03T02:51:57.000Z
2021-01-18T02:24:42.000Z
lib/nostrum/struct/embed/field.ex
jos-b/nostrum
baf5c9de9f17c3bd99c5c06a454e03cc448aad1c
[ "MIT" ]
null
null
null
lib/nostrum/struct/embed/field.ex
jos-b/nostrum
baf5c9de9f17c3bd99c5c06a454e03cc448aad1c
[ "MIT" ]
1
2020-09-03T13:55:55.000Z
2020-09-03T13:55:55.000Z
defmodule Nostrum.Struct.Embed.Field do @moduledoc """ Struct representing a Discord embed field. """ alias Nostrum.Util alias Poison.Encoder defstruct [ :name, :value, :inline ] defimpl Encoder do def encode(field, options) do field |> Map.from_struct() |> Enum.filter(fn {_, v} -> v != nil end) |> Map.new() |> Encoder.encode(options) end end @typedoc "Name of the field" @type name :: String.t() @typedoc "Value of the field" @type value :: String.t() @typedoc "Whether the field should display as inline" @type inline :: boolean | nil @type t :: %__MODULE__{ name: name, value: value, inline: inline } @doc false def to_struct(map) do new = Map.new(map, fn {k, v} -> {Util.maybe_to_atom(k), v} end) struct(__MODULE__, new) end end
18.680851
67
0.589977
93baea36401fd8b97d4a9288346f488902cb7cde
2,467
exs
Elixir
test/commands/role/grant_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
1,003
2016-02-23T17:21:12.000Z
2022-02-20T14:39:35.000Z
test/commands/role/grant_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
906
2016-02-22T22:54:19.000Z
2022-03-11T15:19:43.000Z
test/commands/role/grant_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
95
2016-02-23T13:42:31.000Z
2021-11-30T14:39:55.000Z
defmodule Cog.Test.Commands.Role.GrantTest do use Cog.CommandCase, command_module: Cog.Commands.Role.Grant alias Cog.Repository.Roles import Cog.Support.ModelUtilities, only: [role: 1, group: 1] import DatabaseAssertions, only: [assert_role_is_granted: 2, refute_role_is_granted: 2] test "granting a role to a group works" do role = role("aws-admin") group = group("ops") payload = new_req(args: ["aws-admin", "ops"]) |> send_req() |> unwrap() assert %{role: %{name: "aws-admin"}, group: %{name: "ops"}} = payload assert_role_is_granted(group, role) end test "granting a role to multiple groups fails" do role = role("aws-admin") groups = for name <- ["dev", "ops"] do group(name) end error = new_req(args: ["aws-admin", "dev", "ops"]) |> send_req() |> unwrap_error() assert(error == "Too many args. Arguments required: exactly 2.") for group <- groups do refute_role_is_granted(group, role) end end test "granting a role to a group requires an existing role" do group("ops") error = new_req(args: ["not-real", "ops"]) |> send_req() |> unwrap_error() assert(error == "Could not find 'role' with the name 'not-real'") end test "granting a role to a group requires an existing group" do role("aws-admin") error = new_req(args: ["aws-admin", "not-real"]) |> send_req() |> unwrap_error() assert(error == "Could not find 'group' with the name 'not-real'") end test "granting a role to a group requires the group" do role("aws-admin") error = new_req(args: ["aws-admin"]) |> send_req() |> unwrap_error() assert(error == "Not enough args. Arguments required: exactly 2.") end test "granting roles requires string arguments" do error = new_req(args: [123, 456]) |> send_req() |> unwrap_error() assert(error == "Arguments must be strings") end test "can grant the cog-admin role to a group" do group = group("ops") role("cog-admin") payload = new_req(args: ["cog-admin", "ops"]) |> send_req() |> unwrap() assert %{role: %{name: "cog-admin"}, group: %{name: "ops"}} = payload role = Roles.by_name("cog-admin") assert_role_is_granted(group, role) end end
27.411111
70
0.58411
93bb084ee523190ad7eb939b0719a0826a36308c
2,435
ex
Elixir
lib/commands/user.ex
Celeo/simple_irc_server
090dfdff236c51216922733412339ef477fe43da
[ "MIT" ]
null
null
null
lib/commands/user.ex
Celeo/simple_irc_server
090dfdff236c51216922733412339ef477fe43da
[ "MIT" ]
null
null
null
lib/commands/user.ex
Celeo/simple_irc_server
090dfdff236c51216922733412339ef477fe43da
[ "MIT" ]
null
null
null
defmodule IRC.Commands.User do require Logger use Bitwise @behaviour IRC.Commands.Base @doc """ Update the user information. Numeric replies: - ERR_NEEDMOREPARAMS - ERR_ALREADYREGISTRED """ @impl IRC.Commands.Base def run(parameters, client_state, _server_state) do nick = client_state.nick cond do nick == nil -> Logger.debug("Client sent USER before NICK, disconnecting them") IRC.ClientConnection.force_disconnect(client_state.pid) client_state.user.user != nil -> IRC.ClientConnection.send_to_client( client_state.socket, ":server #{IRC.Models.Errors.lookup(:ERR_ALREADYREGISTRED)} :Unauthorized command (already registered)" ) length(parameters) < 4 -> Logger.debug( "Insufficient number of parameters for USER command (got #{length(parameters)}" ) IRC.ClientConnection.send_to_client( client_state.socket, ":server #{IRC.Models.Errors.lookup(:ERR_NEEDMOREPARAMS)} NICK :Not enough parameters" ) true -> {user, mode, _, real_name} = List.to_tuple(parameters) mode = mode |> String.to_integer() |> mode_to_letters() Logger.debug("Got valid USER command from #{nick}: #{user}, #{mode}, #{real_name}") IRC.ClientConnection.update_user( client_state.pid, user, mode, real_name ) messages = [ ":server 001 #{nick} :Welcome to theInternet Relay Network #{nick}!#{user}@localhost", ":server 002 #{nick} :Your host is localhost, running version IN_DEV", ":server 003 #{nick} :This server was created SOME TIME IN THE RECENT PAST", ":server 004 #{nick} :localhost IN_DEV aiwroOs bcCefFgiIjklmnpqQrsStuz" ] Enum.each(messages, &IRC.ClientConnection.send_to_client(client_state.socket, &1)) end end @doc """ Parse a numeric bitmask of user mode for the USER command into its alpha representation. """ @spec mode_to_letters(mode :: integer()) :: String.t() def mode_to_letters(mode) do # third bit for i mode_i = if (mode &&& 4) > 0 do "i" else "" end # second bit for w mode_w = if (mode &&& 2) > 0 do "w" else "" end Enum.join([ mode_i, mode_w ]) end end
25.904255
113
0.600411
93bb161fcefec09f611e71a65d8c20adce4b79f3
1,540
ex
Elixir
test/support/conn_case.ex
gsarwate/shopix
21d0e85294ee92cb7573d1b5a5746af6824b9355
[ "MIT" ]
196
2019-05-05T15:59:32.000Z
2022-03-15T02:37:19.000Z
test/support/conn_case.ex
gsarwate/shopix
21d0e85294ee92cb7573d1b5a5746af6824b9355
[ "MIT" ]
105
2019-05-04T19:04:40.000Z
2021-07-28T11:21:45.000Z
test/support/conn_case.ex
gsarwate/shopix
21d0e85294ee92cb7573d1b5a5746af6824b9355
[ "MIT" ]
26
2019-05-05T19:40:52.000Z
2021-11-16T00:32:46.000Z
defmodule ShopixWeb.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build common datastructures and query the data layer. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest import ShopixWeb.Router.Helpers import Shopix.Factory alias Shopix.Guardian # The default endpoint for testing @endpoint ShopixWeb.Endpoint def guardian_login(user, key \\ :admin) do insert(:global_config) build_conn() |> bypass_through(ShopixWeb.Router, [:browser]) |> get("/") |> Guardian.Plug.sign_in(user, %{}, key: key) |> send_resp(200, "Flush the session yo") |> recycle() end def put_global_config(conn) do conn |> Plug.Conn.assign(:global_config, %Shopix.Schema.GlobalConfig{}) end end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Shopix.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Shopix.Repo, {:shared, self()}) end {:ok, conn: Phoenix.ConnTest.build_conn()} end end
26.551724
74
0.669481
93bb427230fec34d36d3468923d162e9d6681fce
1,001
ex
Elixir
tests/dummy/lib/dummy.ex
autoxjs/autox-phoenix
6446f4487e3af28955f6560973cff6add34be4d4
[ "MIT" ]
null
null
null
tests/dummy/lib/dummy.ex
autoxjs/autox-phoenix
6446f4487e3af28955f6560973cff6add34be4d4
[ "MIT" ]
null
null
null
tests/dummy/lib/dummy.ex
autoxjs/autox-phoenix
6446f4487e3af28955f6560973cff6add34be4d4
[ "MIT" ]
null
null
null
defmodule Dummy do use Application # See http://elixir-lang.org/docs/stable/elixir/Application.html # for more information on OTP Applications def start(_type, _args) do import Supervisor.Spec, warn: false children = [ # Start the endpoint when the application starts supervisor(Dummy.Endpoint, []), # Start the Ecto repository supervisor(Dummy.Repo, []), # Here you could define other workers and supervisors as children # worker(Dummy.Worker, [arg1, arg2, arg3]), supervisor(Dummy.Presence, []) ] # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Dummy.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do Dummy.Endpoint.config_change(changed, removed) :ok end end
31.28125
71
0.704296
93bb58af6433a42f3b26ece3aa6104ab6dc034a5
1,458
ex
Elixir
lib/draw_something/magic.ex
ShockN745/drawcheat
d02fa05c1499e3c91d7dd85342c0b149b203c240
[ "MIT" ]
null
null
null
lib/draw_something/magic.ex
ShockN745/drawcheat
d02fa05c1499e3c91d7dd85342c0b149b203c240
[ "MIT" ]
null
null
null
lib/draw_something/magic.ex
ShockN745/drawcheat
d02fa05c1499e3c91d7dd85342c0b149b203c240
[ "MIT" ]
null
null
null
defmodule DrawSomething.Magic do alias DrawSomething.Dictionary import DrawSomething.Words def cheat(letters, word_length) do letters |> cheat |> Enum.filter(&(String.length(&1) == word_length)) end def cheat(letters) do Dictionary.Coordinator.get_all_possible_words(letters) end def cheat_old(letters) do Dictionary.words |> Enum.filter(&(can_be_written_with(&1, letters))) end def cheat_old_task(letters) do Dictionary.words |> Enum.map(fn(w) -> Task.async(fn -> {w, can_be_written_with(w, letters)} end) end) |> Enum.map(fn(task) -> Task.await(task) end) |> Enum.filter(fn({_, keep}) -> keep == :true end) |> Enum.map(fn({word, _}) -> word end) end def cheat_old_stream(letters) do Dictionary.words |> Stream.map(fn(w) -> Task.async(fn -> {w, can_be_written_with(w, letters)} end) end) |> Stream.map(fn(task) -> Task.await(task) end) |> Stream.filter(fn({_, keep}) -> keep == :true end) |> Stream.map(fn({word, _}) -> word end) |> Enum.to_list end def bench(:normal) do f = fn -> cheat("asdfasdf") end bench(f) end def bench(:old) do f = fn -> cheat_old("asdfasdf") end bench(f) end def bench(:task) do f = fn -> cheat_old_task("asdfasdf") end bench(f) end def bench(:stream) do f = fn -> cheat_old_stream("asdfasdf") end bench(f) end def bench(func) when is_function(func), do: Benchmark.measure(func) end
26.509091
90
0.63786
93bb6a4d02d31264c860d9be34d4d2fe141ae8cf
2,708
exs
Elixir
test/rock/heaps_test.exs
ayrat555/rock
bd0dfdd3a7bfb028e27cfda32f271879dedac1b9
[ "MIT" ]
10
2017-06-24T10:23:25.000Z
2022-03-28T09:15:00.000Z
test/rock/heaps_test.exs
ayrat555/rock
bd0dfdd3a7bfb028e27cfda32f271879dedac1b9
[ "MIT" ]
2
2017-10-17T21:06:56.000Z
2020-07-14T13:43:32.000Z
test/rock/heaps_test.exs
ayrat555/rock
bd0dfdd3a7bfb028e27cfda32f271879dedac1b9
[ "MIT" ]
3
2017-09-01T09:37:13.000Z
2020-07-13T18:16:58.000Z
defmodule Rock.HeapsTest do use ExUnit.Case alias Rock.Heaps alias Rock.Links alias Rock.NeighbourCriterion alias Rock.Struct.Point alias Rock.Struct.Cluster alias Rock.Struct.Heap setup do theta = 0.5 criterion = NeighbourCriterion.new(theta) points = [ Point.new("1", ["1", "2", "3"], 0), Point.new("2", ["1", "2", "4"], 1), Point.new("3", ["1", "2", "5"], 2), Point.new("4", ["1", "3", "4"], 3), Point.new("5", ["1", "3", "5"], 4), Point.new("6", ["1", "4", "5"], 5), Point.new("7", ["2", "3", "4"], 6), Point.new("8", ["2", "3", "5"], 7), Point.new("9", ["2", "4", "5"], 8), Point.new("10", ["3", "4", "5"], 9), Point.new("11", ["1", "2", "6"], 10), Point.new("12", ["1", "2", "7"], 11), Point.new("13", ["1", "6", "7"], 12), Point.new("14", ["2", "6", "7"], 13) ] link_matrix = points |> Links.matrix(criterion) point_clusters = points |> Enum.chunk_by(fn %Point{attributes: attrs} -> attrs |> Enum.at(0) == "1" end) clusters = point_clusters |> Enum.map(&Cluster.new(&1)) { :ok, [ clusters: clusters, link_matrix: link_matrix, theta: theta ] } end test "initializes heap list", %{clusters: clusters, link_matrix: link_matrix, theta: theta} do heaps = clusters |> Heaps.initialize(link_matrix, theta) clusters |> Enum.each(fn %Cluster{uuid: uuid} -> exists = heaps |> Enum.map(fn %Heap{cluster: %Cluster{uuid: cluster_uuid}} -> cluster_uuid == uuid end) assert exists end) end test "updates heap list", %{clusters: clusters, link_matrix: link_matrix, theta: theta} do heaps = clusters |> Heaps.initialize(link_matrix, theta) cluster1 = %Cluster{uuid: uuid1} = clusters |> Enum.at(0) cluster2 = %Cluster{uuid: uuid2} = clusters |> Enum.at(1) {new_heaps, _cluster3} = heaps |> Heaps.update(cluster1, cluster2, theta) assert Enum.count(heaps) == Enum.count(new_heaps) + 1 refute new_heaps |> Enum.any?(fn %Heap{cluster: %Cluster{uuid: uuid}} -> uuid == uuid1 || uuid == uuid2 end) end test "creates global heap from heap list", %{ clusters: clusters, link_matrix: link_matrix, theta: theta } do heaps = clusters |> Heaps.initialize(link_matrix, theta) global_heap = heaps |> Heaps.global_heap() clusters |> Enum.each(fn %Cluster{uuid: uuid} -> assert global_heap |> Enum.any?(fn {_, _, cluster_uuid, _} -> uuid == cluster_uuid end) end) end end
26.038462
96
0.539143
93bb76d974a2478f49bf12529dfe569d10aceedb
3,463
ex
Elixir
lib/phoenix/transports/websocket.ex
bryanhunter/phoenix
9e836d20452bb1c36acaffb67e242c73b59cb299
[ "MIT" ]
null
null
null
lib/phoenix/transports/websocket.ex
bryanhunter/phoenix
9e836d20452bb1c36acaffb67e242c73b59cb299
[ "MIT" ]
null
null
null
lib/phoenix/transports/websocket.ex
bryanhunter/phoenix
9e836d20452bb1c36acaffb67e242c73b59cb299
[ "MIT" ]
null
null
null
defmodule Phoenix.Transports.WebSocket do use Plug.Builder import Phoenix.Controller, only: [endpoint_module: 1, router_module: 1] @moduledoc """ Handles WebSocket clients for the Channel Transport layer. ## Configuration By default, JSON encoding is used to broker messages to and from clients, but the serializer is configurable via the Endpoint's transport configuration: config :my_app, MyApp.Endpoint, transports: [ websocket_serializer: MySerializer ] The `websocket_serializer` module needs only to implement the `encode!/1` and `decode!/2` functions defined by the `Phoenix.Transports.Serializer` behaviour. Websockets, by default, do not timeout if the connection is lost. To set a maximum timeout duration in milliseconds, add this to your Endpoint's transport configuration: config :my_app, MyApp.Endpoint, transports: [ websocket_timeout: 60000 ] """ alias Phoenix.Channel.Transport alias Phoenix.Socket.Message plug :check_origin plug :upgrade def upgrade(%Plug.Conn{method: "GET"} = conn, _) do put_private(conn, :phoenix_upgrade, {:websocket, __MODULE__}) |> halt end @doc """ Handles initalization of the websocket. """ def ws_init(conn) do Process.flag(:trap_exit, true) endpoint = endpoint_module(conn) serializer = Dict.fetch!(endpoint.config(:transports), :websocket_serializer) timeout = Dict.fetch!(endpoint.config(:transports), :websocket_timeout) {:ok, %{router: router_module(conn), endpoint: endpoint, sockets: HashDict.new, sockets_inverse: HashDict.new, serializer: serializer}, timeout} end @doc """ Receives JSON encoded `%Phoenix.Socket.Message{}` from client and dispatches to Transport layer. """ def ws_handle(opcode, payload, state) do msg = state.serializer.decode!(payload, opcode) case Transport.dispatch(msg, state.sockets, self, state.router, state.endpoint, __MODULE__) do {:ok, socket_pid} -> {:ok, put(state, msg.topic, socket_pid)} _ -> {:ok, state} end end def ws_info({:EXIT, socket_pid, reason}, state) do case HashDict.get(state.sockets_inverse, socket_pid) do nil -> {:ok, state} topic -> new_state = delete(state, topic, socket_pid) case reason do :normal -> {:reply, state.serializer.encode!(%Message{ topic: topic, event: "chan:close", payload: %{} }), new_state} _other -> {:reply, state.serializer.encode!(%Message{ topic: topic, event: "chan:error", payload: %{} }), new_state} end end end def ws_info({:socket_push, message}, %{serializer: serializer} = state) do {:reply, serializer.encode!(message), state} end def ws_terminate(_reason, state) do {:shutdown, state} end defp check_origin(conn, _opts) do Transport.check_origin(conn) end defp put(state, topic, socket_pid) do %{state | sockets: HashDict.put(state.sockets, topic, socket_pid), sockets_inverse: HashDict.put(state.sockets_inverse, socket_pid, topic)} end defp delete(state, topic, socket_pid) do %{state | sockets: HashDict.delete(state.sockets, topic), sockets_inverse: HashDict.delete(state.sockets_inverse, socket_pid)} end end
29.598291
98
0.655501
93bb86b7bafc6c8a8095a67a143e5fa7a3d3a3a6
4,073
ex
Elixir
lib/mitbits/driver.ex
siddhantmittal7/Mitbits_Cryptocurrency
b02060b1fa6ccc14730433bc4b078b8e5c752a8a
[ "MIT" ]
2
2018-12-10T21:20:04.000Z
2020-07-07T07:28:14.000Z
lib/mitbits/driver.ex
prafful13/Mitbits_Cryptocurrency
b02060b1fa6ccc14730433bc4b078b8e5c752a8a
[ "MIT" ]
null
null
null
lib/mitbits/driver.ex
prafful13/Mitbits_Cryptocurrency
b02060b1fa6ccc14730433bc4b078b8e5c752a8a
[ "MIT" ]
1
2018-12-16T03:36:18.000Z
2018-12-16T03:36:18.000Z
defmodule Mitbits.Driver do use GenServer # use ExUnit.Case @me __MODULE__ # API def start_link(_) do GenServer.start_link(__MODULE__, :no_args, name: @me) end # SERVER def init(:no_args) do Process.send_after(self(), :kickoff, 0) {:ok, {}} end def handle_info(:kickoff, {}) do numNodes = 20 numMiners = 5 :ets.new(:mitbits, [:set, :public, :named_table]) {numNodes, numMiners} |> spawn_miners() |> create_genesis_block() |> spawn_miner_nodes() |> spawn_nodes() |> start_mining() |> make_transactions() # assert 1+1 == 1 {:noreply, {}} end def spawn_miners({numNodes, numMiners}) do miner_pk_hash_sk = Enum.map(1..numMiners, fn _ -> {:ok, {sk, pk}} = RsaEx.generate_keypair() hash_name = Mitbits.Utility.getHash(pk) {:ok, _} = Mitbits.MinerSupervisor.add_miner(pk, sk, hash_name) {pk, hash_name, sk} end) miners = Enum.map(miner_pk_hash_sk, fn {_, hash_name, _} -> {hash_name} end) :ets.insert(:mitbits, {"miners", miners}) {miner_pk_hash_sk, numNodes, numMiners} end def create_genesis_block({miner_pk_hash_sk, numNodes, numMiners}) do [{_, first_miner_hash, _} | _] = miner_pk_hash_sk {genesis_block} = GenServer.call( Mitbits.Utility.string_to_atom("miner_" <> first_miner_hash), {:mine_first, "thefoxjkfsndaljd"} ) :ets.insert(:mitbits, {"prev_block_hash", genesis_block.hash}) {genesis_block, miner_pk_hash_sk, numNodes, numMiners} end def spawn_miner_nodes({genesis_block, miner_pk_hash_sk, numNodes, numMiners}) do miner_node_hash = Enum.map(miner_pk_hash_sk, fn {pk, hash_name, sk} -> {:ok, _} = Mitbits.NodeSupervisor.add_node(pk, sk, genesis_block, hash_name) {:ok} = GenServer.call(Mitbits.Utility.string_to_atom("node_" <> hash_name), :update_wallet) {:ok} = GenServer.call( Mitbits.Utility.string_to_atom("node_" <> hash_name), :add_latest_block_to_indexded_blockchain ) {hash_name} end) {genesis_block, miner_node_hash, miner_pk_hash_sk, numNodes, numMiners} end def spawn_nodes({genesis_block, miner_node_hash, miner_pk_hash_sk, numNodes, numMiners}) do [{_, first_miner_hash, _} | _] = miner_pk_hash_sk node_hash = Enum.map(1..numNodes, fn _ -> {:ok, {sk, pk}} = RsaEx.generate_keypair() hash_name = Mitbits.Utility.getHash(pk) if(hash_name != miner_node_hash) do {:ok, _} = Mitbits.NodeSupervisor.add_node(pk, sk, genesis_block, hash_name) {:ok} = GenServer.call( Mitbits.Utility.string_to_atom("node_" <> hash_name), :add_latest_block_to_indexded_blockchain ) end {hash_name} end) all_nodes = miner_node_hash ++ node_hash # IO.inspect(node_hash) :ets.insert(:mitbits, {"nodes", all_nodes}) Enum.each(node_hash, fn {hash} -> GenServer.cast( Mitbits.Utility.string_to_atom("node_" <> first_miner_hash), {:req_for_mitbits, 10, hash} ) end) {node_hash, miner_node_hash, miner_pk_hash_sk, numNodes, numMiners} end def start_mining({node_hash, miner_node_hash, miner_pk_hash_sk, numNodes, numMiners}) do acc = Enum.reduce(miner_pk_hash_sk, 0, fn {_, miner_hash, _}, acc -> Mitbits.Miner.start_mining(miner_hash) acc + 1 end) {acc, node_hash, miner_node_hash, miner_pk_hash_sk, numNodes, numMiners} end def make_transactions({acc, node_hash, miner_node_hash, miner_pk_hash_sk, numNodes, numMiners}) do [{_, all_nodes}] = :ets.lookup(:mitbits, "nodes") Enum.each(1..(acc * 2000), fn i -> {node1_hash} = Enum.random(all_nodes) {node2_hash} = Enum.random(all_nodes) amount = Enum.random(1..10) GenServer.cast( Mitbits.Utility.string_to_atom("node_" <> node1_hash), {:req_for_mitbits, amount, node2_hash} ) end) end end
27.707483
100
0.633685
93bbc4bcd180357a6d07c70ce7ab9a92faeaee88
1,614
ex
Elixir
clients/domains/lib/google_api/domains/v1/model/search_domains_response.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/domains/lib/google_api/domains/v1/model/search_domains_response.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/domains/lib/google_api/domains/v1/model/search_domains_response.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # 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. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Domains.V1.Model.SearchDomainsResponse do @moduledoc """ Response for the `SearchDomains` method. ## Attributes * `registerParameters` (*type:* `list(GoogleApi.Domains.V1.Model.RegisterParameters.t)`, *default:* `nil`) - Results of the domain name search. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :registerParameters => list(GoogleApi.Domains.V1.Model.RegisterParameters.t()) | nil } field(:registerParameters, as: GoogleApi.Domains.V1.Model.RegisterParameters, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Domains.V1.Model.SearchDomainsResponse do def decode(value, options) do GoogleApi.Domains.V1.Model.SearchDomainsResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Domains.V1.Model.SearchDomainsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.340426
147
0.752169
93bbc6e84322b127de3791ec8ebb4aa489086882
1,044
ex
Elixir
farmbot_core/lib/farmbot_core/asset/supervisor.ex
SeppPenner/farmbot_os
39ba5c5880f8aef71792e2c009514bed1177089c
[ "MIT" ]
1
2019-08-06T11:51:48.000Z
2019-08-06T11:51:48.000Z
farmbot_core/lib/farmbot_core/asset/supervisor.ex
SeppPenner/farmbot_os
39ba5c5880f8aef71792e2c009514bed1177089c
[ "MIT" ]
null
null
null
farmbot_core/lib/farmbot_core/asset/supervisor.ex
SeppPenner/farmbot_os
39ba5c5880f8aef71792e2c009514bed1177089c
[ "MIT" ]
null
null
null
defmodule FarmbotCore.Asset.Supervisor do @moduledoc false use Supervisor alias FarmbotCore.{AssetSupervisor, AssetMonitor} alias FarmbotCore.Asset.{ Repo, Device, FarmEvent, FarmwareEnv, FarmwareInstallation, FbosConfig, FirmwareConfig, PinBinding, PublicKey, Peripheral, RegimenInstance } def start_link(args) do Supervisor.start_link(__MODULE__, args, name: __MODULE__) end def init([]) do children = [ Repo, {AssetSupervisor, module: FbosConfig}, {AssetSupervisor, module: FirmwareConfig}, {AssetSupervisor, module: Device}, {AssetSupervisor, module: RegimenInstance}, {AssetSupervisor, module: FarmEvent}, {AssetSupervisor, module: PinBinding}, {AssetSupervisor, module: PublicKey}, {AssetSupervisor, module: Peripheral}, {AssetSupervisor, module: FarmwareInstallation}, {AssetSupervisor, module: FarmwareEnv}, AssetMonitor, ] Supervisor.init(children, strategy: :one_for_one) end end
24.27907
61
0.689655
93bbe035a58dc46d769d08d82b0ac287aac802a8
83
exs
Elixir
apps/admin/test/admin/controllers/page_controller_test.exs
votiakov/petal
ec03551da6dadc0c3482b25a5f5dcd400c36db43
[ "MIT" ]
null
null
null
apps/admin/test/admin/controllers/page_controller_test.exs
votiakov/petal
ec03551da6dadc0c3482b25a5f5dcd400c36db43
[ "MIT" ]
null
null
null
apps/admin/test/admin/controllers/page_controller_test.exs
votiakov/petal
ec03551da6dadc0c3482b25a5f5dcd400c36db43
[ "MIT" ]
null
null
null
defmodule Legendary.Admin.PageControllerTest do use Legendary.Admin.ConnCase end
20.75
47
0.855422
93bbe7eff660747ddefe95b95a75ba8366a6d096
735
ex
Elixir
lib/mogrify/compat.ex
andra49/mogrify
ae8a02f88c979c71808afa09ca024bdc1a74ea25
[ "MIT" ]
494
2015-01-02T15:54:37.000Z
2021-07-05T04:24:30.000Z
lib/mogrify/compat.ex
andra49/mogrify
ae8a02f88c979c71808afa09ca024bdc1a74ea25
[ "MIT" ]
83
2015-04-30T21:03:29.000Z
2021-07-04T23:40:02.000Z
lib/mogrify/compat.ex
andra49/mogrify
ae8a02f88c979c71808afa09ca024bdc1a74ea25
[ "MIT" ]
79
2015-01-18T22:11:03.000Z
2021-06-22T17:24:02.000Z
defmodule Mogrify.Compat do @moduledoc false defmacro __using__(_opts) do quote do Code.ensure_loaded(Kernel.SpecialForms) if not macro_exported?(Kernel.SpecialForms, :__STACKTRACE__, 0) do def __STACKTRACE__, do: System.stacktrace() end end end def rand_uniform(high) do Code.ensure_loaded(:rand) if function_exported?(:rand, :uniform, 1) do :rand.uniform(high) else # Erlang/OTP < 19 apply(:crypto, :rand_uniform, [1, high]) end end def string_trim(string) do Code.ensure_loaded(String) if function_exported?(String, :trim, 1) do String.trim(string) else # Elixir < 1.3 apply(String, :strip, [string]) end end end
22.272727
72
0.64898
93bbe99d93167eb894eb3da4e72f51ec969f4943
5,689
exs
Elixir
test/exponent_server_sdk/push_notification_test.exs
vinagrito/exponent-server-sdk-elixir
d339cceb8ea0a75c3e52cf3d11fd38b63558b98c
[ "MIT" ]
null
null
null
test/exponent_server_sdk/push_notification_test.exs
vinagrito/exponent-server-sdk-elixir
d339cceb8ea0a75c3e52cf3d11fd38b63558b98c
[ "MIT" ]
null
null
null
test/exponent_server_sdk/push_notification_test.exs
vinagrito/exponent-server-sdk-elixir
d339cceb8ea0a75c3e52cf3d11fd38b63558b98c
[ "MIT" ]
null
null
null
defmodule ExponentServerSdk.PushNotificationTest do use ExUnit.Case, async: false import TestHelper alias ExponentServerSdk.PushMessage alias ExponentServerSdk.PushNotification doctest ExponentServerSdk.PushNotification test ".push should return the proper response from Expo" do message_map = %{ to: "ExponentPushToken[XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX]", title: "Pushed!", body: "You got your first message" } response = %{data: %{"status" => "ok", "id" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"}} json = json_response(response, 200) with_fixture(:post!, json, fn -> # expected = {:ok, %{"status" => "ok", "id" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"}} expected = {:ok, %{"status" => "ok", "id" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"}} # {:ok, # %{ # "status" => "error", # "details" => %{"error" => "DeviceNotRegistered"}, # "message" => # "\"ExponentPushToken[XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX]\" is not a registered push notification recipient" # }} assert expected == PushNotification.push(message_map) end) end test ".push_list should return the proper response from Expo" do message_list = [ %{ to: "ExponentPushToken[XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX]", title: "Pushed!", body: "You got your first message", data: %{} }, %{ to: "ExponentPushToken[YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY]", title: "Pushed Again!", body: "You got your second message", data: %{} } ] response = %{ data: [ %{"status" => "ok", "id" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"}, %{"status" => "ok", "id" => "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY"} ] } json = json_response(response, 200) with_fixture(:post!, json, fn -> # expected = { # :ok, # [ # %{"status" => "ok", "id" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"}, # %{"status" => "ok", "id" => "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY"} # ] # } expected = [ ok: [ %{ "details" => %{ "error" => "DeviceNotRegistered" }, "message" => "\"ExponentPushToken[XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX]\" is not a registered push notification recipient", "status" => "error" }, %{ "details" => %{ "error" => "DeviceNotRegistered" }, "message" => "\"ExponentPushToken[YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY]\" is not a registered push notification recipient", "status" => "error" } ] ] assert expected == PushNotification.push_list(message_list) end) end test ".get_receipts should return the proper response from Expo" do ids = ["XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY"] response = %{ data: %{ "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX": %{status: "ok"}, "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY": %{status: "ok"} } } json = json_response(response, 200) with_fixture(:post!, json, fn -> # expected = # {:ok, # %{ # "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" => %{"status" => "ok"}, # "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY" => %{"status" => "ok"} # }} expected = {:ok, %{}} assert expected == PushNotification.get_receipts(ids) end) end ### # HTTPotion API ### test ".process_request_headers adds the correct headers" do headers = PushNotification.process_request_headers([]) accepts = {:Accepts, "application/json"} accepts_encoding = {:"Accepts-Encoding", "gzip, deflate"} content_encoding = {:"Content-Encoding", "gzip"} content_type = {:"Content-Type", "application/json"} assert accepts in headers assert accepts_encoding in headers assert content_encoding in headers assert content_type in headers assert Keyword.keys(headers) == [ :"Content-Type", :"Content-Encoding", :"Accepts-Encoding", :Accepts ] end ### # Helpers ### def with_list_fixture(fun) do data = [ %{ to: "ExponentPushToken[XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX]", title: "Pushed!", body: "You got your first message" }, %{ to: "ExponentPushToken[YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY]", title: "Pushed Again!", body: "You got your second message" } ] json = json_response(data, 200) with_fixture(:post!, json, fn -> expected = { :ok, [ [ %PushMessage{ badge: 0, body: "You got your first message", channelId: "Default", data: %{}, expiration: 2419200, priority: "default", sound: "default", title: "Pushed!", to: "ExponentPushToken[XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX]", ttl: 0 }, %PushMessage{ badge: 0, body: "You got your second message", channelId: "Default", data: %{}, expiration: 2419200, priority: "default", sound: "default", title: "Pushed Again!", to: "ExponentPushToken[YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY]", ttl: 0 } ] ] } fun.(expected) end) end end
28.732323
135
0.541747
93bc05da5086048799f86998b3ec0818ce65ed5e
1,782
exs
Elixir
test/phoenix_client_ssl/plug/common_name_blacklist_test.exs
Prato/phoenix-client-ssl
510c2381e6d95c9baa6de9985d86d0a5dfe27b29
[ "MIT" ]
17
2017-12-01T09:12:41.000Z
2021-04-16T07:53:37.000Z
test/phoenix_client_ssl/plug/common_name_blacklist_test.exs
Prato/phoenix-client-ssl
510c2381e6d95c9baa6de9985d86d0a5dfe27b29
[ "MIT" ]
2
2018-01-29T13:04:26.000Z
2018-05-24T11:03:55.000Z
test/phoenix_client_ssl/plug/common_name_blacklist_test.exs
Prato/phoenix-client-ssl
510c2381e6d95c9baa6de9985d86d0a5dfe27b29
[ "MIT" ]
6
2018-05-24T07:42:22.000Z
2020-11-14T17:41:35.000Z
defmodule PhoenixClientSsl.Plug.CommonNameBlacklistTest do @moduledoc false use ExUnit.Case alias PhoenixClientSsl.Plug.CommonNameBlacklist alias Plug.Conn doctest CommonNameBlacklist defp send_and_return(conn, reason) do send(self(), reason) conn end describe "init/1" do test "config with patterns passes" do options = [patterns: ["foo"], handler: &send_and_return/2] assert %{patterns: [_], handler: _} = CommonNameBlacklist.init(options) end end describe "call/2" do test "passes with valid pattern blacklist" do conn = %Conn{private: %{client_certificate_common_name: "foo"}} options = %{patterns: ["bar"], handler: &send_and_return/2} assert %Conn{} = CommonNameBlacklist.call(conn, options) refute_received(:forbidden) refute_received(:unauthorized) end test "stops with invalid pattern blacklist" do conn = %Conn{private: %{client_certificate_common_name: "foo"}} options = %{patterns: ["foo"], handler: &send_and_return/2} assert %Conn{} = CommonNameBlacklist.call(conn, options) assert_received(:forbidden) refute_received(:unauthorized) end test "passes with empty pattern whitelist" do conn = %Conn{private: %{client_certificate_common_name: "foo"}} options = %{patterns: [], handler: &send_and_return/2} assert %Conn{} = CommonNameBlacklist.call(conn, options) refute_received(:forbidden) refute_received(:unauthorized) end test "stops with missing common name" do options = %{patterns: ["foo"], handler: &send_and_return/2} assert %Conn{} = CommonNameBlacklist.call(%Conn{}, options) assert_received(:unauthorized) refute_received(:forbidden) end end end
27.84375
77
0.686308
93bc39c6606ecafd0c6176b4ca10a8def936a9bc
420
exs
Elixir
create_fun_umbrella/apps/create_fun/priv/repo/migrations/20180524114906_guardiandb.exs
Vorzious/CreateFun
5744c913ef706bc29062fa90a8ec5de12d267dab
[ "MIT" ]
null
null
null
create_fun_umbrella/apps/create_fun/priv/repo/migrations/20180524114906_guardiandb.exs
Vorzious/CreateFun
5744c913ef706bc29062fa90a8ec5de12d267dab
[ "MIT" ]
9
2018-06-17T09:54:03.000Z
2018-06-17T09:55:20.000Z
create_fun_umbrella/apps/create_fun/priv/repo/migrations/20180524114906_guardiandb.exs
Vorzious/CreateFun
5744c913ef706bc29062fa90a8ec5de12d267dab
[ "MIT" ]
1
2018-06-05T18:38:01.000Z
2018-06-05T18:38:01.000Z
defmodule CreateFun.Repo.Migrations.Guardian.DB do use Ecto.Migration def change do create table(:guardian_tokens, primary_key: false) do add(:jti, :string, primary_key: true) add(:aud, :string, primary_key: true) add(:typ, :string) add(:iss, :string) add(:sub, :string) add(:exp, :bigint) add(:jwt, :text) add(:claims, :map) timestamps() end end end
23.333333
57
0.614286
93bc52094d3588e6129bcf391bc7b0899b7d87be
25,441
ex
Elixir
dict.ex
mimicry-tech/openapi_validator
a3207e6bc0ba588493747efe21acbd1730d18ba8
[ "Apache-2.0" ]
3
2021-07-13T21:20:14.000Z
2022-01-09T07:59:58.000Z
dict.ex
mimicry-tech/openapi_validator
a3207e6bc0ba588493747efe21acbd1730d18ba8
[ "Apache-2.0" ]
11
2022-01-09T07:45:30.000Z
2022-02-23T22:27:43.000Z
dict.ex
mimicry-tech/openapi_validator
a3207e6bc0ba588493747efe21acbd1730d18ba8
[ "Apache-2.0" ]
null
null
null
%{"$schema" => "http://json-schema.org/draft-04/schema#", "additionalProperties" => false, "definitions" => %{"Encoding" => %{"additionalProperties" => false, "properties" => %{"allowReserved" => %{"default" => false, "type" => "boolean"}, "contentType" => %{"type" => "string"}, "explode" => %{"type" => "boolean"}, "headers" => %{"additionalProperties" => %{"$ref" => "#/definitions/Header"}, "type" => "object"}, "style" => %{"enum" => ["form", "spaceDelimited", "pipeDelimited", "deepObject"], "type" => "string"}}, "type" => "object"}, "Parameter" => %{"additionalProperties" => false, "allOf" => [%{"$ref" => "#/definitions/ExampleXORExamples"}, %{"$ref" => "#/definitions/SchemaXORContent"}, %{"$ref" => "#/definitions/ParameterLocation"}], "patternProperties" => %{"^x-" => %{}}, "properties" => %{"allowEmptyValue" => %{"default" => false, "type" => "boolean"}, "allowReserved" => %{"default" => false, "type" => "boolean"}, "content" => %{"additionalProperties" => %{"$ref" => "#/definitions/MediaType"}, "maxProperties" => 1, "minProperties" => 1, "type" => "object"}, "deprecated" => %{"default" => false, "type" => "boolean"}, "description" => %{"type" => "string"}, "example" => %{}, "examples" => %{"additionalProperties" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Example"}}]}, "type" => "object"}, "explode" => %{"type" => "boolean"}, "in" => %{"type" => "string"}, "name" => %{"type" => "string"}, "required" => %{"default" => false, "type" => "boolean"}, "schema" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Schema"}}]}, "style" => %{"type" => "string"}}, "required" => ["name", "in"], "type" => "object"}, "Contact" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"email" => %{"format" => "email", "type" => "string"}, "name" => %{"type" => "string"}, "url" => %{"format" => "uri-reference", "type" => "string"}}, "type" => "object"}, "Reference" => %{"properties" => %{"$ref" => %{"format" => "uri-reference", "type" => "string"}}, "required" => ["$ref"], "type" => "object"}, "SecurityScheme" => %{"switch" => [%{"if" => %{"properties" => %{"type" => %{"enum" => ["apiKey"]}}, "required" => ["type"]}, "then" => %{"$ref" => "#/definitions/APIKeySecurityScheme"}}, %{"if" => %{"properties" => %{"type" => %{"enum" => ["http"]}}, "required" => ["type"]}, "then" => %{"$ref" => "#/definitions/HTTPSecurityScheme"}}, %{"if" => %{"properties" => %{"type" => %{"enum" => ["oauth2"]}}, "required" => ["type"]}, "then" => %{"$ref" => "#/definitions/OAuth2SecurityScheme"}}, %{"if" => %{"properties" => %{"type" => %{"enum" => ["openIdConnect"]}}, "required" => ["type"]}, "then" => %{"$ref" => "#/definitions/OpenIdConnectSecurityScheme"}}, %{"then" => %{"properties" => %{"type" => %{"enum" => ["apiKey", "http", "oauth2", "openIdConnect"], "type" => "string"}}, "required" => ["type"]}}], "type" => "object"}, "ParameterLocation" => %{"description" => "Parameter location", "switch" => [%{"if" => %{"properties" => %{"in" => %{"enum" => ["path"]}}, "required" => ["in"]}, "then" => %{"description" => "Parameter in path", "properties" => %{"required" => %{"enum" => [true]}, "style" => %{"default" => "simple", "enum" => ["matrix", "label", "simple"]}}, "required" => ["required"]}}, %{"if" => %{"properties" => %{"in" => %{"enum" => ["query"]}}, "required" => ["in"]}, "then" => %{"description" => "Parameter in query", "properties" => %{"style" => %{"default" => "form", "enum" => ["form", "spaceDelimited", "pipeDelimited", "deepObject"]}}}}, %{"if" => %{"properties" => %{"in" => %{"enum" => ["header"]}}, "required" => ["in"]}, "then" => %{"description" => "Parameter in header", "properties" => %{"style" => %{"default" => "simple", "enum" => ["simple"]}}}}, %{"if" => %{"properties" => %{"in" => %{"enum" => ["cookie"]}}, "required" => ["in"]}, "then" => %{"description" => "Parameter in cookie", "properties" => %{"style" => %{"default" => "form", "enum" => ["form"]}}}}, %{"then" => %{"properties" => %{"in" => %{"enum" => ["path", "query", "header", "cookie"]}}, "required" => ["in"]}}]}, "RequestBody" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"content" => %{"additionalProperties" => %{"$ref" => "#/definitions/MediaType"}, "type" => "object"}, "description" => %{"type" => "string"}, "required" => %{"default" => false, "type" => "boolean"}}, "required" => ["content"], "type" => "object"}, "Response" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"content" => %{"additionalProperties" => %{"$ref" => "#/definitions/MediaType"}, "type" => "object"}, "description" => %{"type" => "string"}, "headers" => %{"additionalProperties" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Header"}}]}, "type" => "object"}, "links" => %{"additionalProperties" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Link"}}]}, "type" => "object"}}, "required" => ["description"], "type" => "object"}, "License" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"name" => %{"type" => "string"}, "url" => %{"format" => "uri-reference", "type" => "string"}}, "required" => ["name"], "type" => "object"}, "XML" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"attribute" => %{"default" => false, "type" => "boolean"}, "name" => %{"type" => "string"}, "namespace" => %{"format" => "uri", "type" => "string"}, "prefix" => %{"type" => "string"}, "wrapped" => %{"default" => false, "type" => "boolean"}}, "type" => "object"}, "Components" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"callbacks" => %{"patternProperties" => %{"^[a-zA-Z0-9\\.\\-_]+$" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Callback"}}]}}, "type" => "object"}, "examples" => %{"patternProperties" => %{"^[a-zA-Z0-9\\.\\-_]+$" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Example"}}]}}, "type" => "object"}, "headers" => %{"patternProperties" => %{"^[a-zA-Z0-9\\.\\-_]+$" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Header"}}]}}, "type" => "object"}, "links" => %{"patternProperties" => %{"^[a-zA-Z0-9\\.\\-_]+$" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Link"}}]}}, "type" => "object"}, "parameters" => %{"patternProperties" => %{"^[a-zA-Z0-9\\.\\-_]+$" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Parameter"}}]}}, "type" => "object"}, "requestBodies" => %{"patternProperties" => %{"^[a-zA-Z0-9\\.\\-_]+$" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/RequestBody"}}]}}, "type" => "object"}, "responses" => %{"patternProperties" => %{"^[a-zA-Z0-9\\.\\-_]+$" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Response"}}]}}, "type" => "object"}, "schemas" => %{"patternProperties" => %{"^[a-zA-Z0-9\\.\\-_]+$" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Schema"}}]}}, "type" => "object"}, "securitySchemes" => %{"patternProperties" => %{"^[a-zA-Z0-9\\.\\-_]+$" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/SecurityScheme"}}]}}, "type" => "object"}}, "type" => "object"}, "Discriminator" => %{"properties" => %{"mapping" => %{"additionalProperties" => %{"type" => "string"}, "type" => "object"}, "propertyName" => %{"type" => "string"}}, "required" => ["propertyName"], "type" => "object"}, "Info" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"contact" => %{"$ref" => "#/definitions/Contact"}, "description" => %{"type" => "string"}, "license" => %{"$ref" => "#/definitions/License"}, "termsOfService" => %{"format" => "uri-reference", "type" => "string"}, "title" => %{"type" => "string"}, "version" => %{"type" => "string"}}, "required" => ["title", "version"], "type" => "object"}, "ServerVariable" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"default" => %{"type" => "string"}, "description" => %{"type" => "string"}, "enum" => %{"items" => %{"type" => "string"}, "type" => "array"}}, "required" => ["default"], "type" => "object"}, "PathItem" => %{"additionalProperties" => false, "patternProperties" => %{"^(get|put|post|delete|options|head|patch|trace)$" => %{"$ref" => "#/definitions/Operation"}, "^x-" => %{}}, "properties" => %{"$ref" => %{"type" => "string"}, "description" => %{"type" => "string"}, "parameters" => %{"items" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Parameter"}}]}, "type" => "array", "uniqueItems" => true}, "servers" => %{"items" => %{"$ref" => "#/definitions/Server"}, "type" => "array"}, "summary" => %{"type" => "string"}}, "type" => "object"}, "Paths" => %{"additionalProperties" => false, "errorMessage" => %{"additionalProperties" => "should only have path names that start with `/`"}, "patternProperties" => %{"^\\/" => %{"$ref" => "#/definitions/PathItem"}, "^x-" => %{}}, "type" => "object"}, "SchemaXORContent" => %{"description" => "Schema and content are mutually exclusive, at least one is required", "errorMessage" => "should have either a `schema` or `content` property", "switch" => [%{"if" => %{"required" => ["schema", "content"]}, "then" => false}, %{"if" => %{"required" => ["schema"]}, "then" => true}, %{"if" => %{"required" => ["content"]}, "then" => %{"allOf" => [%{"not" => %{"required" => ["style"]}}, %{"not" => %{"required" => ["explode"]}}, %{"not" => %{"required" => ["allowReserved"]}}, %{"not" => %{"required" => ["example"]}}, %{"not" => %{"required" => ["examples"]}}], "description" => "Some properties are not allowed if content is present", "errorMessage" => "should not have `style`, `explode`, `allowReserved`, `example`, or `examples` when `content` is present"}}, %{"then" => %{"required" => ["schema", "content"]}}]}, "Header" => %{"additionalProperties" => false, "allOf" => [%{"$ref" => "#/definitions/ExampleXORExamples"}, %{"$ref" => "#/definitions/SchemaXORContent"}], "patternProperties" => %{"^x-" => %{}}, "properties" => %{"allowEmptyValue" => %{"default" => false, "type" => "boolean"}, "allowReserved" => %{"default" => false, "type" => "boolean"}, "content" => %{"additionalProperties" => %{"$ref" => "#/definitions/MediaType"}, "maxProperties" => 1, "minProperties" => 1, "type" => "object"}, "deprecated" => %{"default" => false, "type" => "boolean"}, "description" => %{"type" => "string"}, "example" => %{}, "examples" => %{"additionalProperties" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Example"}}]}, "type" => "object"}, "explode" => %{"type" => "boolean"}, "required" => %{"default" => false, "type" => "boolean"}, "schema" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Schema"}}]}, "style" => %{"default" => "simple", "enum" => ["simple"], "type" => "string"}}, "type" => "object"}, "Callback" => %{"additionalProperties" => %{"$ref" => "#/definitions/PathItem"}, "patternProperties" => %{"^x-" => %{}}, "type" => "object"}, "AuthorizationCodeOAuthFlow" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"authorizationUrl" => %{"format" => "uri-reference", "type" => "string"}, "refreshUrl" => %{"format" => "uri-reference", "type" => "string"}, "scopes" => %{"additionalProperties" => %{"type" => "string"}, "type" => "object"}, "tokenUrl" => %{"format" => "uri-reference", "type" => "string"}}, "required" => ["authorizationUrl", "tokenUrl"], "type" => "object"}, "PasswordOAuthFlow" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"refreshUrl" => %{"format" => "uri-reference", "type" => "string"}, "scopes" => %{"additionalProperties" => %{"type" => "string"}, "type" => "object"}, "tokenUrl" => %{"format" => "uri-reference", "type" => "string"}}, "required" => ["tokenUrl"], "type" => "object"}, "Example" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"description" => %{"type" => "string"}, "externalValue" => %{"format" => "uri-reference", "type" => "string"}, "summary" => %{"type" => "string"}, "value" => %{}}, "type" => "object"}, "OAuthFlows" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"authorizationCode" => %{"$ref" => "#/definitions/AuthorizationCodeOAuthFlow"}, "clientCredentials" => %{"$ref" => "#/definitions/ClientCredentialsFlow"}, "implicit" => %{"$ref" => "#/definitions/ImplicitOAuthFlow"}, "password" => %{"$ref" => "#/definitions/PasswordOAuthFlow"}}, "type" => "object"}, "ExternalDocumentation" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"description" => %{"type" => "string"}, "url" => %{"format" => "uri-reference", "type" => "string"}}, "required" => ["url"], "type" => "object"}, "Schema" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"title" => %{"type" => "string"}, "items" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Schema"}}]}, "oneOf" => %{"items" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Schema"}}]}, "type" => "array"}, "anyOf" => %{"items" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Schema"}}]}, "type" => "array"}, "deprecated" => %{"default" => false, "type" => "boolean"}, "type" => %{"enum" => ["array", "boolean", "integer", "number", "object", "string"], "type" => "string"}, "maxLength" => %{"minimum" => 0, "type" => "integer"}, "uniqueItems" => %{"default" => false, "type" => "boolean"}, "exclusiveMaximum" => %{"default" => false, "type" => "boolean"}, "readOnly" => %{"default" => false, "type" => "boolean"}, "allOf" => %{"items" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Schema"}}]}, "type" => "array"}, "minItems" => %{"default" => 0, "minimum" => 0, "type" => "integer"}, "xml" => %{"$ref" => "#/definitions/XML"}, "additionalProperties" => %{"default" => true, "switch" => [%{"if" => %{"required" => ["$ref"], "type" => "object"}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"if" => %{"type" => "object"}, "then" => %{"$ref" => "#/definitions/Schema"}}, %{"then" => %{"errorMessage" => "should be a Reference Object, Schema Object, or boolean value", "type" => "boolean"}}]}, "required" => %{"errorMessage" => %{"type" => "should be an array of property names required within an object schema"}, "items" => %{"type" => "string"}, "minItems" => 1, "type" => "array", "uniqueItems" => true}, "not" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Schema"}}]}, "example" => %{}, "default" => %{}, "multipleOf" => %{"exclusiveMinimum" => true, "minimum" => 0, "type" => "number"}, "minimum" => %{"type" => "number"}, "pattern" => %{"format" => "regex", "type" => "string"}, "exclusiveMinimum" => %{"default" => false, "type" => "boolean"}, "externalDocs" => %{"$ref" => "#/definitions/ExternalDocumentation"}, "maxItems" => %{"minimum" => 0, "type" => "integer"}, "maxProperties" => %{"minimum" => 0, "type" => "integer"}, "nullable" => %{"default" => false, "type" => "boolean"}, "description" => %{"type" => "string"}, "minProperties" => %{"default" => 0, "minimum" => 0, "type" => "integer"}, "properties" => %{"additionalProperties" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Schema"}}]}, "type" => "object"}, "writeOnly" => %{"default" => false, "type" => "boolean"}, "minLength" => %{"default" => 0, "minimum" => 0, "type" => "integer"}, "format" => %{"type" => "string"}, "maximum" => %{"type" => "number"}, "discriminator" => %{"$ref" => "#/definitions/Discriminator"}, "enum" => %{"items" => %{}, "minItems" => 1, "type" => "array", "uniqueItems" => false}}, "type" => "object"}, "ClientCredentialsFlow" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"refreshUrl" => %{"format" => "uri-reference", "type" => "string"}, "scopes" => %{"additionalProperties" => %{"type" => "string"}, "type" => "object"}, "tokenUrl" => %{"format" => "uri-reference", "type" => "string"}}, "required" => ["tokenUrl"], "type" => "object"}, "Server" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"description" => %{"type" => "string"}, "url" => %{"type" => "string"}, "variables" => %{"additionalProperties" => %{"$ref" => "#/definitions/ServerVariable"}, "type" => "object"}}, "required" => ["url"], "type" => "object"}, "Tag" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"description" => %{"type" => "string"}, "externalDocs" => %{"$ref" => "#/definitions/ExternalDocumentation"}, "name" => %{"type" => "string"}}, "required" => ["name"], "type" => "object"}, "APIKeySecurityScheme" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"description" => %{"type" => "string"}, "in" => %{"enum" => ["header", "query", "cookie"], "type" => "string"}, "name" => %{"type" => "string"}, "type" => %{"enum" => ["apiKey"], "type" => "string"}}, "required" => ["type", "name", "in"], "type" => "object"}, "Link" => %{"additionalProperties" => false, "not" => %{"description" => "Operation Id and Operation Ref are mutually exclusive", "required" => ["operationId", "operationRef"]}, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"description" => %{"type" => "string"}, "operationId" => %{"type" => "string"}, "operationRef" => %{"format" => "uri-reference", "type" => "string"}, "parameters" => %{"additionalProperties" => %{}, "type" => "object"}, "requestBody" => %{}, "server" => %{"$ref" => "#/definitions/Server"}}, "type" => "object"}, "Operation" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"callbacks" => %{"additionalProperties" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Callback"}}]}, "type" => "object"}, "deprecated" => %{"default" => false, "type" => "boolean"}, "description" => %{"type" => "string"}, "externalDocs" => %{"$ref" => "#/definitions/ExternalDocumentation"}, "operationId" => %{"type" => "string"}, "parameters" => %{"items" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Parameter"}}]}, "type" => "array", "uniqueItems" => true}, "requestBody" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/RequestBody"}}]}, "responses" => %{"$ref" => "#/definitions/Responses"}, "security" => %{"items" => %{"$ref" => "#/definitions/SecurityRequirement"}, "type" => "array"}, "servers" => %{"items" => %{"$ref" => "#/definitions/Server"}, "type" => "array"}, "summary" => %{"type" => "string"}, "tags" => %{"items" => %{"type" => "string"}, "type" => "array"}}, "required" => ["responses"], "type" => "object"}, "HTTPSecurityScheme" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"bearerFormat" => %{"type" => "string"}, "description" => %{"type" => "string"}, "scheme" => %{"type" => "string"}, "type" => %{"enum" => ["http"], "type" => "string"}}, "required" => ["scheme", "type"], "switch" => [%{"if" => %{"not" => %{"properties" => %{"scheme" => %{"enum" => ["bearer"]}}, "required" => ["scheme"]}}, "then" => %{"errorMessage" => "should NOT have a `bearerFormat` property without `scheme: bearer` being set", "properties" => %{"bearerFormat" => %{"enum" => [nil]}}}}], "type" => "object"}, "ImplicitOAuthFlow" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"authorizationUrl" => %{"format" => "uri-reference", "type" => "string"}, "refreshUrl" => %{"format" => "uri-reference", "type" => "string"}, "scopes" => %{"additionalProperties" => %{"type" => "string"}, "type" => "object"}}, "required" => ["authorizationUrl", "scopes"], "type" => "object"}, "SecurityRequirement" => %{"additionalProperties" => %{"items" => %{"type" => "string"}, "type" => "array"}, "type" => "object"}, "Responses" => %{"additionalProperties" => false, "errorMessage" => %{"additionalProperties" => "should only have three-digit status codes, `default`, and vendor extensions (`x-*`) as properties", "minProperties" => "should define at least one response", "not" => "should define at least one response, in addition to any vendor extension (`x-*`) fields"}, "minProperties" => 1, "not" => %{"additionalProperties" => false, "minProperties" => 1, "patternProperties" => %{"^x-" => %{}}, "type" => "object"}, "patternProperties" => %{"^[1-5](?:\\d{2}|XX)$" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Response"}}]}, "^x-" => %{}}, "properties" => %{"default" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Response"}}]}}, "type" => "object"}, "OAuth2SecurityScheme" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"description" => %{"type" => "string"}, "flows" => %{"$ref" => "#/definitions/OAuthFlows"}, "type" => %{"enum" => ["oauth2"], "type" => "string"}}, "required" => ["type", "flows"], "type" => "object"}, "OpenIdConnectSecurityScheme" => %{"additionalProperties" => false, "patternProperties" => %{"^x-" => %{}}, "properties" => %{"description" => %{"type" => "string"}, "openIdConnectUrl" => %{"format" => "uri-reference", "type" => "string"}, "type" => %{"enum" => ["openIdConnect"], "type" => "string"}}, "required" => ["type", "openIdConnectUrl"], "type" => "object"}, "ExampleXORExamples" => %{"description" => "Example and examples are mutually exclusive", "errorMessage" => "should not have both `example` and `examples`, as they are mutually exclusive", "not" => %{"required" => ["example", "examples"]}}, "MediaType" => %{"additionalProperties" => false, "allOf" => [%{"$ref" => "#/definitions/ExampleXORExamples"}], "patternProperties" => %{"^x-" => %{}}, "properties" => %{"encoding" => %{"additionalProperties" => %{"$ref" => "#/definitions/Encoding"}, "type" => "object"}, "example" => %{}, "examples" => %{"additionalProperties" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Example"}}]}, "type" => "object"}, "schema" => %{"switch" => [%{"if" => %{"required" => ["$ref"]}, "then" => %{"$ref" => "#/definitions/Reference"}}, %{"then" => %{"$ref" => "#/definitions/Schema"}}]}}, "type" => "object"}}, "description" => "Validation schema for OpenAPI Specification 3.0.X.", "id" => "https://spec.openapis.org/oas/3.0/schema/2019-04-02", "patternProperties" => %{"^x-" => %{}}, "properties" => %{"components" => %{"$ref" => "#/definitions/Components"}, "externalDocs" => %{"$ref" => "#/definitions/ExternalDocumentation"}, "info" => %{"$ref" => "#/definitions/Info"}, "openapi" => %{"pattern" => "^3\\.0\\.\\d(-.+)?$", "type" => "string"}, "paths" => %{"$ref" => "#/definitions/Paths"}, "security" => %{"items" => %{"$ref" => "#/definitions/SecurityRequirement"}, "type" => "array"}, "servers" => %{"items" => %{"$ref" => "#/definitions/Server"}, "type" => "array"}, "tags" => %{"items" => %{"$ref" => "#/definitions/Tag"}, "type" => "array"}}, "required" => ["openapi", "info", "paths"], "type" => "object"}
25,441
25,441
0.531347
93bc64ad79d1704c66c9d6876f9849b129f4d214
14,758
exs
Elixir
test/exq_test.exs
JamesFerguson/exq
4457ea50ad4c8a6a7e127da5acafc130960822bb
[ "Apache-2.0" ]
1,406
2015-01-16T03:00:32.000Z
2022-03-28T11:38:22.000Z
test/exq_test.exs
JamesFerguson/exq
4457ea50ad4c8a6a7e127da5acafc130960822bb
[ "Apache-2.0" ]
372
2015-01-08T05:15:11.000Z
2022-03-18T18:05:34.000Z
test/exq_test.exs
JamesFerguson/exq
4457ea50ad4c8a6a7e127da5acafc130960822bb
[ "Apache-2.0" ]
217
2015-02-01T20:21:36.000Z
2022-01-28T16:19:55.000Z
defmodule ExqTest do use ExUnit.Case alias Exq.Redis.JobQueue import ExqTestUtil defmodule PerformWorker do def perform do send(:exqtest, {:worked}) end end defmodule PerformArgWorker do def perform(arg) do send(:exqtest, {:worked, arg}) end end defmodule SleepWorker do def perform(time, message) do :timer.sleep(time) send(:exqtest, {message}) end end defmodule SleepLastWorker do def perform(time, message) do Process.register(self(), :sleep_last_worker) send(:exqtest, {message}) :timer.sleep(time) end end defmodule EmptyMethodWorker do def perform do end end defmodule MissingMethodWorker do end defmodule FailWorker do def failure_perform do _ = :num + 1 send(:exqtest, {:worked}) end end setup do TestRedis.setup() on_exit(fn -> wait() TestRedis.teardown() end) :ok end test "start using registered name" do {:ok, exq_sup} = Exq.start_link(name: CustomManager) assert_exq_up(CustomManager) stop_process(exq_sup) end test "start multiple exq instances using registered name" do {:ok, sup1} = Exq.start_link(name: CustomManager1) assert_exq_up(CustomManager1) {:ok, sup2} = Exq.start_link(name: CustomManager2) assert_exq_up(CustomManager2) stop_process(sup1) stop_process(sup2) end test "enqueue and run job" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link() {:ok, _} = Exq.enqueue(Exq, "default", ExqTest.PerformWorker, []) assert_receive {:worked} stop_process(sup) end test "enqueue and run job via redis sentinel" do sentinel_args = [ sentinel: [sentinels: [[host: "127.0.0.1", port: 6666]], group: "exq"], database: 0, password: nil, timeout: 5000, name: Exq.Redis.Client, socket_opts: [] ] with_application_env(:exq, :redis_options, sentinel_args, fn -> Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link() {:ok, _} = Exq.enqueue(Exq, "default", ExqTest.PerformWorker, []) assert_receive {:worked} stop_process(sup) end) end test "run jobs from backup queue on boot" do host = elem(:inet.gethostname(), 1) Process.register(self(), :exqtest) # enqueue and dequeue - this should now be in backup queue JobQueue.enqueue(:testredis, "test", "queue", ExqTest.PerformWorker, [], []) JobQueue.dequeue(:testredis, "test", host, ["queue"]) # make sure jobs were requeued from backup queue {:ok, sup} = Exq.start_link(queues: ["default", "queue"]) wait_long() assert_received {:worked} # make sure backup queue was cleared properly if job finished JobQueue.re_enqueue_backup(:testredis, "test", host, "queue") wait_long() refute_received {:worked} stop_process(sup) end test "enqueue_in and run a job" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(scheduler_enable: true) {:ok, _} = Exq.enqueue_in(Exq, "default", 0, ExqTest.PerformWorker, []) assert_receive {:worked} stop_process(sup) end test "enqueue_at and run a job" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(scheduler_enable: true) {:ok, _} = Exq.enqueue_at(Exq, "default", DateTime.utc_now(), ExqTest.PerformWorker, []) assert_receive {:worked} stop_process(sup) end test "enqueue with separate enqueuer" do Process.register(self(), :exqtest) {:ok, exq_sup} = Exq.start_link() {:ok, enq_sup} = Exq.start_link(mode: :enqueuer, name: ExqE) {:ok, _} = Exq.Enqueuer.enqueue(ExqE.Enqueuer, "default", ExqTest.PerformWorker, []) assert_receive {:worked} stop_process(exq_sup) stop_process(enq_sup) end test "enqueue with separate enqueuer and api" do Process.register(self(), :exqtest) {:ok, exq_sup} = Exq.start_link() {:ok, enq_sup} = Exq.start_link(mode: [:enqueuer, :api], name: ExqE) {:ok, _} = Exq.Enqueuer.enqueue(ExqE.Enqueuer, "default", ExqTest.PerformWorker, []) {:ok, _} = Exq.Api.queues(ExqE.Api) assert_receive {:worked} stop_process(exq_sup) stop_process(enq_sup) end test "enqueue with separate enqueuer even if main Exq process is down" do Process.register(self(), :exqtest) {:ok, exq_sup} = Exq.start_link() stop_process(exq_sup) {:ok, enq_sup} = Exq.start_link(mode: :enqueuer) {:ok, _} = Exq.Enqueuer.enqueue(Exq.Enqueuer, "default", ExqTest.PerformWorker, []) stop_process(enq_sup) {:ok, exq_sup} = Exq.start_link() assert_receive {:worked} stop_process(exq_sup) end test "run jobs on multiple queues" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(queues: ["q1", "q2"]) {:ok, _} = Exq.enqueue(Exq, "q1", ExqTest.PerformArgWorker, [1]) {:ok, _} = Exq.enqueue(Exq, "q2", ExqTest.PerformArgWorker, [2]) assert_receive {:worked, 1} assert_receive {:worked, 2} stop_process(sup) end test "register queue and run job" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(queues: ["q1"]) :ok = Exq.subscribe(Exq, "q2", 10) {:ok, _} = Exq.enqueue(Exq, "q1", ExqTest.PerformArgWorker, [1]) {:ok, _} = Exq.enqueue(Exq, "q2", ExqTest.PerformArgWorker, [2]) assert_receive {:worked, 1} assert_receive {:worked, 2} stop_process(sup) end test "unregister queue and run job" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(queues: ["q1", "to_remove"]) :ok = Exq.unsubscribe(Exq, "to_remove") {:ok, _} = Exq.enqueue(Exq, "q1", ExqTest.PerformArgWorker, [1]) {:ok, _} = Exq.enqueue(Exq, "to_remove", ExqTest.PerformArgWorker, [2]) assert_receive {:worked, 1} refute_receive {:worked, 2} stop_process(sup) end test "unregister all queues and run jobs" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(queues: ["q1", "q2"]) :ok = Exq.unsubscribe_all(Exq) {:ok, _} = Exq.enqueue(Exq, "q1", ExqTest.PerformArgWorker, [1]) {:ok, _} = Exq.enqueue(Exq, "q2", ExqTest.PerformArgWorker, [2]) refute_receive {:worked, 1} refute_receive {:worked, 2} stop_process(sup) end test "subscriptions when empty" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(queues: []) assert {:ok, []} = Exq.subscriptions(Exq) stop_process(sup) end test "subscriptions when present" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(queues: ["q1", "q2"]) assert {:ok, ["q1", "q2"]} = Exq.subscriptions(Exq) stop_process(sup) end test "subscriptions after a new registration" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(queues: ["q1"]) :ok = Exq.subscribe(Exq, "q2") assert {:ok, ["q2", "q1"]} = Exq.subscriptions(Exq) stop_process(sup) end test "subscriptions after an unregistration" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(queues: ["q1", "to_unsubscribe"]) :ok = Exq.unsubscribe(Exq, "to_unsubscribe") assert {:ok, ["q1"]} = Exq.subscriptions(Exq) stop_process(sup) end test "throttle workers per queue" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(concurrency: 1, queues: ["q1", "q2"]) {:ok, _} = Exq.enqueue(Exq, "q1", ExqTest.SleepWorker, [40, :worked]) {:ok, _} = Exq.enqueue(Exq, "q1", ExqTest.SleepWorker, [40, :worked2]) {:ok, _} = Exq.enqueue(Exq, "q1", ExqTest.SleepWorker, [100, :finished]) # q2 should be clear {:ok, _} = Exq.enqueue(Exq, "q2", ExqTest.SleepWorker, [100, :q2_finished]) # Timing specific - we want to ensure only x amount of jobs got done :timer.sleep(160) assert_received {"worked"} assert_received {"worked2"} refute_received {"finished"} assert_received {"q2_finished"} stop_process(sup) end test "throttle workers different concurrency per queue" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(queues: [{"q1", 1}, {"q2", 20}]) {:ok, _} = Exq.enqueue(Exq, "q1", ExqTest.SleepWorker, [40, :worked]) {:ok, _} = Exq.enqueue(Exq, "q1", ExqTest.SleepWorker, [40, :worked2]) {:ok, _} = Exq.enqueue(Exq, "q1", ExqTest.SleepWorker, [100, :should_not_finish]) # q2 should be clear {:ok, _} = Exq.enqueue(Exq, "q2", ExqTest.SleepWorker, [100, :q2_work]) {:ok, _} = Exq.enqueue(Exq, "q2", ExqTest.SleepWorker, [100, :q2_work]) {:ok, _} = Exq.enqueue(Exq, "q2", ExqTest.SleepWorker, [100, :q2_work]) {:ok, _} = Exq.enqueue(Exq, "q2", ExqTest.SleepWorker, [100, :q2_finished]) :timer.sleep(150) assert_received {"worked"} assert_received {"worked2"} refute_received {"should_not_finish"} assert_received {"q2_finished"} stop_process(sup) end test "record processes" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(name: ExqP) state = :sys.get_state(ExqP) {:ok, _} = Exq.enqueue(ExqP, "default", ExqTest.SleepWorker, [100, "finished"]) wait_long() # Check that process has been recorded processes = Exq.Redis.JobStat.processes(state.redis, "test") assert Enum.count(processes) == 1 wait_long() assert_received {"finished"} # Check that process has been cleared processes = Exq.Redis.JobStat.processes(state.redis, "test") assert Enum.count(processes) == 0 {:ok, _} = Exq.enqueue(ExqP, "default", ExqTest.InvalidWorker, [100, "finished"]) wait_long() # Check that process has been recorded processes = Exq.Redis.JobStat.processes(state.redis, "test") assert Enum.count(processes) == 0 stop_process(sup) end test "clear processes on boot" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(name: ExqP) state = :sys.get_state(ExqP) {:ok, _} = Exq.enqueue(ExqP, "default", ExqTest.SleepLastWorker, [1000, "started"]) wait_long() assert_received {"started"} # Check that process has been recorded processes = Exq.Redis.JobStat.processes(state.redis, "test") assert Enum.count(processes) == 1 # Clear processes for this node host = Exq.NodeIdentifier.HostnameIdentifier.node_id() Exq.Stats.Server.cleanup_host_stats(ExqP.Stats, "test", host) # Check that process has been cleared processes = Exq.Redis.JobStat.processes(state.redis, "test") assert Enum.count(processes) == 0 stop_process(sup) end test "record processed jobs" do {:ok, sup} = Exq.start_link(name: ExqP) state = :sys.get_state(ExqP) {:ok, _} = Exq.enqueue(ExqP, "default", ExqTest.EmptyMethodWorker, []) wait_long() {:ok, count} = TestStats.processed_count(state.redis, "test") assert count == "1" {:ok, _} = Exq.enqueue(ExqP, "default", ExqTest.EmptyMethodWorker, []) wait_long() {:ok, count} = TestStats.processed_count(state.redis, "test") assert count == "2" stop_process(sup) end test "record failed jobs" do {:ok, sup} = Exq.start_link() state = :sys.get_state(Exq) {:ok, _} = Exq.enqueue(Exq, "default", "ExqTest.MissingMethodWorker/fail", []) wait_long() {:ok, count} = TestStats.failed_count(state.redis, "test") assert count == "1" {:ok, _} = Exq.enqueue(Exq, "default", ExqTest.MissingWorker, []) wait_long() {:ok, count} = TestStats.failed_count(state.redis, "test") assert count == "2" {:ok, jid} = Exq.enqueue(Exq, "default", "ExqTest.FailWorker/failure_perform", []) # if we kill Exq too fast we dont record the failure because exq is gone wait_long() stop_process(sup) {:ok, sup} = Exq.start_link(mode: :api) # Find the job in the processed queue {:ok, _} = Exq.Api.find_failed(Exq.Api, jid) wait_long() stop_process(sup) end test "waiting for workers to finish" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link([]) {:ok, _} = Exq.enqueue(Exq, "default", ExqTest.SleepWorker, [100, :one]) {:ok, _} = Exq.enqueue(Exq, "default", ExqTest.SleepWorker, [100, :two]) wait() stop_process(sup) assert_received {"one"} assert_received {"two"} end test "configure worker shutdown time" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link(shutdown_timeout: 200) {:ok, _} = Exq.enqueue(Exq, "default", ExqTest.SleepWorker, [500, :long]) {:ok, _} = Exq.enqueue(Exq, "default", ExqTest.SleepWorker, [100, :short]) wait() stop_process(sup) refute_received {"long"} assert_received {"short"} end test "handle supervisor tree shutdown properly with stats cleanup" do Process.register(self(), :exqtest) {:ok, sup} = Exq.start_link() # call worker that sends message and sleeps for a bit {:ok, _jid} = Exq.enqueue(Exq, "default", ExqTest.SleepLastWorker, [300, "worked"]) # wait until worker started assert_receive {"worked"}, 100 stop_process(sup) # Make sure everything is shut down properly assert Process.alive?(sup) == false assert Process.whereis(Exq.Manager.Server) == nil assert Process.whereis(Exq.Stats.Server) == nil assert Process.whereis(Exq.Scheduler.Server) == nil assert Process.whereis(:sleep_last_worker) == nil # Check that stats were cleaned up {:ok, sup} = Exq.start_link() assert {:ok, []} == Exq.Api.processes(Exq.Api) stop_process(sup) end test "move to dead queue" do {:ok, sup} = Exq.start_link() enqueue_fail_job(10) assert JobQueue.failed_size(:testredis, "test") == 10 stop_process(sup) end test "trim dead queue by size" do {:ok, sup} = Exq.start_link() with_application_env(:exq, :dead_max_jobs, 5, fn -> enqueue_fail_job(10) end) assert JobQueue.failed_size(:testredis, "test") == 5 stop_process(sup) end test "dead queue can be disabled" do {:ok, sup} = Exq.start_link() with_application_env(:exq, :dead_max_jobs, 0, fn -> enqueue_fail_job(10) end) assert JobQueue.failed_size(:testredis, "test") == 0 stop_process(sup) end test "trim dead queue by timeout" do {:ok, sup} = Exq.start_link() with_application_env(:exq, :dead_timeout_in_seconds, 1, fn -> enqueue_fail_job(10) assert JobQueue.failed_size(:testredis, "test") == 10 :timer.sleep(1000) enqueue_fail_job(1) end) assert JobQueue.failed_size(:testredis, "test") == 1 stop_process(sup) end defp enqueue_fail_job(count) do for _ <- 0..(count - 1) do {:ok, _} = Exq.enqueue(Exq, "default", "ExqTest.MissingMethodWorker/fail", [], max_retries: 0) end wait_long() end end
29.874494
92
0.646632
93bc6abddd2fdbd60448df9fbc4a55c881272849
1,702
ex
Elixir
clients/dataflow/lib/google_api/dataflow/v1b3/model/floating_point_mean.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/floating_point_mean.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/floating_point_mean.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # 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 &quot;AS IS&quot; 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. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Dataflow.V1b3.Model.FloatingPointMean do @moduledoc """ A representation of a floating point mean metric contribution. ## Attributes - count (SplitInt64): The number of values being aggregated. Defaults to: `null`. - sum (float()): The sum of all values being aggregated. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :count => GoogleApi.Dataflow.V1b3.Model.SplitInt64.t(), :sum => any() } field(:count, as: GoogleApi.Dataflow.V1b3.Model.SplitInt64) field(:sum) end defimpl Poison.Decoder, for: GoogleApi.Dataflow.V1b3.Model.FloatingPointMean do def decode(value, options) do GoogleApi.Dataflow.V1b3.Model.FloatingPointMean.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dataflow.V1b3.Model.FloatingPointMean do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.372549
83
0.740893
93bcdcae4d46094d3dda82517f4cd323c0bf23ec
474
exs
Elixir
test/repositories/tags_test.exs
sandisk/tentacat
523791d47d8454e87dc75cf77181b1fc78c125cf
[ "MIT" ]
432
2015-01-19T20:38:35.000Z
2022-01-11T14:32:28.000Z
test/repositories/tags_test.exs
sandisk/tentacat
523791d47d8454e87dc75cf77181b1fc78c125cf
[ "MIT" ]
183
2015-01-19T08:55:29.000Z
2022-03-01T20:26:03.000Z
test/repositories/tags_test.exs
sandisk/tentacat
523791d47d8454e87dc75cf77181b1fc78c125cf
[ "MIT" ]
189
2015-01-04T14:56:59.000Z
2021-12-14T20:48:18.000Z
defmodule Tentacat.Repositories.TagsTest do use ExUnit.Case, async: false use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney import Tentacat.Repositories.Tags doctest Tentacat.Repositories.Tags @client Tentacat.Client.new(%{access_token: "yourtokencomeshere"}) setup_all do HTTPoison.start() end test "list/3" do use_cassette "repositories/tags#list" do assert elem(list(@client, "soudqwiggle", "elixir-conspiracy"), 1) == [] end end end
23.7
77
0.725738
93bce6796d837491b0385f8826d853d475a203e7
638
ex
Elixir
lib/curator_confirmable/plug.ex
curator-ex/curator_confirmable
8b9a000cad58f48987d6fe261b7bfa3c5af1bfbf
[ "MIT" ]
null
null
null
lib/curator_confirmable/plug.ex
curator-ex/curator_confirmable
8b9a000cad58f48987d6fe261b7bfa3c5af1bfbf
[ "MIT" ]
null
null
null
lib/curator_confirmable/plug.ex
curator-ex/curator_confirmable
8b9a000cad58f48987d6fe261b7bfa3c5af1bfbf
[ "MIT" ]
null
null
null
defmodule CuratorConfirmable.Plug do @moduledoc """ """ # import Plug.Conn def init(opts \\ %{}) do opts = Enum.into(opts, %{}) %{ key: Map.get(opts, :key, Curator.default_key), } end def call(conn, opts) do key = Map.get(opts, :key) case Curator.PlugHelper.current_resource(conn, key) do nil -> conn {:error, _error} -> conn current_resource -> case CuratorConfirmable.active_for_authentication?(current_resource) do :ok -> conn {:error, error} -> Curator.PlugHelper.clear_current_resource_with_error(conn, error, key) end end end end
22.785714
99
0.617555
93bd0fd13e0fff920b46539249dbbe8925fd491a
51
ex
Elixir
web/views/page_view.ex
knathan2/dot
2e73d1339592e8d317d1b7c5acf777f86aeebe9d
[ "Apache-2.0" ]
null
null
null
web/views/page_view.ex
knathan2/dot
2e73d1339592e8d317d1b7c5acf777f86aeebe9d
[ "Apache-2.0" ]
null
null
null
web/views/page_view.ex
knathan2/dot
2e73d1339592e8d317d1b7c5acf777f86aeebe9d
[ "Apache-2.0" ]
null
null
null
defmodule Dot.PageView do use Dot.Web, :view end
12.75
25
0.745098
93bd18f9f5024c6fe4617e6b08877ca455910399
1,185
ex
Elixir
elixir/phoenix_demo/lib/phoenix_demo_web/channels/user_socket.ex
gilmoreg/learn
0c4f34387f0d2235ecd88ac62fb86a51f87eb5c2
[ "MIT" ]
null
null
null
elixir/phoenix_demo/lib/phoenix_demo_web/channels/user_socket.ex
gilmoreg/learn
0c4f34387f0d2235ecd88ac62fb86a51f87eb5c2
[ "MIT" ]
null
null
null
elixir/phoenix_demo/lib/phoenix_demo_web/channels/user_socket.ex
gilmoreg/learn
0c4f34387f0d2235ecd88ac62fb86a51f87eb5c2
[ "MIT" ]
null
null
null
defmodule PhoenixDemoWeb.UserSocket do use Phoenix.Socket ## Channels # channel "room:*", PhoenixDemoWeb.RoomChannel ## Transports transport :websocket, Phoenix.Transports.WebSocket # transport :longpoll, Phoenix.Transports.LongPoll # Socket params are passed from the client and can # be used to verify and authenticate a user. After # verification, you can put default assigns into # the socket that will be set for all channels, ie # # {:ok, assign(socket, :user_id, verified_user_id)} # # To deny connection, return `:error`. # # See `Phoenix.Token` documentation for examples in # performing token verification on connect. def connect(_params, socket) do {:ok, socket} end # Socket id's are topics that allow you to identify all sockets for a given user: # # def id(socket), do: "user_socket:#{socket.assigns.user_id}" # # Would allow you to broadcast a "disconnect" event and terminate # all active sockets and channels for a given user: # # PhoenixDemoWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. def id(_socket), do: nil end
31.184211
86
0.706329
93bd4ef7d70de70c3614a82578c11388215984b2
680
ex
Elixir
exercises/concept/stack-underflow/.meta/exemplar.ex
devtayls/elixir
67824de8209ff1b6ed2f736deedfb5bd815130ca
[ "MIT" ]
343
2017-06-22T16:28:28.000Z
2022-03-25T21:33:32.000Z
exercises/concept/stack-underflow/.meta/exemplar.ex
devtayls/elixir
67824de8209ff1b6ed2f736deedfb5bd815130ca
[ "MIT" ]
1,938
2019-12-12T08:07:10.000Z
2021-01-29T12:56:13.000Z
exercises/concept/stack-underflow/.meta/exemplar.ex
devtayls/elixir
67824de8209ff1b6ed2f736deedfb5bd815130ca
[ "MIT" ]
239
2019-12-12T14:09:08.000Z
2022-03-18T00:04:07.000Z
defmodule RPNCalculator.Exception do defmodule DivisionByZeroError do defexception message: "division by zero occurred" end defmodule StackUnderflowError do defexception message: "stack underflow occurred" @impl true def exception(value) do error = %StackUnderflowError{} case value do [] -> error _ -> %{error | message: "#{error.message}, context: #{value}"} end end end def divide(stack) when length(stack) < 2, do: raise(StackUnderflowError, "when dividing") def divide([divisor, _number | _]) when divisor == 0, do: raise(DivisionByZeroError) def divide([divisor, number | _]), do: number / divisor end
28.333333
91
0.679412
93bd5e3adae7ae90c919c204c06b5cf3283c6cbd
1,676
ex
Elixir
lib/observables/zip.ex
macoene/observables
6e43ab9b7ea2afa60160a13ef5c37eb20dc597b7
[ "MIT" ]
4
2018-04-16T20:43:37.000Z
2019-07-18T21:50:49.000Z
lib/observables/zip.ex
macoene/observables
6e43ab9b7ea2afa60160a13ef5c37eb20dc597b7
[ "MIT" ]
null
null
null
lib/observables/zip.ex
macoene/observables
6e43ab9b7ea2afa60160a13ef5c37eb20dc597b7
[ "MIT" ]
1
2021-03-18T18:37:11.000Z
2021-03-18T18:37:11.000Z
defmodule Observables.Operator.Zip do @moduledoc false use Observables.GenObservable def init([]) do Logger.debug("Zip: #{inspect(self())}") {:ok, {:left, [], :right, []}} end def handle_event(value, state) do case {value, state} do # No values at all, and got a left. {{:left, vl}, {:left, [], :right, []}} -> {:novalue, {:left, [vl], :right, []}} # No values yet, and got a right. {{:right, vr}, {:left, [], :right, []}} -> {:novalue, {:left, [], :right, [vr]}} # Already have left, now got right. {{:right, vr}, {:left, [vl | vls], :right, []}} -> {:value, {vl, vr}, {:left, vls, :right, []}} # Already have a right value, and now received left. {{:left, vl}, {:left, [], :right, [vr | vrs]}} -> {:value, {vl, vr}, {:left, [], :right, vrs}} # Already have a left, and received a left. {{:left, vln}, {:left, vls, :right, []}} -> {:novalue, {:left, vls ++ [vln], :right, []}} # Already have a right, and received a right. {{:right, vr}, {:left, [], :right, vrs}} -> {:novalue, {:left, [], :right, vrs ++ [vr]}} # Have left and right, and received a right. {{:right, vrn}, {:left, [vl | vls], :right, [vr | vrs]}} -> {:value, {vl, vr}, {:left, vls, right: vrs ++ [vrn]}} # Have left and right, and received a left. {{:left, vln}, {:left, [vl | vls], :right, [vr | vrs]}} -> {:value, {vl, vr}, {:left, vls ++ [vln], right: vrs}} end end def handle_done(_pid, _state) do Logger.debug("#{inspect(self())}: zip has one dead dependency, stopping.") {:ok, :done} end end
32.862745
78
0.50358
93bd7274c61ca1201c5d3baedec29f204639ac9c
1,453
ex
Elixir
web/router.ex
jschoch/unpolydrab
419fa9ac2e23edcc347dc96102caffaedc0beb36
[ "MIT" ]
null
null
null
web/router.ex
jschoch/unpolydrab
419fa9ac2e23edcc347dc96102caffaedc0beb36
[ "MIT" ]
null
null
null
web/router.ex
jschoch/unpolydrab
419fa9ac2e23edcc347dc96102caffaedc0beb36
[ "MIT" ]
null
null
null
defmodule DrabTestApp.Router do @moduledoc false use DrabTestApp.Web, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", DrabTestApp do pipe_through :browser # Use the default browser stack get "/", PageController, :index, as: :index get "/tests/core", PageController, :core, as: :core get "/tests/query", QueryController, :query, as: :query get "/tests/modal", QueryController, :modal, as: :modal get "/tests/waiter", PageController, :waiter, as: :waiter get "/tests/browser", PageController, :browser, as: :browser get "/tests/broadcast1", Broadcast1Controller, :index, as: :broadcast1 get "/tests/broadcast2", Broadcast2Controller, :index, as: :broadcast2 get "/tests/broadcast2/different_url", Broadcast2Controller, :index, as: :different_url get "/tests/broadcast3", Broadcast3Controller, :index, as: :broadcast3 get "/tests/broadcast4", Broadcast4Controller, :index, as: :broadcast4 get "/tests/live/mini", LiveController, :mini get "/tests/live", LiveController, :index, as: :live get "/welcome", LiveController, :welcome get "/login", LiveController, :login end # Other scopes may use custom stacks. # scope "/api", DrabTestApp do # pipe_through :api # end end
32.288889
91
0.691672
93bd97118c94e2bf32c3dc94e4367fc08555039e
1,175
ex
Elixir
lib/date_range.ex
vfsoraki/ago-times
d46a47111f6c88611c233ff31f4570789b2f6e16
[ "Apache-2.0" ]
null
null
null
lib/date_range.ex
vfsoraki/ago-times
d46a47111f6c88611c233ff31f4570789b2f6e16
[ "Apache-2.0" ]
null
null
null
lib/date_range.ex
vfsoraki/ago-times
d46a47111f6c88611c233ff31f4570789b2f6e16
[ "Apache-2.0" ]
null
null
null
defmodule DateRange do @moduledoc """ A helper library to easily create relative times, like 2 days ago. The result of functions is always a `%DateTime{}`. """ @opaque time_unit :: :seconds | :minutes | :hours | :days | :weeks @spec ago(num :: integer, unit :: time_unit) :: %DateTime{} @doc """ Create a past time, yielding a `%DateTime{}`. Example: ``` # Create a DateTime, indicating 2 days ago DateRange.ago 2, :days ``` Available units are `:seconds`, `:minutes`, `:hours`, `:days` and `:weeks`. """ def ago(num, unit) def ago(days, :days) when is_integer(days) do ago 86400 * days, :seconds end def ago(minutes, :minutes) when is_integer(minutes) do ago 60 * minutes, :seconds end def ago(seconds, :seconds) when is_integer(seconds) do System.system_time(:seconds) |> (fn time -> time - seconds end).() |> DateTime.from_unix(:seconds) |> (fn {:ok, %DateTime{} = datetime} -> datetime end).() end def ago(hours, :hours) when is_integer(hours) do ago 3600 * hours, :seconds end def ago(weeks, :weeks) when is_integer(weeks) do ago 604800 * weeks, :seconds end end
24.479167
77
0.631489
93bdc861a4fea4e29c5837b4f11f3c6229d83dab
366
ex
Elixir
lib/radiator_web/graphql/schema/middleware/require_authentication.ex
optikfluffel/radiator
b1a1b966296fa6bf123e3a2455009ff52099ace6
[ "MIT" ]
1
2021-03-02T16:59:40.000Z
2021-03-02T16:59:40.000Z
lib/radiator_web/graphql/schema/middleware/require_authentication.ex
optikfluffel/radiator
b1a1b966296fa6bf123e3a2455009ff52099ace6
[ "MIT" ]
null
null
null
lib/radiator_web/graphql/schema/middleware/require_authentication.ex
optikfluffel/radiator
b1a1b966296fa6bf123e3a2455009ff52099ace6
[ "MIT" ]
null
null
null
defmodule RadiatorWeb.GraphQL.Schema.Middleware.RequireAuthentication do @behaviour Absinthe.Middleware def call(resolution, _) do case resolution.context do %{authenticated_user: _} -> resolution _ -> resolution |> Absinthe.Resolution.put_result({:error, "Authentication: Needs authenticated user."}) end end end
24.4
96
0.693989
93be649b49357152a740e938b674478be65f9dc5
734
ex
Elixir
lib/hound/helpers.ex
manukall/hound
5a96b714b5ae0b64f9cbee3ee4955d209895b92e
[ "MIT" ]
null
null
null
lib/hound/helpers.ex
manukall/hound
5a96b714b5ae0b64f9cbee3ee4955d209895b92e
[ "MIT" ]
null
null
null
lib/hound/helpers.ex
manukall/hound
5a96b714b5ae0b64f9cbee3ee4955d209895b92e
[ "MIT" ]
null
null
null
defmodule Hound.Helpers do @moduledoc false defmacro __using__([]) do quote do import Hound import Hound.Helpers.Cookie import Hound.Helpers.Dialog import Hound.Helpers.Element import Hound.Helpers.Navigation import Hound.Helpers.Orientation import Hound.Helpers.Page import Hound.Helpers.Screenshot import Hound.Helpers.ScriptExecution import Hound.Helpers.Session import Hound.Helpers.Window import unquote(__MODULE__) end end defmacro hound_session do quote do setup do Hound.start_session parent = self on_exit fn-> Hound.end_session(parent) end :ok end end end end
20.388889
42
0.651226
93bea752ba530300862da5fb39b2debad64a9905
4,969
exs
Elixir
test/blog_web/controllers/post_controller_test.exs
itorisaias/elxpro_blog_phx
872f70a154c15976ed829c5fe6a9767ea28d67a5
[ "MIT" ]
null
null
null
test/blog_web/controllers/post_controller_test.exs
itorisaias/elxpro_blog_phx
872f70a154c15976ed829c5fe6a9767ea28d67a5
[ "MIT" ]
9
2021-08-13T02:21:40.000Z
2021-08-24T05:02:19.000Z
test/blog_web/controllers/post_controller_test.exs
itorisaias/elxpro_blog_phx
872f70a154c15976ed829c5fe6a9767ea28d67a5
[ "MIT" ]
null
null
null
defmodule BlogWeb.PostControllerTest do use BlogWeb.ConnCase alias Blog.{Accounts, Posts} @valid_post %{title: "Post 1", description: "posts 1"} @updated_post %{title: "Post 1 - new", description: "posts 1"} defp fixture(:user) do {:ok, user} = Accounts.create_user(%{ email: "itor isaias", provider: "local", token: "token-fake" }) user end defp fixture(:post) do user = fixture(:user) {:ok, post} = Posts.create_post(user, @valid_post) post end test "listar todos os post - GET /", %{conn: conn} do post = fixture(:post) conn = conn |> Plug.Test.init_test_session(user_id: post.user_id) |> get(Routes.post_path(conn, :index)) assert html_response(conn, 200) =~ "Post 1" end test "detalhe de um post - GET /posts/:id", %{conn: conn} do post = fixture(:post) conn = get(conn, Routes.post_path(conn, :show, post)) assert html_response(conn, 200) =~ "Post 1" end test "entrar no formulario de um novo post - GET /posts/new", %{conn: conn} do conn = conn |> Plug.Test.init_test_session(user_id: fixture(:user).id) |> get(Routes.post_path(conn, :new)) assert html_response(conn, 200) =~ "Criar Post" end test "entrar no formulario de um novo post sem usuario autenticado - GET /posts/new", %{ conn: conn } do conn = conn |> get(Routes.post_path(conn, :new)) assert redirected_to(conn) == Routes.page_path(conn, :index) conn = get(conn, Routes.page_path(conn, :index)) assert html_response(conn, 200) =~ "Voce precisa estar logado!!" end test "criar um novo post - POST /posts", %{conn: conn} do conn = conn |> Plug.Test.init_test_session(user_id: fixture(:user).id) |> post(Routes.post_path(conn, :create), post: @valid_post) assert %{id: id} = redirected_params(conn) assert redirected_to(conn) == Routes.post_path(conn, :show, id) conn = get(conn, Routes.post_path(conn, :show, id)) assert html_response(conn, 200) =~ "Post 1" end test "criar um novo post com valores invalidos - POST /posts", %{conn: conn} do conn = conn |> Plug.Test.init_test_session(user_id: fixture(:user).id) |> post(Routes.post_path(conn, :create), post: %{}) assert html_response(conn, 200) =~ "can&#39;t be blank" end describe "depende de um post" do setup [:criar_post] test "entrar no formulario de edit post - GET /posts/:id/edit", %{conn: conn, post: post} do conn = conn |> Plug.Test.init_test_session(user_id: fixture(:user).id) |> get(Routes.post_path(conn, :edit, post)) assert html_response(conn, 200) =~ "Post 1" assert html_response(conn, 200) =~ "Editar Post" end test "entrar no formulario de edit post com outro dono e tentar alterar post", %{ conn: conn, post: post } do {:ok, user_1} = Accounts.create_user(%{ email: "user_1", provider: "local", token: "token-fake" }) {:ok, user_2} = Accounts.create_user(%{ email: "user_2", provider: "local", token: "token-fake" }) {:ok, post} = Posts.create_post(user_1, @valid_post) conn = conn |> Plug.Test.init_test_session(user_id: user_2.id) |> get(Routes.post_path(conn, :edit, post)) assert redirected_to(conn) == Routes.page_path(conn, :index) conn = get(conn, Routes.page_path(conn, :index)) assert html_response(conn, 200) =~ "Voce não tem permissão para esta operação" end test "atualizar um novo post - PUT /posts/:id", %{conn: conn, post: post} do conn = conn |> Plug.Test.init_test_session(user_id: fixture(:user).id) |> put(Routes.post_path(conn, :update, post), post: @updated_post) assert %{id: id} = redirected_params(conn) assert redirected_to(conn) == Routes.post_path(conn, :show, id) conn = get(conn, Routes.post_path(conn, :show, id)) assert html_response(conn, 200) =~ "Post 1 - new" end test "atualizar um novo post com valores invalidos - PUT /posts/:id", %{ conn: conn, post: post } do conn = conn |> Plug.Test.init_test_session(user_id: fixture(:user).id) |> put(Routes.post_path(conn, :update, post), post: %{title: nil, description: nil}) assert html_response(conn, 200) =~ "can&#39;t be blank" end test "deletar um post - DELTE /posts/:id", %{conn: conn, post: post} do conn = conn |> Plug.Test.init_test_session(user_id: fixture(:user).id) |> delete(Routes.post_path(conn, :delete, post)) assert redirected_to(conn) == Routes.post_path(conn, :index) assert_error_sent(404, fn -> get(conn, Routes.post_path(conn, :show, post)) end) end end defp criar_post(_) do %{post: fixture(:post)} end end
29.229412
96
0.609781
93beea82116efe07a5a64f3c099bf601efc94f71
1,189
exs
Elixir
config/config.exs
gravityblast/matryoshka
f31da33b3ffab626db4bdeab84b2300a02780dc6
[ "MIT" ]
2
2019-03-03T20:32:55.000Z
2019-05-14T11:46:56.000Z
config/config.exs
gravityblast/matryoshka
f31da33b3ffab626db4bdeab84b2300a02780dc6
[ "MIT" ]
null
null
null
config/config.exs
gravityblast/matryoshka
f31da33b3ffab626db4bdeab84b2300a02780dc6
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :matryoshka, key: :value # # And access this configuration in your application as: # # Application.get_env(:matryoshka, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs" config :matryoshka, remote_root: System.get_env("REMOTE_ROOT")
34.970588
73
0.753574
93bef5e0aa484e54f3bfda3e723717381db87dcf
1,268
ex
Elixir
lib/toy_robot/parser.ex
lowski/toy-robot
107e5c68c1ba0813be9efb3949f6fde348aaa05b
[ "MIT" ]
null
null
null
lib/toy_robot/parser.ex
lowski/toy-robot
107e5c68c1ba0813be9efb3949f6fde348aaa05b
[ "MIT" ]
null
null
null
lib/toy_robot/parser.ex
lowski/toy-robot
107e5c68c1ba0813be9efb3949f6fde348aaa05b
[ "MIT" ]
null
null
null
defmodule ToyRobot.Parser do @doc """ Parse the input to turn it into commands list ## Examples iex> alias ToyRobot.Parser ToyRobot.Parser iex> input = ["PLACE 1,2,NORTH", "MOVE", "LEFT", "RIGHT", "UTURN", "REPORT"] ["PLACE 1,2,NORTH", "MOVE", "LEFT", "RIGHT", "UTURN", "REPORT"] iex> Parser.parse(input) [ {:place, %{north: 2, east: 1, facing: :north}}, :move, :turn_left, :turn_right, :uturn, :report ] """ def parse(input) do Enum.map(input, &parse_item/1) end defp parse_item("PLACE " <> _rest = command) do format = ~r/\APLACE (\d+),(\d+),(NORTH|EAST|SOUTH|WEST)\z/ case Regex.run(format, command) do [_command, east, north, facing] -> { :place, %{ north: String.to_integer(north), east: String.to_integer(east), facing: String.downcase(facing) |> String.to_atom() } } nil -> {:invalid, command} end end defp parse_item("MOVE"), do: :move defp parse_item("LEFT"), do: :turn_left defp parse_item("RIGHT"), do: :turn_right defp parse_item("UTURN"), do: :uturn defp parse_item("REPORT"), do: :report defp parse_item(input), do: {:invalid, input} end
24.862745
80
0.566246
93bf4e84a14e653285f0eda17ce287b8f9fccf8a
1,753
exs
Elixir
app/mix.exs
TomFrink/rocdev
5c4a19c2d099bd8bad3377e6e08dfc9aa7e0bcf5
[ "MIT" ]
14
2017-10-10T19:11:21.000Z
2019-04-20T20:11:01.000Z
app/mix.exs
TomFrink/rocdev
5c4a19c2d099bd8bad3377e6e08dfc9aa7e0bcf5
[ "MIT" ]
41
2017-10-08T03:07:20.000Z
2018-10-15T12:47:34.000Z
app/mix.exs
TomFrink/rocdev
5c4a19c2d099bd8bad3377e6e08dfc9aa7e0bcf5
[ "MIT" ]
7
2017-10-18T10:44:04.000Z
2019-04-15T20:44:49.000Z
defmodule Rocdev.Mixfile do use Mix.Project def project do [ app: :rocdev, version: "0.0.1", elixir: "~> 1.4", elixirc_paths: elixirc_paths(Mix.env), compilers: [:phoenix, :gettext] ++ Mix.compilers, start_permanent: Mix.env == :prod, aliases: aliases(), deps: deps() ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {Rocdev.Application, []}, extra_applications: [:logger, :runtime_tools] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:phoenix, "~> 1.3.0"}, {:phoenix_pubsub, "~> 1.0"}, {:phoenix_ecto, "~> 3.2"}, {:postgrex, ">= 0.0.0"}, {:phoenix_html, "~> 2.10"}, {:phoenix_live_reload, "~> 1.0", only: :dev}, {:gettext, "~> 0.11"}, {:cowboy, "~> 1.0"}, {:sparkpost, "~> 0.5.1"}, {:bypass, "~> 0.8.1", only: :test}, {:httpoison, "~> 0.13.0"}, {:credo, "~> 0.8", only: [:dev, :test], runtime: false} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to create, migrate and run the seeds file at once: # # $ mix ecto.setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], "test": ["ecto.create --quiet", "ecto.migrate", "test"] ] end end
26.969231
79
0.567598
93bf7ad4244db8012879d0c5fc4e39c32fb5eacd
2,704
exs
Elixir
home_page_local/config/prod.exs
tlk-emb/CMS_koji
40a93073128bfad7fdfa987c69d4a8759752064f
[ "Apache-2.0" ]
8
2019-06-02T05:02:36.000Z
2021-08-11T04:23:10.000Z
home_page_local/config/prod.exs
tlk-emb/CMS_koji
40a93073128bfad7fdfa987c69d4a8759752064f
[ "Apache-2.0" ]
7
2019-05-15T08:32:51.000Z
2020-06-10T07:46:43.000Z
home_page_local/config/prod.exs
tlk-emb/CMS_koji
40a93073128bfad7fdfa987c69d4a8759752064f
[ "Apache-2.0" ]
1
2019-06-02T05:02:47.000Z
2019-06-02T05:02:47.000Z
use Mix.Config # For production, we often load configuration from external # sources, such as your system environment. For this reason, # you won't find the :http configuration below, but set inside # HomePageWeb.Endpoint.init/2 when load_from_system_env is # true. Any dynamic configuration should be done there. # # Don't forget to configure the url host to something meaningful, # Phoenix uses this information when generating URLs. # # Finally, we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the mix phx.digest task # which you typically run after static files are built. config :home_page, HomePageWeb.Endpoint, load_from_system_env: true, http: [port: {:system, "PORT"}],#4000 url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/cache_manifest.json", version: Mix.Project.config[:version], root: "." # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :home_page, HomePageWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [:inet6, # port: 443, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH")] # # Where those two env variables return an absolute path to # the key and cert in disk or a relative path inside priv, # for example "priv/ssl/server.key". # # We also recommend setting `force_ssl`, ensuring no data is # ever sent via http, always redirecting to https: # # config :home_page, HomePageWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # ## Using releases # # If you are doing OTP releases, you need to instruct Phoenix # to start the server for all endpoints: # config :phoenix, :serve_endpoints, true # # Alternatively, you can configure exactly which server to # start per endpoint: # config :home_page, HomePageWeb.Endpoint, server: true # do the following command to generate secret_key_base:mix phx.gen.secret config :home_page, HomePageWeb.Endpoint, secret_key_base: System.get_env("SECRET_KEY_BASE") # Configure your database config :home_page, HomePage.Repo, adapter: Ecto.Adapters.MySQL, username: "admin", password: System.get_env("DATABASE_PASS"), database: System.get_env("DATABASE_NAME"), hostname: System.get_env("DATABASE_HOSTNAME"), pool_size: 20 # Finally import the config/prod.secret.exs # which should be versioned separately. #import_config "prod.secret.exs"
34.227848
73
0.731139
93bf82f4f09898dfc909ca1d38552a09f68e2870
68
exs
Elixir
test/test_helper.exs
runhyve/webapp
434b074f98c1ebac657b56062c1c1a54e683dea1
[ "BSD-2-Clause" ]
12
2019-07-02T14:30:06.000Z
2022-03-12T08:22:18.000Z
test/test_helper.exs
runhyve/webapp
434b074f98c1ebac657b56062c1c1a54e683dea1
[ "BSD-2-Clause" ]
9
2020-03-16T20:10:50.000Z
2021-06-17T17:45:44.000Z
test/test_helper.exs
runhyve/webapp
434b074f98c1ebac657b56062c1c1a54e683dea1
[ "BSD-2-Clause" ]
null
null
null
ExUnit.start() Ecto.Adapters.SQL.Sandbox.mode(Webapp.Repo, :manual)
22.666667
52
0.779412
93bf90028e1601910617ea0261c96563ef64457a
7,520
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/operation.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/operation.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/compute/lib/google_api/compute/v1/model/operation.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # 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. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Compute.V1.Model.Operation do @moduledoc """ Represents an Operation resource. Google Compute Engine has three Operation resources: * [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) * [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) * [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) You can use an operation resource to manage asynchronous API requests. For more information, read Handling API responses. Operations can be global, regional or zonal. - For global operations, use the `globalOperations` resource. - For regional operations, use the `regionOperations` resource. - For zonal operations, use the `zonalOperations` resource. For more information, read Global, Regional, and Zonal Resources. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) ## Attributes * `clientOperationId` (*type:* `String.t`, *default:* `nil`) - [Output Only] The value of `requestId` if you provided it in the request. Not present otherwise. * `creationTimestamp` (*type:* `String.t`, *default:* `nil`) - [Deprecated] This field is deprecated. * `description` (*type:* `String.t`, *default:* `nil`) - [Output Only] A textual description of the operation, which is set when the operation is created. * `endTime` (*type:* `String.t`, *default:* `nil`) - [Output Only] The time that this operation was completed. This value is in RFC3339 text format. * `error` (*type:* `GoogleApi.Compute.V1.Model.OperationError.t`, *default:* `nil`) - [Output Only] If errors are generated during processing of the operation, this field will be populated. * `httpErrorMessage` (*type:* `String.t`, *default:* `nil`) - [Output Only] If the operation fails, this field contains the HTTP error message that was returned, such as `NOT FOUND`. * `httpErrorStatusCode` (*type:* `integer()`, *default:* `nil`) - [Output Only] If the operation fails, this field contains the HTTP error status code that was returned. For example, a `404` means the resource was not found. * `id` (*type:* `String.t`, *default:* `nil`) - [Output Only] The unique identifier for the operation. This identifier is defined by the server. * `insertTime` (*type:* `String.t`, *default:* `nil`) - [Output Only] The time that this operation was requested. This value is in RFC3339 text format. * `kind` (*type:* `String.t`, *default:* `compute#operation`) - [Output Only] Type of the resource. Always `compute#operation` for Operation resources. * `name` (*type:* `String.t`, *default:* `nil`) - [Output Only] Name of the operation. * `operationType` (*type:* `String.t`, *default:* `nil`) - [Output Only] The type of operation, such as `insert`, `update`, or `delete`, and so on. * `progress` (*type:* `integer()`, *default:* `nil`) - [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement that this be linear or support any granularity of operations. This should not be used to guess when the operation will be complete. This number should monotonically increase as the operation progresses. * `region` (*type:* `String.t`, *default:* `nil`) - [Output Only] The URL of the region where the operation resides. Only applicable when performing regional operations. * `selfLink` (*type:* `String.t`, *default:* `nil`) - [Output Only] Server-defined URL for the resource. * `startTime` (*type:* `String.t`, *default:* `nil`) - [Output Only] The time that this operation was started by the server. This value is in RFC3339 text format. * `status` (*type:* `String.t`, *default:* `nil`) - [Output Only] The status of the operation, which can be one of the following: `PENDING`, `RUNNING`, or `DONE`. * `statusMessage` (*type:* `String.t`, *default:* `nil`) - [Output Only] An optional textual description of the current status of the operation. * `targetId` (*type:* `String.t`, *default:* `nil`) - [Output Only] The unique target ID, which identifies a specific incarnation of the target resource. * `targetLink` (*type:* `String.t`, *default:* `nil`) - [Output Only] The URL of the resource that the operation modifies. For operations related to creating a snapshot, this points to the persistent disk that the snapshot was created from. * `user` (*type:* `String.t`, *default:* `nil`) - [Output Only] User who requested the operation, for example: `user@example.com`. * `warnings` (*type:* `list(GoogleApi.Compute.V1.Model.OperationWarnings.t)`, *default:* `nil`) - [Output Only] If warning messages are generated during processing of the operation, this field will be populated. * `zone` (*type:* `String.t`, *default:* `nil`) - [Output Only] The URL of the zone where the operation resides. Only applicable when performing per-zone operations. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :clientOperationId => String.t(), :creationTimestamp => String.t(), :description => String.t(), :endTime => String.t(), :error => GoogleApi.Compute.V1.Model.OperationError.t(), :httpErrorMessage => String.t(), :httpErrorStatusCode => integer(), :id => String.t(), :insertTime => String.t(), :kind => String.t(), :name => String.t(), :operationType => String.t(), :progress => integer(), :region => String.t(), :selfLink => String.t(), :startTime => String.t(), :status => String.t(), :statusMessage => String.t(), :targetId => String.t(), :targetLink => String.t(), :user => String.t(), :warnings => list(GoogleApi.Compute.V1.Model.OperationWarnings.t()), :zone => String.t() } field(:clientOperationId) field(:creationTimestamp) field(:description) field(:endTime) field(:error, as: GoogleApi.Compute.V1.Model.OperationError) field(:httpErrorMessage) field(:httpErrorStatusCode) field(:id) field(:insertTime) field(:kind) field(:name) field(:operationType) field(:progress) field(:region) field(:selfLink) field(:startTime) field(:status) field(:statusMessage) field(:targetId) field(:targetLink) field(:user) field(:warnings, as: GoogleApi.Compute.V1.Model.OperationWarnings, type: :list) field(:zone) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.Operation do def decode(value, options) do GoogleApi.Compute.V1.Model.Operation.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.Operation do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
59.68254
357
0.68883
93bffd69c86c3702489bd9517704f24b41f76717
4,560
ex
Elixir
lib/panda_doc/request_builder.ex
fbettag/pandadoc.ex
4f7542f8e549e4feeed8e6ea2f76b014ef647d5d
[ "MIT" ]
null
null
null
lib/panda_doc/request_builder.ex
fbettag/pandadoc.ex
4f7542f8e549e4feeed8e6ea2f76b014ef647d5d
[ "MIT" ]
null
null
null
lib/panda_doc/request_builder.ex
fbettag/pandadoc.ex
4f7542f8e549e4feeed8e6ea2f76b014ef647d5d
[ "MIT" ]
null
null
null
defmodule PandaDoc.RequestBuilder do @moduledoc """ Helper functions for building Tesla requests """ @doc """ Specify the request method when building a request ## Parameters - request (Map) - Collected request options - m (atom) - Request method ## Returns Map """ @spec method(map(), atom) :: map() def method(request, m) do Map.put_new(request, :method, m) end @doc """ Specify the request method when building a request ## Parameters - request (Map) - Collected request options - u (String) - Request URL ## Returns Map """ @spec url(map(), String.t()) :: map() def url(request, u) do Map.put_new(request, :url, u) end @doc """ Add optional parameters to the request ## Parameters - request (Map) - Collected request options - definitions (Map) - Map of parameter name to parameter location. - options (KeywordList) - The provided optional parameters ## Returns Map """ @spec add_optional_params(map(), %{optional(atom) => atom}, keyword()) :: map() def add_optional_params(request, _, []), do: request def add_optional_params(request, definitions, [{key, value} | tail]) do case definitions do %{^key => location} -> request |> add_param(location, key, value) |> add_optional_params(definitions, tail) _ -> add_optional_params(request, definitions, tail) end end @doc """ Add optional parameters to the request ## Parameters - request (Map) - Collected request options - location (atom) - Where to put the parameter - key (atom) - The name of the parameter - value (any) - The value of the parameter ## Returns Map """ @spec add_param(map(), atom, atom, any()) :: map() def add_param(request, :body, :body, value), do: Map.put(request, :body, value) def add_param(request, :body, key, value) do request |> Map.put_new_lazy(:body, &Tesla.Multipart.new/0) |> Map.update!( :body, &Tesla.Multipart.add_field(&1, key, Poison.encode!(value), headers: [{"content-type", "application/json"}] ) ) end def add_param(request, :headers, key, value) do request |> Tesla.put_header(key, value) end def add_param(request, :file, name, path) do request |> Map.put_new_lazy(:body, &Tesla.Multipart.new/0) |> Map.update!(:body, &Tesla.Multipart.add_file(&1, path, name: name)) end def add_param(request, :form, name, value) do request |> Map.update(:body, %{name => value}, &Map.put(&1, name, value)) end def add_param(request, location, key, value) do Map.update(request, location, [{key, value}], &(&1 ++ [{key, value}])) end @doc """ Handle the response for a Tesla request ## Parameters - arg1 (Tesla.Env.t | term) - The response object - arg2 (:false | struct | [struct]) - The shape of the struct to deserialize into ## Returns `{:ok, struct()}` on success `{:ok, Tesla.Env.t()}` on failure `{:error, term}` on failure """ @spec decode(Tesla.Env.t() | term(), false | struct() | [struct()]) :: {:ok, struct()} | {:ok, Tesla.Env.t()} | {:error, any} def decode(%Tesla.Env{} = env, false), do: {:ok, env} def decode(%Tesla.Env{}, :ok), do: :ok def decode(%Tesla.Env{body: body}, :bytes), do: {:ok, body} def decode(%Tesla.Env{body: body}, struct), do: Poison.decode(body, as: struct) @doc """ Evaluates the Tesla response ## Parameters - arg1 {:atom, Tesla.Env.t} - The response object - arg2 list - List of Tuples matching something like [{200, %Model.ErrorResponse{}}] ## Returns `{:ok, struct}` on success `{:ok, Tesla.Env.t()}` on failure `{:error, term}` on failure """ @spec evaluate_response({:error, any()} | {:atom, Tesla.Env.t()}, list()) :: {:ok, struct()} | {:ok, Tesla.Env.t()} | {:error, any} def evaluate_response({:ok, %Tesla.Env{} = env}, mapping) do resolve_mapping(env, mapping) end def evaluate_response({:error, _} = error, _), do: error defp resolve_mapping(env, mapping, default \\ nil) defp resolve_mapping(%Tesla.Env{status: status} = env, [{mapping_status, struct} | _], _) when status == mapping_status do decode(env, struct) end defp resolve_mapping(env, [{:default, struct} | tail], _), do: resolve_mapping(env, tail, struct) defp resolve_mapping(env, [_ | tail], struct), do: resolve_mapping(env, tail, struct) defp resolve_mapping(env, [], nil), do: {:error, env} defp resolve_mapping(env, [], struct), do: decode(env, struct) end
26.358382
91
0.628947
93bfff3811fa62a0e82b0158c33788d61011b1f1
1,016
exs
Elixir
WorkingWithMultipleProcesses/14.3.exs
miguelcoba/ProgrammingElixir
c3aee9151ab2346fbd31a5411c473b1a4e626e36
[ "MIT" ]
2
2015-11-14T21:35:01.000Z
2017-07-12T07:09:40.000Z
WorkingWithMultipleProcesses/14.3.exs
miguelcoba/ProgrammingElixir
c3aee9151ab2346fbd31a5411c473b1a4e626e36
[ "MIT" ]
null
null
null
WorkingWithMultipleProcesses/14.3.exs
miguelcoba/ProgrammingElixir
c3aee9151ab2346fbd31a5411c473b1a4e626e36
[ "MIT" ]
null
null
null
defmodule LinkedMessage do import :timer, only: [sleep: 1] def sad_function(parent_pid) do send parent_pid, "bye bye!" exit(:boom) end def receive_messages do receive do msg -> IO.puts "MESSAGE_RECEIVED: #{inspect msg}" receive_messages after 1000 -> IO.puts "Nothing happened as far as I am concerned" end end def run do Process.flag(:trap_exit, true) spawn_link(LinkedMessage, :sad_function, [self]) sleep 500 receive_messages end end LinkedMessage.run # Without the Process.flag(:trap_exit, true) line, the exit(:boom) of # the child immediatly kills the parent and no message is received by parent # With the Process.flag(:trap_exit, true) line, the exit(:boom) of # the child is correctly received by the parent. Additionally the :exit # message is also received by the parent # Does it matter that you weren’t waiting for the notification from the # child when it exited? No, it doesn't matter. As they are linked the # exiting of the child killed the parent too
27.459459
76
0.737205
93c0382d5de2b98beb281982e785938e47bc63a1
1,552
ex
Elixir
apps/red_robin_web/lib/red_robin_web/views/error_helpers.ex
3zcurdia/red_robin
a4aa6870d6bde05c95d375913311ecb392f7c44c
[ "MIT" ]
null
null
null
apps/red_robin_web/lib/red_robin_web/views/error_helpers.ex
3zcurdia/red_robin
a4aa6870d6bde05c95d375913311ecb392f7c44c
[ "MIT" ]
null
null
null
apps/red_robin_web/lib/red_robin_web/views/error_helpers.ex
3zcurdia/red_robin
a4aa6870d6bde05c95d375913311ecb392f7c44c
[ "MIT" ]
null
null
null
defmodule RedRobinWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "invalid-feedback", phx_feedback_for: input_name(form, field) ) end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate "is invalid" in the "errors" domain # dgettext("errors", "is invalid") # # # Translate the number of files with plural rules # dngettext("errors", "1 file", "%{count} files", count) # # Because the error messages we show in our forms and APIs # are defined inside Ecto, we need to translate them dynamically. # This requires us to call the Gettext module passing our gettext # backend as first argument. # # Note we use the "errors" domain, which means translations # should be written to the errors.po file. The :count option is # set by Ecto and indicates we should also apply plural rules. if count = opts[:count] do Gettext.dngettext(RedRobinWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(RedRobinWeb.Gettext, "errors", msg, opts) end end end
32.333333
77
0.666237
93c04ea49a798e472cc046231051a924b50f793d
12,326
ex
Elixir
lib/elixir_ex_aliyun_ots_table_store_row_in_batch_write_row_response.ex
hou8/tablestore_protos
1a3223326b92bbe196d57ce4dd19b5a8db1c728d
[ "MIT" ]
null
null
null
lib/elixir_ex_aliyun_ots_table_store_row_in_batch_write_row_response.ex
hou8/tablestore_protos
1a3223326b92bbe196d57ce4dd19b5a8db1c728d
[ "MIT" ]
1
2022-02-08T06:37:02.000Z
2022-02-08T06:37:02.000Z
lib/elixir_ex_aliyun_ots_table_store_row_in_batch_write_row_response.ex
hou8/tablestore_protos
1a3223326b92bbe196d57ce4dd19b5a8db1c728d
[ "MIT" ]
2
2022-01-24T06:13:03.000Z
2022-01-24T08:33:41.000Z
# credo:disable-for-this-file defmodule(ExAliyunOts.TableStore.RowInBatchWriteRowResponse) do @moduledoc false ( defstruct(is_ok: nil, error: nil, consumed: nil, row: nil) ( ( @spec encode(struct) :: {:ok, iodata} | {:error, any} def(encode(msg)) do try do {:ok, encode!(msg)} rescue e in [Protox.EncodingError, Protox.RequiredFieldsError] -> {:error, e} end end @spec encode!(struct) :: iodata | no_return def(encode!(msg)) do [] |> encode_is_ok(msg) |> encode_error(msg) |> encode_consumed(msg) |> encode_row(msg) end ) [] [ defp(encode_is_ok(acc, msg)) do try do case(msg.is_ok) do nil -> raise(Protox.RequiredFieldsError.new([:is_ok])) _ -> [acc, "\b", Protox.Encode.encode_bool(msg.is_ok)] end rescue ArgumentError -> reraise(Protox.EncodingError.new(:is_ok, "invalid field value"), __STACKTRACE__) end end, defp(encode_error(acc, msg)) do try do case(msg.error) do nil -> acc _ -> [acc, <<18>>, Protox.Encode.encode_message(msg.error)] end rescue ArgumentError -> reraise(Protox.EncodingError.new(:error, "invalid field value"), __STACKTRACE__) end end, defp(encode_consumed(acc, msg)) do try do case(msg.consumed) do nil -> acc _ -> [acc, <<26>>, Protox.Encode.encode_message(msg.consumed)] end rescue ArgumentError -> reraise(Protox.EncodingError.new(:consumed, "invalid field value"), __STACKTRACE__) end end, defp(encode_row(acc, msg)) do try do case(msg.row) do nil -> acc _ -> [acc, "\"", Protox.Encode.encode_bytes(msg.row)] end rescue ArgumentError -> reraise(Protox.EncodingError.new(:row, "invalid field value"), __STACKTRACE__) end end ] [] ) ( ( @spec decode(binary) :: {:ok, struct} | {:error, any} def(decode(bytes)) do try do {:ok, decode!(bytes)} rescue e in [Protox.DecodingError, Protox.IllegalTagError, Protox.RequiredFieldsError] -> {:error, e} end end ( @spec decode!(binary) :: struct | no_return def(decode!(bytes)) do {msg, set_fields} = parse_key_value( [], bytes, struct(ExAliyunOts.TableStore.RowInBatchWriteRowResponse) ) case([:is_ok] -- set_fields) do [] -> msg missing_fields -> raise(Protox.RequiredFieldsError.new(missing_fields)) end end ) ) ( @spec parse_key_value([atom], binary, struct) :: {struct, [atom]} defp(parse_key_value(set_fields, <<>>, msg)) do {msg, set_fields} end defp(parse_key_value(set_fields, bytes, msg)) do {new_set_fields, field, rest} = case(Protox.Decode.parse_key(bytes)) do {0, _, _} -> raise(%Protox.IllegalTagError{}) {1, _, bytes} -> {value, rest} = Protox.Decode.parse_bool(bytes) {[:is_ok | set_fields], [is_ok: value], rest} {2, _, bytes} -> {len, bytes} = Protox.Varint.decode(bytes) {delimited, rest} = Protox.Decode.parse_delimited(bytes, len) {[:error | set_fields], [ error: Protox.MergeMessage.merge( msg.error, ExAliyunOts.TableStore.Error.decode!(delimited) ) ], rest} {3, _, bytes} -> {len, bytes} = Protox.Varint.decode(bytes) {delimited, rest} = Protox.Decode.parse_delimited(bytes, len) {[:consumed | set_fields], [ consumed: Protox.MergeMessage.merge( msg.consumed, ExAliyunOts.TableStore.ConsumedCapacity.decode!(delimited) ) ], rest} {4, _, bytes} -> {len, bytes} = Protox.Varint.decode(bytes) {delimited, rest} = Protox.Decode.parse_delimited(bytes, len) {[:row | set_fields], [row: delimited], rest} {tag, wire_type, rest} -> {_, rest} = Protox.Decode.parse_unknown(tag, wire_type, rest) {set_fields, [], rest} end msg_updated = struct(msg, field) parse_key_value(new_set_fields, rest, msg_updated) end ) [] ) ( @spec json_decode(iodata(), keyword()) :: {:ok, struct()} | {:error, any()} def(json_decode(input, opts \\ [])) do try do {:ok, json_decode!(input, opts)} rescue e in Protox.JsonDecodingError -> {:error, e} end end @spec json_decode!(iodata(), keyword()) :: struct() | no_return() def(json_decode!(input, opts \\ [])) do {json_library_wrapper, json_library} = Protox.JsonLibrary.get_library(opts, :decode) Protox.JsonDecode.decode!( input, ExAliyunOts.TableStore.RowInBatchWriteRowResponse, &json_library_wrapper.decode!(json_library, &1) ) end @spec json_encode(struct(), keyword()) :: {:ok, iodata()} | {:error, any()} def(json_encode(msg, opts \\ [])) do try do {:ok, json_encode!(msg, opts)} rescue e in Protox.JsonEncodingError -> {:error, e} end end @spec json_encode!(struct(), keyword()) :: iodata() | no_return() def(json_encode!(msg, opts \\ [])) do {json_library_wrapper, json_library} = Protox.JsonLibrary.get_library(opts, :encode) Protox.JsonEncode.encode!(msg, &json_library_wrapper.encode!(json_library, &1)) end ) @deprecated "Use fields_defs()/0 instead" @spec defs() :: %{ required(non_neg_integer) => {atom, Protox.Types.kind(), Protox.Types.type()} } def(defs()) do %{ 1 => {:is_ok, {:scalar, false}, :bool}, 2 => {:error, {:scalar, nil}, {:message, ExAliyunOts.TableStore.Error}}, 3 => {:consumed, {:scalar, nil}, {:message, ExAliyunOts.TableStore.ConsumedCapacity}}, 4 => {:row, {:scalar, ""}, :bytes} } end @deprecated "Use fields_defs()/0 instead" @spec defs_by_name() :: %{ required(atom) => {non_neg_integer, Protox.Types.kind(), Protox.Types.type()} } def(defs_by_name()) do %{ consumed: {3, {:scalar, nil}, {:message, ExAliyunOts.TableStore.ConsumedCapacity}}, error: {2, {:scalar, nil}, {:message, ExAliyunOts.TableStore.Error}}, is_ok: {1, {:scalar, false}, :bool}, row: {4, {:scalar, ""}, :bytes} } end @spec fields_defs() :: list(Protox.Field.t()) def(fields_defs()) do [ %{ __struct__: Protox.Field, json_name: "isOk", kind: {:scalar, false}, label: :required, name: :is_ok, tag: 1, type: :bool }, %{ __struct__: Protox.Field, json_name: "error", kind: {:scalar, nil}, label: :optional, name: :error, tag: 2, type: {:message, ExAliyunOts.TableStore.Error} }, %{ __struct__: Protox.Field, json_name: "consumed", kind: {:scalar, nil}, label: :optional, name: :consumed, tag: 3, type: {:message, ExAliyunOts.TableStore.ConsumedCapacity} }, %{ __struct__: Protox.Field, json_name: "row", kind: {:scalar, ""}, label: :optional, name: :row, tag: 4, type: :bytes } ] end [ @spec(field_def(atom) :: {:ok, Protox.Field.t()} | {:error, :no_such_field}), ( def(field_def(:is_ok)) do {:ok, %{ __struct__: Protox.Field, json_name: "isOk", kind: {:scalar, false}, label: :required, name: :is_ok, tag: 1, type: :bool }} end def(field_def("isOk")) do {:ok, %{ __struct__: Protox.Field, json_name: "isOk", kind: {:scalar, false}, label: :required, name: :is_ok, tag: 1, type: :bool }} end def(field_def("is_ok")) do {:ok, %{ __struct__: Protox.Field, json_name: "isOk", kind: {:scalar, false}, label: :required, name: :is_ok, tag: 1, type: :bool }} end ), ( def(field_def(:error)) do {:ok, %{ __struct__: Protox.Field, json_name: "error", kind: {:scalar, nil}, label: :optional, name: :error, tag: 2, type: {:message, ExAliyunOts.TableStore.Error} }} end def(field_def("error")) do {:ok, %{ __struct__: Protox.Field, json_name: "error", kind: {:scalar, nil}, label: :optional, name: :error, tag: 2, type: {:message, ExAliyunOts.TableStore.Error} }} end [] ), ( def(field_def(:consumed)) do {:ok, %{ __struct__: Protox.Field, json_name: "consumed", kind: {:scalar, nil}, label: :optional, name: :consumed, tag: 3, type: {:message, ExAliyunOts.TableStore.ConsumedCapacity} }} end def(field_def("consumed")) do {:ok, %{ __struct__: Protox.Field, json_name: "consumed", kind: {:scalar, nil}, label: :optional, name: :consumed, tag: 3, type: {:message, ExAliyunOts.TableStore.ConsumedCapacity} }} end [] ), ( def(field_def(:row)) do {:ok, %{ __struct__: Protox.Field, json_name: "row", kind: {:scalar, ""}, label: :optional, name: :row, tag: 4, type: :bytes }} end def(field_def("row")) do {:ok, %{ __struct__: Protox.Field, json_name: "row", kind: {:scalar, ""}, label: :optional, name: :row, tag: 4, type: :bytes }} end [] ), def(field_def(_)) do {:error, :no_such_field} end ] [] @spec required_fields() :: [:is_ok] def(required_fields()) do [:is_ok] end @spec syntax() :: atom def(syntax()) do :proto2 end [ @spec(default(atom) :: {:ok, boolean | integer | String.t() | float} | {:error, atom}), def(default(:is_ok)) do {:ok, false} end, def(default(:error)) do {:ok, nil} end, def(default(:consumed)) do {:ok, nil} end, def(default(:row)) do {:ok, ""} end, def(default(_)) do {:error, :no_such_field} end ] ) end
27.209713
97
0.455217
93c05c9f816a4e838c9f28806a7c83ad4e5f711d
1,465
exs
Elixir
test/doctor_schedule_web/controllers/api/session_controller_test.exs
adrianomota/doctor_schedule
626eef47df8f1ff082c7a7d76342cb9c361c75a2
[ "MIT" ]
null
null
null
test/doctor_schedule_web/controllers/api/session_controller_test.exs
adrianomota/doctor_schedule
626eef47df8f1ff082c7a7d76342cb9c361c75a2
[ "MIT" ]
null
null
null
test/doctor_schedule_web/controllers/api/session_controller_test.exs
adrianomota/doctor_schedule
626eef47df8f1ff082c7a7d76342cb9c361c75a2
[ "MIT" ]
null
null
null
defmodule DoctorScheduleWeb.Api.SessionControllerTest do use DoctorScheduleWeb.ConnCase import DoctorScheduleWeb.Auth.Guardian import DoctorSchedule.Factory alias DoctorSchedule.Accounts setup %{conn: conn} do {:ok, user} = build(:user) |> Accounts.create_user() {:ok, token, _} = encode_and_sign(user, %{}, token_type: :access) conn = conn |> put_req_header("accept", "application/json") |> put_req_header("authorization", "bearer " <> token) {:ok, conn: conn} end describe "sessions" do setup [:create_user] test "should authenticate with valid user", %{conn: conn, user: user} do conn = conn |> post(Routes.api_session_path(conn, :create), %{ email: user.email, password: "123456" }) assert json_response(conn, 201)["user"]["data"]["email"] == user.email end test "should not authenticate with invalid user", %{conn: conn, user: user} do conn = conn |> post(Routes.api_session_path(conn, :create), %{ email: user.email, password: "123456789" }) assert json_response(conn, 401) == "Unauthorized" end end defp create_user(_) do {:ok, user} = build(:user, %{ email: "user_logged@doctor_schedule.com", password: "123456", password_confirmation: "123456" }) |> Accounts.create_user() %{user: user} end end
23.629032
82
0.60273
93c06daf6c9850c2bac5f37bb7c76297e9f99806
1,829
exs
Elixir
clients/dataproc/mix.exs
Doerge/elixir-google-api
673cc7c78118684f969b8e2d62d03a273f04ad1b
[ "Apache-2.0" ]
null
null
null
clients/dataproc/mix.exs
Doerge/elixir-google-api
673cc7c78118684f969b8e2d62d03a273f04ad1b
[ "Apache-2.0" ]
null
null
null
clients/dataproc/mix.exs
Doerge/elixir-google-api
673cc7c78118684f969b8e2d62d03a273f04ad1b
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # 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. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Dataproc.Mixfile do use Mix.Project @version "0.31.1" def project() do [ app: :google_api_dataproc, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/dataproc" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.2"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Cloud Dataproc API client library. Manages Hadoop-based clusters and jobs on Google Cloud Platform. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/dataproc", "Homepage" => "https://cloud.google.com/dataproc/" } ] end end
27.298507
103
0.653909
93c077a3484ebbbbeefaa7434acabbbd17a69096
42
exs
Elixir
test/ke_test.exs
mantlecurve/kerala-election-2020
b6c1c9efeea0c37e85cf27bb8fa83cbb8aa1987b
[ "MIT" ]
1
2020-12-18T11:56:47.000Z
2020-12-18T11:56:47.000Z
test/ke_test.exs
mantlecurve/kerala-election-2020
b6c1c9efeea0c37e85cf27bb8fa83cbb8aa1987b
[ "MIT" ]
1
2020-12-18T07:38:57.000Z
2020-12-18T07:38:57.000Z
test/ke_test.exs
mantlecurve/kerala-election-2020
b6c1c9efeea0c37e85cf27bb8fa83cbb8aa1987b
[ "MIT" ]
1
2020-12-18T07:17:09.000Z
2020-12-18T07:17:09.000Z
defmodule KeTest do use ExUnit.Case end
10.5
19
0.785714
93c0805e7260105dbe3b5e11dbe8f5c3ed5262dc
568
exs
Elixir
test/chat_web/views/error_view_test.exs
Zesky665/GradProject
dad0152de7be505338b1ddbbfcfa82fafe613b68
[ "Unlicense" ]
1
2017-09-05T18:43:38.000Z
2017-09-05T18:43:38.000Z
test/chat_web/views/error_view_test.exs
reubenwainaina/phoenix-chat
255aa474ccebf731db2a9361d62b45a0dd6063f7
[ "MIT" ]
null
null
null
test/chat_web/views/error_view_test.exs
reubenwainaina/phoenix-chat
255aa474ccebf731db2a9361d62b45a0dd6063f7
[ "MIT" ]
1
2019-03-31T10:59:53.000Z
2019-03-31T10:59:53.000Z
defmodule ChatWeb.ErrorViewTest do use ChatWeb.ConnCase, async: true # Bring render/3 and render_to_string/3 for testing custom views import Phoenix.View test "renders 404.html" do assert render_to_string(ChatWeb.ErrorView, "404.html", []) == "Page not found" end test "render 500.html" do assert render_to_string(ChatWeb.ErrorView, "500.html", []) == "Internal server error" end test "render any other" do assert render_to_string(ChatWeb.ErrorView, "505.html", []) == "Internal server error" end end
25.818182
66
0.676056
93c09428a75750cf780be171e5f5fa01f2d0e30f
1,836
exs
Elixir
test/ja_serializer/serializer_test.exs
tompesman/ja_serializer
2b4aafece514add516784a6a81f7d6c724df8ac2
[ "Apache-2.0" ]
null
null
null
test/ja_serializer/serializer_test.exs
tompesman/ja_serializer
2b4aafece514add516784a6a81f7d6c724df8ac2
[ "Apache-2.0" ]
null
null
null
test/ja_serializer/serializer_test.exs
tompesman/ja_serializer
2b4aafece514add516784a6a81f7d6c724df8ac2
[ "Apache-2.0" ]
null
null
null
defmodule JaSerializer.SerializerTest do use ExUnit.Case defmodule ArticleSerializer do use JaSerializer attributes [:title] attributes [:body] has_many :comments end defmodule ArticleView do use JaSerializer attributes [:title, :body] has_many :comments def attributes(article, conn) do super(article, conn) |> Map.take([:title]) end def comments(_a, _c), do: [:bar] end defmodule CustomArticle do use JaSerializer def type, do: "article" def attributes(article, _conn) do Map.take(article, [:body]) end end @serializer ArticleSerializer @view ArticleView @custom CustomArticle test "it should determine the type" do assert @serializer.type == "article" assert @view.type == "article" assert @custom.type == "article" end test "it should return the attributes" do article = %TestModel.Article{title: "test", body: "test"} assert @serializer.attributes(article, %{}) == %{ title: "test", body: "test" } assert @view.attributes(article, %{}) == %{title: "test"} assert @custom.attributes(article, %{}) == %{body: "test"} end test "has_many should define an overridable relationship data function" do article = %TestModel.Article{title: "test", body: "test", comments: [:foo]} assert @serializer.comments(article, %{}) == [:foo] assert @view.comments(article, %{}) == [:bar] end test "it should pluralize the type when declared in config" do Application.put_env(:ja_serializer, :pluralize_types, true) defmodule NewArticleSerializer do use JaSerializer attributes [:title, :body] has_many :comments end assert NewArticleSerializer.type() == "new-articles" Application.delete_env(:ja_serlializer, :pluralized_types) end end
24.48
79
0.666667
93c096c27ff5a6920ea01b5d048cb5e56b834004
136
exs
Elixir
config/test.exs
rijavskii/ex_ari
1fd5eabd9b4cb815e260867b0190a7fe635ee38a
[ "MIT" ]
13
2020-04-17T16:48:00.000Z
2022-03-25T19:16:51.000Z
config/test.exs
rijavskii/ex_ari
1fd5eabd9b4cb815e260867b0190a7fe635ee38a
[ "MIT" ]
1
2020-04-02T12:18:59.000Z
2020-04-02T12:18:59.000Z
config/test.exs
rijavskii/ex_ari
1fd5eabd9b4cb815e260867b0190a7fe635ee38a
[ "MIT" ]
7
2020-04-28T19:45:50.000Z
2022-03-25T21:42:03.000Z
use Mix.Config config :ex_ari, clients: %{ ari_test: %{ name: "test", module: ARI.WebSocketTest.TestClient } }
13.6
42
0.580882
93c0c15a9a3f8e9f56e5d4be764278ad172bcc2f
1,940
ex
Elixir
lib/glimesh/payments/subscription.ex
Darkhax-Forked/glimesh.tv
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
[ "MIT" ]
null
null
null
lib/glimesh/payments/subscription.ex
Darkhax-Forked/glimesh.tv
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
[ "MIT" ]
null
null
null
lib/glimesh/payments/subscription.ex
Darkhax-Forked/glimesh.tv
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
[ "MIT" ]
null
null
null
defmodule Glimesh.Payments.Subscription do @moduledoc false use Ecto.Schema import Ecto.Changeset @derive {Jason.Encoder, only: [ :stripe_subscription_id, :stripe_product_id, :stripe_price_id, :stripe_current_period_end, :price, :product_name, :is_active, :started_at, :ended_at ]} schema "subscriptions" do belongs_to :user, Glimesh.Accounts.User belongs_to :streamer, Glimesh.Accounts.User field :stripe_subscription_id, :string field :stripe_product_id, :string field :stripe_price_id, :string field :stripe_current_period_end, :integer field :price, :integer field :product_name, :string field :is_active, :boolean field :started_at, :naive_datetime field :ended_at, :naive_datetime timestamps() end @doc false def create_changeset(subscription, attrs) do subscription |> cast(attrs, [ :stripe_subscription_id, :stripe_product_id, :stripe_price_id, :stripe_current_period_end, :price, :product_name, :started_at, :ended_at, :is_active ]) |> put_assoc(:user, attrs.user) |> maybe_put_assoc(:streamer, Map.get(attrs, :streamer, nil)) |> validate_required([ :user, :stripe_subscription_id, :stripe_product_id, :stripe_price_id, :stripe_current_period_end, :price, :product_name, :started_at, :ended_at ]) end @doc false def update_changeset(subscription, attrs) do subscription |> cast(attrs, [:stripe_current_period_end, :ended_at, :is_active]) |> validate_required([:stripe_current_period_end, :ended_at, :is_active]) end def maybe_put_assoc(changeset, key, value) do if value do changeset |> put_assoc(key, value) else changeset end end end
23.950617
77
0.636082
93c0e6ee7c8ca3b5957ce289e07f72e599dcb8d3
1,675
exs
Elixir
test/crit_biz/view_models/setup/bulk_procedure_vm_4_insert_all_test.exs
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
6
2019-07-16T19:31:23.000Z
2021-06-05T19:01:05.000Z
test/crit_biz/view_models/setup/bulk_procedure_vm_4_insert_all_test.exs
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
null
null
null
test/crit_biz/view_models/setup/bulk_procedure_vm_4_insert_all_test.exs
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
3
2020-02-24T23:38:27.000Z
2020-08-01T23:50:17.000Z
defmodule CritBiz.ViewModels.Setup.BulkProcedureVM.InsertAllTest do use Crit.DataCase, async: true alias CritBiz.ViewModels.Setup, as: VM alias Crit.Schemas setup do procedure = Factory.build(:procedure, name: "Embryo transfer", frequency_id: @once_per_week_frequency_id, species_id: @bovine_id) [procedure: procedure] end describe "success" do test "what the on-disk version looks like", %{procedure: procedure} do {:ok, [%{id: id}]} = VM.BulkProcedure.insert_all([procedure], @institution) Schemas.Procedure.Get.one_by_id(id, @institution) |> assert_same_schema(procedure, ignoring: [:id]) end test "what the returned view models look like", %{procedure: procedure} do {:ok, [view_model]} = VM.BulkProcedure.insert_all([procedure], @institution) view_model |> assert_shape(%VM.Procedure{}) |> assert_fields(frequency_name: "once per week", name: procedure.name, species_name: @bovine) end end test "trying to rename a procedure to an existing procedure", %{procedure: procedure} do # Existing procedure assert {:ok, _} = VM.BulkProcedure.insert_all([procedure], @institution) # Let's not have the first procedure be the one with the problem. ok_procedure = Factory.build(:procedure, name: "ok name") assert {:error, :constraint, description} = VM.BulkProcedure.insert_all([ok_procedure, procedure], @institution) description |> assert_fields(duplicate_name: 1, message: "A procedure named \"#{procedure.name}\" already exists for species bovine") end end
33.5
106
0.671045
93c0f6d02e4798650e3cb982eb7ddcfeeda7db62
300
exs
Elixir
integration_test/cases/browser/attr_test.exs
carl-al/wallaby
a4c9811902370b15db17fc62d451035ee7464eea
[ "MIT" ]
926
2016-03-28T17:01:54.000Z
2019-11-05T11:59:58.000Z
integration_test/cases/browser/attr_test.exs
carl-al/wallaby
a4c9811902370b15db17fc62d451035ee7464eea
[ "MIT" ]
377
2016-03-17T00:35:56.000Z
2019-11-03T07:15:24.000Z
integration_test/cases/browser/attr_test.exs
carl-al/wallaby
a4c9811902370b15db17fc62d451035ee7464eea
[ "MIT" ]
144
2016-03-29T15:28:28.000Z
2019-10-31T00:48:42.000Z
defmodule Wallaby.Integration.Browser.AttrTest do use Wallaby.Integration.SessionCase, async: true test "can get the attributes of a query", %{session: session} do class = session |> visit("/") |> attr(Query.css("body"), "class") assert class =~ "bootstrap" end end
23.076923
66
0.653333
93c0fed2e023976d7e4a3c28aaa33d1d060ce5a9
1,107
ex
Elixir
testData/org/elixir_lang/parser_definition/anonymous_function_parsing_test_case/FnStabExpressionEnd.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
1,668
2015-01-03T05:54:27.000Z
2022-03-25T08:01:20.000Z
testData/org/elixir_lang/parser_definition/anonymous_function_parsing_test_case/FnStabExpressionEnd.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
2,018
2015-01-01T22:43:39.000Z
2022-03-31T20:13:08.000Z
testData/org/elixir_lang/parser_definition/anonymous_function_parsing_test_case/FnStabExpressionEnd.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
fn -> () end fn -> function positional, key: value end fn -> &one end fn -> one \\ default end fn -> one when key: value end fn -> one when guard end fn -> one :: type end fn -> one | two end fn -> one = two end fn -> one or two end fn -> one || two end fn -> one and two end fn -> one && two end fn -> one != two end fn -> one < two end fn -> one + two end fn -> one / two end fn -> one * two end fn -> one <|> two end fn -> one ^^^ two end fn -> !one end fn -> not one end fn -> Module.function positional, key: value end fn -> @function positional, key: value end fn -> function positional, key: value end fn -> One.Two[key] end fn -> Module.function[key] end fn -> Module.function() end fn -> Module.function end fn -> @variable[key] end fn -> @variable end fn -> function positional, key: value end fn -> variable[key] end fn -> variable end fn -> @1 end fn -> &1 end fn -> !1 end fn -> fn -> end end fn -> 1 end fn -> [] end fn -> "one" end fn -> """ one """ end fn -> 'one' end fn -> ''' one ''' end fn -> ~x{sigil}modifiers end fn -> true end fn -> :atom end fn -> Alias end
20.886792
48
0.592593
93c10c12b3aa1232ad49a1350e8b947cf85e63d6
1,170
exs
Elixir
practical1/exercise1/test/exercise1_test.exs
alpdenizz/ElixirPlayground
58b5a16c489058e0067e4811042d96fe6a5f8d59
[ "MIT" ]
null
null
null
practical1/exercise1/test/exercise1_test.exs
alpdenizz/ElixirPlayground
58b5a16c489058e0067e4811042d96fe6a5f8d59
[ "MIT" ]
null
null
null
practical1/exercise1/test/exercise1_test.exs
alpdenizz/ElixirPlayground
58b5a16c489058e0067e4811042d96fe6a5f8d59
[ "MIT" ]
null
null
null
defmodule Exercise1Test do use ExUnit.Case # @tag :pending test "reverses a given 'charlist'" do assert Exercise1.reverse('abracadabra') == 'arbadacarba' assert Exercise1.reverse('Panama') == 'amanaP' end # @tag :pending test "replaces any lowercase character in a given 'charlist' by its corresponding uppercase" do assert Exercise1.upcase('abracadabra') == 'ABRACADABRA' assert Exercise1.upcase('Panama') == 'PANAMA' end # @tag :pending test "removes non alphabetical caracters from a given 'charlist'" do assert Exercise1.remove_non_alpha('w o r d') == 'word' assert Exercise1.remove_non_alpha('w1o2r3d') == 'word' end # @tag :pending test "checks simple words" do assert Exercise1.palindrome('redivider') == true assert Exercise1.palindrome('abracadabra') == false end # @tag :pending test "checks words, case insensitively" do assert Exercise1.palindrome('ReDivider') == true end # @tag :pending test "ignores non alphabetic characters" do assert Exercise1.palindrome('A man, a plan, a canal -- Panama') == true assert Exercise1.palindrome('Madam, I\'m Adam!') == true end end
30
97
0.695726
93c155d50c99e7bbacc602537b46cb9a8f57d054
614
ex
Elixir
lib/cli.ex
msoedov/mix-install
06783319dfe15b6ceb29a6db115fab1dc777812c
[ "MIT" ]
2
2016-02-07T17:07:11.000Z
2018-07-22T20:04:06.000Z
lib/cli.ex
msoedov/mix-install
06783319dfe15b6ceb29a6db115fab1dc777812c
[ "MIT" ]
null
null
null
lib/cli.ex
msoedov/mix-install
06783319dfe15b6ceb29a6db115fab1dc777812c
[ "MIT" ]
1
2018-07-22T20:04:07.000Z
2018-07-22T20:04:07.000Z
defmodule Mix.Tasks.Install.CLI do @moduledoc """ -g, --github: install package from github -t, --test: test only -d, --dev: development only -h --help: print help Usage: mix install foo bar -t -d mix install fizz -g mix install bazz """ @options [t: :test, g: :github, d: :dev, h: :help] def parse(args) do {flags, packages, _} = OptionParser.parse(args, aliases: @options) # if flags.help do # raise @moduledoc # else {Enum.sort(flags), packages} # end end def help do IO.puts(@moduledoc) end end
19.1875
72
0.563518
93c15b9dc601b975b66df11de8840f6966a4b409
1,382
exs
Elixir
.workshop/exercises/iex/exercise.exs
silesian-beamers/elixir-from-the-ground-up
1ad8c2a4d429175461dc45e218849eb6a212c776
[ "MIT" ]
10
2015-12-13T07:29:08.000Z
2016-09-22T03:47:35.000Z
.workshop/exercises/iex/exercise.exs
silesian-beamers/elixir-from-the-ground-up
1ad8c2a4d429175461dc45e218849eb6a212c776
[ "MIT" ]
4
2015-12-02T12:12:14.000Z
2016-01-11T07:33:24.000Z
.workshop/exercises/iex/exercise.exs
silesian-beamers/elixir-from-the-ground-up
1ad8c2a4d429175461dc45e218849eb6a212c776
[ "MIT" ]
null
null
null
defmodule Workshop.Exercise.Iex do use Workshop.Exercise @title "IEx" @weight 500 # Write an exercise description that make the user capable of solving the # given `@task`. @description """ In the exercise you will learn about the Elixir's interactive shell, and how to find documentation. IEx is Elixir's interactive REPL. It can be run simply with `iex` on the command line. You can use the `-r` switch to load a file inside your session. Useful functions: * `h` shows a list of all available commands * `h <function name>` prints documentation for a given function or module * `c <path>` compiles the source file at given path * `r <module>` recompiles and reloads the given module # What's next? Get the task for this exercise by executing `mix workshop.task`. When you are done writing a solution it can be checked and verified using the `mix workshop.check` command. When the workshop check pass you can proceed to the next exercise by executing the `mix workshop.next` command. If you are confused you could try `mix workshop.hint`. Otherwise ask your instructor or follow the directions on `mix workshop.help`. """ @task """ * Open up IEx and play a little bit with it. * Try looking up documentation for `Enum.map` * Try to lookup up documentation for the `h` helper command """ @hint [] end
30.711111
82
0.71563
93c17da14f8fa2c239c025c93c25b222161af296
1,905
ex
Elixir
lib/metrics/collector.ex
dustinrouillard/lanyard-redis
c1bed07df9501c5d8c2373741088b824c3b61331
[ "MIT" ]
null
null
null
lib/metrics/collector.ex
dustinrouillard/lanyard-redis
c1bed07df9501c5d8c2373741088b824c3b61331
[ "MIT" ]
1
2021-11-26T01:07:32.000Z
2021-11-26T01:07:32.000Z
lib/metrics/collector.ex
dustinrouillard/lanyard-redis
c1bed07df9501c5d8c2373741088b824c3b61331
[ "MIT" ]
null
null
null
defmodule Lanyard.Metrics.Collector do use Prometheus.Metric @registry :lanyard_registry def start do Gauge.new( name: :lanyard_connected_sessions, registry: @registry, labels: [], help: "Currently connected sessions count." ) Counter.new( name: :lanyard_messages_outbound, registry: @registry, labels: [], help: "Total socket messages outbout." ) Counter.new( name: :lanyard_messages_inbound, registry: @registry, labels: [], help: "Total messages received count." ) Counter.new( name: :lanyard_presence_updates, registry: @registry, labels: [], help: "Presence updates received count." ) Gauge.new( name: :lanyard_monitored_users, registry: @registry, labels: [], help: "Users monitored by Lanyard count." ) Counter.new( name: :lanyard_2xx_responses, registry: @registry, labels: [], help: "2xx http responses" ) Counter.new( name: :lanyard_4xx_responses, registry: @registry, labels: [], help: "4xx http responses" ) Counter.new( name: :lanyard_5xx_responses, registry: @registry, labels: [], help: "5xx http responses" ) Counter.new( name: :lanyard_discord_messages_sent, registry: @registry, labels: [], help: "Messages sent to discord count" ) end def dec(:gauge, stat) do Gauge.dec(name: stat, registry: @registry) end def inc(:gauge, stat) do Gauge.inc(name: stat, registry: @registry) end def inc(:counter, stat) do Counter.inc(name: stat, registry: @registry) end def inc(:gauge, stat, value) do Gauge.inc([name: stat, registry: @registry], value) end def set(:gauge, stat, value) do Gauge.set([name: stat, registry: @registry], value) end end
20.934066
55
0.608924
93c1c5bd324e6dc25e8a67c38f15b6827a84ffc5
1,075
exs
Elixir
test/nilsimsa_test.exs
philipbrown/elixir-nilsimsa
a5ea50607fbd1372c1a2a146da3ff1b20a44d6bc
[ "MIT" ]
12
2021-07-16T03:41:12.000Z
2022-01-28T07:58:20.000Z
test/nilsimsa_test.exs
philipbrown/elixir-nilsimsa
a5ea50607fbd1372c1a2a146da3ff1b20a44d6bc
[ "MIT" ]
null
null
null
test/nilsimsa_test.exs
philipbrown/elixir-nilsimsa
a5ea50607fbd1372c1a2a146da3ff1b20a44d6bc
[ "MIT" ]
1
2021-07-25T22:01:42.000Z
2021-07-25T22:01:42.000Z
defmodule NilsimsaTest do use ExUnit.Case doctest Nilsimsa # Examples taken from: # https://github.com/rholder/nilsimsa/blob/110b236de3505e4ee64d485f7499d4ce1cf34cc6/src/test/java/com/github/rholder/nilsimsa/NilsimsaHashTest.java @a k: "abcdefgh", v: "14c8118000000000030800000004042004189020001308014088003280000078" @b k: "This is a much more ridiculous test because of 21347597.", v: "5d9c6a6b22384bcd524a8d414d82237777433fc1a07a02c3e06985d96ecdf8fb" @c k: "The rain in Spain falls mostly in the plains.", v: "039020eb1050188be400091130981860648e39f5b1246d8c3c3c7623801186ac" @d k: "The rain in Spain falls mainly in the plains.", v: "23b000e908501883c408019410d83a60c48f1977a3246ccc3cbc7213c81104bc" test "compare" do a = Nilsimsa.process(@a[:k]) b = Nilsimsa.process(@b[:k]) assert Nilsimsa.compare(a, b) == 4 assert Nilsimsa.compare(b, a) == 4 end for n <- [@a, @b, @c, @d] do test "process: #{n[:k]}" do assert to_string(Nilsimsa.process(unquote(n[:k]))) == unquote(n[:v]) end end end
30.714286
149
0.71814
93c20919f7b73d53f781b18f3c28372cffad963c
3,766
ex
Elixir
apps/forklift/lib/forklift/event/event_handler.ex
smartcitiesdata/smartcitiesdata
c926c25003a8ee2d09b933c521c49f674841c0b6
[ "Apache-2.0" ]
26
2019-09-20T23:54:45.000Z
2020-08-20T14:23:32.000Z
apps/forklift/lib/forklift/event/event_handler.ex
smartcitiesdata/smartcitiesdata
c926c25003a8ee2d09b933c521c49f674841c0b6
[ "Apache-2.0" ]
757
2019-08-15T18:15:07.000Z
2020-09-18T20:55:31.000Z
apps/forklift/lib/forklift/event/event_handler.ex
smartcitiesdata/smartcitiesdata
c926c25003a8ee2d09b933c521c49f674841c0b6
[ "Apache-2.0" ]
9
2019-11-12T16:43:46.000Z
2020-03-25T16:23:16.000Z
defmodule Forklift.Event.EventHandler do @moduledoc false use Brook.Event.Handler alias SmartCity.Dataset alias SmartCity.Ingestion require Logger import SmartCity.Event, only: [ data_ingest_start: 0, dataset_update: 0, data_ingest_end: 0, data_write_complete: 0, error_dataset_update: 0, dataset_delete: 0 ] import Brook.ViewState @instance_name Forklift.instance_name() def handle_event(%Brook.Event{ type: data_ingest_start(), data: %Ingestion{targetDataset: dataset_id} = _ingestion, author: author }) do data_ingest_start() |> add_event_count(author, dataset_id) dataset = Forklift.Datasets.get!(dataset_id) if dataset != nil do :ok = Forklift.DataReaderHelper.init(dataset) end :ok end def handle_event(%Brook.Event{ type: dataset_update(), data: %Dataset{technical: %{sourceType: type}} = dataset, author: author }) when type in ["stream", "ingest"] do dataset_update() |> add_event_count(author, dataset.id) Forklift.Datasets.update(dataset) [table: dataset.technical.systemName, schema: dataset.technical.schema] |> Forklift.DataWriter.init() :discard rescue reason -> Brook.Event.send(@instance_name, error_dataset_update(), :forklift, %{"reason" => reason, "dataset" => dataset}) :discard end def handle_event(%Brook.Event{type: data_ingest_end(), data: %Dataset{} = dataset, author: author}) do data_ingest_end() |> add_event_count(author, dataset.id) Forklift.DataReaderHelper.terminate(dataset) Forklift.Datasets.delete(dataset.id) end def handle_event(%Brook.Event{type: "migration:last_insert_date:start", author: author}) do "migration:last_insert_date:start" |> add_event_count(author, nil) Logger.info("Starting last insert date migration") keys = Redix.command!(:redix, ["KEYS", "forklift:last_insert_date:*"]) keys |> Enum.map(fn key -> {key, Redix.command!(:redix, ["GET", key])} end) |> Enum.map(fn {key, timestamp} -> {parse_dataset_id(key), timestamp} end) |> Enum.each(fn {dataset_id, timestamp} -> {:ok, event} = SmartCity.DataWriteComplete.new(%{id: dataset_id, timestamp: timestamp}) Brook.Event.send(@instance_name, data_write_complete(), :forklift, event) end) thirty_days = 2_592_000 keys |> Enum.each(fn key -> Redix.command!(:redix, ["EXPIRE", key, thirty_days]) end) Logger.info("Completed last insert date migration") create(:migration, "last_insert_date_migration_completed", true) rescue error -> Logger.error("Failure in last insert date migration" <> error) end def handle_event(%Brook.Event{type: dataset_delete(), data: %SmartCity.Dataset{} = dataset, author: author}) do Logger.debug("#{__MODULE__}: Deleting Datatset: #{dataset.id}") dataset_delete() |> add_event_count(author, dataset.id) case delete_dataset(dataset) do :ok -> Logger.debug("#{__MODULE__}: Deleted dataset for dataset: #{dataset.id}") {:error, error} -> Logger.error("#{__MODULE__}: Failed to delete dataset for dataset: #{dataset.id}, Reason: #{inspect(error)}") end end defp delete_dataset(dataset) do Forklift.DataReaderHelper.terminate(dataset) Forklift.DataWriter.delete(dataset) Forklift.Datasets.delete(dataset.id) end defp parse_dataset_id("forklift:last_insert_date:" <> dataset_id), do: dataset_id defp add_event_count(event_type, author, dataset_id) do [ app: "forklift", author: author, dataset_id: dataset_id, event_type: event_type ] |> TelemetryEvent.add_event_metrics([:events_handled]) end end
29.421875
118
0.678704
93c258c97f8727df2421fe7d8646a05aaae13896
229
ex
Elixir
apps/blunt_absinthe/test/support/update_person.ex
blunt-elixir/blunt
a88b88984022db7ba2110204248fdb541121e3a0
[ "MIT" ]
1
2022-03-07T11:54:47.000Z
2022-03-07T11:54:47.000Z
apps/blunt_absinthe/test/support/update_person.ex
elixir-cqrs/cqrs_tools
afbf82da522a10d2413547a46f316ed3aadebba5
[ "MIT" ]
null
null
null
apps/blunt_absinthe/test/support/update_person.ex
elixir-cqrs/cqrs_tools
afbf82da522a10d2413547a46f316ed3aadebba5
[ "MIT" ]
null
null
null
defmodule Blunt.Absinthe.Test.UpdatePerson do use Blunt.Command alias Blunt.Absinthe.Test.ReadModel.Person field :id, :binary_id field :name, :string field :gender, :enum, values: Person.genders(), required: false end
25.444444
65
0.755459
93c26c4338936bf1afed9f53867fa3dfb8832449
9,201
ex
Elixir
lib/gateway/client.ex
LeonardSSH/lanyard
407bc5c7dfcfcaf28ee72a70dc8695c39980f87d
[ "MIT" ]
323
2021-03-12T17:42:44.000Z
2022-03-31T21:32:30.000Z
lib/gateway/client.ex
LeonardSSH/lanyard
407bc5c7dfcfcaf28ee72a70dc8695c39980f87d
[ "MIT" ]
56
2021-03-22T12:30:36.000Z
2022-03-25T17:56:01.000Z
lib/gateway/client.ex
LeonardSSH/lanyard
407bc5c7dfcfcaf28ee72a70dc8695c39980f87d
[ "MIT" ]
113
2021-03-13T17:30:36.000Z
2022-03-29T13:19:24.000Z
defmodule Lanyard.Gateway.Client do # a lot of functionality here is taken from: https://github.com/rmcafee/discord_ex/blob/master/lib/discord_ex/client/client.ex require Logger alias Lanyard.Gateway.Heartbeat import Lanyard.Gateway.Utility @behaviour :websocket_client def opcodes do %{ :dispatch => 0, :heartbeat => 1, :identify => 2, :status_update => 3, :voice_state_update => 4, :voice_server_ping => 5, :resume => 6, :reconnect => 7, :request_guild_members => 8, :invalid_session => 9, :hello => 10, :heartbeat_ack => 11 } end def start_link(state) do # state = state # |> Map.put(:guilds, []) # |> Map.put(:token, state.token) :crypto.start() :ssl.start() :websocket_client.start_link("wss://gateway.discord.gg/?v=9&encoding=etf", __MODULE__, [state]) end def init([state]) do {:ok, agent_seq_num} = Agent.start_link(fn -> nil end) new_state = state # Pass the client state to use it |> Map.put(:client_pid, self()) # Pass agent sequence num |> Map.put(:agent_seq_num, agent_seq_num) # Place for Heartbeat process pid |> Map.put(:heartbeat_pid, nil) {:once, new_state} end def onconnect(_WSReq, state) do # Send identifier to discord gateway identify(state) {:ok, state} end def ondisconnect({:remote, :closed}, state) do # Reconnection with resume opcode should be attempted here {:close, {:remote, :closed}, state} end def websocket_handle({:binary, payload}, _socket, state) do data = payload_decode(opcodes(), {:binary, payload}) # Keeps the sequence tracker process updated _update_agent_sequence(data, state) # Handle data based on opcode sent by Discord _handle_data(data, state) end defp _handle_data(%{op: :hello} = data, state) do # Discord sends hello op immediately after connection # Start sending heartbeat with interval defined by the hello packet Logger.debug("Discord: Hello") {:ok, heartbeat_pid} = Heartbeat.start_link( state[:agent_seq_num], data.data.heartbeat_interval, self() ) {:ok, %{state | heartbeat_pid: heartbeat_pid}} end defp _handle_data(%{op: :heartbeat_ack} = _data, state) do # Discord sends heartbeat_ack after we send a heartbeat # If ack is not received, the connection is stale Logger.debug("Discord: Heartbeat ACK") Heartbeat.ack(state[:heartbeat_pid]) {:ok, state} end defp _handle_data(%{op: :dispatch, event_name: event_name} = data, state) do # Dispatch op carries actual content like channel messages if event_name == :READY do # Client is ready # Logger.debug(fn -> "Discord: Dispatch #{event_name}" end) end event = normalize_atom(event_name) handle_event({event, data}, state) end defp _handle_data(%{op: :reconnect} = _data, state) do Logger.warn("Discord enforced Reconnect") # Discord enforces reconnection. Websocket should be # reconnected and resume opcode sent to playback missed messages. # For now just kill the connection so that a supervisor can restart us. {:close, "Discord enforced reconnect", state} end defp _handle_data(%{op: :invalid_session} = _data, state) do Logger.warn("Discord: Invalid session") # On resume Discord will send invalid_session if our session id is too old # to be resumed. # For now just kill the connection so that a supervisor can restart us. {:close, "Invalid session", state} end def websocket_info(:start, _connection, state) do {:ok, state} end @doc "Look into state - grab key value and pass it back to calling process" def websocket_info({:get_state, key, pid}, _connection, state) do send(pid, {key, state[key]}) {:ok, state} end @doc "Ability to update websocket client state" def websocket_info({:update_state, update_values}, _connection, state) do {:ok, Map.merge(state, update_values)} end @doc "Remove key from state" def websocket_info({:clear_from_state, keys}, _connection, state) do new_state = Map.drop(state, keys) {:ok, new_state} end def websocket_info({:update_status, new_status}, _connection, state) do payload = payload_build(opcode(opcodes(), :status_update), new_status) :websocket_client.cast(self(), {:binary, payload}) {:ok, state} end def websocket_info(:heartbeat_stale, _connection, state) do # Heartbeat process reports stale connection. Websocket should be # reconnected and resume opcode sent to playback missed messages. # For now just kill the connection so that a supervisor can restart us. {:close, "Heartbeat stale", state} end @spec websocket_terminate(any(), any(), nil | keyword() | map()) :: :ok def websocket_terminate(reason, _conn_state, state) do Logger.info("Websocket closed in state #{inspect(state)} with reason #{inspect(reason)}") Logger.info("Killing seq_num process!") Process.exit(state[:agent_seq_num], :kill) Logger.info("Killing rest_client process!") Process.exit(state[:rest_client], :kill) Logger.info("Killing heartbeat process!") Process.exit(state[:heartbeat_pid], :kill) :ok end def handle_event({:ready, payload}, state) do new_state = Map.put(state, :session_id, payload.data[:session_id]) {:ok, new_state} end def handle_event({:message_create, payload}, state) do Task.start(fn -> Lanyard.DiscordBot.CommandHandler.handle_message(payload) end) {:ok, state} end def handle_event({:guild_create, payload}, state) do create_member_presences(payload) # The Lanyard guild is above the large_threshold, so we need to use Opcode 8: Request Guild Members request_payload = payload_build(opcode(opcodes(), :request_guild_members), %{ "guild_id" => payload.data.id, "limit" => 0, "query" => "", "presences" => true }) :websocket_client.cast(self(), {:binary, request_payload}) {:ok, state} end def handle_event({:presence_update, payload}, state) do with {:ok, pid} <- GenRegistry.lookup(Lanyard.Presence, Integer.to_string(payload.data.user.id)) do GenServer.cast(pid, {:sync, %{discord_presence: payload.data}}) end {:ok, state} end def handle_event({:guild_member_add, payload}, state) do Logger.debug("User #{payload.data["user"]["id"]} joined guild") request_payload = payload_build(opcode(opcodes(), :request_guild_members), %{ "guild_id" => payload.data["guild_id"], "user_ids" => [payload.data["user"]["id"]], "limit" => 1, "presences" => true }) :websocket_client.cast(self(), {:binary, request_payload}) {:ok, state} end def handle_event({:guild_member_update, payload}, state) do Logger.debug("User object for #{payload.data.user.id} was updated") with {:ok, pid} <- GenRegistry.lookup(Lanyard.Presence, Integer.to_string(payload.data.user.id)) do GenServer.cast(pid, {:sync, %{discord_user: payload.data.user}}) end {:ok, state} end def handle_event({:guild_member_remove, payload}, state) do Logger.debug("User #{payload.data["user"]["id"]} left guild") str_id = Integer.to_string(payload.data["user"]["id"]) GenRegistry.stop(Lanyard.Presence, str_id) :ets.delete(:cached_presences, str_id) {:ok, state} end def handle_event({:guild_members_chunk, payload}, state) do create_member_presences(payload) {:ok, state} end def handle_event({_event, _payload}, state) do {:ok, state} end def identify(state) do data = %{ "token" => state.token, "properties" => %{ "$os" => "erlang-vm", "$browser" => "lanyard-worker", "$device" => "lanyard-genserver", "$referrer" => "", "$referring_domain" => "" }, "presence" => %{ "since" => nil, "game" => %{ "name" => Application.get_env(:lanyard, :bot_presence), "type" => Application.get_env(:lanyard, :bot_presence_type) }, "status" => "online" }, "compress" => false, "large_threshold" => 250, "intents" => 4867 } payload = payload_build(opcode(opcodes(), :identify), data) :websocket_client.cast(self(), {:binary, payload}) end defp _update_agent_sequence(data, state) do if state[:agent_seq_num] && data.seq_num do agent_update(state[:agent_seq_num], data.seq_num) end end defp create_member_presences(payload) do Task.start(fn -> Enum.each(payload.data.members, fn member -> presence = payload.data.presences |> Enum.find(fn presence -> presence.user.id === member.user.id end) gen_init = %{ user_id: Integer.to_string(member.user.id), discord_presence: presence, discord_user: member.user } {:ok, pid} = GenRegistry.lookup_or_start(Lanyard.Presence, gen_init.user_id, [gen_init]) GenServer.cast(pid, {:sync, gen_init}) end) end) end end
29.490385
128
0.649712
93c2869563a1b14563c0325f70599114ad36f3f2
679
ex
Elixir
lib/altstatus/admission/batch.ex
AltCampus/altstatus_backend
70bf7a9d337e570f54002c3a7df264e88372adfa
[ "MIT" ]
1
2020-01-20T18:17:59.000Z
2020-01-20T18:17:59.000Z
lib/altstatus/admission/batch.ex
AltCampus/altstatus_backend
70bf7a9d337e570f54002c3a7df264e88372adfa
[ "MIT" ]
null
null
null
lib/altstatus/admission/batch.ex
AltCampus/altstatus_backend
70bf7a9d337e570f54002c3a7df264e88372adfa
[ "MIT" ]
2
2018-09-09T08:05:24.000Z
2018-09-09T08:35:18.000Z
defmodule Altstatus.Admission.Batch do use Ecto.Schema import Ecto.Changeset schema "batches" do field :name, :string field :slug, :string timestamps() end @doc false def changeset(batch, attrs) do batch |> cast(attrs, [:name, :slug]) |> validate_required([:name]) |> unique_constraint(:name) |> slugify end def slugify(changeset) do if name = get_change(changeset, :name) do put_change(changeset, :slug, generate_slug(name)) else changeset end end def generate_slug(name) do name |> String.trim |> String.downcase |> String.split([" ", ",", ", "]) |> Enum.join("-") end end
17.868421
55
0.612666
93c2b6fdc87409f9cb499dfb6301a2852d8af6ab
660
ex
Elixir
lib/doctor_schedule_web/controllers/fallback_controller.ex
romenigld/doctor_schedule
40fb31b58d5d1f9f2b1809b869396d9f57244cc5
[ "MIT" ]
2
2022-03-11T12:15:01.000Z
2022-03-11T13:53:21.000Z
lib/doctor_schedule_web/controllers/fallback_controller.ex
theguuholi/doctor_schedule
a92dfa92d1398c59718be2428d36bb326d6bc361
[ "MIT" ]
3
2020-12-12T22:10:17.000Z
2021-04-05T12:53:12.000Z
lib/doctor_schedule_web/controllers/fallback_controller.ex
romenigld/doctor_schedule
40fb31b58d5d1f9f2b1809b869396d9f57244cc5
[ "MIT" ]
1
2021-02-26T04:24:34.000Z
2021-02-26T04:24:34.000Z
defmodule DoctorScheduleWeb.FallbackController do @moduledoc """ Translates controller action results into valid `Plug.Conn` responses. See `Phoenix.Controller.action_fallback/1` for more details. """ use DoctorScheduleWeb, :controller # This clause handles errors returned by Ecto's insert/update/delete. def call(conn, {:error, %Ecto.Changeset{} = changeset}) do conn |> put_status(:unprocessable_entity) |> put_view(DoctorScheduleWeb.ChangesetView) |> render("error.json", changeset: changeset) end def call(conn, {:error, message}) do conn |> put_status(:bad_request) |> json(%{message: message}) end end
28.695652
72
0.715152
93c2f2e739c6aa5422ab08ea748c79ea853cc771
3,105
ex
Elixir
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/binding.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/binding.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/binding.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # 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 &quot;AS IS&quot; 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. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.CloudResourceManager.V1.Model.Binding do @moduledoc """ Associates &#x60;members&#x60; with a &#x60;role&#x60;. ## Attributes - condition (Expr): The condition that is associated with this binding. NOTE: An unsatisfied condition will not allow user access via current binding. Different bindings, including their conditions, are examined independently. Defaults to: `null`. - members ([String.t]): Specifies the identities requesting access for a Cloud Platform resource. &#x60;members&#x60; can have the following values: * &#x60;allUsers&#x60;: A special identifier that represents anyone who is on the internet; with or without a Google account. * &#x60;allAuthenticatedUsers&#x60;: A special identifier that represents anyone who is authenticated with a Google account or a service account. * &#x60;user:{emailid}&#x60;: An email address that represents a specific Google account. For example, &#x60;alice@gmail.com&#x60; . * &#x60;serviceAccount:{emailid}&#x60;: An email address that represents a service account. For example, &#x60;my-other-app@appspot.gserviceaccount.com&#x60;. * &#x60;group:{emailid}&#x60;: An email address that represents a Google group. For example, &#x60;admins@example.com&#x60;. * &#x60;domain:{domain}&#x60;: The G Suite domain (primary) that represents all the users of that domain. For example, &#x60;google.com&#x60; or &#x60;example.com&#x60;. Defaults to: `null`. - role (String.t): Role that is assigned to &#x60;members&#x60;. For example, &#x60;roles/viewer&#x60;, &#x60;roles/editor&#x60;, or &#x60;roles/owner&#x60;. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :condition => GoogleApi.CloudResourceManager.V1.Model.Expr.t(), :members => list(any()), :role => any() } field(:condition, as: GoogleApi.CloudResourceManager.V1.Model.Expr) field(:members, type: :list) field(:role) end defimpl Poison.Decoder, for: GoogleApi.CloudResourceManager.V1.Model.Binding do def decode(value, options) do GoogleApi.CloudResourceManager.V1.Model.Binding.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudResourceManager.V1.Model.Binding do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
57.5
1,058
0.732367
93c2fb3ffb72e1f546334e7b665ddccb9871ebf0
2,036
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_ban.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_ban.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_ban.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # 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. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.YouTube.V3.Model.LiveChatBan do @moduledoc """ A liveChatBan resource represents a ban for a YouTube live chat. ## Attributes * `etag` (*type:* `String.t`, *default:* `nil`) - Etag of this resource. * `id` (*type:* `String.t`, *default:* `nil`) - The ID that YouTube assigns to uniquely identify the ban. * `kind` (*type:* `String.t`, *default:* `youtube#liveChatBan`) - Identifies what kind of resource this is. Value: the fixed string "youtube#liveChatBan". * `snippet` (*type:* `GoogleApi.YouTube.V3.Model.LiveChatBanSnippet.t`, *default:* `nil`) - The snippet object contains basic details about the ban. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :etag => String.t(), :id => String.t(), :kind => String.t(), :snippet => GoogleApi.YouTube.V3.Model.LiveChatBanSnippet.t() } field(:etag) field(:id) field(:kind) field(:snippet, as: GoogleApi.YouTube.V3.Model.LiveChatBanSnippet) end defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.LiveChatBan do def decode(value, options) do GoogleApi.YouTube.V3.Model.LiveChatBan.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.LiveChatBan do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.357143
158
0.70776
93c329478b6eb37d8152942af3e494dc1c0c66da
3,144
exs
Elixir
apps/artemis/test/artemis/contexts/key_value/create_or_update_key_value_test.exs
artemis-platform/artemis_dashboard
5ab3f5ac4c5255478bbebf76f0e43b44992e3cab
[ "MIT" ]
9
2019-08-19T19:56:34.000Z
2022-03-22T17:56:38.000Z
apps/artemis/test/artemis/contexts/key_value/create_or_update_key_value_test.exs
chrislaskey/artemis_teams
9930c3d9528e37b76f0525390e32b66eed7eadde
[ "MIT" ]
7
2019-07-12T21:41:01.000Z
2020-08-17T21:29:22.000Z
apps/artemis/test/artemis/contexts/key_value/create_or_update_key_value_test.exs
chrislaskey/artemis_teams
9930c3d9528e37b76f0525390e32b66eed7eadde
[ "MIT" ]
2
2019-07-05T22:51:47.000Z
2019-08-19T19:56:37.000Z
defmodule Artemis.CreateOrUpdateKeyValueTest do use Artemis.DataCase import Artemis.Factories alias Artemis.CreateOrUpdateKeyValue alias Artemis.KeyValue describe "call!" do test "returns error when params are empty" do assert_raise Artemis.Context.Error, fn -> CreateOrUpdateKeyValue.call!(%{}, Mock.system_user()) end end test "creates a key-value when passed valid params" do params = params_for(:key_value) key_value = CreateOrUpdateKeyValue.call!(params, Mock.system_user()) assert key_value.key == params.key assert key_value.size == byte_size(params.value) assert key_value.value == params.value end end describe "call" do test "returns error when params are empty" do {:error, changeset} = CreateOrUpdateKeyValue.call(%{}, Mock.system_user()) assert errors_on(changeset).key == ["can't be blank"] assert errors_on(changeset).size == ["can't be blank"] assert errors_on(changeset).value == ["can't be blank"] end test "creates a key-value when passed valid binary params" do params = params_for(:key_value, key: "hello", value: "world") {:ok, key_value} = CreateOrUpdateKeyValue.call(params, Mock.system_user()) assert key_value.key == params.key assert key_value.size == byte_size(KeyValue.encode(params.value)) assert key_value.value == params.value end test "creates a key-value when passed valid non-binary params" do params = params_for(:key_value, key: 'hello', value: %{hello: %{world: true}}) {:ok, key_value} = CreateOrUpdateKeyValue.call(params, Mock.system_user()) assert key_value.key == params.key assert key_value.size == byte_size(KeyValue.encode(params.value)) assert key_value.value == params.value end test "updates a key-value when passed valid non-binary params" do create_params = params_for(:key_value, key: 'hello', value: %{hello: %{world: true}}) {:ok, created} = CreateOrUpdateKeyValue.call(create_params, Mock.system_user()) assert created.key == create_params.key assert created.size == byte_size(KeyValue.encode(create_params.value)) assert created.value == create_params.value update_params = params_for(:key_value, key: 'hello', value: %{hello: "world"}) {:ok, updated} = CreateOrUpdateKeyValue.call(update_params, Mock.system_user()) assert updated.key == update_params.key assert updated.size == byte_size(KeyValue.encode(update_params.value)) assert updated.value == update_params.value assert updated.key == created.key assert updated.size != created.size assert updated.value != created.value end end describe "broadcasts" do test "publishes event and record" do ArtemisPubSub.subscribe(Artemis.Event.get_broadcast_topic()) {:ok, key_value} = CreateOrUpdateKeyValue.call(params_for(:key_value), Mock.system_user()) assert_received %Phoenix.Socket.Broadcast{ event: "key-value:updated", payload: %{ data: ^key_value } } end end end
33.446809
96
0.684796
93c33b943079bb5c2ae648d761000a670ff6b0d7
1,744
exs
Elixir
config/config.exs
erickbarcenas/metro_cdmx_api
6a598fe0b0e8a2bb999ea6c517053f902f16662b
[ "MIT" ]
null
null
null
config/config.exs
erickbarcenas/metro_cdmx_api
6a598fe0b0e8a2bb999ea6c517053f902f16662b
[ "MIT" ]
null
null
null
config/config.exs
erickbarcenas/metro_cdmx_api
6a598fe0b0e8a2bb999ea6c517053f902f16662b
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. # General application configuration import Config config :metro_cdmx_api, ecto_repos: [MetroCdmxApi.Repo] # Configures the endpoint config :metro_cdmx_api, MetroCdmxApiWeb.Endpoint, url: [host: "localhost"], render_errors: [view: MetroCdmxApiWeb.ErrorView, accepts: ~w(html json), layout: false], pubsub_server: MetroCdmxApi.PubSub, live_view: [signing_salt: "FJZKfk5p"] # Configures the mailer # # By default it uses the "Local" adapter which stores the emails # locally. You can see the emails in your browser, at "/dev/mailbox". # # For production it's recommended to configure a different adapter # at the `config/runtime.exs`. config :metro_cdmx_api, MetroCdmxApi.Mailer, adapter: Swoosh.Adapters.Local # Swoosh API client is needed for adapters other than SMTP. config :swoosh, :api_client, false # Configure esbuild (the version is required) config :esbuild, version: "0.14.0", default: [ args: ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*), cd: Path.expand("../assets", __DIR__), env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} ] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Use Jason for JSON parsing in Phoenix config :phoenix, :json_library, Jason # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{config_env()}.exs"
32.90566
117
0.739679
93c33e2a951c1ee524013f9ced10bd8c2a2927fe
1,055
exs
Elixir
rockelivery/test/rockelivery/accounts_test.exs
arilsonsouza/rocketseat-ignite-elixir
93e32d52d589336dfd2d81e755d6dd7f05ee40b8
[ "MIT" ]
null
null
null
rockelivery/test/rockelivery/accounts_test.exs
arilsonsouza/rocketseat-ignite-elixir
93e32d52d589336dfd2d81e755d6dd7f05ee40b8
[ "MIT" ]
null
null
null
rockelivery/test/rockelivery/accounts_test.exs
arilsonsouza/rocketseat-ignite-elixir
93e32d52d589336dfd2d81e755d6dd7f05ee40b8
[ "MIT" ]
null
null
null
defmodule Rockelivery.AccountsTest do use Rockelivery.DataCase, async: true import Mox import Rockelivery.Factory alias Rockelivery.Error alias Rockelivery.Accounts alias Rockelivery.Accounts.User alias Rockelivery.ViaCep.ClientMock describe "register_user/1" do test "should return a user when all attrs are valid" do attrs = build(:user_attrs) expect(ClientMock, :get_cep_info, fn _cep -> {:ok, build(:cep_info)} end) response = Accounts.register_user(attrs) assert {:ok, %User{email: "joe@email.com", name: "Joe", tax_id: "12345678912"}} = response end test "should return an error when there are invalid attrs" do attrs = build(:user_attrs, %{"tax_id" => "", "password" => "123"}) expected = %{ password: ["should be at least 6 character(s)"], tax_id: ["can't be blank"] } assert {:error, %Error{status: :bad_request, result: changeset}} = Accounts.register_user(attrs) assert errors_on(changeset) == expected end end end
27.763158
96
0.662559
93c34038b6b0cf54889260bdf9c9cacd886a0ed7
33,172
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/api/captions.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/api/captions.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/api/captions.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # 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 &quot;AS IS&quot; 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. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.YouTube.V3.Api.Captions do @moduledoc """ API calls for all endpoints tagged `Captions`. """ alias GoogleApi.YouTube.V3.Connection import GoogleApi.YouTube.V3.RequestBuilder @doc """ Deletes a specified caption track. ## Parameters - connection (GoogleApi.YouTube.V3.Connection): Connection to server - id (String.t): The id parameter identifies the caption track that is being deleted. The value is a caption track ID as identified by the id property in a caption resource. - opts (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - :userIp (String.t): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :onBehalfOf (String.t): ID of the Google+ Page for the channel that the request is be on behalf of - :onBehalfOfContentOwner (String.t): Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request&#39;s authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner. ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec youtube_captions_delete(Tesla.Env.client(), String.t(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t()} def youtube_captions_delete(connection, id, opts \\ []) do optional_params = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :onBehalfOf => :query, :onBehalfOfContentOwner => :query } %{} |> method(:delete) |> url("/youtube/v3/captions") |> add_param(:query, :id, id) |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(false) end @doc """ Downloads a caption track. The caption track is returned in its original format unless the request specifies a value for the tfmt parameter and in its original language unless the request specifies a value for the tlang parameter. ## Parameters - connection (GoogleApi.YouTube.V3.Connection): Connection to server - id (String.t): The id parameter identifies the caption track that is being retrieved. The value is a caption track ID as identified by the id property in a caption resource. - opts (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - :userIp (String.t): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :onBehalfOf (String.t): ID of the Google+ Page for the channel that the request is be on behalf of - :onBehalfOfContentOwner (String.t): Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request&#39;s authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner. - :tfmt (String.t): The tfmt parameter specifies that the caption track should be returned in a specific format. If the parameter is not included in the request, the track is returned in its original format. - :tlang (String.t): The tlang parameter specifies that the API response should return a translation of the specified caption track. The parameter value is an ISO 639-1 two-letter language code that identifies the desired caption language. The translation is generated by using machine translation, such as Google Translate. ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec youtube_captions_download(Tesla.Env.client(), String.t(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t()} def youtube_captions_download(connection, id, opts \\ []) do optional_params = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :onBehalfOf => :query, :onBehalfOfContentOwner => :query, :tfmt => :query, :tlang => :query } %{} |> method(:get) |> url("/youtube/v3/captions/{id}", %{ "id" => URI.encode_www_form(id) }) |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(false) end @doc """ Uploads a caption track. ## Parameters - connection (GoogleApi.YouTube.V3.Connection): Connection to server - part (String.t): The part parameter specifies the caption resource parts that the API response will include. Set the parameter value to snippet. - opts (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - :userIp (String.t): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :onBehalfOf (String.t): ID of the Google+ Page for the channel that the request is be on behalf of - :onBehalfOfContentOwner (String.t): Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request&#39;s authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner. - :sync (boolean()): The sync parameter indicates whether YouTube should automatically synchronize the caption file with the audio track of the video. If you set the value to true, YouTube will disregard any time codes that are in the uploaded caption file and generate new time codes for the captions. You should set the sync parameter to true if you are uploading a transcript, which has no time codes, or if you suspect the time codes in your file are incorrect and want YouTube to try to fix them. - :body (Caption): ## Returns {:ok, %GoogleApi.YouTube.V3.Model.Caption{}} on success {:error, info} on failure """ @spec youtube_captions_insert(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.YouTube.V3.Model.Caption.t()} | {:error, Tesla.Env.t()} def youtube_captions_insert(connection, part, opts \\ []) do optional_params = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :onBehalfOf => :query, :onBehalfOfContentOwner => :query, :sync => :query, :body => :body } %{} |> method(:post) |> url("/youtube/v3/captions") |> add_param(:query, :part, part) |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.YouTube.V3.Model.Caption{}) end @doc """ Uploads a caption track. ## Parameters - connection (GoogleApi.YouTube.V3.Connection): Connection to server - part (String.t): The part parameter specifies the caption resource parts that the API response will include. Set the parameter value to snippet. - upload_type (String.t): Upload type. Must be \&quot;resumable\&quot;. - opts (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - :userIp (String.t): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :onBehalfOf (String.t): ID of the Google+ Page for the channel that the request is be on behalf of - :onBehalfOfContentOwner (String.t): Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request&#39;s authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner. - :sync (boolean()): The sync parameter indicates whether YouTube should automatically synchronize the caption file with the audio track of the video. If you set the value to true, YouTube will disregard any time codes that are in the uploaded caption file and generate new time codes for the captions. You should set the sync parameter to true if you are uploading a transcript, which has no time codes, or if you suspect the time codes in your file are incorrect and want YouTube to try to fix them. - :body (Caption): ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec youtube_captions_insert_resumable(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t()} def youtube_captions_insert_resumable(connection, part, upload_type, opts \\ []) do optional_params = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :onBehalfOf => :query, :onBehalfOfContentOwner => :query, :sync => :query, :body => :body } %{} |> method(:post) |> url("/resumable/upload/youtube/v3/captions") |> add_param(:query, :part, part) |> add_param(:query, :uploadType, upload_type) |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(false) end @doc """ Uploads a caption track. ## Parameters - connection (GoogleApi.YouTube.V3.Connection): Connection to server - part (String.t): The part parameter specifies the caption resource parts that the API response will include. Set the parameter value to snippet. - upload_type (String.t): Upload type. Must be \&quot;multipart\&quot;. - metadata (Caption): Caption metadata. - data (String.t): The file to upload. - opts (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - :userIp (String.t): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :onBehalfOf (String.t): ID of the Google+ Page for the channel that the request is be on behalf of - :onBehalfOfContentOwner (String.t): Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request&#39;s authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner. - :sync (boolean()): The sync parameter indicates whether YouTube should automatically synchronize the caption file with the audio track of the video. If you set the value to true, YouTube will disregard any time codes that are in the uploaded caption file and generate new time codes for the captions. You should set the sync parameter to true if you are uploading a transcript, which has no time codes, or if you suspect the time codes in your file are incorrect and want YouTube to try to fix them. ## Returns {:ok, %GoogleApi.YouTube.V3.Model.Caption{}} on success {:error, info} on failure """ @spec youtube_captions_insert_simple( Tesla.Env.client(), String.t(), String.t(), GoogleApi.YouTube.V3.Model.Caption.t(), String.t(), keyword() ) :: {:ok, GoogleApi.YouTube.V3.Model.Caption.t()} | {:error, Tesla.Env.t()} def youtube_captions_insert_simple(connection, part, upload_type, metadata, data, opts \\ []) do optional_params = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :onBehalfOf => :query, :onBehalfOfContentOwner => :query, :sync => :query } %{} |> method(:post) |> url("/upload/youtube/v3/captions") |> add_param(:query, :part, part) |> add_param(:query, :uploadType, upload_type) |> add_param(:body, :metadata, metadata) |> add_param(:file, :data, data) |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.YouTube.V3.Model.Caption{}) end @doc """ Returns a list of caption tracks that are associated with a specified video. Note that the API response does not contain the actual captions and that the captions.download method provides the ability to retrieve a caption track. ## Parameters - connection (GoogleApi.YouTube.V3.Connection): Connection to server - part (String.t): The part parameter specifies a comma-separated list of one or more caption resource parts that the API response will include. The part names that you can include in the parameter value are id and snippet. - video_id (String.t): The videoId parameter specifies the YouTube video ID of the video for which the API should return caption tracks. - opts (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - :userIp (String.t): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :id (String.t): The id parameter specifies a comma-separated list of IDs that identify the caption resources that should be retrieved. Each ID must identify a caption track associated with the specified video. - :onBehalfOf (String.t): ID of the Google+ Page for the channel that the request is on behalf of. - :onBehalfOfContentOwner (String.t): Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request&#39;s authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner. ## Returns {:ok, %GoogleApi.YouTube.V3.Model.CaptionListResponse{}} on success {:error, info} on failure """ @spec youtube_captions_list(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.YouTube.V3.Model.CaptionListResponse.t()} | {:error, Tesla.Env.t()} def youtube_captions_list(connection, part, video_id, opts \\ []) do optional_params = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :id => :query, :onBehalfOf => :query, :onBehalfOfContentOwner => :query } %{} |> method(:get) |> url("/youtube/v3/captions") |> add_param(:query, :part, part) |> add_param(:query, :videoId, video_id) |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.YouTube.V3.Model.CaptionListResponse{}) end @doc """ Updates a caption track. When updating a caption track, you can change the track&#39;s draft status, upload a new caption file for the track, or both. ## Parameters - connection (GoogleApi.YouTube.V3.Connection): Connection to server - part (String.t): The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. Set the property value to snippet if you are updating the track&#39;s draft status. Otherwise, set the property value to id. - opts (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - :userIp (String.t): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :onBehalfOf (String.t): ID of the Google+ Page for the channel that the request is be on behalf of - :onBehalfOfContentOwner (String.t): Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request&#39;s authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner. - :sync (boolean()): Note: The API server only processes the parameter value if the request contains an updated caption file. The sync parameter indicates whether YouTube should automatically synchronize the caption file with the audio track of the video. If you set the value to true, YouTube will automatically synchronize the caption track with the audio track. - :body (Caption): ## Returns {:ok, %GoogleApi.YouTube.V3.Model.Caption{}} on success {:error, info} on failure """ @spec youtube_captions_update(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.YouTube.V3.Model.Caption.t()} | {:error, Tesla.Env.t()} def youtube_captions_update(connection, part, opts \\ []) do optional_params = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :onBehalfOf => :query, :onBehalfOfContentOwner => :query, :sync => :query, :body => :body } %{} |> method(:put) |> url("/youtube/v3/captions") |> add_param(:query, :part, part) |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.YouTube.V3.Model.Caption{}) end @doc """ Updates a caption track. When updating a caption track, you can change the track&#39;s draft status, upload a new caption file for the track, or both. ## Parameters - connection (GoogleApi.YouTube.V3.Connection): Connection to server - part (String.t): The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. Set the property value to snippet if you are updating the track&#39;s draft status. Otherwise, set the property value to id. - upload_type (String.t): Upload type. Must be \&quot;resumable\&quot;. - opts (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - :userIp (String.t): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :onBehalfOf (String.t): ID of the Google+ Page for the channel that the request is be on behalf of - :onBehalfOfContentOwner (String.t): Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request&#39;s authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner. - :sync (boolean()): Note: The API server only processes the parameter value if the request contains an updated caption file. The sync parameter indicates whether YouTube should automatically synchronize the caption file with the audio track of the video. If you set the value to true, YouTube will automatically synchronize the caption track with the audio track. - :body (Caption): ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec youtube_captions_update_resumable(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t()} def youtube_captions_update_resumable(connection, part, upload_type, opts \\ []) do optional_params = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :onBehalfOf => :query, :onBehalfOfContentOwner => :query, :sync => :query, :body => :body } %{} |> method(:put) |> url("/resumable/upload/youtube/v3/captions") |> add_param(:query, :part, part) |> add_param(:query, :uploadType, upload_type) |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(false) end @doc """ Updates a caption track. When updating a caption track, you can change the track&#39;s draft status, upload a new caption file for the track, or both. ## Parameters - connection (GoogleApi.YouTube.V3.Connection): Connection to server - part (String.t): The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. Set the property value to snippet if you are updating the track&#39;s draft status. Otherwise, set the property value to id. - upload_type (String.t): Upload type. Must be \&quot;multipart\&quot;. - metadata (Caption): Caption metadata. - data (String.t): The file to upload. - opts (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - :userIp (String.t): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :onBehalfOf (String.t): ID of the Google+ Page for the channel that the request is be on behalf of - :onBehalfOfContentOwner (String.t): Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request&#39;s authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner. - :sync (boolean()): Note: The API server only processes the parameter value if the request contains an updated caption file. The sync parameter indicates whether YouTube should automatically synchronize the caption file with the audio track of the video. If you set the value to true, YouTube will automatically synchronize the caption track with the audio track. ## Returns {:ok, %GoogleApi.YouTube.V3.Model.Caption{}} on success {:error, info} on failure """ @spec youtube_captions_update_simple( Tesla.Env.client(), String.t(), String.t(), GoogleApi.YouTube.V3.Model.Caption.t(), String.t(), keyword() ) :: {:ok, GoogleApi.YouTube.V3.Model.Caption.t()} | {:error, Tesla.Env.t()} def youtube_captions_update_simple(connection, part, upload_type, metadata, data, opts \\ []) do optional_params = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :onBehalfOf => :query, :onBehalfOfContentOwner => :query, :sync => :query } %{} |> method(:put) |> url("/upload/youtube/v3/captions") |> add_param(:query, :part, part) |> add_param(:query, :uploadType, upload_type) |> add_param(:body, :metadata, metadata) |> add_param(:file, :data, data) |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.YouTube.V3.Model.Caption{}) end end
64.286822
720
0.718467
93c36c154dd2b8e351852f35992dab31637205b3
4,868
ex
Elixir
clients/firebase_dynamic_links/lib/google_api/firebase_dynamic_links/v1/model/dynamic_link_info.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/firebase_dynamic_links/lib/google_api/firebase_dynamic_links/v1/model/dynamic_link_info.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/firebase_dynamic_links/lib/google_api/firebase_dynamic_links/v1/model/dynamic_link_info.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # 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. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.FirebaseDynamicLinks.V1.Model.DynamicLinkInfo do @moduledoc """ Information about a Dynamic Link. ## Attributes * `analyticsInfo` (*type:* `GoogleApi.FirebaseDynamicLinks.V1.Model.AnalyticsInfo.t`, *default:* `nil`) - Parameters used for tracking. See all tracking parameters in the [documentation](https://firebase.google.com/docs/dynamic-links/create-manually). * `androidInfo` (*type:* `GoogleApi.FirebaseDynamicLinks.V1.Model.AndroidInfo.t`, *default:* `nil`) - Android related information. See Android related parameters in the [documentation](https://firebase.google.com/docs/dynamic-links/create-manually). * `desktopInfo` (*type:* `GoogleApi.FirebaseDynamicLinks.V1.Model.DesktopInfo.t`, *default:* `nil`) - Desktop related information. See desktop related parameters in the [documentation](https://firebase.google.com/docs/dynamic-links/create-manually). * `domainUriPrefix` (*type:* `String.t`, *default:* `nil`) - E.g. https://maps.app.goo.gl, https://maps.page.link, https://g.co/maps More examples can be found in description of getNormalizedUriPrefix in j/c/g/firebase/dynamiclinks/uri/DdlDomain.java Will fallback to dynamic_link_domain is this field is missing * `dynamicLinkDomain` (*type:* `String.t`, *default:* `nil`) - Dynamic Links domain that the project owns, e.g. abcd.app.goo.gl [Learn more](https://firebase.google.com/docs/dynamic-links/android/receive) on how to set up Dynamic Link domain associated with your Firebase project. Required if missing domain_uri_prefix. * `iosInfo` (*type:* `GoogleApi.FirebaseDynamicLinks.V1.Model.IosInfo.t`, *default:* `nil`) - iOS related information. See iOS related parameters in the [documentation](https://firebase.google.com/docs/dynamic-links/create-manually). * `link` (*type:* `String.t`, *default:* `nil`) - The link your app will open, You can specify any URL your app can handle. This link must be a well-formatted URL, be properly URL-encoded, and use the HTTP or HTTPS scheme. See 'link' parameters in the [documentation](https://firebase.google.com/docs/dynamic-links/create-manually). Required. * `navigationInfo` (*type:* `GoogleApi.FirebaseDynamicLinks.V1.Model.NavigationInfo.t`, *default:* `nil`) - Information of navigation behavior of a Firebase Dynamic Links. * `socialMetaTagInfo` (*type:* `GoogleApi.FirebaseDynamicLinks.V1.Model.SocialMetaTagInfo.t`, *default:* `nil`) - Parameters for social meta tag params. Used to set meta tag data for link previews on social sites. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :analyticsInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.AnalyticsInfo.t(), :androidInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.AndroidInfo.t(), :desktopInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.DesktopInfo.t(), :domainUriPrefix => String.t(), :dynamicLinkDomain => String.t(), :iosInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.IosInfo.t(), :link => String.t(), :navigationInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.NavigationInfo.t(), :socialMetaTagInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.SocialMetaTagInfo.t() } field(:analyticsInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.AnalyticsInfo) field(:androidInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.AndroidInfo) field(:desktopInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.DesktopInfo) field(:domainUriPrefix) field(:dynamicLinkDomain) field(:iosInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.IosInfo) field(:link) field(:navigationInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.NavigationInfo) field(:socialMetaTagInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.SocialMetaTagInfo) end defimpl Poison.Decoder, for: GoogleApi.FirebaseDynamicLinks.V1.Model.DynamicLinkInfo do def decode(value, options) do GoogleApi.FirebaseDynamicLinks.V1.Model.DynamicLinkInfo.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.FirebaseDynamicLinks.V1.Model.DynamicLinkInfo do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
68.56338
346
0.753698
93c38c3b6d38db83b10ef432cbf7374ee6308247
1,356
ex
Elixir
lib/test.ex
doorgan/credo_fixes
e64869bbd53644bb11480f925540cf75c73432af
[ "Apache-2.0" ]
null
null
null
lib/test.ex
doorgan/credo_fixes
e64869bbd53644bb11480f925540cf75c73432af
[ "Apache-2.0" ]
null
null
null
lib/test.ex
doorgan/credo_fixes
e64869bbd53644bb11480f925540cf75c73432af
[ "Apache-2.0" ]
null
null
null
defmodule CredoFixes.Test do @moduledoc """ Helpers to test fixes """ @type fix_case :: %{ name: String.t(), original: String.t(), expected: String.t() } @doc """ Generates test cases for a fix module from a list of fix cases. A fix case is a map with `:name`, `:original` and `:expected` keys, representing the test name, the original source code annd what the fix should produce. The fix module must implement the `CredoFixes.Fixer` behaviour. The `get_fixes` function will be called with the original source code, and the resulting fixes will then be applied to it with `Sourceror.patch_string/2`. Both the resulting source code and the expected source code will have their trailing newlines trimmed to avoid issues with sigils like `~S` """ defmacro test_fixes(module, cases) do quote location: :keep, bind_quoted: [module: module, cases: cases] do for test_case <- cases do @case test_case @module module test @case.name do fixes = @module.get_fixes(@case.original) expected = String.trim_trailing(@case.expected) actual = @case.original |> Sourceror.patch_string(fixes) |> String.trim_trailing() assert expected == actual end end end end end
28.851064
79
0.644543
93c3aa7644af5b78edf07a45279fcb21bab6e181
271
exs
Elixir
config/test.exs
esl/buildex_poller
dd535ea5cb903a0a476b5310e7d9127672206b08
[ "Apache-2.0" ]
4
2019-04-06T21:36:13.000Z
2021-03-11T23:23:30.000Z
config/test.exs
esl/buildex_poller
dd535ea5cb903a0a476b5310e7d9127672206b08
[ "Apache-2.0" ]
1
2019-01-29T20:02:20.000Z
2019-01-30T09:22:12.000Z
config/test.exs
esl/buildex_poller
dd535ea5cb903a0a476b5310e7d9127672206b08
[ "Apache-2.0" ]
2
2021-03-11T23:27:11.000Z
2022-03-06T10:20:25.000Z
use Mix.Config config :logger, level: :warn config :buildex_poller, :db_name, "test.tab" # https://github.com/pma/amqp/wiki/Upgrade-from-0.X-to-1.0#lager config :lager, handlers: [level: :critical] config :buildex_poller, :database, Buildex.Common.Services.FakeDatabase
33.875
71
0.763838
93c3ad05cb95051d1165632cc1f9b24391322d87
346
ex
Elixir
lib/grax/application.ex
rdf-elixir/grax
9628f66d7961cbe62fb38803cb172e67006093af
[ "MIT" ]
17
2021-01-06T12:11:28.000Z
2021-05-26T00:39:37.000Z
lib/grax/application.ex
rdf-elixir/grax
9628f66d7961cbe62fb38803cb172e67006093af
[ "MIT" ]
null
null
null
lib/grax/application.ex
rdf-elixir/grax
9628f66d7961cbe62fb38803cb172e67006093af
[ "MIT" ]
null
null
null
defmodule Grax.Application do @moduledoc false use Application @impl true def start(_type, _args) do children = [ Grax.Id.Counter.Supervisor, {Registry, keys: :unique, name: Grax.Id.Counter.registry()} ] opts = [strategy: :one_for_one, name: Grax.Supervisor] Supervisor.start_link(children, opts) end end
20.352941
65
0.679191
93c3f33eeb0dc8e7100a72dcc1d9a05afd81f646
1,612
ex
Elixir
lib/basic_web/live/delivery_live/form_component.ex
ysaito8015/communitex
d469447a62029d59883d95df4df3c9b09e0022e2
[ "Apache-2.0" ]
7
2021-07-14T15:45:55.000Z
2022-01-25T11:13:01.000Z
lib/basic_web/live/delivery_live/form_component.ex
ysaito8015/communitex
d469447a62029d59883d95df4df3c9b09e0022e2
[ "Apache-2.0" ]
10
2021-08-09T15:54:05.000Z
2022-02-17T04:18:38.000Z
lib/basic_web/live/delivery_live/form_component.ex
ysaito8015/communitex
d469447a62029d59883d95df4df3c9b09e0022e2
[ "Apache-2.0" ]
5
2021-07-23T05:54:35.000Z
2022-01-28T04:14:51.000Z
defmodule BasicWeb.DeliveryLive.FormComponent do use BasicWeb, :live_component alias Basic.Deliveries @impl true def update(%{delivery: delivery} = assigns, socket) do changeset = Deliveries.change_delivery(delivery) {:ok, socket |> assign(assigns) |> assign(:changeset, changeset)} end @impl true def handle_event("validate", %{"delivery" => delivery_params}, socket) do changeset = socket.assigns.delivery |> Deliveries.change_delivery(delivery_params) |> Map.put(:action, :validate) {:noreply, assign(socket, :changeset, changeset)} end def handle_event("save", %{"delivery" => delivery_params}, socket) do save_delivery(socket, socket.assigns.action, delivery_params) end defp save_delivery(socket, :edit, delivery_params) do case Deliveries.update_delivery(socket.assigns.delivery, delivery_params) do {:ok, _delivery} -> {:noreply, socket |> put_flash(:info, "Delivery updated successfully") |> push_redirect(to: socket.assigns.return_to)} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, :changeset, changeset)} end end defp save_delivery(socket, :new, delivery_params) do case Deliveries.create_delivery(delivery_params) do {:ok, _delivery} -> {:noreply, socket |> put_flash(:info, "Delivery created successfully") |> push_redirect(to: socket.assigns.return_to)} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, changeset: changeset)} end end end
28.785714
80
0.663772
93c3fe20de6b9aa34da5735d14074ee5ec159511
1,743
exs
Elixir
phoenix/config/dev.exs
MilesChou/ironman2020-sample
0d0c22fd744cd9605eb5b95668dc00a7bbec7a57
[ "MIT" ]
null
null
null
phoenix/config/dev.exs
MilesChou/ironman2020-sample
0d0c22fd744cd9605eb5b95668dc00a7bbec7a57
[ "MIT" ]
null
null
null
phoenix/config/dev.exs
MilesChou/ironman2020-sample
0d0c22fd744cd9605eb5b95668dc00a7bbec7a57
[ "MIT" ]
null
null
null
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with webpack to recompile .js and .css sources. config :ironman, IronmanWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :ironman, IronmanWeb.Endpoint, live_reload: [ patterns: [ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", ~r"lib/ironman_web/(live|views)/.*(ex)$", ~r"lib/ironman_web/templates/.*(eex)$" ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime
29.05
68
0.701664
93c3ffc9f24b52e3521f2eb2573019ef57791f83
1,714
exs
Elixir
config/config.exs
hyperserve/portfolio
5a144c33ad0d26ec188da07f8cdece05cd821ed7
[ "MIT" ]
1
2022-03-18T10:57:04.000Z
2022-03-18T10:57:04.000Z
config/config.exs
hyperserve/portfolio
5a144c33ad0d26ec188da07f8cdece05cd821ed7
[ "MIT" ]
null
null
null
config/config.exs
hyperserve/portfolio
5a144c33ad0d26ec188da07f8cdece05cd821ed7
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. # General application configuration import Config config :portfolio, ecto_repos: [Portfolio.Repo] # Configures the endpoint config :portfolio, PortfolioWeb.Endpoint, url: [host: "localhost"], render_errors: [view: PortfolioWeb.ErrorView, accepts: ~w(html json), layout: false], pubsub_server: Portfolio.PubSub, live_view: [signing_salt: "+1muUeRV"] # Configures the mailer # # By default it uses the "Local" adapter which stores the emails # locally. You can see the emails in your browser, at "/dev/mailbox". # # For production it's recommended to configure a different adapter # at the `config/runtime.exs`. config :portfolio, Portfolio.Mailer, adapter: Swoosh.Adapters.Local # Swoosh API client is needed for adapters other than SMTP. config :swoosh, :api_client, false # Configure esbuild (the version is required) config :esbuild, version: "0.14.0", default: [ args: ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*), cd: Path.expand("../assets", __DIR__), env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} ] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Use Jason for JSON parsing in Phoenix config :phoenix, :json_library, Jason # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{config_env()}.exs"
32.339623
117
0.734539
93c425cd62012d69afd18dde3d3a1500a2d5f122
1,500
ex
Elixir
clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_get_policy_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_get_policy_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_get_policy_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # 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. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.SASPortal.V1alpha1.Model.SasPortalGetPolicyRequest do @moduledoc """ Request message for `GetPolicy` method. ## Attributes * `resource` (*type:* `String.t`, *default:* `nil`) - Required. The resource for which the policy is being requested. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :resource => String.t() } field(:resource) end defimpl Poison.Decoder, for: GoogleApi.SASPortal.V1alpha1.Model.SasPortalGetPolicyRequest do def decode(value, options) do GoogleApi.SASPortal.V1alpha1.Model.SasPortalGetPolicyRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.SASPortal.V1alpha1.Model.SasPortalGetPolicyRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.914894
121
0.748667
93c4288260eca508407b97cbc4182e8f0302b19c
1,479
ex
Elixir
lib/basic_web/live/item_live/form_component.ex
naritomo08/communitex
21d27b6fa497cfd28fab03e36593eb530268efe6
[ "Apache-2.0" ]
1
2022-03-06T09:24:41.000Z
2022-03-06T09:24:41.000Z
lib/basic_web/live/item_live/form_component.ex
naritomo08/communitex
21d27b6fa497cfd28fab03e36593eb530268efe6
[ "Apache-2.0" ]
null
null
null
lib/basic_web/live/item_live/form_component.ex
naritomo08/communitex
21d27b6fa497cfd28fab03e36593eb530268efe6
[ "Apache-2.0" ]
null
null
null
defmodule BasicWeb.ItemLive.FormComponent do use BasicWeb, :live_component alias Basic.Items @impl true def update(%{item: item} = assigns, socket) do changeset = Items.change_item(item) {:ok, socket |> assign(assigns) |> assign(:changeset, changeset)} end @impl true def handle_event("validate", %{"item" => item_params}, socket) do changeset = socket.assigns.item |> Items.change_item(item_params) |> Map.put(:action, :validate) {:noreply, assign(socket, :changeset, changeset)} end def handle_event("save", %{"item" => item_params}, socket) do save_item(socket, socket.assigns.action, item_params) end defp save_item(socket, :edit, item_params) do case Items.update_item(socket.assigns.item, item_params) do {:ok, _item} -> {:noreply, socket |> put_flash(:info, "Item updated successfully") |> push_redirect(to: socket.assigns.return_to)} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, :changeset, changeset)} end end defp save_item(socket, :new, item_params) do case Items.create_item(item_params) do {:ok, _item} -> {:noreply, socket |> put_flash(:info, "Item created successfully") |> push_redirect(to: socket.assigns.return_to)} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, changeset: changeset)} end end end
26.410714
67
0.633536
93c455890c769982fbd8509ef276ffbca857ecd0
7,107
ex
Elixir
lib/grizzly/zwave/commands/alarm_report.ex
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
null
null
null
lib/grizzly/zwave/commands/alarm_report.ex
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
null
null
null
lib/grizzly/zwave/commands/alarm_report.ex
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
null
null
null
defmodule Grizzly.ZWave.Commands.AlarmReport do @moduledoc """ This command notifies the application of the alarm state (v1, v2) or the notification state (v8). Params: * `:type` - the specific alarm type being reported - this different for each application, see device user manual for more details (required) * `:level` - the level is device specific, see device user manual for more details (required) * `:zensor_net_node_id` - the Zensor net node, if the device is not based off of Zensor Net, then this field is `0` (v2, optional, default 0) * `:zwave_status` - if the device alarm status is :enabled or :disabled (v2) * `:zwave_type` - part of `Grizzly.ZWave.Notifications` spec (v2) * `:zwave_event` - part of the `Grizzly.ZWave.Notifications` spec (v2) * `:event_parameters` - additional parameters for the event as keyword list, see user manual for more information (v2+, optional, default `[]`) """ @behaviour Grizzly.ZWave.Command alias Grizzly.ZWave alias Grizzly.ZWave.{Command, DecodeError, Notifications} alias Grizzly.ZWave.CommandClasses.Alarm @type param :: {:type, byte()} | {:level, byte()} | {:zensor_net_node_id, ZWave.node_id()} | {:zwave_status, Notifications.status()} | {:zwave_event, Notifications.event()} | {:zwave_type, Notifications.type()} | {:sequence_number, byte()} | {:event_parameters, [byte()]} @impl true @spec new([param()]) :: {:ok, Command.t()} def new(params) do # TODO: validate params command = %Command{ name: :alarm_report, command_byte: 0x05, command_class: Alarm, params: build_params(params), impl: __MODULE__ } {:ok, command} end @impl true @spec encode_params(Command.t()) :: binary() def encode_params(command) do cond do Command.param(command, :sequence_number) != nil -> encode_v8(command) Command.param(command, :zensor_net_node_id) != nil -> encode_v2(command) true -> encode_v1(command) end end @impl true @spec decode_params(binary()) :: {:ok, [param()]} | {:error, DecodeError.t()} def decode_params(<<type, level>>) do {:ok, [type: type, level: level]} end def decode_params(<< type, level, zensor_node_id, status_byte, zwave_type_byte, zwave_event_byte, 0x00::size(1), 0x00::size(2), params_length::size(5), event_params::binary-size(params_length), # Sometimes a 0 seq_number is added _::binary >>) do with {:ok, zwave_type} <- Notifications.type_from_byte(zwave_type_byte), {:ok, zwave_event} <- Notifications.event_from_byte(zwave_type, zwave_event_byte), {:ok, zwave_status} <- Notifications.status_from_byte(status_byte), {:ok, event_parameters} <- Notifications.decode_event_params(zwave_type, zwave_event, event_params) do {:ok, [ type: type, level: level, zensor_net_node_id: zensor_node_id, zwave_status: zwave_status, zwave_type: zwave_type, zwave_event: zwave_event, event_parameters: event_parameters ]} else {:error, :invalid_type_byte} -> {:error, %DecodeError{value: zwave_type_byte, param: :zwave_type, command: :alarm_report}} {:error, :invalid_event_byte} -> {:error, %DecodeError{value: zwave_event_byte, param: :zwave_event, command: :alarm_report}} error -> error end end def decode_params( <<type, level, zensor_node_id, status_byte, zwave_type_byte, zwave_event_byte, 0x01::size(1), 0x00::size(2), params_length::size(5), event_params::binary-size(params_length), sequence_number>> ) do with {:ok, zwave_type} <- Notifications.type_from_byte(zwave_type_byte), {:ok, zwave_event} <- Notifications.event_from_byte(zwave_type, zwave_event_byte), {:ok, zwave_status} <- Notifications.status_from_byte(status_byte), {:ok, event_parameters} <- Notifications.decode_event_params(zwave_type, zwave_event, event_params) do {:ok, [ type: type, level: level, zensor_net_node_id: zensor_node_id, zwave_status: zwave_status, zwave_type: zwave_type, zwave_event: zwave_event, event_parameters: event_parameters, sequence_number: sequence_number ]} else {:error, :invalid_type_byte} -> {:error, %DecodeError{value: zwave_type_byte, param: :zwave_type, command: :alarm_report}} {:error, :invalid_event_byte} -> {:error, %DecodeError{value: zwave_event_byte, param: :zwave_event, command: :alarm_report}} error -> error end end defp encode_v1(command) do type = Command.param!(command, :type) level = Command.param!(command, :level) <<type, level>> end defp encode_v2(command) do type = Command.param!(command, :type) level = Command.param!(command, :level) zensor_node_id = Command.param!(command, :zensor_net_node_id) zwave_status = Command.param!(command, :zwave_status) zwave_type = Command.param!(command, :zwave_type) zwave_event = Command.param!(command, :zwave_event) event_params = Command.param!(command, :event_parameters) encoded_event_params = Notifications.encode_event_params(zwave_type, zwave_event, event_params) params_length = byte_size(encoded_event_params) <<type, level, zensor_node_id, Notifications.status_to_byte(zwave_status), Notifications.type_to_byte(zwave_type), Notifications.event_to_byte(zwave_type, zwave_event), params_length>> <> encoded_event_params end defp encode_v8(command) do type = Command.param!(command, :type) level = Command.param!(command, :level) zwave_status = Command.param!(command, :zwave_status) zwave_type = Command.param!(command, :zwave_type) zwave_event = Command.param!(command, :zwave_event) sequence_number = Command.param!(command, :sequence_number) event_params = Command.param!(command, :event_parameters) encoded_event_params = Notifications.encode_event_params(zwave_type, zwave_event, event_params) params_length = byte_size(encoded_event_params) <<type, level, 0x00, Notifications.status_to_byte(zwave_status), Notifications.type_to_byte(zwave_type), Notifications.event_to_byte(zwave_type, zwave_event), 0x01::size(1), 0x00::size(2), params_length::size(5)>> <> encoded_event_params <> <<sequence_number>> end # TODO - Actually translate into report commands # defp params_from_binary(<<0>>), do: [] # defp params_from_binary(params_bin), do: :erlang.binary_to_list(params_bin) defp build_params(params) do if Keyword.has_key?(params, :zwave_type) do Keyword.merge([zensor_net_node_id: 0, event_parameters: []], params) else params end end end
33.842857
99
0.659772
93c45855cf070f3d1b0431307f2c8614bb98d02d
501
ex
Elixir
lib/mail_slurp_api/model/inbox_ruleset_test_options.ex
mailslurp/mailslurp-client-elixir
5b98b91bb327de5216e873cd45b4fbb3c1b55c90
[ "MIT" ]
1
2021-06-17T18:07:49.000Z
2021-06-17T18:07:49.000Z
lib/mail_slurp_api/model/inbox_ruleset_test_options.ex
mailslurp/mailslurp-client-elixir
5b98b91bb327de5216e873cd45b4fbb3c1b55c90
[ "MIT" ]
null
null
null
lib/mail_slurp_api/model/inbox_ruleset_test_options.ex
mailslurp/mailslurp-client-elixir
5b98b91bb327de5216e873cd45b4fbb3c1b55c90
[ "MIT" ]
1
2021-03-16T18:55:56.000Z
2021-03-16T18:55:56.000Z
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule MailSlurpAPI.Model.InboxRulesetTestOptions do @moduledoc """ """ @derive [Poison.Encoder] defstruct [ :"testTarget" ] @type t :: %__MODULE__{ :"testTarget" => String.t } end defimpl Poison.Decoder, for: MailSlurpAPI.Model.InboxRulesetTestOptions do def decode(value, _options) do value end end
19.269231
91
0.706587
93c45ab5887595e0032214b87d71ee637bab56cd
1,918
ex
Elixir
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/product_visibility.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/product_visibility.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/product_visibility.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # 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 &quot;AS IS&quot; 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. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AndroidEnterprise.V1.Model.ProductVisibility do @moduledoc """ A product to be made visible to a user. ## Attributes - productId (String.t): The product ID to make visible to the user. Required for each item in the productVisibility list. Defaults to: `null`. - trackIds ([String.t]): Grants the user visibility to the specified product track(s), identified by trackIds. Defaults to: `null`. - tracks ([String.t]): Deprecated. Use trackIds instead. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :productId => any(), :trackIds => list(any()), :tracks => list(any()) } field(:productId) field(:trackIds, type: :list) field(:tracks, type: :list) end defimpl Poison.Decoder, for: GoogleApi.AndroidEnterprise.V1.Model.ProductVisibility do def decode(value, options) do GoogleApi.AndroidEnterprise.V1.Model.ProductVisibility.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidEnterprise.V1.Model.ProductVisibility do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.518519
144
0.732013
93c4682c130d521f90cf7e4d70c33631d411a992
1,437
exs
Elixir
rel/config.exs
mbta/alerts_concierge
d8e643445ef06f80ca273f2914c6959daea146f6
[ "MIT" ]
null
null
null
rel/config.exs
mbta/alerts_concierge
d8e643445ef06f80ca273f2914c6959daea146f6
[ "MIT" ]
21
2021-03-12T17:05:30.000Z
2022-02-16T21:48:35.000Z
rel/config.exs
mbta/alerts_concierge
d8e643445ef06f80ca273f2914c6959daea146f6
[ "MIT" ]
1
2021-12-09T15:09:53.000Z
2021-12-09T15:09:53.000Z
# Import all plugins from `rel/plugins` # They can then be used by adding `plugin MyPlugin` to # either an environment, or release definition, where # `MyPlugin` is the name of the plugin module. Path.join(["rel", "plugins", "*.exs"]) |> Path.wildcard() |> Enum.map(&Code.eval_file(&1)) use Mix.Releases.Config, # This sets the default release built by `mix release` default_release: :default, # This sets the default environment used by `mix release` default_environment: Mix.env() # For a full list of config options for both releases # and environments, visit https://hexdocs.pm/distillery/configuration.html # You may define one or more environments in this file, # an environment's settings will override those of a release # when building in that environment, this combination of release # and environment configuration is called a profile environment :prod do set(include_erts: true) set(include_src: false) set(cookie: :";=M!```gFQ$}jAUj(N2_%dhCerD]s^3w7J.`bx=w[i.&h%InUY^V4J,]vyKH!~Ds") set(vm_args: "rel/prod.vm.args") end # You may define one or more releases in this file. # If you have not set a default release, or selected one # when running `mix release`, the first release in the file # will be used by default release :alerts_concierge do set(version: "current") set( applications: [ :runtime_tools, alert_processor: :permanent, concierge_site: :permanent ] ) end
31.23913
82
0.725818
93c47cae8e3302785abf74de2e584fa2d4553343
1,492
ex
Elixir
clients/webmaster/lib/google_api/webmaster/v3/model/api_data_row.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/webmaster/lib/google_api/webmaster/v3/model/api_data_row.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/webmaster/lib/google_api/webmaster/v3/model/api_data_row.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # 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 &quot;AS IS&quot; 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. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Webmaster.V3.Model.ApiDataRow do @moduledoc """ ## Attributes - clicks (Float): Defaults to: `null`. - ctr (Float): Defaults to: `null`. - impressions (Float): Defaults to: `null`. - keys (List[String]): Defaults to: `null`. - position (Float): Defaults to: `null`. """ defstruct [ :"clicks", :"ctr", :"impressions", :"keys", :"position" ] end defimpl Poison.Decoder, for: GoogleApi.Webmaster.V3.Model.ApiDataRow do def decode(value, _options) do value end end defimpl Poison.Encoder, for: GoogleApi.Webmaster.V3.Model.ApiDataRow do def encode(value, options) do GoogleApi.Webmaster.V3.Deserializer.serialize_non_nil(value, options) end end
27.62963
77
0.714477
93c49d131ceb8e3f363fc6792e4578c5d72b9d2b
16,413
ex
Elixir
lib/elixir/lib/gen_server.ex
jw2013/elixir
ebc5afed90576a16c4f6e22d68222413db8358cc
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/gen_server.ex
jw2013/elixir
ebc5afed90576a16c4f6e22d68222413db8358cc
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/gen_server.ex
jw2013/elixir
ebc5afed90576a16c4f6e22d68222413db8358cc
[ "Apache-2.0" ]
null
null
null
defmodule GenServer do @moduledoc """ A behaviour module for implementing the server of a client-server relation. A GenServer is a process as any other Elixir process and it can be used to keep state, execute code asynchronously and so on. The advantage of using a generic server process (GenServer) implemented using this module is that it will have a standard set of interface functions and include functionality for tracing and error reporting. It will also fit into a supervision tree. ## Example The GenServer behaviour abstracts the common client-server interaction. Developers are only required to implement the callbacks and functionality they are interested in. Let's start with a code example and then explore the available callbacks. Imagine we want a GenServer that works like a stack, allowing us to push and pop items: defmodule Stack do use GenServer # Callbacks def handle_call(:pop, _from, [h|t]) do {:reply, h, t} end def handle_cast({:push, item}, state) do {:noreply, [item|state]} end end # Start the server {:ok, pid} = GenServer.start_link(Stack, [:hello]) # This is the client GenServer.call(pid, :pop) #=> :hello GenServer.cast(pid, {:push, :world}) #=> :ok GenServer.call(pid, :pop) #=> :world We start our `Stack` by calling `start_link/3`, passing the module with the server implementation and its initial argument (a list representing the stack containing the item `:hello`). We can primarily interact with the server by sending two types of messages. **call** messages expect a reply from the server (and are therefore synchronous) while **cast** messages do not. Every time you do a `GenServer.call/3`, the client will send a message that must be handled by the `handle_call/3` callback in the GenServer. A `cast/2` message must be handled by `handle_cast/2`. ## Callbacks There are 6 callbacks required to be implemented in a `GenServer`. By adding `use GenServer` to your module, Elixir will automatically define all 6 callbacks for you, leaving it up to you to implement the ones you want to customize. The callbacks are: * `init(args)` - invoked when the server is started. It must return: - `{:ok, state}` - `{:ok, state, timeout}` - `{:ok, state, :hibernate}` - `:ignore` - `{:stop, reason}` * `handle_call(msg, {from, ref}, state)` and `handle_cast(msg, state)` - invoked to handle call (sync) and cast (async) messages. It must return: - `{:reply, reply, new_state}` - `{:reply, reply, new_state, timeout}` - `{:reply, reply, new_state, :hibernate}` - `{:noreply, new_state}` - `{:noreply, new_state, timeout}` - `{:noreply, new_state, :hibernate}` - `{:stop, reason, new_state}` - `{:stop, reason, reply, new_state}` * `handle_info(msg, state)` - invoked to handle all other messages which are received by the process. It must return: - `{:noreply, state}` - `{:noreply, state, timeout}` - `{:stop, reason, state}` * `terminate(reason, state)` - called when the server is about to terminate, useful for cleaning up. It must return `:ok`. * `code_change(old_vsn, state, extra)` - called when the application code is being upgraded live (hot code swapping). It must return: - `{:ok, new_state}` - `{:error, reason}` ## Name Registration Both `start_link/3` and `start/3` support the `GenServer` to register a name on start via the `:name` option. Registered names are also automatically cleaned up on termination. The supported values are: * an atom - the GenServer is registered locally with the given name using `Process.register/2`. * `{:global, term}`- the GenServer is registered globally with the given term using the functions in the `:global` module. * `{:via, module, term}` - the GenServer is registered with the given mechanism and name. The `:via` option expects a module name to control the registration mechanism alongside a name which can be any term. For example, we could start and register our Stack server locally as follows: # Start the server and register it locally with name MyStack {:ok, _} = GenServer.start_link(Stack, [:hello], name: MyStack) # Now messages can be sent directly to MyStack GenServer.call(MyStack, :pop) #=> :hello Once the server is started, the remaining functions in this module (`call/3`, `cast/2`, and friends) will also accept an atom, or any `:global` or `:via` tuples. In general, the following formats are supported: * a `pid` * an `atom` if the server is locally registered * `{atom, node}` if the server is locally registered at another node * `{:global, term}` if the server is globally registered * `{:via, module, name}` if the server is registered through an alternative registry ## Client / Server APIs Although in the example above we have used `GenServer.start_link/3` and friends to directly start and communicate with the server, most of the time we don't call the `GenServer` functions directly. Instead, we wrap the calls in new functions representing the public API of the server. Here is a better implementation of our Stack module: defmodule Stack do use GenServer # Client def start_link(default) do GenServer.start_link(__MODULE__, default) end def push(pid, item) do GenServer.cast(pid, {:push, item}) end def pop(pid) do GenServer.call(pid, :pop) end # Server (callbacks) def handle_call(:pop, _from, [h|t]) do {:reply, h, t} end def handle_call(request, from, state) do # Call the default implementation from GenServer super(request, from, state) end def handle_cast({:push, item}, state) do {:noreply, [item|state]} end def handle_cast(request, state) do super(request, state) end end In practice, it is common to have both server and client functions in the same module. If the server and/or client implementations are growing complex, you may want to have them in different modules. ## Learn more If you wish to find out more about gen servers, Elixir getting started guides provide a tutorial-like introduction. The documentation and links in Erlang can also provide extra insight. * http://elixir-lang.org/getting_started/mix_otp/1.html * http://www.erlang.org/doc/man/gen_server.html * http://www.erlang.org/doc/design_principles/gen_server_concepts.html * http://learnyousomeerlang.com/clients-and-servers """ @typedoc "Return values of `start*` functions" @type on_start :: {:ok, pid} | :ignore | {:error, {:already_started, pid} | term} @typedoc "The GenServer name" @type name :: atom | {:global, term} | {:via, module, term} @typedoc "Options used by the `start*` functions" @type options :: [debug: debug, name: name, timeout: timeout, spawn_opt: Process.spawn_opt] @typedoc "debug options supported by the `start*` functions" @type debug :: [:trace | :log | :statistics | {:log_to_file, Path.t}] @typedoc "The server reference" @type server :: pid | name | {atom, node} @doc false defmacro __using__(_) do quote location: :keep do @behaviour :gen_server @doc false def init(args) do {:ok, args} end @doc false def handle_call(msg, _from, state) do {:stop, {:bad_call, msg}, state} end @doc false def handle_info(_msg, state) do {:noreply, state} end @doc false def handle_cast(msg, state) do {:stop, {:bad_cast, msg}, state} end @doc false def terminate(_reason, _state) do :ok end @doc false def code_change(_old, state, _extra) do {:ok, state} end defoverridable [init: 1, handle_call: 3, handle_info: 2, handle_cast: 2, terminate: 2, code_change: 3] end end @doc """ Starts a `GenServer` process linked to the current process. This is often used to start the `GenServer` as part of a supervision tree. Once the server is started, it calls the `init/1` function in the given `module` passing the given `args` to initialize it. To ensure a synchronized start-up procedure, this function does not return until `init/1` has returned. Note that a `GenServer` started with `start_link/3` is linked to the parent process and will exit in case of crashes. The GenServer will also exit due to the `:normal` reasons in case it is configured to trap exits in the `init/1` callback. ## Options The `:name` option is used for name registration as described in the module documentation. If the option `:timeout` option is present, the server is allowed to spend the given milliseconds initializing or it will be terminated and the start function will return `{:error, :timeout}`. If the `:debug` option is present, the corresponding function in the [`:sys` module](http://www.erlang.org/doc/man/sys.html) will be invoked. If the `:spawn_opt` option is present, its value will be passed as options to the underlying process as in `Process.spawn/4`. ## Return values If the server is successfully created and initialized, the function returns `{:ok, pid}`, where pid is the pid of the server. If there already exists a process with the specified server name, the function returns `{:error, {:already_started, pid}}` with the pid of that process. If the `init/1` callback fails with `reason`, the function returns `{:error, reason}`. Otherwise, if it returns `{:stop, reason}` or `:ignore`, the process is terminated and the function returns `{:error, reason}` or `:ignore`, respectively. """ @spec start_link(module, any, options) :: on_start def start_link(module, args, options \\ []) when is_atom(module) and is_list(options) do do_start(:link, module, args, options) end @doc """ Starts a `GenServer` process without links (outside of a supervision tree). See `start_link/3` for more information. """ @spec start(module, any, options) :: on_start def start(module, args, options \\ []) when is_atom(module) and is_list(options) do do_start(:nolink, module, args, options) end defp do_start(link, module, args, options) do case Keyword.pop(options, :name) do {nil, opts} -> :gen.start(:gen_server, link, module, args, opts) {atom, opts} when is_atom(atom) -> :gen.start(:gen_server, link, {:local, atom}, module, args, opts) {other, opts} when is_tuple(other) -> :gen.start(:gen_server, link, other, module, args, opts) end end @doc """ Makes a synchronous call to the `server` and waits for its reply. The client sends the given `request` to the server and waits until a reply arrives or a timeout occurs. `handle_call/3` will be called on the server to handle the request. The server can be any of the values described in the `Name Registration` section of the module documentation. ## Timeouts The `timeout` is an integer greater than zero which specifies how many milliseconds to wait for a reply, or the atom `:infinity` to wait indefinitely. The default value is 5000. If no reply is received within the specified time, the function call fails. If the caller catches the failure and continues running, and the server is just late with the reply, it may arrive at any time later into the caller's message queue. The caller must in this case be prepared for this and discard any such garbage messages that are two element tuples with a reference as the first element. """ @spec call(server, term, timeout) :: term def call(server, request, timeout \\ 5000) do try do :gen.call(server, :"$gen_call", request, timeout) catch :exit, reason -> exit({reason, {__MODULE__, :call, [server, request, timeout]}}) else {:ok, res} -> res end end @doc """ Sends an asynchronous request to the `server`. This function returns `:ok` without waiting for the destination `server` to handle the message. Therefore it is unknown whether the destination `server` successfully handled the message. If the `server` is an atom without an associated process an `ArgumentError` is raised. In all other cases the function returns `:ok` regardless of whether the destination `server` (or node) exists. Note that `{name, node()}` can be used when an exception is not desired if no process is locally associated with the atom `name`. `handle_cast/2` will be called on the server to handle the request. In case the `server` is on a node which is not yet connected to the caller one, the call is going to block until a connection happens. This is different than the behaviour in OTP's `:gen_server` where the message is sent by another process in this case, which could cause messages to other nodes to arrive out of order. """ @spec cast(server, term) :: :ok def cast(server, request) def cast({:global, name}, request) do try do :global.send(name, cast_msg(request)) :ok catch _, _ -> :ok end end def cast({:via, mod, name}, request) do try do mod.send(name, cast_msg(request)) :ok catch _, _ -> :ok end end def cast({name, node}, request) when is_atom(name) and is_atom(node), do: do_send({name, node}, cast_msg(request)) def cast(dest, request) when is_atom(dest) or is_pid(dest), do: do_send(dest, cast_msg(request)) @doc """ Casts all servers locally registered as `name` at the specified nodes. The function returns immediately and ignores nodes that do not exist, or where the server name does not exist. See `multi_call/4` for more information. """ @spec abcast([node], name :: atom, term) :: :abcast def abcast(nodes \\ nodes(), name, request) when is_list(nodes) and is_atom(name) do msg = cast_msg(request) _ = for node <- nodes, do: do_send({name, node}, msg) :abcast end defp cast_msg(req) do {:"$gen_cast", req} end defp do_send(dest, msg) do send(dest, msg) :ok end @doc """ Calls all servers locally registered as `name` at the specified `nodes`. The `request` is first sent to every node and then we wait for the replies. This function returns a tuple containing the node and its reply as first element and all bad nodes as second element. The bad nodes is a list of nodes that either did not exist, or where a server with the given `name` did not exist or did not reply. Nodes is a list of node names to which the request is sent. The default value is the list of all known nodes. To avoid that late answers (after the timeout) pollute the caller's message queue, a middleman process is used to do the actual calls. Late answers will then be discarded when they arrive to a terminated process. """ @spec multi_call([node], name :: atom, term, timeout) :: {replies :: [{node, term}], bad_nodes :: [node]} def multi_call(nodes \\ nodes(), name, request, timeout \\ :infinity) do :gen_server.multi_call(nodes, name, request, timeout) end @doc """ Replies to a client. This function can be used by a server to explicitly send a reply to a client that called `call/3` or `multi_call/4`. When the reply cannot be defined in the return value of `handle_call/3`. The `client` must be the `from` argument (the second argument) received in `handle_call/3` callbacks. Reply is an arbitrary term which will be given back to the client as the return value of the call. This function always returns `:ok`. """ @spec reply({pid, reference}, term) :: :ok def reply(client, reply) def reply({to, tag}, reply) do try do send(to, {tag, reply}) :ok catch _, _ -> :ok end end @compile {:inline, [nodes: 0]} defp nodes do [node()|:erlang.nodes()] end end
33.564417
90
0.669835
93c4c65136c3db251b3a41ef8902579a58abaea6
1,850
ex
Elixir
lib/events_tools/comments/comments.ex
community-tools/community-tools
40b0e6cc9234b44593d2ab60bb2303d7224deb30
[ "Apache-2.0" ]
2
2017-10-06T01:14:35.000Z
2017-11-18T16:44:44.000Z
lib/events_tools/comments/comments.ex
community-tools/community-tools
40b0e6cc9234b44593d2ab60bb2303d7224deb30
[ "Apache-2.0" ]
6
2017-10-06T00:04:59.000Z
2017-10-06T00:09:27.000Z
lib/events_tools/comments/comments.ex
apps-team/community-tools
40b0e6cc9234b44593d2ab60bb2303d7224deb30
[ "Apache-2.0" ]
1
2017-10-06T01:17:35.000Z
2017-10-06T01:17:35.000Z
defmodule CommunityTools.Comments do @moduledoc """ The boundary for the Comments system. """ import Ecto.Query, warn: false alias CommunityTools.Repo alias CommunityTools.Comments.Comment @doc """ Returns the list of comments. ## Examples iex> list_comments() [%Comment{}, ...] """ def list_comments do Repo.all(Comment) end @doc """ Gets a single comment. Raises `Ecto.NoResultsError` if the Comment does not exist. ## Examples iex> get_comment!(123) %Comment{} iex> get_comment!(456) ** (Ecto.NoResultsError) """ def get_comment!(id), do: Repo.get!(Comment, id) @doc """ Creates a comment. ## Examples iex> create_comment(%{field: value}) {:ok, %Comment{}} iex> create_comment(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ def create_comment(attrs \\ %{}) do %Comment{} |> Comment.changeset(attrs) |> Repo.insert() end @doc """ Updates a comment. ## Examples iex> update_comment(comment, %{field: new_value}) {:ok, %Comment{}} iex> update_comment(comment, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def update_comment(%Comment{} = comment, attrs) do comment |> Comment.changeset(attrs) |> Repo.update() end @doc """ Deletes a Comment. ## Examples iex> delete_comment(comment) {:ok, %Comment{}} iex> delete_comment(comment) {:error, %Ecto.Changeset{}} """ def delete_comment(%Comment{} = comment) do Repo.delete(comment) end @doc """ Returns an `%Ecto.Changeset{}` for tracking comment changes. ## Examples iex> change_comment(comment) %Ecto.Changeset{source: %Comment{}} """ def change_comment(%Comment{} = comment) do Comment.changeset(comment, %{}) end end
17.619048
62
0.608108
93c52990ccd94e2c23872d8975410e98787dafd4
1,567
exs
Elixir
test/norm/contract_test.exs
blackbox-solutions/norm
12ea8e191b48b58a5a92f7e4ae92084a4ccd8669
[ "MIT" ]
1
2019-12-27T18:28:14.000Z
2019-12-27T18:28:14.000Z
test/norm/contract_test.exs
wojtekmach/norm
651266a07e947d1057d31744e9eab459dcc4afe7
[ "MIT" ]
1
2020-10-01T22:40:59.000Z
2020-10-01T22:40:59.000Z
test/norm/contract_test.exs
NarrativeApp/norm
a66621c8a31d57370d56c07dec5bc035dc7f3c75
[ "MIT" ]
1
2021-03-02T10:49:33.000Z
2021-03-02T10:49:33.000Z
defmodule Norm.ContractTest do use ExUnit.Case, async: true test "success" do defmodule Success do use Norm @contract foo(n :: spec(is_integer())) :: spec(is_integer()) def foo(n), do: n end assert Success.foo(42) == 42 end test "arg mismatch" do defmodule ArgMismatch do use Norm @contract foo(n :: spec(is_integer())) :: spec(is_integer()) def foo(n), do: n end assert_raise Norm.MismatchError, ~r/val: "42" fails: is_integer\(\)/, fn -> ArgMismatch.foo("42") end end test "result mismatch" do defmodule ResultMismatch do use Norm @contract foo(n :: spec(is_integer())) :: spec(is_binary()) def foo(n), do: n end assert_raise Norm.MismatchError, ~r/val: 42 fails: is_binary\(\)/, fn -> ResultMismatch.foo(42) end end test "bad contract" do assert_raise ArgumentError, ~r/got: `@contract\(foo\(n\)\)`/, fn -> defmodule BadContract do use Norm @contract foo(n) def foo(n), do: n end end end test "bad arg" do assert_raise ArgumentError, ~r/`arg :: spec`, got: `spec\(is_integer\(\)\)`/, fn -> defmodule BadArg do use Norm @contract foo(spec(is_integer())) :: spec(is_integer()) def foo(n), do: n end end end test "no function" do assert_raise ArgumentError, "contract for undefined function foo/0", fn -> defmodule NoFunction do use Norm @contract foo() :: spec(is_integer()) end end end end
21.465753
87
0.588385
93c5332703b14f8616b17262989176c9aa412058
1,521
exs
Elixir
test/extracker/router_test.exs
Cantido/ex_tracker
32f5785a39b5da209e2a4564f6e004479283fc1e
[ "MIT" ]
1
2021-11-23T04:29:37.000Z
2021-11-23T04:29:37.000Z
test/extracker/router_test.exs
Cantido/ex_tracker
32f5785a39b5da209e2a4564f6e004479283fc1e
[ "MIT" ]
6
2020-11-10T03:44:44.000Z
2022-02-28T11:05:39.000Z
test/extracker/router_test.exs
Cantido/ex_tracker
32f5785a39b5da209e2a4564f6e004479283fc1e
[ "MIT" ]
1
2020-01-08T16:23:42.000Z
2020-01-08T16:23:42.000Z
# SPDX-FileCopyrightText: 2021 Rosa Richter # # SPDX-License-Identifier: MIT defmodule Extracker.RouterTest do use ExUnit.Case, async: true use Plug.Test setup_all do Extracker.set_interval(120) end describe "announce" do test "returns an empty response on the first announce" do info_hash = :crypto.strong_rand_bytes(20) on_exit(fn -> Extracker.drop(info_hash) end) params = %{ info_hash: Base.encode16(info_hash, lower: true), peer_id: "12345678901234567890", port: 8001, uploaded: 0, downloaded: 0, left: 0, event: "started" } |> URI.encode_query(:rfc3986) conn = conn(:get, "/announce?" <> params) conn = Extracker.Router.call(conn, []) assert conn.state == :sent assert conn.status == 200 body = Bento.decode!(conn.resp_body) assert body["complete"] == 0 assert body["incomplete"] == 1 assert body["interval"] == 120 end end describe "scrape" do test "returns ok" do info_hash = :crypto.strong_rand_bytes(20) params = %{ info_hash: Base.encode16(info_hash) } |> URI.encode_query(:rfc3986) conn = conn(:get, "/scrape?" <> params) conn = Extracker.Router.call(conn, []) assert conn.state == :sent assert conn.status == 200 body = Bento.decode!(conn.resp_body) assert Map.has_key?(body, info_hash) end end end
21.422535
61
0.587771
93c53971fc59c75f018c4aaca7419f8a70e0a090
205
exs
Elixir
priv/repo/migrations/20211104161120_resource_gating_index.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
1
2022-03-17T20:35:47.000Z
2022-03-17T20:35:47.000Z
priv/repo/migrations/20211104161120_resource_gating_index.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
9
2021-11-02T16:52:09.000Z
2022-03-25T15:14:01.000Z
priv/repo/migrations/20211104161120_resource_gating_index.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
null
null
null
defmodule Oli.Repo.Migrations.ResourceGatingIndex do use Ecto.Migration def change do alter table(:sections) do add :resource_gating_index, :map, default: %{}, null: false end end end
20.5
65
0.712195
93c53f2d4ff9170b06ac68bc6b8569155e1f2c66
999
ex
Elixir
Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/verification_ip_flow_parameters.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
4
2018-09-29T03:43:15.000Z
2021-04-01T18:30:46.000Z
Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/verification_ip_flow_parameters.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/verification_ip_flow_parameters.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
# NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule Microsoft.Azure.Management.Network.Model.VerificationIpFlowParameters do @moduledoc """ Parameters that define the IP flow to be verified. """ @derive [Poison.Encoder] defstruct [ :"targetResourceId", :"direction", :"protocol", :"localPort", :"remotePort", :"localIPAddress", :"remoteIPAddress", :"targetNicResourceId" ] @type t :: %__MODULE__{ :"targetResourceId" => String.t, :"direction" => String.t, :"protocol" => String.t, :"localPort" => String.t, :"remotePort" => String.t, :"localIPAddress" => String.t, :"remoteIPAddress" => String.t, :"targetNicResourceId" => String.t } end defimpl Poison.Decoder, for: Microsoft.Azure.Management.Network.Model.VerificationIpFlowParameters do def decode(value, _options) do value end end
24.975
101
0.677678
93c54d7db42f38c944e94c238dda0f811eed886c
423
ex
Elixir
lib/live_view_demo/code_breaker/solution.ex
manojsamanta/codebreaker-prototype
14d521db45784dee692de9e7252dd6a54bb793bb
[ "MIT" ]
null
null
null
lib/live_view_demo/code_breaker/solution.ex
manojsamanta/codebreaker-prototype
14d521db45784dee692de9e7252dd6a54bb793bb
[ "MIT" ]
null
null
null
lib/live_view_demo/code_breaker/solution.ex
manojsamanta/codebreaker-prototype
14d521db45784dee692de9e7252dd6a54bb793bb
[ "MIT" ]
null
null
null
defmodule LiveViewDemo.CodeBreaker.Solution do use Ecto.Schema import Ecto.Changeset schema "games" do field :exact, :integer field :partial, :integer field :solution, :string field :user_uid, :string timestamps() end @doc false def changeset(game, attrs) do game |> cast(attrs, [:user_uid, :colors, :solution]) |> validate_required([:user_uid, :colors, :solution]) end end
20.142857
57
0.673759
93c55ed4fc1b85254c2498ff84227cf82a67d2e9
2,116
ex
Elixir
lib/hl7/2.5.1/segments/in1.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
lib/hl7/2.5.1/segments/in1.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
lib/hl7/2.5.1/segments/in1.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
defmodule HL7.V2_5_1.Segments.IN1 do @moduledoc false require Logger alias HL7.V2_5_1.{DataTypes} use HL7.Segment, fields: [ segment: nil, set_id_in1: nil, insurance_plan_id: DataTypes.Ce, insurance_company_id: DataTypes.Cx, insurance_company_name: DataTypes.Xon, insurance_company_address: DataTypes.Xad, insurance_co_contact_person: DataTypes.Xpn, insurance_co_phone_number: DataTypes.Xtn, group_number: nil, group_name: DataTypes.Xon, insureds_group_emp_id: DataTypes.Cx, insureds_group_emp_name: DataTypes.Xon, plan_effective_date: nil, plan_expiration_date: nil, authorization_information: DataTypes.Aui, plan_type: nil, name_of_insured: DataTypes.Xpn, insureds_relationship_to_patient: DataTypes.Ce, insureds_date_of_birth: DataTypes.Ts, insureds_address: DataTypes.Xad, assignment_of_benefits: nil, coordination_of_benefits: nil, coord_of_ben_priority: nil, notice_of_admission_flag: nil, notice_of_admission_date: nil, report_of_eligibility_flag: nil, report_of_eligibility_date: nil, release_information_code: nil, pre_admit_cert_pac: nil, verification_date_time: DataTypes.Ts, verification_by: DataTypes.Xcn, type_of_agreement_code: nil, billing_status: nil, lifetime_reserve_days: nil, delay_before_l_r_day: nil, company_plan_code: nil, policy_number: nil, policy_deductible: DataTypes.Cp, policy_limit_amount: DataTypes.Cp, policy_limit_days: nil, room_rate_semi_private: DataTypes.Cp, room_rate_private: DataTypes.Cp, insureds_employment_status: DataTypes.Ce, insureds_administrative_sex: nil, insureds_employers_address: DataTypes.Xad, verification_status: nil, prior_insurance_plan_id: nil, coverage_type: nil, handicap: nil, insureds_id_number: DataTypes.Cx, signature_code: nil, signature_code_date: nil, insureds_birth_place: nil, vip_indicator: nil ] end
32.553846
53
0.712665
93c56d2eb0f74c6e929c543c9797e809a7039c4d
34,123
ex
Elixir
lib/ash/engine/request.ex
mhussa/ash
983a711837e4091d49a2ebff8010827ca2e8c889
[ "MIT" ]
null
null
null
lib/ash/engine/request.ex
mhussa/ash
983a711837e4091d49a2ebff8010827ca2e8c889
[ "MIT" ]
null
null
null
lib/ash/engine/request.ex
mhussa/ash
983a711837e4091d49a2ebff8010827ca2e8c889
[ "MIT" ]
null
null
null
defmodule Ash.Engine.Request do @moduledoc """ Represents an individual request to be processed by the engine. See `new/1` for more information """ alias Ash.Error.Forbidden.MustPassStrictCheck alias Ash.Error.Framework.AssumptionFailed alias Ash.Error.Invalid.{DuplicatedPath, ImpossiblePath} require Ash.Query defmodule UnresolvedField do @moduledoc """ Represents an unresolved field to be resolved by the engine """ defstruct [:resolver, deps: [], data?: false] @type t :: %__MODULE__{} def new(dependencies, func) do %__MODULE__{ resolver: func, deps: deps(dependencies) } end defp deps(deps) do deps |> List.wrap() |> Enum.map(fn dep -> List.wrap(dep) end) end end defimpl Inspect, for: UnresolvedField do import Inspect.Algebra def inspect(field, opts) do concat([ "#UnresolvedField<", to_doc(field.deps, opts), ">" ]) end end defstruct [ :id, :async?, :error?, :resource, :changeset, :path, :action_type, :action, :data, :name, :api, :query, :authorization_filter, :write_to_data?, :strict_check_only?, :verbose?, :state, :actor, :authorize?, :engine_pid, manage_changeset?: false, notify?: false, authorized?: false, authorizer_state: %{}, dependencies_to_send: %{}, dependency_data: %{}, dependencies_requested: [] ] @type t :: %__MODULE__{} require Logger alias Ash.Authorizer @doc """ Create an unresolved field. Can have dependencies, which is a list of atoms. All elements before the last comprise the path of a request that is also being processed, like `[:data]`, and the last element is the key of that request that is required. Make sure to pass a list of lists of atoms. The second argument is a map, which contains all the values you requested, at the same path that they were requested. For example: resolve([[:data, :query], [:data, :data]], fn %{data: %{query: query, data: data}} -> data # This is the data field of the [:data] request query # This is the query field of the [:data] request {:ok, result} # or {:error, error} # or result end) """ def resolve(dependencies \\ [], func) do UnresolvedField.new(dependencies, func) end @doc """ Creates a new request. The field values may be explicit values, or they may be instances of `UnresolvedField`. When other requests depend on a value from this request, they will not be sent unless this request has completed its authorization (or this request has been configured not to do authorization). This allows requests to depend on eachother without those requests happening just before a request fails with a forbidden error. These fields are `data`, `query`, `changeset` and `authorized?`. A field may not be resolved if the data of a request has been resolved and no other requests depend on that field. Options: * query - The query to be used to fetch data. Used to authorize reads. * data - The ultimate goal of a request is to compute the data * resource - The primary resource of the request. Used for openeing transactions on creates/updates/destroys * changeset - Any changes to be made to the resource. Used to authorize writes. * path - The path of the request. This serves as a unique id, and is the way that other requests can refer to this one * action_type - The action_type of the request * action - The action being performed on the data * async? - Whether or not the request *can* be asynchronous, defaults to `true`. * api - The api module being called * name - A human readable name for the request, used when logging/in errors * strict_check_only? - If true, authorization will not be allowed to proceed to a runtime check (so it cannot run db queries unless authorization is assured) * actor - The actor performing the action, used for authorization * authorize? - Wether or not to perform authorization (defaults to true) * verbose? - print informational logs (warning, this will be a whole lot of logs) * write_to_data? - If set to false, this value is not returned from the initial call to the engine """ def new(opts) do query = case opts[:query] do %UnresolvedField{} = query -> query %Ash.Query{} = query -> query nil -> nil other -> raise "Got a weird thing #{inspect(other)}" end id = Ecto.UUID.generate() data = case opts[:data] do %UnresolvedField{} = unresolved -> %{unresolved | data?: true} other -> other end %__MODULE__{ id: id, resource: opts[:resource], changeset: opts[:changeset], path: List.wrap(opts[:path]), action_type: opts[:action_type], action: opts[:action], async?: Keyword.get(opts, :async?, true), data: data, query: query, manage_changeset?: opts[:manage_changeset?] || false, api: opts[:api], name: opts[:name], strict_check_only?: opts[:strict_check_only?], state: :strict_check, actor: opts[:actor], notify?: opts[:notify?] == true, authorized?: opts[:authorize?] == false, verbose?: opts[:verbose?] || false, authorize?: opts[:authorize?] || true, write_to_data?: Keyword.get(opts, :write_to_data?, true) } end def resource_notification(request) do %Ash.Notifier.Notification{ resource: request.resource, api: request.api, actor: request.actor, action: request.action, data: request.data, changeset: request.changeset } end def next(request) do case do_next(request) do {:complete, new_request, notifications, dependencies} -> notifications = update_changeset(request, new_request.changeset, notifications) if request.state != :complete do {:complete, new_request, notifications, dependencies} else {:already_complete, new_request, notifications, dependencies} end {:waiting, new_request, notifications, dependencies} -> notifications = update_changeset(request, new_request.changeset, notifications) {:wait, new_request, notifications, dependencies} {:continue, new_request, notifications} -> notifications = update_changeset(request, new_request.changeset, notifications) {:continue, new_request, notifications} {:error, error, request} -> if request.manage_changeset? && !match?(%UnresolvedField{}, request.changeset) do new_changeset = Ash.Changeset.add_error(request.changeset, error) notifications = update_changeset(request, new_changeset, []) {:error, error, notifications, %{request | changeset: new_changeset}} else {:error, error, request} end end end defp update_changeset( %{manage_changeset?: true, changeset: changeset}, new_changeset, notifications ) do if new_changeset != changeset && not match?(%UnresolvedField{}, new_changeset) do [{:update_changeset, changeset} | notifications] else notifications end end defp update_changeset(_, _, notifications), do: notifications def do_next(%{state: :strict_check, authorize?: false} = request) do log(request, fn -> "Skipping strict check due to authorize?: false" end) {:continue, %{request | state: :fetch_data}, []} end def do_next(%{state: :strict_check} = request) do case Ash.Resource.authorizers(request.resource) do [] -> log(request, fn -> "No authorizers found, skipping strict check" end) {:continue, %{request | state: :fetch_data}, []} authorizers -> case strict_check(authorizers, request) do {:ok, new_request, notifications, []} -> new_request = set_authorized(new_request) log(new_request, fn -> "Strict check complete" end) {:continue, %{new_request | state: :fetch_data}, notifications} {:ok, new_request, notifications, dependencies} -> log(new_request, fn -> "Strict check incomplete, waiting on dependencies" end) {:waiting, new_request, notifications, dependencies} {:error, error} -> log(request, fn -> "Strict checking failed" end) {:error, error, request} end end end def do_next(%{state: :fetch_data} = request) do key = case request.changeset do %UnresolvedField{} -> :changeset _ -> :data end case try_resolve_local(request, key, true) do {:skipped, _, _, _} -> {:error, AssumptionFailed.exception(message: "Skipped fetching data"), request} {:ok, request, notifications, []} -> if key == :changeset do {:continue, request, notifications} else log(request, fn -> "data fetched: #{inspect(notifications)}" end) {:continue, %{request | state: :check}, notifications} end {:ok, new_request, notifications, waiting_for} -> log(request, fn -> "#{key} waiting on dependencies: #{inspect(waiting_for)}" end) {:waiting, new_request, notifications, waiting_for} {:error, error} -> log(request, fn -> "error fetching data: #{inspect(error)}" end) {:error, error, request} end end def do_next(%{state: :check, authorize?: false} = request) do log(request, fn -> "Skipping check due to `authorize?: false`" end) {:complete, %{request | state: :complete}, [], []} end def do_next(%{state: :check} = request) do case Ash.Resource.authorizers(request.resource) do [] -> log(request, fn -> "No authorizers found, skipping check" end) {:complete, %{request | state: :complete}, [], []} authorizers -> case check(authorizers, request) do {:ok, new_request, notifications, []} -> log(new_request, fn -> "Check complete" end) new_request = set_authorized(new_request) {:complete, %{new_request | state: :complete}, notifications, []} {:ok, new_request, notifications, waiting} -> log(request, fn -> "Check incomplete, waiting on dependencies" end) {:waiting, new_request, notifications, waiting} {:error, error} -> log(request, fn -> "Check failed" end) {:error, error, request} end end end def do_next(%{state: :complete} = request) do if request.dependencies_to_send == %{} do {:complete, request, [], []} else Enum.reduce_while(request.dependencies_to_send, {:complete, request, [], []}, fn {field, _paths}, {:complete, request, notifications, deps} -> case try_resolve_local(request, field, false) do {:skipped, new_request, new_notifications, other_deps} -> new_request = %{new_request | state: :complete} {:cont, {:complete, new_request, new_notifications ++ notifications, other_deps ++ deps}} {:ok, new_request, new_notifications, other_deps} -> new_request = %{new_request | state: :complete} {:cont, {:complete, new_request, new_notifications ++ notifications, other_deps ++ deps}} {:error, error} -> {:halt, {:error, error, request}} end end) end end def wont_receive(request, path, field) do log(request, fn -> "Request failed due to failed dependency #{inspect(path ++ [field])}" end) {:stop, :dependency_failed, request} end def send_field(request, receiver_path, field) do log(request, fn -> "Attempting to provide #{inspect(field)} for #{inspect(receiver_path)}" end) case store_dependency(request, receiver_path, field) do {:value, value, new_request} -> {:ok, new_request, [{receiver_path, request.path, field, value}]} {:ok, new_request, notifications} -> {:ok, new_request, notifications} {:waiting, new_request, notifications, []} -> {:ok, new_request, notifications} {:waiting, new_request, notifications, waiting_for} -> {:waiting, new_request, notifications, waiting_for} {:error, error, new_request} -> log(request, fn -> "Error resolving #{field}: #{inspect(error)}" end) {:error, error, new_request} end end def receive_field(request, path, field, value) do log(request, fn -> "Receiving field #{field} from #{inspect(path)}" end) new_request = put_dependency_data(request, path ++ [field], value) {:continue, new_request} end defp set_authorized(%{authorized?: false, resource: resource} = request) do authorized? = resource |> Ash.Resource.authorizers() |> Enum.all?(fn authorizer -> authorizer_state(request, authorizer) == :authorizer end) %{request | authorized?: authorized?} end defp set_authorized(request), do: request def put_dependency_data(request, dep, value) do %{request | dependency_data: Map.put(request.dependency_data, dep, value)} end def store_dependency(request, receiver_path, field, internal? \\ false) do request = do_store_dependency(request, field, receiver_path) case try_resolve_local(request, field, internal?) do {:skipped, new_request, notifications, []} -> log(request, fn -> "Field #{field} was skipped, no additional dependencies" end) {:ok, new_request, notifications} {:skipped, new_request, notifications, waiting} -> log(request, fn -> "Field #{field} was skipped, registering dependencies: #{inspect(waiting)}" end) {:waiting, new_request, notifications, waiting} {:ok, new_request, _, _} -> case Map.get(new_request, field) do %UnresolvedField{} -> log(request, fn -> "Field could not be resolved #{field}, registering dependency" end) {:ok, new_request, []} value -> log(request, fn -> "Field #{field}, was resolved and provided" end) {:value, value, new_request} end {:error, error} -> {:error, error, request} end end defp do_store_dependency(request, field, receiver_path) do log(request, fn -> "storing dependency on #{field} from #{inspect(receiver_path)}" end) new_deps_to_send = Map.update(request.dependencies_to_send, field, [receiver_path], fn paths -> paths = Enum.reject(paths, &Kernel.==(&1, receiver_path)) [receiver_path | paths] end) %{request | dependencies_to_send: new_deps_to_send} end defp strict_check(authorizers, request) do authorizers |> Enum.reject(&(authorizer_state(request, &1) == :authorized)) |> Enum.reduce_while({:ok, request, [], []}, fn authorizer, {:ok, request, notifications, waiting_for} -> log(request, fn -> "strict checking" end) case do_strict_check(authorizer, request) do {:ok, new_request} -> log(new_request, fn -> "strict check succeeded for #{inspect(authorizer)}" end) {:cont, {:ok, new_request, notifications, waiting_for}} {:ok, new_request, new_notifications, new_deps} -> log(new_request, fn -> "strict check succeeded for #{inspect(authorizer)}" end) {:cont, {:ok, new_request, new_notifications ++ notifications, waiting_for ++ new_deps}} {:waiting, new_request, new_notifications, new_deps} -> log( new_request, fn -> "waiting on dependencies: #{inspect(new_deps)} for #{inspect(authorizer)}" end ) {:cont, {:ok, new_request, notifications ++ new_notifications, new_deps ++ waiting_for}} {:error, error} -> log(request, fn -> "strict check failed for #{inspect(authorizer)}: #{inspect(error)}" end) {:halt, {:error, error}} end end) end defp do_strict_check(authorizer, request, notifications \\ []) do strict_check_only? = request.strict_check_only? case missing_strict_check_dependencies?(authorizer, request) do [] -> case strict_check_authorizer(authorizer, request) do :authorized -> {:ok, set_authorizer_state(request, authorizer, :authorized)} {:filter, filter} -> apply_filter(request, authorizer, filter, true) {:filter_and_continue, _, _} when strict_check_only? -> {:error, MustPassStrictCheck.exception(resource: request.resource)} {:filter_and_continue, filter, new_authorizer_state} -> request |> set_authorizer_state(authorizer, new_authorizer_state) |> apply_filter(authorizer, filter) {:continue, _} when strict_check_only? -> {:error, MustPassStrictCheck.exception(resource: request.resource)} {:continue, authorizer_state} -> {:ok, set_authorizer_state(request, authorizer, authorizer_state)} {:error, error} -> {:error, error} end deps -> deps = Enum.map(deps, fn dep -> request.path ++ [dep] end) case try_resolve(request, deps, true) do {:ok, new_request, new_notifications, []} -> do_strict_check(authorizer, new_request, notifications ++ new_notifications) {:ok, new_request, new_notifications, waiting_for} -> {:waiting, new_request, notifications ++ new_notifications, waiting_for} {:error, error} -> {:error, error} end end end defp apply_filter(request, authorizer, filter, resolve_data? \\ false) defp apply_filter(%{action: %{type: :read}} = request, authorizer, filter, resolve_data?) do request = request |> Map.update!(:query, &Ash.Query.filter(&1, ^filter)) |> Map.update( :authorization_filter, filter, &add_to_or_parse(&1, filter, request.resource) ) |> set_authorizer_state(authorizer, :authorized) if resolve_data? do try_resolve(request, [request.path ++ [:query]], false) else {:ok, request} end end defp apply_filter(request, authorizer, filter, resolve_data?) do case do_runtime_filter(request, filter) do {:ok, request} -> request = set_authorizer_state(request, authorizer, :authorized) if resolve_data? do try_resolve(request, [request.path ++ [:query]], false) else {:ok, request} end {:error, error} -> {:error, error} end end defp add_to_or_parse(existing_authorization_filter, filter, resource) do if existing_authorization_filter do Ash.Filter.add_to_filter(existing_authorization_filter, filter) else Ash.Filter.parse!(resource, filter) end end defp check(authorizers, request) do authorizers |> Enum.reject(&(authorizer_state(request, &1) == :authorized)) |> Enum.reduce_while({:ok, request, [], []}, fn authorizer, {:ok, request, notifications, waiting_for} -> case do_check(authorizer, request) do {:ok, new_request} -> log(request, fn -> "check succeeded for #{inspect(authorizer)}" end) {:cont, {:ok, new_request, notifications, waiting_for}} {:ok, new_request, new_notifications, new_deps} -> log(request, fn -> "check succeeded for #{inspect(authorizer)}" end) {:cont, {:ok, new_request, new_notifications ++ notifications, new_deps ++ waiting_for}} {:waiting, new_request, new_notifications, new_deps} -> log( request, fn -> "waiting on dependencies: #{inspect(new_deps)} for #{inspect(authorizer)}" end ) {:cont, {:ok, new_request, new_notifications ++ notifications, new_deps ++ waiting_for}} {:error, error} -> log(request, fn -> "check failed for #{inspect(authorizer)}: #{inspect(error)}" end) {:halt, {:error, error}} end end) end defp do_check(authorizer, request, notifications \\ []) do case missing_check_dependencies(authorizer, request) do [] -> case check_authorizer(authorizer, request) do :authorized -> {:ok, set_authorizer_state(request, authorizer, :authorized)} {:filter, filter} -> request |> set_authorizer_state(authorizer, :authorized) |> Map.update( :authorization_filter, filter, &Ash.Filter.add_to_filter(&1, filter) ) |> runtime_filter(authorizer, filter) {:error, error} -> {:error, error} end deps -> deps = Enum.map(deps, fn dep -> request.path ++ [dep] end) case try_resolve(request, deps, true) do {:ok, new_request, new_notifications, []} -> do_check(authorizer, new_request, notifications ++ new_notifications) {:ok, new_request, new_notifications, waiting_for} -> {:waiting, new_request, new_notifications ++ notifications, waiting_for} {:error, error} -> {:error, error} end end end defp runtime_filter(request, authorizer, filter) do case do_runtime_filter(request, filter) do {:ok, request} -> request |> set_authorizer_state(authorizer, :authorized) |> try_resolve([request.path ++ [:data], request.path ++ [:query]], false) {:error, error} -> {:error, error} end end defp do_runtime_filter(%{action: %{type: :read}, data: empty} = request, _filter) when empty in [nil, []], do: {:ok, request} defp do_runtime_filter(%{action: %{type: :read}} = request, filter) do pkey = Ash.Resource.primary_key(request.resource) pkeys = request.data |> List.wrap() |> Enum.map(fn record -> record |> Map.take(pkey) |> Map.to_list() end) primary_key_filter = case pkeys do [pkey] -> [pkey] pkeys -> [or: pkeys] end new_query = request.query |> Ash.Query.filter(^primary_key_filter) |> Ash.Query.filter(^filter) new_query |> Ash.Actions.Read.unpaginated_read() |> case do {:ok, results} -> pkey = Ash.Resource.primary_key(request.resource) pkeys = Enum.map(results, &Map.take(&1, pkey)) new_data = Enum.filter(request.data, &(Map.take(&1, pkey) in pkeys)) {:ok, %{request | data: new_data, query: new_query}} {:error, error} -> {:error, error} end end defp do_runtime_filter(request, filter) do pkey = Ash.Resource.primary_key(request.resource) pkey = request.changeset.data |> Map.take(pkey) |> Map.to_list() new_query = request.resource |> Ash.Query.set_tenant(request.changeset.tenant) |> Ash.Query.set_context(request.changeset.context) |> Ash.Query.filter(^pkey) |> Ash.Query.filter(^filter) |> Ash.Query.limit(1) new_query |> Ash.Actions.Read.unpaginated_read() |> case do {:ok, []} -> {:error, Ash.Error.Forbidden.exception([])} {:ok, [_]} -> {:ok, request} {:error, error} -> {:error, error} end end defp try_resolve(request, deps, internal?) do Enum.reduce_while(deps, {:ok, request, [], []}, fn dep, {:ok, request, notifications, skipped} -> case get_dependency_data(request, dep) do {:ok, _value} -> {:cont, {:ok, request, notifications, skipped}} :error -> do_try_resolve(request, notifications, skipped, dep, internal?) end end) end defp do_try_resolve(request, notifications, skipped, dep, internal?) do if local_dep?(request, dep) do case try_resolve_local(request, List.last(dep), internal?) do {:skipped, request, new_notifications, other_deps} -> {:cont, {:ok, request, new_notifications ++ notifications, skipped ++ other_deps}} {:ok, request, new_notifications, other_deps} -> {:cont, {:ok, request, new_notifications ++ notifications, skipped ++ other_deps}} {:error, error} -> {:halt, {:error, error}} end else {:cont, {:ok, request, notifications, [dep | skipped]}} end end defp try_resolve_local(request, field, internal?) do authorized? = Enum.all?(Map.values(request.authorizer_state), &(&1 == :authorized)) # Don't fetch honor requests for data until the request is authorized if field in [:data, :query, :changeset, :authorized?] and not authorized? and not internal? do try_resolve_dependencies_of(request, field, internal?) else case Map.get(request, field) do %UnresolvedField{} = unresolved -> do_try_resolve_local(request, field, unresolved, internal?) value -> notify_existing_value(request, field, value, internal?) end end end defp try_resolve_dependencies_of(request, field, internal?) do case Map.get(request, field) do %UnresolvedField{deps: deps} -> case try_resolve(request, deps, internal?) do {:ok, new_request, notifications, remaining_deps} -> {:skipped, new_request, notifications, remaining_deps} error -> error end _ -> {:skipped, request, [], []} end end defp notify_existing_value(request, field, value, internal?) do if internal? do {:ok, request, [], []} else {new_request, notifications} = notifications(request, field, value) {:ok, new_request, notifications, []} end end defp do_try_resolve_local(request, field, unresolved, internal?) do %{deps: deps, resolver: resolver} = unresolved with {:ok, new_request, notifications, []} <- try_resolve(request, deps, internal?) do resolver_context = resolver_context(new_request, deps) log(request, fn -> "resolving #{field}" end) case resolver.(resolver_context) do {:ok, value, instructions} -> set_data_notifications = Enum.map(Map.get(instructions, :extra_data, %{}), fn {key, value} -> {:set_extra_data, key, value} end) resource_notifications = Map.get(instructions, :notifications, []) handle_successful_resolve( field, value, request, new_request, notifications ++ resource_notifications ++ set_data_notifications, internal? ) {:ok, value} -> handle_successful_resolve( field, value, request, new_request, notifications, internal? ) {:error, error} -> {:error, error} end end end defp handle_successful_resolve(field, value, request, new_request, notifications, internal?) do value = process_resolved_field(field, value, request) {new_request, notifications} = if internal? do {new_request, new_notifications} = notifications(new_request, field, value) notifications = Enum.concat([ notifications, new_notifications ]) {new_request, notifications} else {request, []} end new_request = Map.put(new_request, field, value) {:ok, new_request, notifications, []} end defp process_resolved_field(:query, %Ash.Query{} = query, request) do Ash.Query.set_context(query, %{ authorize?: request.authorize?, actor: request.actor }) end defp process_resolved_field(:changeset, %Ash.Changeset{} = changeset, request) do Ash.Changeset.set_context(changeset, %{ authorize?: request.authorize?, actor: request.actor }) end defp process_resolved_field(_, value, _), do: value defp get_dependency_data(request, dep) do if local_dep?(request, dep) do case Map.fetch(request, List.last(dep)) do {:ok, %UnresolvedField{}} -> :error {:ok, value} -> {:ok, value} :error -> :error end else Map.fetch(request.dependency_data, dep) end end defp notifications(request, field, value) do case Map.fetch(request.dependencies_to_send, field) do {:ok, paths} -> new_request = %{ request | dependencies_to_send: Map.delete(request.dependencies_to_send, field) } notifications = Enum.map(paths, fn path -> {path, request.path, field, value} end) {new_request, notifications} :error -> {request, []} end end defp resolver_context(request, deps) do Enum.reduce(deps, %{}, fn dep, resolver_context -> case get_dependency_data(request, dep) do {:ok, value} -> Ash.Engine.put_nested_key(resolver_context, dep, value) :error -> resolver_context end end) end defp local_dep?(request, dep) do :lists.droplast(dep) == request.path end def add_initial_authorizer_state(request) do request.resource |> Ash.Resource.authorizers() |> Enum.reduce(request, fn authorizer, request -> if request.authorize? do initial_state = Authorizer.initial_state( authorizer, request.actor, request.resource, request.action, request.verbose? ) set_authorizer_state(request, authorizer, initial_state) else set_authorizer_state(request, authorizer, :authorized) end end) end defp missing_strict_check_dependencies?(authorizer, request) do authorizer |> Authorizer.strict_check_context(authorizer_state(request, authorizer)) |> List.wrap() |> Enum.filter(fn dependency -> match?(%UnresolvedField{}, Map.get(request, dependency)) end) end defp missing_check_dependencies(authorizer, request) do authorizer |> Authorizer.check_context(authorizer_state(request, authorizer)) |> Enum.filter(fn dependency -> match?(%UnresolvedField{}, Map.get(request, dependency)) end) end defp strict_check_authorizer(authorizer, request) do log(request, fn -> "strict checking for #{inspect(authorizer)}" end) authorizer_state = authorizer_state(request, authorizer) keys = Authorizer.strict_check_context(authorizer, authorizer_state) Authorizer.strict_check(authorizer, authorizer_state, Map.take(request, keys)) end defp check_authorizer(authorizer, request) do log(request, fn -> "checking for #{inspect(authorizer)}" end) authorizer_state = authorizer_state(request, authorizer) keys = Authorizer.check_context(authorizer, authorizer_state) Authorizer.check(authorizer, authorizer_state, Map.take(request, keys)) end defp set_authorizer_state(request, authorizer, authorizer_state) do %{ request | authorizer_state: Map.put(request.authorizer_state, authorizer, authorizer_state) } end defp authorizer_state(request, authorizer) do Map.get(request.authorizer_state, authorizer) || %{} end def validate_requests!(requests) do validate_unique_paths!(requests) validate_dependencies!(requests) :ok end defp validate_unique_paths!(requests) do requests |> Enum.group_by(& &1.path) |> Enum.filter(fn {_path, value} -> Enum.count(value, & &1.write_to_data?) > 1 end) |> case do [] -> :ok invalid_paths -> invalid_paths = Enum.map(invalid_paths, &elem(&1, 0)) raise DuplicatedPath, paths: invalid_paths end end defp validate_dependencies!(requests) do Enum.each(requests, &do_build_dependencies(&1, requests)) :ok end defp do_build_dependencies(request, requests, trail \\ []) do request |> Map.from_struct() |> Enum.each(fn {_key, %UnresolvedField{deps: deps}} -> expand_deps(deps, requests, trail) _ -> :ok end) end defp expand_deps(deps, requests, trail) do case do_expand_deps(deps, requests, trail) do :ok -> :ok {:error, {:impossible, dep}} -> raise ImpossiblePath, impossible_path: dep end end defp do_expand_deps([], _, _), do: :ok defp do_expand_deps(deps, requests, trail) do Enum.reduce_while(deps, :ok, fn dep, :ok -> case do_expand_dep(dep, requests, trail) do :ok -> {:cont, :ok} {:error, error} -> {:halt, {:error, error}} end end) end defp do_expand_dep(dep, requests, trail) do if dep in trail do {:error, {:circular, dep}} else request_path = :lists.droplast(dep) request_key = List.last(dep) case Enum.find(requests, &(&1.path == request_path)) do nil -> {:error, {:impossible, dep}} %{^request_key => %UnresolvedField{deps: nested_deps}} -> case do_expand_deps(nested_deps, requests, [dep | trail]) do :ok -> :ok other -> other end _ -> :ok end end end defp log(request, message, level \\ :debug) defp log(%{verbose?: true, name: name} = request, message, level) do if is_list(request.data) do Logger.log(level, fn -> message = message.() "#{name}: #{Enum.count(request.data)} #{message}" end) else Logger.log(level, fn -> message = message.() "#{name}: #{message}" end) end end defp log(_, _, _) do false end end
30.385574
161
0.614161
93c58c7ee2a576a4632dfeb0ed34fbe35bbf8586
2,194
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/target_pool_aggregated_list_warning.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/compute/lib/google_api/compute/v1/model/target_pool_aggregated_list_warning.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/compute/lib/google_api/compute/v1/model/target_pool_aggregated_list_warning.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # 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. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Compute.V1.Model.TargetPoolAggregatedListWarning do @moduledoc """ [Output Only] Informational warning message. ## Attributes * `code` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning code, if applicable. For example, Compute Engine returns NO_RESULTS_ON_PAGE if there are no results in the response. * `data` (*type:* `list(GoogleApi.Compute.V1.Model.TargetPoolAggregatedListWarningData.t)`, *default:* `nil`) - [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": "scope", "value": "zones/us-east1-d" } * `message` (*type:* `String.t`, *default:* `nil`) - [Output Only] A human-readable description of the warning code. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :code => String.t() | nil, :data => list(GoogleApi.Compute.V1.Model.TargetPoolAggregatedListWarningData.t()) | nil, :message => String.t() | nil } field(:code) field(:data, as: GoogleApi.Compute.V1.Model.TargetPoolAggregatedListWarningData, type: :list) field(:message) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.TargetPoolAggregatedListWarning do def decode(value, options) do GoogleApi.Compute.V1.Model.TargetPoolAggregatedListWarning.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.TargetPoolAggregatedListWarning do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.396226
251
0.728806
93c5a98115c31db648536513d9e7362f8ccaf908
938
ex
Elixir
elixirpay/lib/elixirpay/accounts/transaction.ex
fcsouza/elixir-project
e6212c4def050400eb4fcc50c6a8274409b1f0c7
[ "MIT" ]
null
null
null
elixirpay/lib/elixirpay/accounts/transaction.ex
fcsouza/elixir-project
e6212c4def050400eb4fcc50c6a8274409b1f0c7
[ "MIT" ]
null
null
null
elixirpay/lib/elixirpay/accounts/transaction.ex
fcsouza/elixir-project
e6212c4def050400eb4fcc50c6a8274409b1f0c7
[ "MIT" ]
null
null
null
defmodule Elixirpay.Accounts.Transaction do alias Ecto.Multi alias Elixirpay.Accounts.Operation alias Elixirpay.Accounts.Transactions.Response, as: TransactionResponse alias Elixirpay.Repo def call(%{"from" => from_id, "to" => to_id, "value" => value}) do withdraw_params = build_params(from_id, value) deposit_params = build_params(to_id, value) Multi.new() |> Multi.merge(fn _changes -> Operation.call(withdraw_params, :withdraw) end) |> Multi.merge(fn _changes -> Operation.call(deposit_params, :deposit) end) |> run_transaction() end defp build_params(id, value), do: %{"id" => id, "value" => value} defp run_transaction(multi) do case Repo.transaction(multi) do {:error, _operation, reason, _changes} -> {:error, reason} {:ok, %{deposit: to_account, withdraw: from_account}} -> {:ok, TransactionResponse.build(from_account, to_account)} end end end
31.266667
81
0.688699
93c5ba16cdd9b6d59e0f789995a274deea43aac1
718
ex
Elixir
lib/example_16_web/gettext.ex
pzingg/phoenix_16_example
7f4160de837229101e18a4e1cc97a00f4af5aaa7
[ "MIT" ]
null
null
null
lib/example_16_web/gettext.ex
pzingg/phoenix_16_example
7f4160de837229101e18a4e1cc97a00f4af5aaa7
[ "MIT" ]
null
null
null
lib/example_16_web/gettext.ex
pzingg/phoenix_16_example
7f4160de837229101e18a4e1cc97a00f4af5aaa7
[ "MIT" ]
null
null
null
defmodule Example16Web.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](https://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import Example16Web.Gettext # Simple translation gettext("Here is the string to translate") # Plural translation ngettext("Here is the string to translate", "Here are the strings to translate", 3) # Domain-based translation dgettext("errors", "Here is the error message to translate") See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :example_16 end
28.72
72
0.681058
93c5e822b939310e15e49c9f8e2979b46bd9f458
199
ex
Elixir
lib/battle_city/environment/brick_wall.ex
clszzyh/battle_city_core
7a3aca9000b186382f1faf526ebce837a76ef86e
[ "MIT" ]
null
null
null
lib/battle_city/environment/brick_wall.ex
clszzyh/battle_city_core
7a3aca9000b186382f1faf526ebce837a76ef86e
[ "MIT" ]
38
2020-12-17T12:40:44.000Z
2022-03-31T02:05:59.000Z
lib/battle_city/environment/brick_wall.ex
clszzyh/battle_city
7a3aca9000b186382f1faf526ebce837a76ef86e
[ "MIT" ]
null
null
null
defmodule BattleCity.Environment.BrickWall do @moduledoc false use BattleCity.Environment, solid?: true, enter?: false @impl true def handle_init(map), do: Environment.handle_init(map) end
22.111111
57
0.768844
93c5f85768eceda88c9d94b0b65534e75dcdb7d0
7,364
ex
Elixir
clients/cloud_billing/lib/google_api/cloud_billing/v1/api/services.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/cloud_billing/lib/google_api/cloud_billing/v1/api/services.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/cloud_billing/lib/google_api/cloud_billing/v1/api/services.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # 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 &quot;AS IS&quot; 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. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.CloudBilling.V1.Api.Services do @moduledoc """ API calls for all endpoints tagged `Services`. """ alias GoogleApi.CloudBilling.V1.Connection import GoogleApi.CloudBilling.V1.RequestBuilder @doc """ Lists all public cloud services. ## Parameters - connection (GoogleApi.CloudBilling.V1.Connection): Connection to server - opts (KeywordList): [optional] Optional parameters - :access_token (String): OAuth access token. - :pretty_print (Boolean): Returns response with indentations and line breaks. - :key (String): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :quota_user (String): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :pp (Boolean): Pretty-print response. - :fields (String): Selector specifying which fields to include in a partial response. - :alt (String): Data format for response. - :__/xgafv (String): V1 error format. - :callback (String): JSONP - :oauth_token (String): OAuth 2.0 token for the current user. - :upload_type (String): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :bearer_token (String): OAuth bearer token. - :upload_protocol (String): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :page_size (Integer): Requested page size. Defaults to 5000. - :page_token (String): A token identifying a page of results to return. This should be a &#x60;next_page_token&#x60; value returned from a previous &#x60;ListServices&#x60; call. If unspecified, the first page of results is returned. ## Returns {:ok, %GoogleApi.CloudBilling.V1.Model.ListServicesResponse{}} on success {:error, info} on failure """ @spec cloudbilling_services_list(Tesla.Env.client, keyword()) :: {:ok, GoogleApi.CloudBilling.V1.Model.ListServicesResponse.t} | {:error, Tesla.Env.t} def cloudbilling_services_list(connection, opts \\ []) do optional_params = %{ :"access_token" => :query, :"prettyPrint" => :query, :"key" => :query, :"quotaUser" => :query, :"pp" => :query, :"fields" => :query, :"alt" => :query, :"$.xgafv" => :query, :"callback" => :query, :"oauth_token" => :query, :"uploadType" => :query, :"bearer_token" => :query, :"upload_protocol" => :query, :"pageSize" => :query, :"pageToken" => :query } %{} |> method(:get) |> url("/v1/services") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.CloudBilling.V1.Model.ListServicesResponse{}) end @doc """ Lists all publicly available SKUs for a given cloud service. ## Parameters - connection (GoogleApi.CloudBilling.V1.Connection): Connection to server - parent (String): The name of the service. Example: \&quot;services/DA34-426B-A397\&quot; - opts (KeywordList): [optional] Optional parameters - :access_token (String): OAuth access token. - :pretty_print (Boolean): Returns response with indentations and line breaks. - :key (String): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :quota_user (String): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :pp (Boolean): Pretty-print response. - :fields (String): Selector specifying which fields to include in a partial response. - :alt (String): Data format for response. - :__/xgafv (String): V1 error format. - :callback (String): JSONP - :oauth_token (String): OAuth 2.0 token for the current user. - :upload_type (String): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :bearer_token (String): OAuth bearer token. - :upload_protocol (String): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :currency_code (String): The ISO 4217 currency code for the pricing info in the response proto. Will use the conversion rate as of start_time. Optional. If not specified USD will be used. - :end_time (String): Optional exclusive end time of the time range for which the pricing versions will be returned. Timestamps in the future are not allowed. Maximum allowable time range is 1 month (31 days). Time range as a whole is optional. If not specified, the latest pricing will be returned (up to 12 hours old at most). - :page_size (Integer): Requested page size. Defaults to 5000. - :start_time (String): Optional inclusive start time of the time range for which the pricing versions will be returned. Timestamps in the future are not allowed. Maximum allowable time range is 1 month (31 days). Time range as a whole is optional. If not specified, the latest pricing will be returned (up to 12 hours old at most). - :page_token (String): A token identifying a page of results to return. This should be a &#x60;next_page_token&#x60; value returned from a previous &#x60;ListSkus&#x60; call. If unspecified, the first page of results is returned. ## Returns {:ok, %GoogleApi.CloudBilling.V1.Model.ListSkusResponse{}} on success {:error, info} on failure """ @spec cloudbilling_services_skus_list(Tesla.Env.client, String.t, keyword()) :: {:ok, GoogleApi.CloudBilling.V1.Model.ListSkusResponse.t} | {:error, Tesla.Env.t} def cloudbilling_services_skus_list(connection, parent, opts \\ []) do optional_params = %{ :"access_token" => :query, :"prettyPrint" => :query, :"key" => :query, :"quotaUser" => :query, :"pp" => :query, :"fields" => :query, :"alt" => :query, :"$.xgafv" => :query, :"callback" => :query, :"oauth_token" => :query, :"uploadType" => :query, :"bearer_token" => :query, :"upload_protocol" => :query, :"currencyCode" => :query, :"endTime" => :query, :"pageSize" => :query, :"startTime" => :query, :"pageToken" => :query } %{} |> method(:get) |> url("/v1/#{parent}/skus") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.CloudBilling.V1.Model.ListSkusResponse{}) end end
49.756757
336
0.685904
93c60c007387f344e259661af5604fa675237eca
425
ex
Elixir
lib/flux/file.ex
cjfreeze/Flux
ea1eb29932db806c06fcd6cdcc625df04b83f8bc
[ "MIT" ]
1
2021-10-05T02:22:22.000Z
2021-10-05T02:22:22.000Z
lib/flux/file.ex
cjfreeze/Flux
ea1eb29932db806c06fcd6cdcc625df04b83f8bc
[ "MIT" ]
null
null
null
lib/flux/file.ex
cjfreeze/Flux
ea1eb29932db806c06fcd6cdcc625df04b83f8bc
[ "MIT" ]
null
null
null
defmodule Flux.File do def read_file(file, offset \\ 0, length \\ :all) def read_file(file, _, :all) do with {:ok, content} <- File.read(file) do content else _ -> :error end end def read_file(file, offset, length) do with {:ok, pid} <- File.open(file, [:binary]), {:ok, content} <- :file.pread(pid, offset, length) do content else _ -> :error end end end
20.238095
62
0.567059
93c61b63e3e16efccda1d38909e064394f99d857
3,769
ex
Elixir
clients/dataflow/lib/google_api/dataflow/v1b3/model/source.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/source.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/source.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # 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. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Dataflow.V1b3.Model.Source do @moduledoc """ A source that records can be read and decoded from. ## Attributes * `baseSpecs` (*type:* `list(map())`, *default:* `nil`) - While splitting, sources may specify the produced bundles as differences against another source, in order to save backend-side memory and allow bigger jobs. For details, see SourceSplitRequest. To support this use case, the full set of parameters of the source is logically obtained by taking the latest explicitly specified value of each parameter in the order: base_specs (later items win), spec (overrides anything in base_specs). * `codec` (*type:* `map()`, *default:* `nil`) - The codec to use to decode data read from the source. * `doesNotNeedSplitting` (*type:* `boolean()`, *default:* `nil`) - Setting this value to true hints to the framework that the source doesn't need splitting, and using SourceSplitRequest on it would yield SOURCE_SPLIT_OUTCOME_USE_CURRENT. E.g. a file splitter may set this to true when splitting a single file into a set of byte ranges of appropriate size, and set this to false when splitting a filepattern into individual files. However, for efficiency, a file splitter may decide to produce file subranges directly from the filepattern to avoid a splitting round-trip. See SourceSplitRequest for an overview of the splitting process. This field is meaningful only in the Source objects populated by the user (e.g. when filling in a DerivedSource). Source objects supplied by the framework to the user don't have this field populated. * `metadata` (*type:* `GoogleApi.Dataflow.V1b3.Model.SourceMetadata.t`, *default:* `nil`) - Optionally, metadata for this source can be supplied right away, avoiding a SourceGetMetadataOperation roundtrip (see SourceOperationRequest). This field is meaningful only in the Source objects populated by the user (e.g. when filling in a DerivedSource). Source objects supplied by the framework to the user don't have this field populated. * `spec` (*type:* `map()`, *default:* `nil`) - The source to read from, plus its parameters. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :baseSpecs => list(map()), :codec => map(), :doesNotNeedSplitting => boolean(), :metadata => GoogleApi.Dataflow.V1b3.Model.SourceMetadata.t(), :spec => map() } field(:baseSpecs, type: :list) field(:codec, type: :map) field(:doesNotNeedSplitting) field(:metadata, as: GoogleApi.Dataflow.V1b3.Model.SourceMetadata) field(:spec, type: :map) end defimpl Poison.Decoder, for: GoogleApi.Dataflow.V1b3.Model.Source do def decode(value, options) do GoogleApi.Dataflow.V1b3.Model.Source.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dataflow.V1b3.Model.Source do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.829545
160
0.713717
93c629457e3b3811a7fde36d9dd6dc07d0a0a0a0
2,250
exs
Elixir
test/copy_me/problems/problems_test.exs
csfalcione/open-submissions-api
b7af153ebe9c1a9bd487f7fc30a25007bdf2b9c3
[ "MIT" ]
7
2019-02-11T14:31:24.000Z
2021-12-28T08:15:00.000Z
test/copy_me/problems/problems_test.exs
tblount/open-submissions-api
fb7395175e8079a659bc65ff7c5a7f1f4fc4b422
[ "MIT" ]
null
null
null
test/copy_me/problems/problems_test.exs
tblount/open-submissions-api
fb7395175e8079a659bc65ff7c5a7f1f4fc4b422
[ "MIT" ]
2
2019-02-11T14:31:37.000Z
2021-12-28T08:15:01.000Z
defmodule CopyMe.ProblemsTest do use CopyMe.DataCase alias CopyMe.Problems describe "problems" do alias CopyMe.Problems.Problem @valid_attrs %{description: "some description", name: "some name"} @update_attrs %{description: "some updated description", name: "some updated name"} @invalid_attrs %{description: nil, name: nil} def problem_fixture(attrs \\ %{}) do {:ok, problem} = attrs |> Enum.into(@valid_attrs) |> Problems.create_problem() problem end test "list_problems/0 returns all problems" do problem = problem_fixture() assert Problems.list_problems() == [problem] end test "get_problem!/1 returns the problem with given id" do problem = problem_fixture() assert Problems.get_problem!(problem.id) == problem end test "create_problem/1 with valid data creates a problem" do assert {:ok, %Problem{} = problem} = Problems.create_problem(@valid_attrs) assert problem.description == "some description" assert problem.name == "some name" end test "create_problem/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Problems.create_problem(@invalid_attrs) end test "update_problem/2 with valid data updates the problem" do problem = problem_fixture() assert {:ok, %Problem{} = problem} = Problems.update_problem(problem, @update_attrs) assert problem.description == "some updated description" assert problem.name == "some updated name" end test "update_problem/2 with invalid data returns error changeset" do problem = problem_fixture() assert {:error, %Ecto.Changeset{}} = Problems.update_problem(problem, @invalid_attrs) assert problem == Problems.get_problem!(problem.id) end test "delete_problem/1 deletes the problem" do problem = problem_fixture() assert {:ok, %Problem{}} = Problems.delete_problem(problem) assert_raise Ecto.NoResultsError, fn -> Problems.get_problem!(problem.id) end end test "change_problem/1 returns a problem changeset" do problem = problem_fixture() assert %Ecto.Changeset{} = Problems.change_problem(problem) end end end
33.58209
91
0.686667
93c6590a39ae26ffcb427882a379c4b73dde41fc
1,675
ex
Elixir
clients/tool_results/lib/google_api/tool_results/v1beta3/model/test_timing.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/tool_results/lib/google_api/tool_results/v1beta3/model/test_timing.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/tool_results/lib/google_api/tool_results/v1beta3/model/test_timing.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # 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. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.ToolResults.V1beta3.Model.TestTiming do @moduledoc """ Testing timing break down to know phases. ## Attributes * `testProcessDuration` (*type:* `GoogleApi.ToolResults.V1beta3.Model.Duration.t`, *default:* `nil`) - How long it took to run the test process. - In response: present if previously set. - In create/update request: optional """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :testProcessDuration => GoogleApi.ToolResults.V1beta3.Model.Duration.t() } field(:testProcessDuration, as: GoogleApi.ToolResults.V1beta3.Model.Duration) end defimpl Poison.Decoder, for: GoogleApi.ToolResults.V1beta3.Model.TestTiming do def decode(value, options) do GoogleApi.ToolResults.V1beta3.Model.TestTiming.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ToolResults.V1beta3.Model.TestTiming do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.5
148
0.74806
93c6831abe0812a7538674fe7065c6aecb37813f
1,745
ex
Elixir
chromoid_link/lib/chromoid/config_wizard.ex
ConnorRigby/chromoid
6424a9234227d18d7c287ded869caeb31511bb97
[ "Apache-2.0" ]
7
2020-11-18T11:29:20.000Z
2022-01-16T03:16:14.000Z
chromoid_link/lib/chromoid/config_wizard.ex
ConnorRigby/chromoid
6424a9234227d18d7c287ded869caeb31511bb97
[ "Apache-2.0" ]
null
null
null
chromoid_link/lib/chromoid/config_wizard.ex
ConnorRigby/chromoid
6424a9234227d18d7c287ded869caeb31511bb97
[ "Apache-2.0" ]
1
2021-01-06T15:40:46.000Z
2021-01-06T15:40:46.000Z
defmodule Chromoid.ConfigWizard do use GenServer alias Chromoid.Config def start_link(args) do GenServer.start_link(__MODULE__, args, name: __MODULE__) end def init(_args) do if should_start_wizard?() do args = [ ifname: "wlan0", device_info: get_info() ] VintageNetWizard.run_wizard(args) end :ok = VintageNet.subscribe(["interface", :_, "connection"]) {:ok, %{}} end def handle_info({VintageNet, ["interface", :_, "connection"], _, new_value, _}, state) when new_value in [:lan, :internet] do :ok = Config.set_wifi_provisioned() {:noreply, state} end def handle_info({VintageNet, ["interface", :_, "connection"], _, _, _}, state) do {:noreply, state} end def should_start_wizard?() do not currently_connected?() || not Config.wifi_provisioned?() end def currently_connected?() do # VintageNet.get_by_prefix(["interface", _, "connection"]) VintageNet.get_by_prefix([]) |> Enum.find_value(fn {["interface", _ifname, "connection"], value} when value in [:lan, :internet] -> true _ -> false end) end def get_info do %{ "nerves_serial_number" => serial } = Nerves.Runtime.KV.get_all() %{ "nerves_fw_platform" => platform, "nerves_fw_product" => product, "nerves_fw_uuid" => uuid, "nerves_fw_vcs_identifier" => vcs, "nerves_fw_version" => version } = Nerves.Runtime.KV.get_all_active() socket_url = Config.get_socket_url() [ {"Serial", serial}, {"Chromoid URL", socket_url || "UNPROVISIONED"}, {"Platform", platform}, {"Product", product}, {"UUID", uuid}, {"VCS", vcs}, {"Version", version} ] end end
24.577465
127
0.618338
93c6fbef1218a792f927623e5d3e89fccd5a4479
3,175
exs
Elixir
test/xema/use/combi_test.exs
xadhoom/xema
267fbdbdd30c3e9a99542141d3959dd6cd7f5708
[ "MIT" ]
49
2018-06-05T09:42:19.000Z
2022-02-15T12:50:51.000Z
test/xema/use/combi_test.exs
xadhoom/xema
267fbdbdd30c3e9a99542141d3959dd6cd7f5708
[ "MIT" ]
152
2017-06-11T13:43:06.000Z
2022-01-09T17:13:45.000Z
test/xema/use/combi_test.exs
xadhoom/xema
267fbdbdd30c3e9a99542141d3959dd6cd7f5708
[ "MIT" ]
6
2019-05-31T05:41:47.000Z
2021-12-14T08:09:36.000Z
defmodule Xema.Use.CombiTest do use ExUnit.Case, async: true alias Xema.Builder describe "any_of schema:" do defmodule MySchema.Any do use Xema xema do any_of [ list(items: integer(minimum: 1, maximum: 66)), list(items: integer(minimum: 33, maximum: 100)) ] end end test "valild?/1 returns true for a valid list" do assert MySchema.Any.valid?([20, 30]) assert MySchema.Any.valid?([40, 50]) assert MySchema.Any.valid?([60, 70]) end test "valid?/1 returns false for an invalid list" do refute MySchema.Any.valid?([10, 90]) end end describe "any_of integer schema:" do setup do schema = :integer |> Builder.any_of([[minimum: 10], [maximum: 5]]) |> Xema.new() %{schema: schema} end test "valid?/1 returns true", %{schema: schema} do assert Xema.valid?(schema, 1) assert Xema.valid?(schema, 11) end test "valid?/1 returns false", %{schema: schema} do refute Xema.valid?(schema, 7) end end describe "all_of schema:" do defmodule MySchema.All do use Xema xema do all_of [ list(items: integer(minimum: 1, maximum: 66)), list(items: integer(minimum: 33, maximum: 100)) ] end end test "valild?/1 returns true for a valid list" do assert MySchema.All.valid?([40, 50]) end test "valid?/1 returns false for an invalid list" do refute MySchema.All.valid?([10, 90]) refute MySchema.All.valid?([20, 30]) refute MySchema.All.valid?([60, 70]) end end describe "all_of integer schema:" do setup do schema = :integer |> Builder.all_of([[multiple_of: 2], [multiple_of: 3]]) |> Xema.new() %{schema: schema} end test "valid?/1 returns true", %{schema: schema} do assert Xema.valid?(schema, 6) assert Xema.valid?(schema, 12) end test "valid?/1 returns false", %{schema: schema} do refute Xema.valid?(schema, 8) refute Xema.valid?(schema, 9) end end describe "one_of schema:" do defmodule MySchema.One do use Xema xema do one_of [ list(items: integer(minimum: 1, maximum: 66)), list(items: integer(minimum: 33, maximum: 100)) ] end end test "valild?/1 returns true for a valid list" do assert MySchema.One.valid?([20, 30]) assert MySchema.One.valid?([60, 70]) end test "valid?/1 returns false for an invalid list" do refute MySchema.One.valid?([10, 90]) refute MySchema.One.valid?([40, 50]) end end describe "one_of integer schema:" do setup do schema = :integer |> Builder.one_of([[multiple_of: 2], [multiple_of: 3]]) |> Xema.new() %{schema: schema} end test "valid?/1 returns true", %{schema: schema} do assert Xema.valid?(schema, 8) assert Xema.valid?(schema, 9) end test "valid?/1 returns false", %{schema: schema} do refute Xema.valid?(schema, 6) refute Xema.valid?(schema, 12) end end end
23.175182
63
0.582992