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
ff4a6e47d5b7ffab92759836c187ccecc1782dcf
113
ex
Elixir
lib/repo.ex
irisTa56/sdo_elixir
de856596c462141477bb27aee5d63cb7b95a3b67
[ "MIT" ]
null
null
null
lib/repo.ex
irisTa56/sdo_elixir
de856596c462141477bb27aee5d63cb7b95a3b67
[ "MIT" ]
2
2021-03-10T17:42:11.000Z
2021-05-11T13:38:31.000Z
lib/repo.ex
irisTa56/sdo_elixir
de856596c462141477bb27aee5d63cb7b95a3b67
[ "MIT" ]
null
null
null
defmodule SdoPhoenix.Repo do use Ecto.Repo, otp_app: :sdo_phoenix, adapter: Ecto.Adapters.Postgres end
18.833333
35
0.743363
ff4aa134f15448f27f6796dbb62eb8f14f3a7d9e
1,112
ex
Elixir
lib/vuetaba_web/channels/user_socket.ex
fobo66/vuetaba
629514acd9680190085e35ec497b68191115e508
[ "MIT" ]
9
2019-04-10T12:30:20.000Z
2020-09-07T15:07:02.000Z
lib/vuetaba_web/channels/user_socket.ex
fobo66/vuetaba
629514acd9680190085e35ec497b68191115e508
[ "MIT" ]
3
2019-10-28T10:39:06.000Z
2020-09-30T21:56:31.000Z
lib/vuetaba_web/channels/user_socket.ex
fobo66/vuetaba
629514acd9680190085e35ec497b68191115e508
[ "MIT" ]
null
null
null
defmodule VuetabaWeb.UserSocket do use Phoenix.Socket use Absinthe.Phoenix.Socket, schema: VuetabaWeb.Schema ## Channels # channel "room:*", VuetabaWeb.RoomChannel # 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: # # VuetabaWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. def id(_socket), do: nil end
30.054054
83
0.696942
ff4ac2f36a4f126b34faba5f4214444ef4e5935a
505
ex
Elixir
lib/quadquizaminos_web/views/error_view.ex
StickyFloors/quizquadaminos
03e3b5f150d3a911efa2174bc4631a0ee6b54888
[ "MIT" ]
1
2022-01-11T20:06:31.000Z
2022-01-11T20:06:31.000Z
lib/quadquizaminos_web/views/error_view.ex
StickyFloors/quizquadaminos
03e3b5f150d3a911efa2174bc4631a0ee6b54888
[ "MIT" ]
484
2021-02-15T18:43:40.000Z
2022-03-29T12:27:24.000Z
lib/quadquizaminos_web/views/error_view.ex
StickyFloors/quizquadaminos
03e3b5f150d3a911efa2174bc4631a0ee6b54888
[ "MIT" ]
8
2021-02-15T19:12:51.000Z
2021-12-15T03:02:46.000Z
defmodule QuadquizaminosWeb.ErrorView do use QuadquizaminosWeb, :view # If you want to customize a particular status code # for a certain format, you may uncomment below. # def render("500.html", _assigns) do # "Internal Server Error" # end # By default, Phoenix returns the status message from # the template name. For example, "404.html" becomes # "Not Found". def template_not_found(template, _assigns) do Phoenix.Controller.status_message_from_template(template) end end
29.705882
61
0.742574
ff4ad8b740980b8a73f84ac0448e84d8a579d7ed
316
ex
Elixir
apps/web_api/lib/web_api/router.ex
msdmazarei/LRUCache
3287467056588971a8018ad5b661f58058f12f4d
[ "BSD-2-Clause" ]
null
null
null
apps/web_api/lib/web_api/router.ex
msdmazarei/LRUCache
3287467056588971a8018ad5b661f58058f12f4d
[ "BSD-2-Clause" ]
1
2020-03-15T18:18:57.000Z
2020-03-15T20:38:18.000Z
apps/web_api/lib/web_api/router.ex
msdmazarei/LRUCache
3287467056588971a8018ad5b661f58058f12f4d
[ "BSD-2-Clause" ]
1
2020-07-13T03:01:46.000Z
2020-07-13T03:01:46.000Z
defmodule WebApi.Router do use WebApi, :router pipeline :api do plug :accepts, ["json"] end scope "/api", WebApi do pipe_through :api get "/cache/:key", LruCacheController, :get post "/cache/:key", LruCacheController, :create delete "/cache/:key", LruCacheController, :delete end end
21.066667
53
0.670886
ff4afb8e3aed242f7c6dba0f7f1f8f1649d8ec34
1,037
exs
Elixir
apps/site/test/site_web/views/helpers/search_helpers_test.exs
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
42
2019-05-29T16:05:30.000Z
2021-08-09T16:03:37.000Z
apps/site/test/site_web/views/helpers/search_helpers_test.exs
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
872
2019-05-29T17:55:50.000Z
2022-03-30T09:28:43.000Z
apps/site/test/site_web/views/helpers/search_helpers_test.exs
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
12
2019-07-01T18:33:21.000Z
2022-03-10T02:13:57.000Z
defmodule SiteWeb.SearchHelpersTest do use SiteWeb.ConnCase, async: true import SiteWeb.SearchHelpers describe "desktop_form/2" do test "renders with default text", %{conn: conn} do conn = get(conn, search_path(conn, :index, %{"search" => %{"query" => "Search Query Format"}})) response = Phoenix.HTML.safe_to_string(desktop_form(conn, conn.params)) assert response =~ "Search Query Format" end test "renders with search param as a string", %{conn: conn} do conn = get(conn, search_path(conn, :index, %{"search" => "String Value"})) response = Phoenix.HTML.safe_to_string(desktop_form(conn, conn.params)) refute response =~ "String Value" end test "renders without default text, ignore querystring", %{conn: conn} do conn = get(conn, search_path(conn, :index, %{"search" => %{"query" => "Search Query Format"}})) response = Phoenix.HTML.safe_to_string(desktop_form(conn, %{})) refute response =~ "Search Query Format" end end end
35.758621
96
0.658631
ff4b05c269c1f4c7596221e18481d376680f86ed
915
exs
Elixir
apps/elixir_ls_utils/mix.exs
zetaron/elixir-ls
3a94455f90927601d0d3bb46f837a4f3944c5ab9
[ "Apache-2.0" ]
null
null
null
apps/elixir_ls_utils/mix.exs
zetaron/elixir-ls
3a94455f90927601d0d3bb46f837a4f3944c5ab9
[ "Apache-2.0" ]
null
null
null
apps/elixir_ls_utils/mix.exs
zetaron/elixir-ls
3a94455f90927601d0d3bb46f837a4f3944c5ab9
[ "Apache-2.0" ]
null
null
null
defmodule ElixirLS.Utils.Mixfile do use Mix.Project def project do [ app: :elixir_ls_utils, version: "0.5.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", elixirc_paths: elixirc_paths(Mix.env()), lockfile: "../../mix.lock", elixir: ">= 1.8.0", build_embedded: false, start_permanent: false, build_per_environment: false, consolidate_protocols: false, deps: deps() ] end def application do # We must NOT start ANY applications as this is taken care in code. [applications: []] end defp deps do [ {:jason_vendored, github: "elixir-lsp/jason", branch: "vendored"}, {:mix_task_archive_deps, github: "JakeBecker/mix_task_archive_deps"} ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] end
24.72973
74
0.614208
ff4b1e4881ca6935271cc2915825ef4e4144b50f
5,970
ex
Elixir
lib/five_hundred/game.ex
hugomd/five_hundred
74d5b251d4da05ff650d786d5627965114f26447
[ "MIT" ]
2
2021-06-28T07:06:13.000Z
2021-07-18T01:13:27.000Z
lib/five_hundred/game.ex
hugomd/five_hundred
74d5b251d4da05ff650d786d5627965114f26447
[ "MIT" ]
1
2021-06-20T07:49:56.000Z
2021-06-20T07:49:56.000Z
lib/five_hundred/game.ex
hugomd/five_hundred
74d5b251d4da05ff650d786d5627965114f26447
[ "MIT" ]
1
2021-07-17T10:23:36.000Z
2021-07-17T10:23:36.000Z
defmodule FiveHundred.Game do @moduledoc """ Models a game of 500 TODO: - score - turn """ alias FiveHundred.{Bid, Game, Player, PlayerBid} @derive Jason.Encoder defstruct [ :winning_bid, :players, :turn, :code, :max_players, :last_round_winner, :bid_exclusion, state: :waiting_for_players ] @type code :: String.t() @type state :: :bidding | :playing | :waiting_for_players | :finished @type t :: %Game{ code: nil | code(), players: [Player.t()], turn: nil | integer(), state: state, winning_bid: nil | PlayerBid.t(), max_players: integer(), bid_exclusion: [Player.t()], last_round_winner: nil | integer() } @spec new_game(Player.t()) :: t() def new_game(%Player{} = player, max_players \\ 4), do: %Game{ code: code(), players: [player], max_players: max_players, last_round_winner: 0, turn: 0, bid_exclusion: [], winning_bid: nil } @spec join_game(t(), Player.t()) :: {:ok, t()} | {:error, :max_players} def join_game(%Game{players: players} = game, %Player{}) when length(players) == game.max_players, do: {:error, :max_players} def join_game(%Game{players: players} = game, %Player{} = player) do {:ok, %Game{game | players: [player | players]}} |> ready_for_bidding? end @spec bid(t(), PlayerBid.t()) :: {:ok, %Game{}} | {:error, :last_round_winner_must_bid_first | :not_bidding | :bid_not_high_enough | :cannot_bid} def bid(%Game{} = game, %PlayerBid{player_index: player_index} = playerBid) do with {:ok, game} <- ensure_bidding(game), {:ok, game} <- ensure_last_winner_has_bid_first(game, playerBid), {:ok, game} <- ensure_turn(game, player_index), {:ok, game} <- ensure_can_bid(game, player_index), {:ok, game} <- ensure_bid_is_higher(game, playerBid), {:ok, game} <- set_winning_bid(game, playerBid), {:ok, game} <- exclude_from_bidding(game, player_index), {:ok, game} <- bid_advance(game), {:ok, game} <- advance_turn(game), do: {:ok, game} end @spec ensure_last_winner_has_bid_first(t(), %PlayerBid{}) :: {:ok, t()} | {:error, :last_round_winner_bid_first} def ensure_last_winner_has_bid_first(%Game{winning_bid: nil, last_round_winner: last_round_winner, bid_exclusion: bid_exclusion} = game, %PlayerBid{ player_index: player_index }) do cond do Enum.member?(bid_exclusion, last_round_winner) -> {:ok, game} player_index != last_round_winner -> {:error, :last_round_winner_must_bid_first} true -> {:ok, game} end end def ensure_last_winner_has_bid_first(%Game{} = game, %PlayerBid{}), do: {:ok, game} @spec pass(t(), integer()) :: {:ok, t()} | {:error, :not_your_turn | :not_bidding} def pass(%Game{} = game, player_index) do with {:ok, game} <- ensure_bidding(game), {:ok, game} <- ensure_turn(game, player_index), {:ok, game} <- ensure_can_bid(game, player_index), {:ok, game} <- exclude_from_bidding(game, player_index), {:ok, game} <- bid_advance(game), {:ok, game} <- advance_turn(game), do: {:ok, game} end @spec bid_advance(t()) :: {:ok, t()} | {:error, :not_bidding} def bid_advance(%Game{bid_exclusion: bid_exclusion, players: players} = game) when length(bid_exclusion) == length(players), do: {:ok, %Game{game | state: :playing}} def bid_advance(%Game{} = game), do: {:ok, game} @spec advance_turn(t()) :: {:ok, t()} def advance_turn(%Game{players: players, turn: current_turn} = game), do: {:ok, %Game{game | turn: rem(current_turn + 1, length(players))}} @spec ensure_bidding(t()) :: {:ok, t()} | {:error, :not_bidding} def ensure_bidding(%Game{state: state}) when state != :bidding, do: {:error, :not_bidding} def ensure_bidding(%Game{} = game), do: {:ok, game} @spec ensure_turn(t(), integer()) :: {:ok, t()} | {:error, :not_your_turn} def ensure_turn(%Game{turn: turn}, player_index) when turn != player_index, do: {:error, :not_your_turn} def ensure_turn(%Game{} = game, _player_index), do: {:ok, game} @spec ensure_bid_is_higher(t(), PlayerBid.t()) :: {:ok, t()} | {:error, :bid_not_high_enough} def ensure_bid_is_higher(%Game{winning_bid: nil} = game, %PlayerBid{}), do: {:ok, game} def ensure_bid_is_higher( %Game{winning_bid: %PlayerBid{bid: winning_bid}} = game, %PlayerBid{bid: new_bid} = playerBid ) do case Bid.compare(new_bid, winning_bid) do :gt -> set_winning_bid(game, playerBid) _ -> {:error, :bid_not_high_enough} end end @spec ensure_can_bid(t(), integer()) :: {:ok, t()} | {:error, atom()} def ensure_can_bid(%Game{bid_exclusion: bid_exclusion} = game, player_index) do if Enum.member?(bid_exclusion, player_index) do {:error, :cannot_bid} else {:ok, game} end end @spec set_winning_bid(t(), PlayerBid.t()) :: {:ok, t()} | {:error, atom()} def set_winning_bid(%Game{} = game, %PlayerBid{} = playerBid), do: {:ok, %Game{game | winning_bid: playerBid}} @spec exclude_from_bidding(t(), integer()) :: {:ok, t()} | {:error, atom()} def exclude_from_bidding(%Game{bid_exclusion: bid_exclusion} = game, player_index), do: {:ok, %Game{game | bid_exclusion: [player_index | bid_exclusion]}} @spec ready_for_bidding?({:ok, t()}) :: {:ok, t()} def ready_for_bidding?({:ok, %Game{players: players, max_players: max_players} = game}) when length(players) == max_players, do: {:ok, %Game{game | state: :bidding}} def ready_for_bidding?({:ok, %Game{} = game}), do: {:ok, game} @spec code(integer) :: String.t() def code(length \\ 5), do: :crypto.strong_rand_bytes(length) |> Base.url_encode64() |> binary_part(0, length) |> String.upcase() end
34.912281
150
0.613065
ff4b3cbcab0de62310b3c1ab42e560c414a75d05
730
exs
Elixir
priv/repo/migrations/20200515091329_create_commits.exs
calleluks/ex-remit
893dbc42c9ace6db6ee044f82371075198089fdc
[ "MIT" ]
17
2020-06-28T19:01:49.000Z
2021-11-24T23:55:09.000Z
priv/repo/migrations/20200515091329_create_commits.exs
calleluks/ex-remit
893dbc42c9ace6db6ee044f82371075198089fdc
[ "MIT" ]
29
2020-06-27T17:44:38.000Z
2022-01-17T10:00:12.000Z
priv/repo/migrations/20200515091329_create_commits.exs
calleluks/ex-remit
893dbc42c9ace6db6ee044f82371075198089fdc
[ "MIT" ]
2
2021-03-01T09:51:56.000Z
2021-03-04T21:27:56.000Z
defmodule Remit.Repo.Migrations.CreateCommits do use Ecto.Migration def change do create table(:commits) do add :sha, :string, null: false add :author_email, :string, null: false add :author_name, :string, null: false add :author_usernames, {:array, :string}, null: false add :owner, :string, null: false add :repo, :string, null: false add :message, :text, null: false add :url, :text, null: false add :committed_at, :utc_datetime, null: false add :review_started_at, :utc_datetime add :reviewed_at, :utc_datetime add :review_started_by_email, :string add :reviewed_by_email, :string timestamps(type: :utc_datetime) end end end
29.2
59
0.661644
ff4b961d4980e1ea528840b8483b4685b28e942f
441
ex
Elixir
lib/goldie/supervisor_npc.ex
scatterbrain/goldie
db649f9555d453541d01d0707d86b41f41156640
[ "MIT" ]
null
null
null
lib/goldie/supervisor_npc.ex
scatterbrain/goldie
db649f9555d453541d01d0707d86b41f41156640
[ "MIT" ]
null
null
null
lib/goldie/supervisor_npc.ex
scatterbrain/goldie
db649f9555d453541d01d0707d86b41f41156640
[ "MIT" ]
null
null
null
defmodule Goldie.SupervisorNPC do @moduledoc """ NPC supervisor """ use Supervisor require Logger def start_npc(opts) do Supervisor.start_child(__MODULE__, opts) end def start_link do Supervisor.start_link(__MODULE__, :ok, [name: __MODULE__]) end def init(:ok) do children = [ worker(Goldie.NPC, [], restart: :temporary) ] supervise(children, strategy: :simple_one_for_one) end end
17.64
62
0.673469
ff4b9f59c62720a81d806746fd72b0053fa4df84
14,570
ex
Elixir
deps/phoenix/lib/phoenix/channel/server.ex
thaisfiori/blog_da_tha
e860e64e5251dae03b95fdf1e339ec0a3d789a29
[ "Apache-2.0" ]
2
2020-05-06T14:51:56.000Z
2020-05-06T14:52:21.000Z
deps/phoenix/lib/phoenix/channel/server.ex
rwtrecs/rocketseat-nlw5-inmana
8ce8bc32e0bdd005c423394bb163945747b557e2
[ "MIT" ]
3
2021-06-20T14:51:14.000Z
2021-06-25T00:56:11.000Z
deps/phoenix/lib/phoenix/channel/server.ex
rwtrecs/rocketseat-nlw5-inmana
8ce8bc32e0bdd005c423394bb163945747b557e2
[ "MIT" ]
1
2020-05-16T22:44:14.000Z
2020-05-16T22:44:14.000Z
defmodule Phoenix.Channel.Server do @moduledoc false use GenServer, restart: :temporary require Logger require Phoenix.Endpoint alias Phoenix.PubSub alias Phoenix.Socket alias Phoenix.Socket.{Broadcast, Message, Reply, PoolSupervisor} ## Socket API @doc """ Joins the channel in socket with authentication payload. """ @spec join(Socket.t(), module, Message.t(), keyword) :: {:ok, term, pid} | {:error, term} def join(socket, channel, message, opts) do %{topic: topic, payload: payload, ref: ref, join_ref: join_ref} = message assigns = Map.merge(socket.assigns, Keyword.get(opts, :assigns, %{})) socket = %{socket | topic: topic, channel: channel, join_ref: join_ref || ref, assigns: assigns} ref = make_ref() from = {self(), ref} child_spec = channel.child_spec({socket.endpoint, from}) case PoolSupervisor.start_child(socket.endpoint, socket.handler, from, child_spec) do {:ok, pid} -> send(pid, {Phoenix.Channel, payload, from, socket}) mon_ref = Process.monitor(pid) receive do {^ref, {:ok, reply}} -> Process.demonitor(mon_ref, [:flush]) {:ok, reply, pid} {^ref, {:error, reply}} -> Process.demonitor(mon_ref, [:flush]) {:error, reply} {:DOWN, ^mon_ref, _, _, reason} -> Logger.error(fn -> Exception.format_exit(reason) end) {:error, %{reason: "join crashed"}} end {:error, reason} -> Logger.error(fn -> Exception.format_exit(reason) end) {:error, %{reason: "join crashed"}} end end @doc """ Gets the socket from the channel. Used by channel tests. """ @spec socket(pid) :: Socket.t() def socket(pid) do GenServer.call(pid, :socket) end @doc """ Emulates the socket being closed. Used by channel tests. """ @spec close(pid, timeout) :: :ok def close(pid, timeout) do GenServer.cast(pid, :close) ref = Process.monitor(pid) receive do {:DOWN, ^ref, _, _, _} -> :ok after timeout -> Process.exit(pid, :kill) receive do: ({:DOWN, ^ref, _, _, _} -> :ok) end end ## Channel API @doc """ Hook invoked by Phoenix.PubSub dispatch. """ def dispatch(subscribers, from, %Broadcast{event: event} = msg) do Enum.reduce(subscribers, %{}, fn {pid, _}, cache when pid == from -> cache {pid, {:fastlane, fastlane_pid, serializer, event_intercepts}}, cache -> if event in event_intercepts do send(pid, msg) cache else case cache do %{^serializer => encoded_msg} -> send(fastlane_pid, encoded_msg) cache %{} -> encoded_msg = serializer.fastlane!(msg) send(fastlane_pid, encoded_msg) Map.put(cache, serializer, encoded_msg) end end {pid, _}, cache -> send(pid, msg) cache end) :ok end def dispatch(entries, :none, message) do for {pid, _} <- entries do send(pid, message) end :ok end def dispatch(entries, from, message) do for {pid, _} <- entries, pid != from do send(pid, message) end :ok end @doc """ Broadcasts on the given pubsub server with the given `topic`, `event` and `payload`. The message is encoded as `Phoenix.Socket.Broadcast`. """ def broadcast(pubsub_server, topic, event, payload) when is_binary(topic) and is_binary(event) do broadcast = %Broadcast{ topic: topic, event: event, payload: payload } PubSub.broadcast(pubsub_server, topic, broadcast, __MODULE__) end @doc """ Broadcasts on the given pubsub server with the given `topic`, `event` and `payload`. Raises in case of crashes. """ def broadcast!(pubsub_server, topic, event, payload) when is_binary(topic) and is_binary(event) do broadcast = %Broadcast{ topic: topic, event: event, payload: payload } PubSub.broadcast!(pubsub_server, topic, broadcast, __MODULE__) end @doc """ Broadcasts on the given pubsub server with the given `from`, `topic`, `event` and `payload`. The message is encoded as `Phoenix.Socket.Broadcast`. """ def broadcast_from(pubsub_server, from, topic, event, payload) when is_binary(topic) and is_binary(event) do broadcast = %Broadcast{ topic: topic, event: event, payload: payload } PubSub.broadcast_from(pubsub_server, from, topic, broadcast, __MODULE__) end @doc """ Broadcasts on the given pubsub server with the given `from`, `topic`, `event` and `payload`. Raises in case of crashes. """ def broadcast_from!(pubsub_server, from, topic, event, payload) when is_binary(topic) and is_binary(event) do broadcast = %Broadcast{ topic: topic, event: event, payload: payload } PubSub.broadcast_from!(pubsub_server, from, topic, broadcast, __MODULE__) end @doc """ Broadcasts on the given pubsub server with the given `topic`, `event` and `payload`. The message is encoded as `Phoenix.Socket.Broadcast`. """ def local_broadcast(pubsub_server, topic, event, payload) when is_binary(topic) and is_binary(event) do broadcast = %Broadcast{ topic: topic, event: event, payload: payload } PubSub.local_broadcast(pubsub_server, topic, broadcast, __MODULE__) end @doc """ Broadcasts on the given pubsub server with the given `from`, `topic`, `event` and `payload`. The message is encoded as `Phoenix.Socket.Broadcast`. """ def local_broadcast_from(pubsub_server, from, topic, event, payload) when is_binary(topic) and is_binary(event) do broadcast = %Broadcast{ topic: topic, event: event, payload: payload } PubSub.local_broadcast_from(pubsub_server, from, topic, broadcast, __MODULE__) end @doc """ Pushes a message with the given topic, event and payload to the given process. """ def push(pid, join_ref, topic, event, payload, serializer) when is_binary(topic) and is_binary(event) do message = %Message{join_ref: join_ref, topic: topic, event: event, payload: payload} send(pid, serializer.encode!(message)) :ok end @doc """ Replies to a given ref to the transport process. """ def reply(pid, join_ref, ref, topic, {status, payload}, serializer) when is_binary(topic) do reply = %Reply{topic: topic, join_ref: join_ref, ref: ref, status: status, payload: payload} send(pid, serializer.encode!(reply)) :ok end ## Callbacks @doc false def init({_endpoint, {pid, _}}) do {:ok, Process.monitor(pid)} end @doc false def handle_call(:socket, _from, socket) do {:reply, socket, socket} end @doc false def handle_call(msg, from, socket) do msg |> socket.channel.handle_call(from, socket) |> handle_result(:handle_call) end @doc false def handle_cast(:close, socket) do {:stop, {:shutdown, :closed}, socket} end @doc false def handle_cast(msg, socket) do msg |> socket.channel.handle_cast(socket) |> handle_result(:handle_cast) end @doc false def handle_info({Phoenix.Channel, auth_payload, {pid, _} = from, socket}, ref) do Process.demonitor(ref) %{channel: channel, topic: topic, private: private} = socket Process.put(:"$callers", [pid]) socket = %{ socket | channel_pid: self(), private: Map.merge(channel.__socket__(:private), private) } start = System.monotonic_time() {reply, state} = channel_join(channel, topic, auth_payload, socket) duration = System.monotonic_time() - start metadata = %{params: auth_payload, socket: socket, result: elem(reply, 0)} :telemetry.execute([:phoenix, :channel_joined], %{duration: duration}, metadata) GenServer.reply(from, reply) state end def handle_info(%Message{topic: topic, event: "phx_leave", ref: ref}, %{topic: topic} = socket) do handle_in({:stop, {:shutdown, :left}, :ok, put_in(socket.ref, ref)}) end def handle_info( %Message{topic: topic, event: event, payload: payload, ref: ref}, %{topic: topic} = socket ) do start = System.monotonic_time() result = socket.channel.handle_in(event, payload, put_in(socket.ref, ref)) duration = System.monotonic_time() - start metadata = %{ref: ref, event: event, params: payload, socket: socket} :telemetry.execute([:phoenix, :channel_handled_in], %{duration: duration}, metadata) handle_in(result) end def handle_info( %Broadcast{topic: topic, event: event, payload: payload}, %Socket{topic: topic} = socket ) do event |> socket.channel.handle_out(payload, socket) |> handle_result(:handle_out) end def handle_info({:DOWN, ref, _, _, reason}, ref) do {:stop, reason, ref} end def handle_info({:DOWN, _, _, transport_pid, reason}, %{transport_pid: transport_pid} = socket) do reason = if reason == :normal, do: {:shutdown, :closed}, else: reason {:stop, reason, socket} end def handle_info(msg, %{channel: channel} = socket) do if function_exported?(channel, :handle_info, 2) do msg |> socket.channel.handle_info(socket) |> handle_result(:handle_info) else warn_unexpected_msg(:handle_info, 2, msg) {:noreply, socket} end end @doc false def code_change(old, %{channel: channel} = socket, extra) do if function_exported?(channel, :code_change, 3) do channel.code_change(old, socket, extra) else {:ok, socket} end end @doc false def terminate(reason, %{channel: channel} = socket) do if function_exported?(channel, :terminate, 2) do channel.terminate(reason, socket) else :ok end end def terminate(_reason, _socket) do :ok end ## Joins defp channel_join(channel, topic, auth_payload, socket) do case channel.join(topic, auth_payload, socket) do {:ok, socket} -> {{:ok, %{}}, init_join(socket, channel, topic)} {:ok, reply, socket} -> {{:ok, reply}, init_join(socket, channel, topic)} {:error, reply} -> {{:error, reply}, {:stop, :shutdown, socket}} other -> raise """ channel #{inspect(socket.channel)}.join/3 is expected to return one of: {:ok, Socket.t} | {:ok, reply :: map, Socket.t} | {:error, reply :: map} got #{inspect(other)} """ end end defp init_join(socket, channel, topic) do %{transport_pid: transport_pid, serializer: serializer, pubsub_server: pubsub_server} = socket unless pubsub_server do raise """ The :pubsub_server was not configured for endpoint #{inspect(socket.endpoint)}. Make sure to start a PubSub process in your application supervision tree: {Phoenix.PubSub, [name: YOURAPP.PubSub, adapter: Phoenix.PubSub.PG2]} And then add it to your endpoint config: config :YOURAPP, YOURAPPWeb.Endpoint, # ... pubsub_server: YOURAPP.PubSub """ end Process.monitor(transport_pid) fastlane = {:fastlane, transport_pid, serializer, channel.__intercepts__()} PubSub.subscribe(pubsub_server, topic, metadata: fastlane) {:noreply, %{socket | joined: true}} end ## Handle results defp handle_result({:stop, reason, socket}, _callback) do case reason do :normal -> send_socket_close(socket, reason) :shutdown -> send_socket_close(socket, reason) {:shutdown, _} -> send_socket_close(socket, reason) _ -> :noop end {:stop, reason, socket} end defp handle_result({:reply, resp, socket}, :handle_call) do {:reply, resp, socket} end defp handle_result({:noreply, socket}, callback) when callback in [:handle_call, :handle_cast] do {:noreply, socket} end defp handle_result({:noreply, socket}, _callback) do {:noreply, put_in(socket.ref, nil)} end defp handle_result({:noreply, socket, timeout_or_hibernate}, _callback) do {:noreply, put_in(socket.ref, nil), timeout_or_hibernate} end defp handle_result(result, :handle_in) do raise """ Expected handle_in/3 to return one of: {:noreply, Socket.t} | {:noreply, Socket.t, timeout | :hibernate} | {:reply, {status :: atom, response :: map}, Socket.t} | {:reply, status :: atom, Socket.t} | {:stop, reason :: term, Socket.t} | {:stop, reason :: term, {status :: atom, response :: map}, Socket.t} | {:stop, reason :: term, status :: atom, Socket.t} got #{inspect(result)} """ end defp handle_result(result, callback) do raise """ Expected #{callback} to return one of: {:noreply, Socket.t} | {:noreply, Socket.t, timeout | :hibernate} | {:stop, reason :: term, Socket.t} | got #{inspect(result)} """ end defp send_socket_close(%{transport_pid: transport_pid}, reason) do send(transport_pid, {:socket_close, self(), reason}) end ## Handle in/replies defp handle_in({:reply, reply, %Socket{} = socket}) do handle_reply(socket, reply) {:noreply, put_in(socket.ref, nil)} end defp handle_in({:stop, reason, reply, socket}) do handle_reply(socket, reply) handle_result({:stop, reason, socket}, :handle_in) end defp handle_in(other) do handle_result(other, :handle_in) end defp handle_reply(socket, {status, payload}) when is_atom(status) do reply( socket.transport_pid, socket.join_ref, socket.ref, socket.topic, {status, payload}, socket.serializer ) end defp handle_reply(socket, status) when is_atom(status) do handle_reply(socket, {status, %{}}) end defp handle_reply(_socket, reply) do raise """ Channel replies from handle_in/3 are expected to be one of: status :: atom {status :: atom, response :: map} for example: {:reply, :ok, socket} {:reply, {:ok, %{}}, socket} {:stop, :shutdown, {:error, %{}}, socket} got #{inspect(reply)} """ end defp warn_unexpected_msg(fun, arity, msg) do proc = case Process.info(self(), :registered_name) do {_, []} -> self() {_, name} -> name end :error_logger.warning_msg( ~c"~p ~p received unexpected message in #{fun}/#{arity}: ~p~n", [__MODULE__, proc, msg] ) end end
26.587591
100
0.626424
ff4bb4edcd6d19db533f2002ba7b7a7fd78fcf93
417
ex
Elixir
2016/day06/lib/day06.ex
matt-thomson/advent-of-code
feff903151284240a9d3f0c84cdfe52d8d11ef06
[ "MIT" ]
null
null
null
2016/day06/lib/day06.ex
matt-thomson/advent-of-code
feff903151284240a9d3f0c84cdfe52d8d11ef06
[ "MIT" ]
null
null
null
2016/day06/lib/day06.ex
matt-thomson/advent-of-code
feff903151284240a9d3f0c84cdfe52d8d11ef06
[ "MIT" ]
null
null
null
defmodule Day06 do @moduledoc """ Entry point for day 6 solver. """ alias Day06.Message def part_one(filename) do filename |> solve(&Message.most_common/1) end def part_two(filename) do filename |> solve(&Message.least_common/1) end defp solve(filename, select_char) do filename |> File.stream! |> Message.group_letters |> Enum.map(select_char) |> Enum.join end end
18.130435
46
0.666667
ff4bf364f376e7ffe0bca53370808d4ea1727b05
4,495
ex
Elixir
apps/ewallet_db/test/support/factory.ex
turbo-play/ewallet
b7fee3eed62ac716f46246132c2ead1045f2e4f3
[ "Apache-2.0" ]
2
2019-07-13T05:49:03.000Z
2021-08-19T23:58:23.000Z
apps/ewallet_db/test/support/factory.ex
turbo-play/ewallet
b7fee3eed62ac716f46246132c2ead1045f2e4f3
[ "Apache-2.0" ]
null
null
null
apps/ewallet_db/test/support/factory.ex
turbo-play/ewallet
b7fee3eed62ac716f46246132c2ead1045f2e4f3
[ "Apache-2.0" ]
3
2018-05-08T17:15:42.000Z
2021-11-10T04:08:33.000Z
defmodule EWalletDB.Factory do @moduledoc """ Factories used for testing. """ use ExMachina.Ecto, repo: EWalletDB.Repo alias ExMachina.Strategy alias EWalletDB.{ Account, APIKey, AuthToken, Balance, ForgetPasswordRequest, Invite, Key, Membership, Mint, MintedToken, Role, TransactionRequest, TransactionRequestConsumption, Transfer, User } alias EWalletDB.Helpers.Crypto alias Ecto.UUID @doc """ Get factory name (as atom) from schema. The function should explicitly handle schemas that produce incorrect factory name, e.g. when APIKey becomes :a_p_i_key """ def get_factory(APIKey), do: :api_key def get_factory(schema) when is_atom(schema) do schema |> struct |> Strategy.name_from_struct end def balance_factory do %Balance{ address: sequence("address"), name: sequence("name"), identifier: Balance.primary, user: insert(:user), minted_token: nil, metadata: %{} } end def minted_token_factory do %MintedToken{ friendly_id: sequence("jon") <> ":" <> UUID.generate(), symbol: sequence("jon"), iso_code: sequence("JON"), name: sequence("John Currency"), description: sequence("Official currency of Johndoeland"), short_symbol: sequence("J"), subunit: "Doe", subunit_to_unit: 100, symbol_first: true, html_entity: "&curren;", iso_numeric: sequence("990"), smallest_denomination: 1, locked: false, account: insert(:account) } end def user_factory do %User{ username: sequence("johndoe"), provider_user_id: sequence("provider_id"), metadata: %{ "first_name" => sequence("John"), "last_name" => sequence("Doe") }, encrypted_metadata: %{} } end def admin_factory do password = sequence("password") %User{ email: sequence("johndoe") <> "@example.com", password: password, password_hash: Crypto.hash_password(password), invite: nil, metadata: %{ "first_name" => sequence("John"), "last_name" => sequence("Doe") } } end def invite_factory do %Invite{ token: Crypto.generate_key(32) } end def role_factory do %Role{ name: sequence("role"), display_name: "Role display name" } end def membership_factory do %Membership{ user: insert(:user), role: insert(:role), account: insert(:account) } end def mint_factory do %Mint{ amount: 100_000, minted_token_id: insert(:minted_token).id, transfer_id: insert(:transfer).id } end def account_factory do %Account{ name: sequence("account"), description: sequence("description for account"), parent: Account.get_master_account() } end def key_factory do access_key = sequence("access_key") secret_key = sequence("secret_key") %Key{ access_key: access_key, secret_key: secret_key, secret_key_hash: Crypto.hash_password(secret_key), account: insert(:account), deleted_at: nil } end def api_key_factory do %APIKey{ key: sequence("api_key"), owner_app: "some_app_name", account: insert(:account), expired: false, } end def auth_token_factory do %AuthToken{ token: sequence("auth_token"), owner_app: "some_app_name", user: insert(:user), expired: false, } end def transfer_factory do %Transfer{ idempotency_token: UUID.generate(), payload: %{example: "Payload"}, metadata: %{some: "metadata"}, amount: 100, minted_token: insert(:minted_token), from_balance: insert(:balance), to_balance: insert(:balance) } end def forget_password_request_factory do %ForgetPasswordRequest{ token: sequence("123"), } end def transaction_request_factory do %TransactionRequest{ type: "receive", amount: 100, correlation_id: sequence("correlation"), minted_token_id: insert(:minted_token).id, user_id: insert(:user).id, balance: insert(:balance) } end def transaction_request_consumption_factory do %TransactionRequestConsumption{ idempotency_token: sequence("123"), minted_token_id: insert(:minted_token).id, user_id: insert(:user).id, balance: insert(:transaction_request) } end end
22.252475
84
0.629143
ff4bf5892ffd6ecd3dfc87df9e063c5a07a11294
598
ex
Elixir
lib/octopus/accounts/request.ex
ubudget/octopus
84087fbb6bfd5e7611583d7c1098e18d4239f036
[ "MIT" ]
null
null
null
lib/octopus/accounts/request.ex
ubudget/octopus
84087fbb6bfd5e7611583d7c1098e18d4239f036
[ "MIT" ]
null
null
null
lib/octopus/accounts/request.ex
ubudget/octopus
84087fbb6bfd5e7611583d7c1098e18d4239f036
[ "MIT" ]
null
null
null
defmodule Octopus.Accounts.Request do @moduledoc """ Defines the fields of an auth request. """ use Ecto.Schema import Ecto.Changeset alias Octopus.Accounts.User @primary_key {:id, :binary_id, autogenerate: true} @foreign_key_type :binary_id schema "requests" do field(:secure_hash, :string) field(:token, :string) field(:ip, :string) belongs_to(:user, User) timestamps() end def changeset(request, attrs) do request |> cast(attrs, [:secure_hash, :token, :ip, :user_id]) |> validate_required([:secure_hash, :token, :ip, :user_id]) end end
23
63
0.677258
ff4bfe193aa94a8f3aeeec0d108ff449846eb9d1
632
ex
Elixir
lib/text_2_sign/fetcher.ex
Waasi/text_2_sign
6edc91f12253817dbebb687cf24bc1dbe78888a1
[ "MIT" ]
7
2016-10-23T20:01:52.000Z
2021-03-16T06:16:05.000Z
lib/text_2_sign/fetcher.ex
Waasi/text_2_sign
6edc91f12253817dbebb687cf24bc1dbe78888a1
[ "MIT" ]
4
2016-10-25T00:16:24.000Z
2018-05-09T17:08:35.000Z
lib/text_2_sign/fetcher.ex
Waasi/text_2_sign
6edc91f12253817dbebb687cf24bc1dbe78888a1
[ "MIT" ]
4
2018-05-09T13:56:24.000Z
2021-12-23T02:14:56.000Z
defmodule Text2Sign.Fetcher do @moduledoc """ The Text2Sign.Fetcher module allows the fetching of the url for the given word. """ @doc """ The fetch/1 function takes a string type word as an argument and returns a tuple with the status and the url for the given word. ### Example: iex> Text2Sign.Fetcher.fetch("Word")\n {:ok, some_url} """ def fetch(word, url) do response = HTTPoison.get!("#{url}search/#{word}") endpoint = response.body |> Floki.find("a[href*=#{String.upcase(word)}]") |> Floki.attribute("href") |> Enum.at(0) {:ok, endpoint} end end
21.066667
54
0.621835
ff4c0abd56257a3cb80adcbab2abac2cabbccbd9
282
exs
Elixir
elixir/priv/repo/migrations/20210209205011_create_companies.exs
XanderHarris/web-homework
d0b5c2bbbd055341d51f02f824a2020188f6c094
[ "MIT" ]
null
null
null
elixir/priv/repo/migrations/20210209205011_create_companies.exs
XanderHarris/web-homework
d0b5c2bbbd055341d51f02f824a2020188f6c094
[ "MIT" ]
null
null
null
elixir/priv/repo/migrations/20210209205011_create_companies.exs
XanderHarris/web-homework
d0b5c2bbbd055341d51f02f824a2020188f6c094
[ "MIT" ]
null
null
null
defmodule Homework.Repo.Migrations.CreateCompanies do use Ecto.Migration def change do create table(:companies, primary_key: false) do add(:id, :uuid, primary_key: true) add(:name, :string) add(:credit_line, :integer) timestamps() end end end
21.692308
53
0.673759
ff4c1f9986934d90a5078a0ae5d103a420dbfeb8
1,840
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/video_formats_list_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/video_formats_list_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/video_formats_list_response.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.DFAReporting.V34.Model.VideoFormatsListResponse do @moduledoc """ Video Format List Response ## Attributes * `kind` (*type:* `String.t`, *default:* `dfareporting#videoFormatsListResponse`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#videoFormatsListResponse". * `videoFormats` (*type:* `list(GoogleApi.DFAReporting.V34.Model.VideoFormat.t)`, *default:* `nil`) - Video format collection. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :kind => String.t(), :videoFormats => list(GoogleApi.DFAReporting.V34.Model.VideoFormat.t()) } field(:kind) field(:videoFormats, as: GoogleApi.DFAReporting.V34.Model.VideoFormat, type: :list) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.VideoFormatsListResponse do def decode(value, options) do GoogleApi.DFAReporting.V34.Model.VideoFormatsListResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.VideoFormatsListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.8
194
0.747826
ff4c1fdbb6610f940f274129ca1f0ea9398ac797
2,174
ex
Elixir
clients/os_login/lib/google_api/os_login/v1alpha/model/login_profile.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/os_login/lib/google_api/os_login/v1alpha/model/login_profile.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/os_login/lib/google_api/os_login/v1alpha/model/login_profile.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "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.OSLogin.V1alpha.Model.LoginProfile do @moduledoc """ The user profile information used for logging in to a virtual machine on Google Compute Engine. ## Attributes * `name` (*type:* `String.t`, *default:* `nil`) - A unique user ID. * `posixAccounts` (*type:* `list(GoogleApi.OSLogin.V1alpha.Model.PosixAccount.t)`, *default:* `nil`) - The list of POSIX accounts associated with the user. * `sshPublicKeys` (*type:* `%{optional(String.t) => GoogleApi.OSLogin.V1alpha.Model.SshPublicKey.t}`, *default:* `nil`) - A map from SSH public key fingerprint to the associated key object. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :name => String.t(), :posixAccounts => list(GoogleApi.OSLogin.V1alpha.Model.PosixAccount.t()), :sshPublicKeys => %{ optional(String.t()) => GoogleApi.OSLogin.V1alpha.Model.SshPublicKey.t() } } field(:name) field(:posixAccounts, as: GoogleApi.OSLogin.V1alpha.Model.PosixAccount, type: :list) field(:sshPublicKeys, as: GoogleApi.OSLogin.V1alpha.Model.SshPublicKey, type: :map) end defimpl Poison.Decoder, for: GoogleApi.OSLogin.V1alpha.Model.LoginProfile do def decode(value, options) do GoogleApi.OSLogin.V1alpha.Model.LoginProfile.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.OSLogin.V1alpha.Model.LoginProfile do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.527273
193
0.722171
ff4c2ecf34c4b623dd61336cd06f6f0666c355f4
73
exs
Elixir
test/test_helper.exs
Atla0903/nano_planner
6ffc83e09853084e932a063a9ce651563b8b38e1
[ "MIT" ]
null
null
null
test/test_helper.exs
Atla0903/nano_planner
6ffc83e09853084e932a063a9ce651563b8b38e1
[ "MIT" ]
null
null
null
test/test_helper.exs
Atla0903/nano_planner
6ffc83e09853084e932a063a9ce651563b8b38e1
[ "MIT" ]
null
null
null
ExUnit.start Ecto.Adapters.SQL.Sandbox.mode(NanoPlanner.Repo, :manual)
14.6
57
0.794521
ff4c34a3b7cceb9c590120b18034cebd372138c6
1,031
exs
Elixir
mix.exs
b1az/elixir-keycloak
1252c68bcc6e8198e16877e824af1508b10007e8
[ "MIT" ]
38
2017-07-31T22:30:26.000Z
2022-02-01T11:24:42.000Z
mix.exs
b1az/elixir-keycloak
1252c68bcc6e8198e16877e824af1508b10007e8
[ "MIT" ]
6
2018-12-17T16:31:46.000Z
2021-12-07T15:34:35.000Z
mix.exs
b1az/elixir-keycloak
1252c68bcc6e8198e16877e824af1508b10007e8
[ "MIT" ]
8
2018-12-15T05:51:39.000Z
2021-12-14T12:42:17.000Z
defmodule Keycloak.Mixfile do use Mix.Project def project do [ app: :keycloak, version: "1.1.0", elixir: "~> 1.6", name: "keycloak", description: "Library for interacting with a Keycloak authorization server", package: package(), deps: deps(), docs: [extras: ["README.md"], main: "readme"], source_url: "https://github.com/vanetix/elixir-keycloak" ] end # Configuration for the OTP application def application do [extra_applications: [:logger, :oauth2]] end defp deps do [ {:joken, "~> 2.0"}, {:oauth2, "~> 2.0"}, {:plug, "~> 1.4"}, {:poison, "~> 4.0"}, {:credo, "~> 1.4", only: [:dev, :test], runtime: false}, {:ex_doc, "~> 0.26", only: :dev, runtime: false}, {:rexbug, "~> 1.0", only: :dev, runtime: false} ] end defp package do [ maintainers: ["Matthew McFarland"], licenses: ["MIT"], links: %{"Github" => "https://github.com/vanetix/elixir-keycloak"} ] end end
23.976744
82
0.548982
ff4c42a02a7ec90143302b75d8aecc10643aee68
1,892
ex
Elixir
clients/discovery/lib/google_api/discovery/v1/model/directory_list.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/discovery/lib/google_api/discovery/v1/model/directory_list.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/discovery/lib/google_api/discovery/v1/model/directory_list.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.Discovery.V1.Model.DirectoryList do @moduledoc """ ## Attributes * `discoveryVersion` (*type:* `String.t`, *default:* `v1`) - Indicate the version of the Discovery API used to generate this doc. * `items` (*type:* `list(GoogleApi.Discovery.V1.Model.DirectoryListItems.t)`, *default:* `nil`) - The individual directory entries. One entry per api/version pair. * `kind` (*type:* `String.t`, *default:* `discovery#directoryList`) - The kind for this response. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :discoveryVersion => String.t(), :items => list(GoogleApi.Discovery.V1.Model.DirectoryListItems.t()), :kind => String.t() } field(:discoveryVersion) field(:items, as: GoogleApi.Discovery.V1.Model.DirectoryListItems, type: :list) field(:kind) end defimpl Poison.Decoder, for: GoogleApi.Discovery.V1.Model.DirectoryList do def decode(value, options) do GoogleApi.Discovery.V1.Model.DirectoryList.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Discovery.V1.Model.DirectoryList do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.698113
167
0.723573
ff4c4a67869205aa4940c5ef9dcbff5cecb24b94
200
exs
Elixir
example/config/dev.exs
rschef/paper_trail
6ab8b29ee97b46222cc48d376daea70fc5cb8105
[ "MIT" ]
484
2016-06-19T19:33:31.000Z
2022-03-30T00:04:06.000Z
example/config/dev.exs
rschef/paper_trail
6ab8b29ee97b46222cc48d376daea70fc5cb8105
[ "MIT" ]
125
2016-12-13T14:28:45.000Z
2022-03-01T00:07:06.000Z
example/config/dev.exs
rschef/paper_trail
6ab8b29ee97b46222cc48d376daea70fc5cb8105
[ "MIT" ]
80
2016-09-09T02:12:41.000Z
2022-03-29T20:51:12.000Z
use Mix.Config config :example, Repo, adapter: Ecto.Adapters.Postgres, database: "papertrail_example_dev", username: "postgres", password: "postgres", hostname: "localhost", poolsize: 10
20
37
0.725
ff4c4f8eab41994a3a5951dbe9aafdd620504b10
490
ex
Elixir
lib/open_graph/application.ex
goofansu/ogp
f012a9d6caaf2cc62a58b037cb16dff53d809d4a
[ "MIT" ]
15
2021-06-04T02:43:20.000Z
2022-01-25T01:37:37.000Z
lib/open_graph/application.ex
goofansu/ogp
f012a9d6caaf2cc62a58b037cb16dff53d809d4a
[ "MIT" ]
1
2021-05-29T03:31:19.000Z
2021-05-29T03:31:19.000Z
lib/open_graph/application.ex
goofansu/ogp
f012a9d6caaf2cc62a58b037cb16dff53d809d4a
[ "MIT" ]
null
null
null
defmodule OpenGraph.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application @impl true def start(_type, _args) do children = [ {Finch, name: OpenGraph.Finch} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: OpenGraph.Supervisor] Supervisor.start_link(children, opts) end end
24.5
63
0.712245
ff4c70bf640db5001d13cd5341bfc22b6c4ac62c
3,209
ex
Elixir
lib/mix/task/radiator.adduser.ex
bhtabor/radiator
39c137a18d36d6f418f9d1ffb7aa2c99011d66cf
[ "MIT" ]
92
2019-01-03T11:46:23.000Z
2022-02-19T21:28:44.000Z
lib/mix/task/radiator.adduser.ex
bhtabor/radiator
39c137a18d36d6f418f9d1ffb7aa2c99011d66cf
[ "MIT" ]
350
2019-04-11T07:55:51.000Z
2021-08-03T11:19:05.000Z
lib/mix/task/radiator.adduser.ex
bhtabor/radiator
39c137a18d36d6f418f9d1ffb7aa2c99011d66cf
[ "MIT" ]
10
2019-04-18T12:47:27.000Z
2022-01-25T20:49:15.000Z
defmodule Mix.Tasks.Radiator.AddUser do use Mix.Task @shortdoc "Add a user." @moduledoc """ Add a user. Use `-a` to pre-confirm the email address. mix radiator.adduser username email password ## Options * `-a/--activate` - activates the newly created user so no more email verification is necessary. * `-d/--debug` - output more information for debugging. """ @switches [debug: :boolean, activate: :boolean] @aliases [d: :debug, a: :activate] alias Radiator.Auth defmacrop with_services(_opts \\ [], do: block) do quote do start_services() unquote(block) stop_services() end end @impl true @doc false def run(argv) do case parse_opts(argv) do {opts, [name, email, password]} -> opts = Map.new(opts) unless opts[:debug], do: Logger.configure(level: :info) with_services do case Auth.Register.create_user(%{ name: name, email: email, password: password }) do {:ok, user} -> Mix.Shell.IO.info([ "Created user ", :bright, "#{name} <#{email}>", :reset, " with id ", :bright, "#{user.id}" ]) if opts[:activate] do case Auth.Register.activate_user(user) do {:ok, user} -> Mix.Shell.IO.info(["Activated user ", :bright, "#{user.name} <#{user.email}>"]) _ -> Mix.Shell.IO.error(["error: ", :reset, "could not activate user"]) end end {:error, changeset} -> Mix.Shell.IO.error(["error: ", :reset, "Failed to create #{name} <#{email}>"]) changeset.errors |> Enum.each(fn {key, {msg, opts}} -> Mix.Shell.IO.error([ :cyan, " ", "#{key}", :reset, " ", Enum.reduce(opts, msg, fn {key, value}, acc -> String.replace(acc, "%{#{key}}", to_string(value)) end), " ", :light_black, "(", inspect(opts), ")" ]) end) end end _ -> Mix.Tasks.Help.run(["radiator.add_user"]) end end defp parse_opts(argv) do case OptionParser.parse(argv, strict: @switches, aliases: @aliases) do {opts, argv, []} -> {opts, argv} {_opts, _argv, [switch | _]} -> Mix.raise("Invalid option: " <> switch_to_string(switch)) end end defp switch_to_string({name, nil}), do: name defp switch_to_string({name, val}), do: name <> "=" <> val @start_apps [:metalove, :postgrex, :ecto, :ecto_sql] @repos Application.get_env(:radiator, :ecto_repos, []) defp start_services do Enum.each(@start_apps, &Application.ensure_all_started/1) Enum.each(@repos, & &1.start_link(pool_size: 2)) end defp stop_services do :init.stop() end end
26.520661
100
0.486133
ff4c76baf2f9ef6b1b86a118843cb8ade2fa4c40
1,899
ex
Elixir
clients/content/lib/google_api/content/v21/model/localinventory_custom_batch_response.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v21/model/localinventory_custom_batch_response.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/content/lib/google_api/content/v21/model/localinventory_custom_batch_response.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "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.Content.V21.Model.LocalinventoryCustomBatchResponse do @moduledoc """ ## Attributes * `entries` (*type:* `list(GoogleApi.Content.V21.Model.LocalinventoryCustomBatchResponseEntry.t)`, *default:* `nil`) - The result of the execution of the batch requests. * `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "content#localinventoryCustomBatchResponse". """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :entries => list(GoogleApi.Content.V21.Model.LocalinventoryCustomBatchResponseEntry.t()), :kind => String.t() } field(:entries, as: GoogleApi.Content.V21.Model.LocalinventoryCustomBatchResponseEntry, type: :list ) field(:kind) end defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.LocalinventoryCustomBatchResponse do def decode(value, options) do GoogleApi.Content.V21.Model.LocalinventoryCustomBatchResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.LocalinventoryCustomBatchResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.527273
173
0.743023
ff4c8508af0dbaabb3553b19b81a5567803f9b98
1,178
exs
Elixir
clients/games_configuration/mix.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/games_configuration/mix.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/games_configuration/mix.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
defmodule GoogleApi.GamesConfiguration.V1configuration.Mixfile do use Mix.Project @version "0.2.0" def project do [app: :google_api_games_configuration, version: @version, elixir: "~> 1.4", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/FIXME" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.1"}, {:ex_doc, "~> 0.16", only: :dev}, {:dialyxir, "~> 0.5", only: [:dev], runtime: false} ] end defp description() do """ The Publishing API for Google Play Game Services. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/FIXME", "Homepage" => "https://developers.google.com/games/services" } ] end end
24.040816
105
0.601019
ff4c8c3873d2c5ba6feabb16f2257eb0a69f494b
1,583
exs
Elixir
simple-linked-list/linked_list.exs
ChrisWilding/exercism-elixir
ee966439b460f82ef9581611f71c2f626402d14a
[ "MIT" ]
null
null
null
simple-linked-list/linked_list.exs
ChrisWilding/exercism-elixir
ee966439b460f82ef9581611f71c2f626402d14a
[ "MIT" ]
null
null
null
simple-linked-list/linked_list.exs
ChrisWilding/exercism-elixir
ee966439b460f82ef9581611f71c2f626402d14a
[ "MIT" ]
null
null
null
defmodule LinkedList do @opaque t :: tuple() @doc """ Construct a new LinkedList """ @spec new() :: t def new() do [] end @doc """ Push an item onto a LinkedList """ @spec push(t, any()) :: t def push(list, elem) do [elem | list] end @doc """ Calculate the length of a LinkedList """ @spec length(t) :: non_neg_integer() def length(list) do Kernel.length(list) end @doc """ Determine if a LinkedList is empty """ @spec empty?(t) :: boolean() def empty?([]), do: true def empty?(_), do: false @doc """ Get the value of a head of the LinkedList """ @spec peek(t) :: {:ok, any()} | {:error, :empty_list} def peek([]) do {:error, :empty_list} end def peek([head | _]) do {:ok, head} end @doc """ Get tail of a LinkedList """ @spec tail(t) :: {:ok, t} | {:error, :empty_list} def tail([]) do {:error, :empty_list} end def tail([_ | tail]) do {:ok, tail} end @doc """ Remove the head from a LinkedList """ @spec pop(t) :: {:ok, any(), t} | {:error, :empty_list} def pop([]) do {:error, :empty_list} end def pop([head | tail]) do {:ok, head, tail} end @doc """ Construct a LinkedList from a stdlib List """ @spec from_list(list()) :: t def from_list(list) do list end @doc """ Construct a stdlib List LinkedList from a LinkedList """ @spec to_list(t) :: list() def to_list(list) do list end @doc """ Reverse a LinkedList """ @spec reverse(t) :: t def reverse(list) do Enum.reverse(list) end end
16.663158
57
0.561592
ff4cef8788be11455a9816747beec1f57c89e74d
1,473
ex
Elixir
clients/drive_activity/lib/google_api/drive_activity/v2/model/data_leak_prevention_change.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/drive_activity/lib/google_api/drive_activity/v2/model/data_leak_prevention_change.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/drive_activity/lib/google_api/drive_activity/v2/model/data_leak_prevention_change.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.DriveActivity.V2.Model.DataLeakPreventionChange do @moduledoc """ A change in the object's data leak prevention status. ## Attributes * `type` (*type:* `String.t`, *default:* `nil`) - The type of Data Leak Prevention (DLP) change. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :type => String.t() } field(:type) end defimpl Poison.Decoder, for: GoogleApi.DriveActivity.V2.Model.DataLeakPreventionChange do def decode(value, options) do GoogleApi.DriveActivity.V2.Model.DataLeakPreventionChange.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DriveActivity.V2.Model.DataLeakPreventionChange do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.340426
100
0.742702
ff4cf08374029e672575213a9cd8af91258499bd
253
ex
Elixir
examples/phoenix_basic_example/lib/dripper_example/accounts/account_users.ex
Ninigi/ecto_dripper
ca472e90aafd3313b91a268f81e6aa936c59e021
[ "MIT" ]
1
2018-06-28T11:15:14.000Z
2018-06-28T11:15:14.000Z
examples/phoenix_basic_example/lib/dripper_example/accounts/account_users.ex
Ninigi/ecto_dripper
ca472e90aafd3313b91a268f81e6aa936c59e021
[ "MIT" ]
null
null
null
examples/phoenix_basic_example/lib/dripper_example/accounts/account_users.ex
Ninigi/ecto_dripper
ca472e90aafd3313b91a268f81e6aa936c59e021
[ "MIT" ]
null
null
null
defmodule DripperExample.AccountUsers do alias DripperExample.{ Repo, Accounts, UserQuery } def find_user(args) do Accounts.User |> UserQuery.query_username(args) |> UserQuery.query_email(args) |> Repo.one() end end
16.866667
40
0.675889
ff4cf88202b3ebe6470a8fed179508ca7ab44869
1,145
exs
Elixir
config/config.exs
CatCalZone/eurexa
d428d57ed66a7ec58e42eefefd85d1e61f33ea80
[ "Apache-2.0" ]
6
2015-11-29T22:59:30.000Z
2020-02-27T11:41:54.000Z
config/config.exs
CatCalZone/eurexa
d428d57ed66a7ec58e42eefefd85d1e61f33ea80
[ "Apache-2.0" ]
2
2016-01-21T12:28:57.000Z
2016-01-21T16:07:59.000Z
config/config.exs
CatCalZone/eurexa
d428d57ed66a7ec58e42eefefd85d1e61f33ea80
[ "Apache-2.0" ]
2
2016-01-20T20:21:55.000Z
2022-02-19T22:13:23.000Z
# 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 third- # party users, it should be done in your mix.exs file. # Sample configuration: # # config :logger, :console, # level: :info, # format: "$date $time [$level] $metadata$message\n", # metadata: [:user_id] config :eurexa, :eurexa, eureka_server: "127.0.0.1", eureka_port: 8761, eureka_prefix: "/", eureka_version: 2 # 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"
36.935484
73
0.737991
ff4d07ad4f000a09c48a15257c2060cb5396069a
179
exs
Elixir
priv/repo/migrations/20161026231540_create_user.exs
bschmeck/ex_gnarl
25d6961795f10a2d49efd1a29167a771ef9772f1
[ "MIT" ]
null
null
null
priv/repo/migrations/20161026231540_create_user.exs
bschmeck/ex_gnarl
25d6961795f10a2d49efd1a29167a771ef9772f1
[ "MIT" ]
1
2017-04-21T17:02:56.000Z
2017-04-21T17:02:56.000Z
priv/repo/migrations/20161026231540_create_user.exs
bschmeck/ex_gnarl
25d6961795f10a2d49efd1a29167a771ef9772f1
[ "MIT" ]
null
null
null
defmodule ExGnarl.Repo.Migrations.CreateUser do use Ecto.Migration def change do create table(:users) do add :email, :string timestamps() end end end
13.769231
47
0.670391
ff4d3934ac8af4065e64e55ad25ffd3e954c0e52
1,827
exs
Elixir
clients/genomics/mix.exs
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
clients/genomics/mix.exs
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
clients/genomics/mix.exs
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "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.Genomics.Mixfile do use Mix.Project @version "0.15.0" def project() do [ app: :google_api_genomics, 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/genomics" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Genomics API client library. Uploads, processes, queries, and searches Genomics data in the cloud. """ 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/genomics", "Homepage" => "https://cloud.google.com/genomics" } ] end end
27.268657
102
0.652983
ff4d4c4aa31c44130f7492ac216d7f69f028fca2
130
ex
Elixir
lib/produto.ex
rodrigocaldeira/estoque_de_casa_bot
30a561630ac1cedf42bb37969ac833e9a6507c25
[ "MIT" ]
null
null
null
lib/produto.ex
rodrigocaldeira/estoque_de_casa_bot
30a561630ac1cedf42bb37969ac833e9a6507c25
[ "MIT" ]
null
null
null
lib/produto.ex
rodrigocaldeira/estoque_de_casa_bot
30a561630ac1cedf42bb37969ac833e9a6507c25
[ "MIT" ]
null
null
null
defmodule EstoqueDeCasaBot.Produto do defstruct nome: "", quantidade_atual: 0, quantidade_minima: 0 end
21.666667
37
0.653846
ff4d538a73e29ddd2539262ac6d7e4057183ef79
997
ex
Elixir
lib/ticketo_web/plugs/refresh_token.ex
alejandronanez/phoenix-absinthe-auth-template
e4e72f52247cb4c880ddc058beaa7b5eecb68980
[ "MIT" ]
8
2020-06-25T03:15:06.000Z
2021-12-10T10:52:26.000Z
lib/ticketo_web/plugs/refresh_token.ex
alejandronanez/phoenix-absinthe-auth-template
e4e72f52247cb4c880ddc058beaa7b5eecb68980
[ "MIT" ]
null
null
null
lib/ticketo_web/plugs/refresh_token.ex
alejandronanez/phoenix-absinthe-auth-template
e4e72f52247cb4c880ddc058beaa7b5eecb68980
[ "MIT" ]
null
null
null
defmodule TicketoWeb.Plugs.RefreshToken do @moduledoc """ Idenfity if the request is a `tokenRefresh` mutation and let it continue. Getting all the data from the token should happen at the resolver/context level not in the plug as this will log the user back in and we don't want that. """ @behaviour Plug alias Plug.Conn def init(opts) do opts end def call(%{body_params: _body_params = %{"query" => query}} = conn, _options) do # Refresh token - put the authorization in the cookie in the Absinthe execution context case query =~ "tokenRefresh" do true -> with refresh_token <- get_auth_token_from_cookie(conn) do Absinthe.Plug.put_options(conn, context: %{auth_token: refresh_token}) end false -> conn end end def call(conn, _options) do conn end defp get_auth_token_from_cookie(conn) do conn |> Conn.fetch_cookies() |> Map.get(:req_cookies) |> Map.get("auth_token") end end
24.925
91
0.675025
ff4d9a449054e91bd9a8ae7a9d92848f16d09083
2,539
exs
Elixir
spec/protocol/publish_spec.exs
rdalin82/pixie
add50e2bd7fbd807c7b82cd10a2123828be4c58f
[ "MIT" ]
null
null
null
spec/protocol/publish_spec.exs
rdalin82/pixie
add50e2bd7fbd807c7b82cd10a2123828be4c58f
[ "MIT" ]
null
null
null
spec/protocol/publish_spec.exs
rdalin82/pixie
add50e2bd7fbd807c7b82cd10a2123828be4c58f
[ "MIT" ]
null
null
null
defmodule PixiePublishSpec do use ESpec describe "handle" do let :client_id do {id, _} = Pixie.Backend.create_client id end let :event do m = Pixie.Message.Publish.init message r = Pixie.Response.init m %Pixie.Event{message: m, response: r} end let :handled, do: Pixie.Publish.handle event let :response do %{response: response} = handled response end let :client do %{client: client} = handled client end let :valid_message, do: %{channel: "/foo", client_id: client_id, data: %{message: "I like turtles!"}} before do old_config = Pixie.backend_options Application.put_env :pixie, :backend, [name: :ETS] {:ok, pid} = Pixie.Backend.start_link :ETS, [] {:ok, pid: pid, old_config: old_config} end finally do Application.put_env :pixie, :backend, shared.old_config Process.exit(shared.pid, :normal) end describe "When sent a messages with no channel" do let :message, do: %{valid_message | channel: nil} it "sets a parameter missing response" do expect(response.error).to start_with("402:channel:") end end describe "When sent a message with no data" do let :message, do: %{valid_message | data: nil} it "sets a parameter missing response" do expect(response.error).to start_with("402:data:") end end describe "When sent a message with no client_id" do let :client_id, do: nil let :message, do: valid_message it "sets a parameter missing response" do expect(response.error).to start_with("402:clientId:") end end describe "When sent message with a valid clientId" do let :message, do: valid_message it "copies the clientId to the event" do expect(handled.client_id).to eq(message.client_id) end end describe "When sent message with an invalid clientId" do let :client_id, do: "abcd1234" let :message, do: valid_message it "sets a client unknown response" do expect(response.error).to start_with("401:abcd1234:") end end describe "When sent a valid message" do let :message, do: valid_message it "pipes it through the extensions" do allow(Pixie.ExtensionRegistry).to accept(:incoming, fn(%{message: m}=e)-> %{e | message: %{m | data: %{message: "Turtles suck"}}} end) expect(handled.message.data.message).to eq("Turtles suck") end end end end
27.010638
142
0.635289
ff4d9c7410646eac6e04846f38ee46a871323116
114
exs
Elixir
basic/run_element_demo.exs
varnit/membrane-demo
c22aefddca7719f5dc9041d2e016aec560a6ceae
[ "Apache-2.0" ]
null
null
null
basic/run_element_demo.exs
varnit/membrane-demo
c22aefddca7719f5dc9041d2e016aec560a6ceae
[ "Apache-2.0" ]
null
null
null
basic/run_element_demo.exs
varnit/membrane-demo
c22aefddca7719f5dc9041d2e016aec560a6ceae
[ "Apache-2.0" ]
null
null
null
alias Membrane.Demo.Basic.FirstElement.Pipeline {:ok, pid} = Pipeline.start_link("sample.mp3") Pipeline.play(pid)
28.5
47
0.780702
ff4da0ec4821f32f87f9de9941adeff15ccc2f53
3,643
exs
Elixir
test/ex_doc/cli_test.exs
bortzmeyer/ex_doc
dd10dd43c0ac135ef1d9c029e75a5da251f550af
[ "Apache-2.0", "CC-BY-4.0" ]
1,206
2015-01-02T02:05:12.000Z
2022-03-29T17:18:10.000Z
test/ex_doc/cli_test.exs
bortzmeyer/ex_doc
dd10dd43c0ac135ef1d9c029e75a5da251f550af
[ "Apache-2.0", "CC-BY-4.0" ]
1,266
2015-01-03T03:26:04.000Z
2022-03-31T09:43:53.000Z
test/ex_doc/cli_test.exs
LaudateCorpus1/ex_doc
0612bac649cbb44ef09c20dedcf7e588a150606c
[ "Apache-2.0", "CC-BY-4.0" ]
300
2015-01-03T04:07:24.000Z
2022-03-29T08:10:56.000Z
defmodule ExDoc.CLITest do use ExUnit.Case, async: true import ExUnit.CaptureIO @ebin "_build/test/lib/ex_doc/ebin" defp run(args) do ExDoc.CLI.main(args, &{&1, &2, &3}) end test "minimum command-line options" do assert {"ExDoc", "1.2.3", [apps: [:ex_doc], source_beam: @ebin]} == run(["ExDoc", "1.2.3", @ebin]) end test "version" do assert capture_io(fn -> run(["--version"]) end) == "ExDoc v#{ExDoc.version()}\n" assert capture_io(fn -> run(["-v"]) end) == "ExDoc v#{ExDoc.version()}\n" end test "too many arguments" do fun = fn -> run(["ExDoc", "1.2.3", "/", "kaboom"]) end assert catch_exit(capture_io(fun)) == {:shutdown, 1} end test "too few arguments" do fun = fn -> run(["ExDoc"]) end assert catch_exit(capture_io(fun)) == {:shutdown, 1} end test "arguments that are not aliased" do File.write!("not_aliased.exs", ~s([key: "val"])) args = ~w( ExDoc 1.2.3 #{@ebin} --config not_aliased.exs --output html --formatter html --source-url http://example.com/username/project --source-ref abcdefg --main Main --homepage-url http://example.com --logo logo.png --canonical http://example.com/project ) {project, version, opts} = run(args) assert project == "ExDoc" assert version == "1.2.3" assert Enum.sort(opts) == [ apps: [:ex_doc], canonical: "http://example.com/project", formatter: "html", homepage_url: "http://example.com", key: "val", logo: "logo.png", main: "Main", output: "html", source_beam: "#{@ebin}", source_ref: "abcdefg", source_url: "http://example.com/username/project" ] after File.rm!("not_aliased.exs") end describe "--config .exs" do test "loading" do File.write!("test.exs", ~s([extras: ["README.md"]])) {project, version, opts} = run(["ExDoc", "--extra-section", "Guides", "1.2.3", @ebin, "-c", "test.exs"]) assert project == "ExDoc" assert version == "1.2.3" assert Enum.sort(opts) == [ apps: [:ex_doc], extra_section: "Guides", extras: ["README.md"], source_beam: @ebin ] after File.rm!("test.exs") end test "missing" do assert_raise File.Error, fn -> run(["ExDoc", "1.2.3", @ebin, "-c", "test.exs"]) end end test "invalid" do File.write!("test.exs", ~s(%{"extras" => "README.md"})) assert_raise RuntimeError, ~S(expected a keyword list from config file: "test.exs"), fn -> run(["ExDoc", "1.2.3", @ebin, "-c", "test.exs"]) end after File.rm!("test.exs") end end describe "--config .config" do test "loading" do File.write!("test.config", ~s({extras, [<<"README.md">>]}.)) {project, version, opts} = run(["ExDoc", "1.2.3", @ebin, "-c", "test.config"]) assert project == "ExDoc" assert version == "1.2.3" assert Enum.sort(opts) == [ apps: [:ex_doc], extras: ["README.md"], source_beam: @ebin ] after File.rm!("test.config") end test "invalid" do File.write!("test.config", "bad") assert_raise RuntimeError, ~r/error parsing test.config/, fn -> run(["ExDoc", "1.2.3", @ebin, "-c", "test.config"]) end after File.rm!("test.config") end end end
25.124138
96
0.516882
ff4db64fed2f2aa4f6c0c0eda52c9b13d61e7839
1,088
exs
Elixir
mix.exs
TwistingTwists/logger_exporter
21639b1cf3cf1f7867e241d9a2ec920531b8b693
[ "MIT" ]
null
null
null
mix.exs
TwistingTwists/logger_exporter
21639b1cf3cf1f7867e241d9a2ec920531b8b693
[ "MIT" ]
null
null
null
mix.exs
TwistingTwists/logger_exporter
21639b1cf3cf1f7867e241d9a2ec920531b8b693
[ "MIT" ]
null
null
null
defmodule LoggerExporter.MixProject do use Mix.Project @source_url "https://github.com/romariolopezc/logger_exporter" @version "0.1.1" def project do [ app: :logger_exporter, version: @version, elixir: "~> 1.9", deps: deps(), description: "Export your logs to the service of your choice.", name: "LoggerExporter", source_url: @source_url, package: package(), docs: docs() ] end def application do [] end defp deps do [ {:jason, "~> 1.2"}, {:finch, "~> 0.8"}, {:telemetry, "~> 0.4.2 or ~> 1.0"}, {:credo, "~> 1.6", only: [:dev, :test], runtime: false}, {:ex_doc, "~> 0.27", only: :dev, runtime: false} ] end defp package do [ files: ["lib", "mix.exs", "README*", "LICENSE*"], mantainers: ["Romario López"], licenses: ["MIT"], links: %{"GitHub" => @source_url} ] end defp docs do [ main: "LoggerExporter", api_referencee: false, source_ref: "#{@version}", source_url: @source_url ] end end
20.528302
69
0.54136
ff4dbb0042ad915063b7650679ef2577fd86ae7d
606
exs
Elixir
mix.exs
Redeux/identicon
c81c9ca3de5a0a6c3699e0671a1697b034b01a0d
[ "MIT" ]
4
2017-12-04T11:00:46.000Z
2017-12-04T11:13:31.000Z
mix.exs
Redeux/identicon
c81c9ca3de5a0a6c3699e0671a1697b034b01a0d
[ "MIT" ]
null
null
null
mix.exs
Redeux/identicon
c81c9ca3de5a0a6c3699e0671a1697b034b01a0d
[ "MIT" ]
null
null
null
defmodule Identicon.Mixfile do use Mix.Project def project do [ app: :identicon, version: "0.1.0", elixir: "~> 1.5", start_permanent: Mix.env == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}, {:egd, github: "erlang/egd"} ] end end
20.2
88
0.574257
ff4e0e842bb3d6e59fba3b99d0506f927a922ff5
1,149
ex
Elixir
test/support/channel_case.ex
vsyrovat/inn-checker
03cb3f282af598c7d62ea96c483540edead4ba1e
[ "MIT" ]
null
null
null
test/support/channel_case.ex
vsyrovat/inn-checker
03cb3f282af598c7d62ea96c483540edead4ba1e
[ "MIT" ]
null
null
null
test/support/channel_case.ex
vsyrovat/inn-checker
03cb3f282af598c7d62ea96c483540edead4ba1e
[ "MIT" ]
null
null
null
defmodule AppWeb.ChannelCase do # credo:disable-for-this-file Credo.Check.Design.AliasUsage @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use AppWeb.ChannelCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with channels import Phoenix.ChannelTest import AppWeb.ChannelCase # The default endpoint for testing @endpoint AppWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(App.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(App.Repo, {:shared, self()}) end :ok end end
27.357143
65
0.724978
ff4e15e8511e6ae069bf4a814d31dfa9e5bc63dc
633
exs
Elixir
test/grpc/server_test.exs
scohen/grpc-elixir
c0eaa61d789f5c5b9e3c2f4c213944bebaf2c72c
[ "Apache-2.0" ]
null
null
null
test/grpc/server_test.exs
scohen/grpc-elixir
c0eaa61d789f5c5b9e3c2f4c213944bebaf2c72c
[ "Apache-2.0" ]
null
null
null
test/grpc/server_test.exs
scohen/grpc-elixir
c0eaa61d789f5c5b9e3c2f4c213944bebaf2c72c
[ "Apache-2.0" ]
null
null
null
defmodule GRPC.ServerTest do use ExUnit.Case, async: true defmodule Greeter.Service do use GRPC.Service, name: "hello" end defmodule Greeter.Server do use GRPC.Server, service: Greeter.Service end test "stop/2 works" do assert {%{"hello" => GRPC.ServerTest.Greeter.Server}} = GRPC.Server.stop(Greeter.Server, adapter: GRPC.Test.ServerAdapter) end test "stream_send/2 works" do stream = %GRPC.Server.Stream{adapter: GRPC.Test.ServerAdapter, marshal: & &1} response = <<1, 2, 3, 4, 5, 6, 7, 8>> assert %GRPC.Server.Stream{} = GRPC.Server.stream_send(stream, response) end end
27.521739
81
0.680885
ff4e3b290a5a9977820683adb1145f81b5229179
1,998
exs
Elixir
test/grizzly/command_class/thermostat_setback/set_test.exs
pragdave/grizzly
bcd7b46ab2cff1797dac04bc3cd12a36209dd579
[ "Apache-2.0" ]
null
null
null
test/grizzly/command_class/thermostat_setback/set_test.exs
pragdave/grizzly
bcd7b46ab2cff1797dac04bc3cd12a36209dd579
[ "Apache-2.0" ]
null
null
null
test/grizzly/command_class/thermostat_setback/set_test.exs
pragdave/grizzly
bcd7b46ab2cff1797dac04bc3cd12a36209dd579
[ "Apache-2.0" ]
null
null
null
defmodule Grizzly.CommandClass.ThermostatSetback.Set.Test do use ExUnit.Case, async: true alias Grizzly.Packet alias Grizzly.CommandClass.ThermostatSetback.Set alias Grizzly.Command.EncodeError describe "implements the Grizzly command behaviour" do test "initializes the command state" do {:ok, command} = Set.init(type: :temporary_override, state: -128) assert %Set{type: :temporary_override, state: -128} == command end test "encodes correctly" do {:ok, command} = Set.init(type: :temporary_override, state: -128, seq_number: 0x06) binary = <<35, 2, 128, 208, 6, 0, 0, 3, 2, 0, 0x47, 0x01, 0x00::size(6), 0x01::size(2), 0x80>> assert {:ok, binary} == Set.encode(command) end test "encodes incorrectly" do {:ok, command} = Set.init(type: :blue, state: -128, seq_number: 0x06) error = EncodeError.new({:invalid_argument_value, :type, :blue, Set}) assert {:error, error} == Set.encode(command) end test "handles an ack response" do {:ok, command} = Set.init(type: :no_overriding, state: 0, seq_number: 0x01) packet = Packet.new(seq_number: 0x01, types: [:ack_response]) assert {:done, :ok} == Set.handle_response(command, packet) end test "handles a nack response" do {:ok, command} = Set.init(type: :no_overriding, state: 0, seq_number: 0x01, retries: 0) packet = Packet.new(seq_number: 0x01, types: [:nack_response]) assert {:done, {:error, :nack_response}} == Set.handle_response(command, packet) end test "handles retries" do {:ok, command} = Set.init(type: :no_overriding, state: 0, seq_number: 0x01) packet = Packet.new(seq_number: 0x01, types: [:nack_response]) assert {:retry, %Set{}} = Set.handle_response(command, packet) end test "handles responses" do {:ok, command} = Set.init(type: :no_overriding, state: 0) assert {:continue, _} = Set.handle_response(command, %{}) end end end
33.3
93
0.655155
ff4e4f22a52140441681f41da41897dc99cf280c
965
ex
Elixir
test/support/channel_case.ex
zegohome/phoenix-boilerplate
38d7a978dd1ace4885217dba601a7369d50a72e0
[ "Apache-2.0" ]
null
null
null
test/support/channel_case.ex
zegohome/phoenix-boilerplate
38d7a978dd1ace4885217dba601a7369d50a72e0
[ "Apache-2.0" ]
null
null
null
test/support/channel_case.ex
zegohome/phoenix-boilerplate
38d7a978dd1ace4885217dba601a7369d50a72e0
[ "Apache-2.0" ]
null
null
null
defmodule PhxBoilerplateWeb.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` 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 channels use Phoenix.ChannelTest # The default endpoint for testing @endpoint PhxBoilerplateWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(PhxBoilerplate.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(PhxBoilerplate.Repo, {:shared, self()}) end :ok end end
25.394737
76
0.724352
ff4e5f516c7cb90b40c7e7fcd63204d78a61465d
1,856
exs
Elixir
apps/ewallet_db/priv/repo/migrations/20180424131331_add_symbol_to_minted_token_id.exs
jimpeebles/ewallet
ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405
[ "Apache-2.0" ]
null
null
null
apps/ewallet_db/priv/repo/migrations/20180424131331_add_symbol_to_minted_token_id.exs
jimpeebles/ewallet
ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405
[ "Apache-2.0" ]
null
null
null
apps/ewallet_db/priv/repo/migrations/20180424131331_add_symbol_to_minted_token_id.exs
jimpeebles/ewallet
ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 OmiseGO Pte Ltd # # 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. defmodule EWalletDB.Repo.Migrations.AddSymbolToMintedTokenId do use Ecto.Migration import Ecto.Query alias EWalletDB.Repo @table_name "minted_token" def up do for [uuid, id, symbol] <- get_all(@table_name) do id |> add_symbol(symbol) |> update_id(@table_name, uuid) end end def down do for [uuid, id, _symbol] <- get_all(@table_name) do id |> remove_symbol() |> update_id(@table_name, uuid) end end defp get_all(table_name) do query = from(t in table_name, select: [t.uuid, t.id, t.symbol], lock: "FOR UPDATE") Repo.all(query) end defp add_symbol(id, symbol) do # Add the symbol only if the pattern is strictly: # `<non_underscores>_<non_underscores>` String.replace(id, ~r/^([^_]+)_([^_]+)$/, "\\1_#{symbol}_\\2") end defp remove_symbol(id) do # Remove the symbol only if the pattern is strictly # `<non_underscores>_<non_underscores>_<non_underscores>` String.replace(id, ~r/^([^_]+)_([^_]+)_([^_]+)$/, "\\1_\\3") end defp update_id(id, table_name, uuid) do query = from(t in table_name, where: t.uuid == ^uuid, update: [set: [id: ^id]]) Repo.update_all(query, []) end end
28.121212
74
0.650323
ff4e72caa577269c52e90b04653b565153ea5884
1,788
exs
Elixir
test/ex_appointment_web/controllers/user_registration_controller_test.exs
amalgamated-tools/ex_appointment
095237f0bd6746afd8ec93d92540158aa1934075
[ "MIT" ]
1
2021-03-28T17:41:37.000Z
2021-03-28T17:41:37.000Z
test/ex_appointment_web/controllers/user_registration_controller_test.exs
amalgamated-tools/ex_appointment
095237f0bd6746afd8ec93d92540158aa1934075
[ "MIT" ]
null
null
null
test/ex_appointment_web/controllers/user_registration_controller_test.exs
amalgamated-tools/ex_appointment
095237f0bd6746afd8ec93d92540158aa1934075
[ "MIT" ]
null
null
null
defmodule ExAppointmentWeb.UserRegistrationControllerTest do use ExAppointmentWeb.ConnCase, async: true import ExAppointment.AccountsFixtures describe "GET /users/register" do test "renders registration page", %{conn: conn} do conn = get(conn, Routes.user_registration_path(conn, :new)) response = html_response(conn, 200) assert response =~ "<h1>Register</h1>" assert response =~ "Log in</a>" assert response =~ "Register</a>" end test "redirects if already logged in", %{conn: conn} do conn = conn |> log_in_user(user_fixture()) |> get(Routes.user_registration_path(conn, :new)) assert redirected_to(conn) == "/" end end describe "POST /users/register" do @tag :capture_log test "creates account and logs the user in", %{conn: conn} do email = unique_user_email() conn = post(conn, Routes.user_registration_path(conn, :create), %{ "user" => valid_user_attributes(email: email) }) assert get_session(conn, :user_token) assert redirected_to(conn) =~ "/" # Now do a logged in request and assert on the menu conn = get(conn, "/") response = html_response(conn, 200) assert response =~ email assert response =~ "Settings</a>" assert response =~ "Log out</a>" end test "render errors for invalid data", %{conn: conn} do conn = post(conn, Routes.user_registration_path(conn, :create), %{ "user" => %{"email" => "with spaces", "password" => "too short"} }) response = html_response(conn, 200) assert response =~ "<h1>Register</h1>" assert response =~ "must have the @ sign and no spaces" assert response =~ "should be at least 12 character" end end end
32.509091
98
0.633669
ff4e917a9f111b0b4169fb5cb6fcca412ff9ea0b
1,765
ex
Elixir
clients/classroom/lib/google_api/classroom/v1/model/shared_drive_file.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/classroom/lib/google_api/classroom/v1/model/shared_drive_file.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/classroom/lib/google_api/classroom/v1/model/shared_drive_file.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "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.Classroom.V1.Model.SharedDriveFile do @moduledoc """ Drive file that is used as material for course work. ## Attributes - driveFile (DriveFile): Drive file details. Defaults to: `null`. - shareMode (String.t): Mechanism by which students access the Drive item. Defaults to: `null`. - Enum - one of [UNKNOWN_SHARE_MODE, VIEW, EDIT, STUDENT_COPY] """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :driveFile => GoogleApi.Classroom.V1.Model.DriveFile.t(), :shareMode => any() } field(:driveFile, as: GoogleApi.Classroom.V1.Model.DriveFile) field(:shareMode) end defimpl Poison.Decoder, for: GoogleApi.Classroom.V1.Model.SharedDriveFile do def decode(value, options) do GoogleApi.Classroom.V1.Model.SharedDriveFile.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Classroom.V1.Model.SharedDriveFile do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.942308
97
0.739943
ff4e9889e8b4dbf3b221a46cccee9dfd9d498dec
5,233
ex
Elixir
clients/content/lib/google_api/content/v2/model/inventory_set_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/inventory_set_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/inventory_set_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.Content.V2.Model.InventorySetRequest do @moduledoc """ ## Attributes * `availability` (*type:* `String.t`, *default:* `nil`) - The availability of the product. Acceptable values are: - "`in stock`" - "`out of stock`" - "`preorder`" * `customLabel0` (*type:* `String.t`, *default:* `nil`) - Custom label 0 for custom grouping of items in a Shopping campaign. Only supported for online products. * `customLabel1` (*type:* `String.t`, *default:* `nil`) - Custom label 1 for custom grouping of items in a Shopping campaign. Only supported for online products. * `customLabel2` (*type:* `String.t`, *default:* `nil`) - Custom label 2 for custom grouping of items in a Shopping campaign. Only supported for online products. * `customLabel3` (*type:* `String.t`, *default:* `nil`) - Custom label 3 for custom grouping of items in a Shopping campaign. Only supported for online products. * `customLabel4` (*type:* `String.t`, *default:* `nil`) - Custom label 3 for custom grouping of items in a Shopping campaign. Only supported for online products. * `installment` (*type:* `GoogleApi.Content.V2.Model.Installment.t`, *default:* `nil`) - Number and amount of installments to pay for an item. Brazil only. * `instoreProductLocation` (*type:* `String.t`, *default:* `nil`) - The instore product location. Supported only for local products. * `loyaltyPoints` (*type:* `GoogleApi.Content.V2.Model.LoyaltyPoints.t`, *default:* `nil`) - Loyalty points that users receive after purchasing the item. Japan only. * `pickup` (*type:* `GoogleApi.Content.V2.Model.InventoryPickup.t`, *default:* `nil`) - Store pickup information. Only supported for local inventory. Not setting `pickup` means "don't update" while setting it to the empty value (`{}` in JSON) means "delete". Otherwise, `pickupMethod` and `pickupSla` must be set together, unless `pickupMethod` is "not supported". * `price` (*type:* `GoogleApi.Content.V2.Model.Price.t`, *default:* `nil`) - The price of the product. * `quantity` (*type:* `integer()`, *default:* `nil`) - The quantity of the product. Must be equal to or greater than zero. Supported only for local products. * `salePrice` (*type:* `GoogleApi.Content.V2.Model.Price.t`, *default:* `nil`) - The sale price of the product. Mandatory if `sale_price_effective_date` is defined. * `salePriceEffectiveDate` (*type:* `String.t`, *default:* `nil`) - A date range represented by a pair of ISO 8601 dates separated by a space, comma, or slash. Both dates might be specified as 'null' if undecided. * `sellOnGoogleQuantity` (*type:* `integer()`, *default:* `nil`) - The quantity of the product that is available for selling on Google. Supported only for online products. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :availability => String.t(), :customLabel0 => String.t(), :customLabel1 => String.t(), :customLabel2 => String.t(), :customLabel3 => String.t(), :customLabel4 => String.t(), :installment => GoogleApi.Content.V2.Model.Installment.t(), :instoreProductLocation => String.t(), :loyaltyPoints => GoogleApi.Content.V2.Model.LoyaltyPoints.t(), :pickup => GoogleApi.Content.V2.Model.InventoryPickup.t(), :price => GoogleApi.Content.V2.Model.Price.t(), :quantity => integer(), :salePrice => GoogleApi.Content.V2.Model.Price.t(), :salePriceEffectiveDate => String.t(), :sellOnGoogleQuantity => integer() } field(:availability) field(:customLabel0) field(:customLabel1) field(:customLabel2) field(:customLabel3) field(:customLabel4) field(:installment, as: GoogleApi.Content.V2.Model.Installment) field(:instoreProductLocation) field(:loyaltyPoints, as: GoogleApi.Content.V2.Model.LoyaltyPoints) field(:pickup, as: GoogleApi.Content.V2.Model.InventoryPickup) field(:price, as: GoogleApi.Content.V2.Model.Price) field(:quantity) field(:salePrice, as: GoogleApi.Content.V2.Model.Price) field(:salePriceEffectiveDate) field(:sellOnGoogleQuantity) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.InventorySetRequest do def decode(value, options) do GoogleApi.Content.V2.Model.InventorySetRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.InventorySetRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
55.670213
368
0.70151
ff4ea49d8d77fc00d908bbd275b51837ca576aa1
1,721
ex
Elixir
lib/poe_api/token/authorization_code.ex
simplecastapps/poe-api
56e9b6ebfcd931c4023e555534a753f5ad32cf9c
[ "MIT" ]
4
2016-01-14T05:33:21.000Z
2017-02-01T14:10:57.000Z
lib/poe_api/token/authorization_code.ex
poegroup/poe-api
d056412c336e30747f811fb5124e14ecb1b43b98
[ "MIT" ]
null
null
null
lib/poe_api/token/authorization_code.ex
poegroup/poe-api
d056412c336e30747f811fb5124e14ecb1b43b98
[ "MIT" ]
3
2017-01-09T14:34:54.000Z
2020-12-17T07:14:33.000Z
defmodule PoeApi.Token.AuthorizationCode do alias PoeApi.Token.{Config,RelativeExpiration,Utils} @salt_length 6 defstruct [client: nil, scopes: [], user: nil, expiration: %RelativeExpiration{hours: 1}, redirect_uri: nil] def encode(%__MODULE__{client: client, user: user, redirect_uri: redirect_uri, scopes: enabled_scopes, expiration: expiration}) do [{sender, epoch} | _] = Config.senders() expiration = expiration || %RelativeExpiration{hours: 1} salt = :crypto.strong_rand_bytes(@salt_length) params = %{ "c" => client, "s" => Utils.pack_scopes(enabled_scopes), "u" => user, "e" => Utils.pack_date(expiration, epoch), "r" => hash_redirect_uri(redirect_uri, salt) } code = SimpleSecrets.pack!(params, sender) {:ok, "c" <> code, DateTime.to_unix(Utils.unpack_date(params["e"], 0))} end def decode("c" <> token) do Config.senders() |> Enum.find_value({:error, :invalid}, fn({sender, epoch}) -> case SimpleSecrets.unpack(token, sender) do {:error, _} -> false {:ok, %{"c" => client, "s" => scopes, "e" => expiration, "u" => user, "r" => redirect_uri}} -> {:ok, %__MODULE__{ client: client, scopes: Utils.unpack_scopes(scopes), user: user, redirect_uri: redirect_uri, expiration: Utils.unpack_date(expiration, epoch) }} end end) end def validate_redirect_uri(redirect_uri, <<salt :: size(@salt_length)-binary, _ :: binary>> = hash) do {:ok, hash_redirect_uri(redirect_uri, salt) == hash} end defp hash_redirect_uri(redirect_uri, salt) do salt <> :crypto.hash(:sha, [salt, 0, redirect_uri]) end end
35.122449
132
0.624637
ff4eae5c2285b9f3ac77e3431c107d23465cae3d
2,080
ex
Elixir
lib/mix/tasks/rustler_precompiled.download.ex
philss/baked_nifs
bd3086c84e59c5eb5c5d7cc5484bf6e069c63925
[ "Apache-2.0" ]
1
2022-02-05T21:20:07.000Z
2022-02-05T21:20:07.000Z
lib/mix/tasks/rustler_precompiled.download.ex
philss/baked_nifs
bd3086c84e59c5eb5c5d7cc5484bf6e069c63925
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/rustler_precompiled.download.ex
philss/baked_nifs
bd3086c84e59c5eb5c5d7cc5484bf6e069c63925
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.RustlerPrecompiled.Download do @shortdoc "Download precompiled NIFs and build the checksums" @moduledoc """ A task responsible for downloading the precompiled NIFs for a given module. This task must only be used by package creators who want to ship the precompiled NIFs. The goal is to download the precompiled packages and generate a checksum to check-in alongside the project in the the Hex repository. This is done by passing the `--all` flag. You can also use the `--only-local` flag to download only the precompiled package for use during development. You can use the `--ignore-unavailable` flag to ignore any NIFs that are not available. This is useful when you are developing a new NIF that does not support all platforms. This task also accept the `--print` flag to print the checksums. """ use Mix.Task @switches [ all: :boolean, only_local: :boolean, print: :boolean, ignore_unavailable: :boolean ] @impl true def run([module_name | flags]) do module = String.to_atom("Elixir.#{module_name}") {options, _args, _invalid} = OptionParser.parse(flags, strict: @switches) urls = cond do Keyword.get(options, :all) -> RustlerPrecompiled.available_nif_urls(module) Keyword.get(options, :only_local) -> [RustlerPrecompiled.current_target_nif_url(module)] true -> raise "you need to specify either \"--all\" or \"--only-local\" flags" end result = RustlerPrecompiled.download_nif_artifacts_with_checksums!(urls, options) if Keyword.get(options, :print) do result |> Enum.map(fn map -> {Path.basename(Map.fetch!(map, :path)), Map.fetch!(map, :checksum)} end) |> Enum.sort() |> Enum.map_join("\n", fn {file, checksum} -> "#{checksum} #{file}" end) |> IO.puts() end RustlerPrecompiled.write_checksum!(module, result) end @impl true def run([]) do raise "the module name and a flag is expected. Use \"--all\" or \"--only-local\" flags" end end
30.588235
91
0.675
ff4eb0763d0fe2b36749319275e487d5b1512d39
14,939
ex
Elixir
lib/moebius/query.ex
cpursley/moebius
5a6993dd06bfc05840bd1e1bdb60beeabec5ef81
[ "BSD-3-Clause" ]
null
null
null
lib/moebius/query.ex
cpursley/moebius
5a6993dd06bfc05840bd1e1bdb60beeabec5ef81
[ "BSD-3-Clause" ]
null
null
null
lib/moebius/query.ex
cpursley/moebius
5a6993dd06bfc05840bd1e1bdb60beeabec5ef81
[ "BSD-3-Clause" ]
null
null
null
defmodule Moebius.Query do import Inflex, only: [singularize: 1] alias Moebius.QueryCommand alias Moebius.CommandBatch use Moebius.QueryFilter @moduledoc """ The main query interface for Moebius. Import this module into your code and query like a champ """ @doc """ Specifies the table or view you want to query and returns a QueryCommand struct. "table" - the name of the table you want to query, such as `membership.users` :table - the name of the table you want to query, such as `:users` Example ``` result = db(:users) |> to_list result = db("membership.users") |> to_list ``` """ def db(table) when is_atom(table), do: db(Atom.to_string(table)) def db(table), do: %QueryCommand{table_name: table} @doc """ Executes a given pipeline and returns the last matching result. You should specify a `sort` to be sure first works as intended. cols - Any columns (specified as a string) that you want to have aliased or restricted in your return. For example `now() as current_time, name, description`. Defaults to "*" Example: ``` cheap_skate = db(:users) |> sort(:money_spent, :desc) |> last("first, last, email") ``` """ def last(%QueryCommand{} = cmd, sort_by) when is_atom(sort_by) do cmd |> sort(sort_by, :desc) |> select end @doc """ Sets the order by. Ascending using `:asc` is the default, you can send in `:desc` if you like. cols - The atomized name of the columns, such as `:company` direction - `:asc` (default) or `:desc` Example: ``` result = db(:users) |> sort(:name, :desc) |> to_list ``` """ #def sort(%QueryCommand{} = cmd, cols, direction \\ :asc) def sort(%QueryCommand{} = cmd, cols, direction) when is_atom(cols), do: sort(cmd, Atom.to_string(cols), direction) def sort(%QueryCommand{} = cmd, cols, direction) when is_binary(cols), do: %{cmd | order: " order by #{cols} #{direction}"} @doc """ Sets the limit of the return. bound - And integer limiter Example: ``` result = db(:users) |> limit(20) |> to_list ``` """ def limit(cmd, bound) when is_integer(bound), do: %{cmd | limit: " limit #{bound}"} @doc """ Offsets the limit and is an alias for `skip/1`" Example: ``` result = db(:users) |> limit(20) |> offset(2) |> to_list ``` """ def offset(cmd, n), do: %{cmd | offset: " offset #{n}"} @doc """ Offsets the limit and is an alias for `offset/1`" Example: ``` result = db(:users) |> limit(20) |> skip(2) |> to_list ``` """ def skip(%QueryCommand{} = cmd, n), do: offset(cmd, n) @doc """ Creates a SELECT command based on the assembled pipeline. Uses the QueryCommand as its core structure. cols - Any columns (specified as a string) that you want to have aliased or restricted in your return. For example `now() as current_time, name, description` Example: ``` command = db(:users) |> limit(20) |> offset(2) |> select("now() as current_time, name, description") #command is a QueryCommand object with all of the pipelined settings applied ``` """ def select(%QueryCommand{} = cmd, cols \\ "*") when is_bitstring(cols) do %{cmd | sql: "select #{cols} from #{cmd.table_name}#{cmd.join}#{cmd.where}#{cmd.order}#{cmd.limit}#{cmd.offset};"} end @doc """ Executes a COUNT query based on the assembled pipeline. Analagous to `map/reduce(:count)`. Returns an integer. Example: count = db(:users) |> limit(20) |> count |> single #count == 20 """ def count(%QueryCommand{} = cmd) do %{cmd | type: :count, sql: "select count(1) from #{cmd.table_name}#{cmd.join}#{cmd.where}#{cmd.order}#{cmd.limit}#{cmd.offset};"} end @doc """ Specifies a GROUP BY for a `map/reduce` (aggregate) query. cols - An atom indicating the column to GROUP BY. Will also be part of the SELECT list. Example: ``` result = db(:users) |> map("money_spent > 100") |> group(:company) |> reduce(:sum, :money_spent) ``` """ def group(%QueryCommand{} = cmd, cols) when is_atom(cols), do: group(cmd, Atom.to_string(cols)) @doc """ Specifies a GROUP BY for a `map/reduce` (aggregate) query that is a string. cols - A string specifying the column to GROUP BY. Will also be part of the SELECT list. Example: ``` result = db(:users) |> map("money_spent > 100") |> group("company, state") |> reduce(:sum, :money_spent) ``` """ def group(%QueryCommand{} = cmd, cols), do: %{cmd | group_by: cols} @doc """ An alias for `filter`, specifies a range to rollup on for an aggregate query using a WHERE statement. criteria - A string, atom or list (see `filter`) Example: ``` result = db(:users) |> map("money_spent > 100") |> reduce(:sum, :money_spent) ``` """ def map(%QueryCommand{} = cmd, criteria), do: filter(cmd, criteria) @doc """ A rollup operation that aggregates the mapped result set by the specified operation. op - An atom indicating what you want to have happen, such as `:sum`, `:avg`, `:min`, `:max`. Corresponds directly to a PostgreSQL rollup function. Example: ``` result = db(:users) |> map("money_spent > 100") |> reduce(:sum, :money_spent) ``` """ def reduce(%QueryCommand{} = cmd, op, column) when is_atom(column), do: reduce(cmd, op, Atom.to_string(column)) def reduce(%QueryCommand{} = cmd, op, column) when is_bitstring(column) do sql = cond do cmd.group_by -> "select #{op}(#{column}), #{cmd.group_by} from #{cmd.table_name}#{cmd.join}#{cmd.where} GROUP BY #{cmd.group_by}" true -> "select #{op}(#{column}) from #{cmd.table_name}#{cmd.join}#{cmd.where}" end %{cmd | sql: sql} end @doc """ Full text search using Postgres' built in indexing, ranked using `tsrank`. This query will result in a full table scan and is not optimized for large result sets. For better results, create a `tsvector` field and populate it with a trigger on insert/update. This will cause some side effects, one of them being that Postgrex, the Elixir driver we use, doesn't know how to resolve the tsvector type, and will throw. You will need to be sure that you exclude that search column from your query. for: - The string term you want to query against. in: - An atomized list of columns to search againts. Example: ``` result = db(:users) |> search(for: "Mike", in: [:first, :last, :email]) |> run ``` """ def search(%QueryCommand{} = cmd, for: term, in: columns) when is_list columns do concat_list = Enum.map_join(columns, ", ' ', ", &"#{&1}") sql = """ select *, ts_rank_cd(to_tsvector(concat(#{concat_list})),to_tsquery($1)) as rank from #{cmd.table_name} where to_tsvector(concat(#{concat_list})) @@ to_tsquery($1) order by rank desc """ %{cmd | sql: sql, params: [term]} end @doc """ Insert multiple rows at once, within a single transaction, returning the inserted records. Pass in a composite list, containing the rows to be inserted. Note, the columns to be inserted are defined based on the first record in the list. All records to be inserted must adhere to the same schema. Example: ``` data = [ [first_name: "John", last_name: "Lennon", address: "123 Main St.", city: "Portland", state: "OR", zip: "98204"], [first_name: "Paul", last_name: "McCartney", address: "456 Main St.", city: "Portland", state: "OR", zip: "98204"], [first_name: "George", last_name: "Harrison", address: "789 Main St.", city: "Portland", state: "OR", zip: "98204"], [first_name: "Paul", last_name: "Starkey", address: "012 Main St.", city: "Portland", state: "OR", zip: "98204"], ] result = db(:people) |> insert(data) ``` """ def bulk_insert(%QueryCommand{} = cmd, list) when is_list(list) do # do this once and get a canonnical map for the records - column_map = list |> hd |> Keyword.keys cmd |> bulk_insert_batch(list, [], column_map) end defp bulk_insert_batch(%QueryCommand{} = cmd, list, acc, column_map) when is_list(list) do # split the records into command batches that won't overwhelm postgres with params: # 20,000 seems to be the optimal number here. Technically you can go up to 34,464, but I think Postgrex imposes a lower limit, as I # hit a wall at 34,000, but succeeded at 30,000. Perf on 100k records is best at 20,000. max_params = 20000 column_count = length(column_map) max_records_per_command = div(max_params, column_count) { current, next_batch } = Enum.split(list, max_records_per_command) new_cmd = bulk_insert_command(cmd, current, column_map) case next_batch do [] -> %CommandBatch{commands: Enum.reverse([new_cmd | acc])} _ -> db(cmd.table_name) |> bulk_insert_batch(next_batch, [new_cmd | acc], column_map) end end defp bulk_insert_command(%QueryCommand{} = cmd, list, column_map) when is_list(list) do column_count = length(column_map) row_count = length(list) param_list = for row <- 0..row_count-1 do list = (row * column_count + 1 .. (row * column_count) + column_count) |> Enum.to_list |> Enum.map_join(",", &"$#{&1}") "(#{list})" end params = for row <- list, {_k, v} <- row, do: v column_names = Enum.map_join(column_map,", ", &"#{&1}") value_sql = Enum.join param_list, "," sql = "insert into #{cmd.table_name}(#{column_names}) values #{value_sql};" %{cmd | sql: sql, params: params, type: :insert} end @doc """ Creates an insert command based on the assembled pipeline """ def insert(%QueryCommand{} = cmd, criteria) do cols = Keyword.keys(criteria) vals = Keyword.values(criteria) column_names = Enum.map_join(cols,", ", &"#{&1}") parameter_placeholders = Enum.map_join(1..length(cols), ", ", &"$#{&1}") sql = "insert into #{cmd.table_name}(#{column_names}) values(#{parameter_placeholders}) returning *;" %{cmd | sql: sql, params: vals, type: :insert} end @doc """ Creates an update command based on the assembled pipeline. """ def update(%QueryCommand{} = cmd, criteria) do cols = Keyword.keys(criteria) vals = Keyword.values(criteria) {cols, col_count} = Enum.map_reduce cols, 1, fn col, acc -> {"#{col} = $#{acc}", acc + 1} end #here's something for John to clean up :):) where = cond do length(cmd.where_columns) > 0 -> {filters, _count} = Enum.map_reduce cmd.where_columns, col_count, fn col, acc -> {"#{col} = $#{acc}", acc + 1} end " where " <> Enum.join(filters, " and ") cmd.where -> cmd.where end #add the filter criteria to the update list params = vals ++ cmd.params columns = Enum.join(cols, ", ") sql = "update #{cmd.table_name} set #{columns}#{where} returning *;" %{cmd | sql: sql, type: :update, params: params} end @doc """ Creates a DELETE command """ def delete(%QueryCommand{} = cmd) do sql = "delete from #{cmd.table_name}" <> cmd.where <> ";" %{cmd | sql: sql, type: :delete} end @doc """ Build a table join for your query. There are a number of options to handle various joins. Joins can also be piped for multiple joins. :join - set the type of join. LEFT, RIGHT, FULL, etc. defaults to INNER :on - specify the table to join on :foreign_key - specify the tables foreign key column :primary_key - specify the joining tables primary key column :using - used to specify a USING queries list of columns to join on Example of simple join: ``` cmd = db(:customers) |> join(:orders) |> select ``` Example of multiple table joins: ``` cmd = db(:customers) |> join(:orders, on: :customers) |> join(:items, on: :orders) |> select ``` """ def join(%QueryCommand{} = cmd, table, opts \\ []) do join_type = Keyword.get(opts, :join, "inner") join_table = Keyword.get(opts, :on, cmd.table_name) foreign_key = Keyword.get(opts, :foreign_key, "#{singularize(join_table)}_id") primary_key = Keyword.get(opts, :primary_key, "id") using = Keyword.get(opts, :using, nil) join_condition = case using do nil -> " #{join_type} join #{table} on #{join_table}.#{primary_key} = #{table}.#{foreign_key}" cols -> " #{join_type} join #{table} using (#{Enum.join(cols, ", ")})" end %{cmd | join: [cmd.join|join_condition]} end @doc """ Executes the SQL in a given SQL file without parameters. Specify the scripts directory by setting the `scripts` directive in the config. Pass the file name as an atom, without extension. ``` result = sql_file(:simple) """ def sql_file(file) do file |> sql_file_command([]) end @doc """ Executes the SQL in a given SQL file with the specified parameters. Specify the scripts directory by setting the `scripts` directive in the config. Pass the file name as an atom, without extension. ``` result = sql_file(:save_user, [1]) ``` """ def sql_file(file, params) do file |> sql_file_command(params) end @doc """ Creates a SQL File command """ def sql_file_command(file, params \\ []) def sql_file_command(file, params) when not is_list(params), do: sql_file_command(file, [params]) def sql_file_command(file, params) do #find the DB dir scripts_dir = Application.get_env(:moebius, :scripts) file_path = Path.join(scripts_dir, "#{Atom.to_string(file)}.sql") sql=File.read!(file_path) %Moebius.QueryCommand{sql: String.trim(sql), params: params} end @doc """ Executes a function with the given name, passed as an atom. Example: ``` result = db(:users) |> function(:all_users) ``` """ def function(function_name) do function_name |> function_command([]) end @doc """ Executes a function with the given name, passed as an atom. params: - An array of values to be passed to the function. Example: ``` result = db(:users) |> function(:friends, ["mike","jane"]) ``` """ def function(function_name, params) do function_name |> function_command(params) end @doc """ Creates a function command """ def function_command(function_name, params \\ []) def function_command(function_name, params) when not is_list(params), do: function_command(function_name, [params]) def function_command(function_name, params) do arg_list = cond do length(params) > 0 -> Enum.map_join(1..length(params), ", ", &"$#{&1}") true -> "" end sql = "select * from #{function_name}(#{arg_list});" %Moebius.QueryCommand{sql: sql, params: params} end end
28.186792
158
0.629092
ff4ec61ca93a1e64107fe14b4abdab7ade19c4a7
761
exs
Elixir
mix.exs
gr8Adakron/minio_ex
7f448f921eb38ef8464ae0097bcb93741bea84e1
[ "MIT" ]
null
null
null
mix.exs
gr8Adakron/minio_ex
7f448f921eb38ef8464ae0097bcb93741bea84e1
[ "MIT" ]
null
null
null
mix.exs
gr8Adakron/minio_ex
7f448f921eb38ef8464ae0097bcb93741bea84e1
[ "MIT" ]
null
null
null
defmodule Minio.MixProject do use Mix.Project def project do [ app: :minio, version: "0.1.0", elixir: "~> 1.9", start_permanent: Mix.env() == :prod, deps: deps(), package: package(), description: description(), name: "minio", source_url: "https://github.com/gr8Adakron/minio_ex" ] end def application do [] end defp deps do [ {:ex_doc, "~> 0.19.1", only: :dev, runtime: false} ] end defp description() do "A client library to use the Minio API" end defp package() do [ name: "minio", maintainers: ["Srivathsan Murali"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/srivathsanmurali/minio_ex"} ] end end
18.560976
74
0.55979
ff4ed8d8480ea537b36e98a3e54fcd40721a46f3
151
exs
Elixir
config/test.exs
Celeo/gandalf_bot
f8e48b9a0b403fac5e29e514ce6c684d1bebeecc
[ "MIT" ]
null
null
null
config/test.exs
Celeo/gandalf_bot
f8e48b9a0b403fac5e29e514ce6c684d1bebeecc
[ "MIT" ]
null
null
null
config/test.exs
Celeo/gandalf_bot
f8e48b9a0b403fac5e29e514ce6c684d1bebeecc
[ "MIT" ]
null
null
null
import Config config :logger, level: :warning config :gandalf_discord_bot, config_file_name: "config.test.json", db_file_name: "roles.test.db"
16.777778
39
0.754967
ff4f0bd58686bc6b52ebecaedba3f2e7878f31f1
1,654
ex
Elixir
apps/artemis/lib/artemis/schemas/user.ex
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
10
2019-07-05T19:59:20.000Z
2021-05-23T07:36:11.000Z
apps/artemis/lib/artemis/schemas/user.ex
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
3
2019-03-05T23:55:09.000Z
2019-05-29T13:46:34.000Z
apps/artemis/lib/artemis/schemas/user.ex
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
4
2019-07-05T20:04:08.000Z
2021-05-13T16:28:33.000Z
defmodule Artemis.User do use Artemis.Schema use Assoc.Schema, repo: Artemis.Repo schema "users" do field :client_key, :string field :client_secret, :string field :description, :string field :email, :string field :first_name, :string field :image, :string field :last_log_in_at, :utc_datetime field :last_name, :string field :name, :string field :session_id, :string has_many :auth_providers, Artemis.AuthProvider, on_delete: :delete_all has_many :user_roles, Artemis.UserRole, on_delete: :delete_all, on_replace: :delete has_many :roles, through: [:user_roles, :role] has_many :permissions, through: [:roles, :permissions] timestamps() end # Callbacks def updatable_fields, do: [ :client_key, :client_secret, :description, :email, :name, :first_name, :image, :last_log_in_at, :last_name, :session_id ] def required_fields, do: [ :email ] def updatable_associations, do: [ user_roles: Artemis.UserRole ] def event_log_fields, do: [ :id, :name ] # Changesets def changeset(struct, params \\ %{}) do params = params |> Artemis.Helpers.keys_to_strings() |> downcase_email_param() struct |> cast(params, updatable_fields()) |> validate_required(required_fields()) |> unique_constraint(:email) end # Helpers defp downcase_email_param(%{"email" => email} = params) when is_bitstring(email) do Map.put(params, "email", String.downcase(email)) end defp downcase_email_param(params), do: params end
20.936709
87
0.643894
ff4f1e58dbbb26b2668a10017ea4a4cd0914c016
2,136
ex
Elixir
lib/mongoose_push_web/schemas/request/send_notification/deep.ex
4nirmall/MongoosePush
6c8c53234f8623a1abeb115c8fbdab691a95ed2f
[ "Apache-2.0" ]
107
2017-02-10T00:26:05.000Z
2022-02-23T00:50:07.000Z
lib/mongoose_push_web/schemas/request/send_notification/deep.ex
4nirmall/MongoosePush
6c8c53234f8623a1abeb115c8fbdab691a95ed2f
[ "Apache-2.0" ]
109
2017-02-09T14:40:20.000Z
2021-04-30T22:01:20.000Z
lib/mongoose_push_web/schemas/request/send_notification/deep.ex
4nirmall/MongoosePush
6c8c53234f8623a1abeb115c8fbdab691a95ed2f
[ "Apache-2.0" ]
25
2017-08-21T20:55:33.000Z
2022-03-06T10:01:13.000Z
defmodule MongoosePushWeb.Schemas.Request.SendNotification.Deep do alias OpenApiSpex.Schema def base() do %{ properties: %{ service: %Schema{ type: :string, description: "Push notification service", format: :text, enum: ["fcm", "apns"] }, mode: %Schema{type: :string, enum: ["prod", "dev"]}, priority: %Schema{ type: :string, description: "The default one is chosen based on the service being used", enum: ["normal", "high"] }, time_to_live: %Schema{type: :integer, format: :int32}, mutable_content: %Schema{type: :boolean, default: false}, tags: %Schema{ type: :array, description: "Used when choosing pool to match request tags when sending a notification", items: %Schema{type: :string, format: :text} }, # Only for APNS, alert/data independent topic: %Schema{type: :string} }, required: [:service], example: %{ "service" => "apns", "mode" => "prod", "priority" => "normal", "time_to_live" => 3600, "mutable_content" => false, "tags" => ["some", "tags", "for", "pool", "selection"], "topic" => "com.someapp" } } end def alert() do %{ properties: %{ alert: MongoosePushWeb.Schemas.Request.SendNotification.Deep.Common.Alert }, required: [:alert], example: %{ "alert" => %{ "body" => "A message from someone", "title" => "Notification title", "badge" => 7, "click_action" => ".SomeApp.Handler.action", "tag" => "info", "sound" => "standard.mp3" } } } end def data() do %{ properties: %{ data: MongoosePushWeb.Schemas.Request.SendNotification.Deep.Common.Data }, required: [:data], example: %{ "data" => %{ "custom" => "data fields", "some_id" => 345_645_332, "nested" => %{"fields" => "allowed"} } } } end end
27.384615
88
0.507959
ff4f2029ac9e03f3324167a2c4a1651281d4ae13
1,224
exs
Elixir
mix.exs
elcritch/nerves_system_amd64
d6c5470af78545bb77259fe7653cae6b53059b2a
[ "Apache-2.0" ]
null
null
null
mix.exs
elcritch/nerves_system_amd64
d6c5470af78545bb77259fe7653cae6b53059b2a
[ "Apache-2.0" ]
null
null
null
mix.exs
elcritch/nerves_system_amd64
d6c5470af78545bb77259fe7653cae6b53059b2a
[ "Apache-2.0" ]
null
null
null
defmodule NervesSystemRpi3.Mixfile do use Mix.Project @version Path.join(__DIR__, "VERSION") |> File.read! |> String.strip def project do [app: :nerves_system_amd64, version: @version, elixir: "~> 1.4", compilers: Mix.compilers ++ [:nerves_package], description: description(), package: package(), deps: deps(), aliases: ["deps.precompile": ["nerves.env", "deps.precompile"]]] end def application do [] end defp deps do [{:nerves, "~> 0.7.1", runtime: false }, {:nerves_system_br, "~> 0.13.3", runtime: false }, {:nerves_toolchain_x86_64_unknown_linux_gnu, "~> 0.10.0", runtime: false}] end defp description do """ Nerves System - NanoPi Neo """ end defp package do [maintainers: [ "Jaremy Creechley <creechley@gmail.com>" ], files: [ "rootfs-additions", "LICENSE", "mix.exs", "nerves_defconfig", "nerves.exs", "README.md", "VERSION", "fwup.conf", "post-createfs.sh", "uboot-script.cmd", "linux", ], licenses: ["Apache 2.0"], links: %{"Github" => "https://github.com/elcritch/nerves_system_amd64"}] end end
22.666667
79
0.575163
ff4f28c047fae0a298eaf7c993275deaec689fae
992
ex
Elixir
lib/phoenix_inline_svg/utils.ex
qdentity/phoenix_inline_svg
b920af17ab568a88b5493cd8d8651ba00e87dc3c
[ "MIT" ]
58
2016-07-19T13:45:57.000Z
2022-03-04T15:45:35.000Z
lib/phoenix_inline_svg/utils.ex
qdentity/phoenix_inline_svg
b920af17ab568a88b5493cd8d8651ba00e87dc3c
[ "MIT" ]
44
2016-07-20T22:27:03.000Z
2021-05-06T22:06:28.000Z
lib/phoenix_inline_svg/utils.ex
qdentity/phoenix_inline_svg
b920af17ab568a88b5493cd8d8651ba00e87dc3c
[ "MIT" ]
33
2017-01-27T20:15:25.000Z
2022-03-02T16:32:07.000Z
defmodule PhoenixInlineSvg.Utils do @moduledoc false def insert_attrs(html, []), do: html def insert_attrs(html, attrs) do Enum.reduce(attrs, html, fn {attr, value}, acc -> attr = attr |> to_string |> String.replace("_", "-") acc |> Floki.parse_fragment() |> case do {:ok, html_tree} -> html_tree |> Floki.attr("svg", attr, &String.trim("#{&1} #{value}")) |> Floki.raw_html() {:error, html} -> raise("Unable to parse html\n#{html}") end end) end def safety_string(html) do {:safe, html} end def insert_generic_funcs(ast, collection) do default = config_or_default(:default_collection, "generic") if default == collection do ast end end def config_or_default(config, default) do case Application.fetch_env(:phoenix_inline_svg, config) do :error -> default {:ok, data} -> data end end end
20.244898
68
0.569556
ff4f42ee2bab1cfbf7738d691f249ae54e7bef99
1,528
ex
Elixir
ex_api/ex_api/mongo_db.ex
zemuldo/zemuldo.com.backend
0d9ee45e8595f9e154744e68eb820cce01905bac
[ "MIT" ]
2
2018-03-02T11:29:33.000Z
2019-10-26T18:38:01.000Z
ex_api/ex_api/mongo_db.ex
zemuldo/zemuldo.com.backend
0d9ee45e8595f9e154744e68eb820cce01905bac
[ "MIT" ]
5
2018-01-30T11:40:56.000Z
2021-07-12T05:30:02.000Z
ex_api/ex_api/mongo_db.ex
zemuldo/zemuldo.com.backend
0d9ee45e8595f9e154744e68eb820cce01905bac
[ "MIT" ]
1
2020-07-25T15:07:12.000Z
2020-07-25T15:07:12.000Z
defmodule ExApi.MongoDB do use GenServer alias ExApi.Posts.FeaturedPost @env Application.get_env(:ex_api, ExApi.MongoDB) @uri "mongodb://#{@env[:host]}:27017/#{@env[:database]}" @server __MODULE__ def init(init_arg) do {:ok, init_arg} end def start_link(_) do case @env[:user] do nil -> Mongo.start_link(name: @server, url: @uri) _ -> Mongo.start_link( name: @server, url: @uri, username: @env[:user], password: @env[:password], auth_source: @env[:database] ) end end def get_posts_tags() do Mongo.find(@server, "posts", %{}) |> Enum.to_list() end def log_resume_request(email, resume) do Mongo.insert_one(@server, "resume_request", %{ email: email, resume: resume, timestamp: DateTime.utc_now() }) end def get_featured_post() do case FeaturedPost.get() do %{post_id: post_id} -> Mongo.find_one(@server, "posts", %{_id: BSON.ObjectId.decode!(post_id)}) _ -> Mongo.find_one(@server, "posts", %{}, sort: [createdAt: -1]) end end def new_resume(filename) do Mongo.insert_one(@server, "resumes", %{filename: filename, timestamp: DateTime.utc_now()}) end def find_by_filename(filename) do Mongo.find_one(@server, "resumes", %{filename: filename}) end def get_latest_resume() do [resume] = Mongo.find(@server, "resumes", %{}, limit: 1, sort: %{_id: -1}) |> Enum.to_list() {:ok, resume} end end
22.470588
96
0.60144
ff4f45c3dc67ba452ef536884a3805014a978129
343
ex
Elixir
lib/animu/account/auth/pipeline.ex
elarkham/animu
0f0c7b0b34168e69255943bdede60e03df057a44
[ "MIT" ]
1
2018-01-02T06:59:08.000Z
2018-01-02T06:59:08.000Z
lib/animu/account/auth/pipeline.ex
elarkham/Animu
0f0c7b0b34168e69255943bdede60e03df057a44
[ "MIT" ]
null
null
null
lib/animu/account/auth/pipeline.ex
elarkham/Animu
0f0c7b0b34168e69255943bdede60e03df057a44
[ "MIT" ]
null
null
null
defmodule Animu.Auth.Pipeline do use Guardian.Plug.Pipeline, otp_app: :animu, error_handler: Animu.Auth.ErrorHandler, module: Animu.Auth.Guardian #plug Guardian.Plug.VerifySession plug Guardian.Plug.VerifyHeader, realm: :none plug Guardian.Plug.EnsureAuthenticated plug Guardian.Plug.LoadResource, allow_blank: true end
28.583333
52
0.778426
ff4f750c79ba27c28d4be8d1ae0d0f3d96e88555
12,947
ex
Elixir
clients/compute/lib/google_api/compute/v1/api/ssl_certificates.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/ssl_certificates.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/ssl_certificates.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.Compute.V1.Api.SslCertificates do @moduledoc """ API calls for all endpoints tagged `SslCertificates`. """ alias GoogleApi.Compute.V1.Connection import GoogleApi.Compute.V1.RequestBuilder @doc """ Deletes the specified SslCertificate resource. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - ssl_certificate (String): Name of the SslCertificate resource to delete. - opts (KeywordList): [optional] Optional parameters - :alt (String): Data format for the response. - :fields (String): Selector specifying which fields to include in a partial response. - :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. - :oauth_token (String): OAuth 2.0 token for the current user. - :pretty_print (Boolean): Returns response with indentations and line breaks. - :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. Overrides userIp if both are provided. - :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :request_id (String): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_ssl_certificates_delete(Tesla.Env.client, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t} | {:error, Tesla.Env.t} def compute_ssl_certificates_delete(connection, project, ssl_certificate, opts \\ []) do optional_params = %{ :"alt" => :query, :"fields" => :query, :"key" => :query, :"oauth_token" => :query, :"prettyPrint" => :query, :"quotaUser" => :query, :"userIp" => :query, :"requestId" => :query } %{} |> method(:delete) |> url("/#{project}/global/sslCertificates/#{ssl_certificate}") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.Operation{}) end @doc """ Returns the specified SslCertificate resource. Get a list of available SSL certificates by making a list() request. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - ssl_certificate (String): Name of the SslCertificate resource to return. - opts (KeywordList): [optional] Optional parameters - :alt (String): Data format for the response. - :fields (String): Selector specifying which fields to include in a partial response. - :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. - :oauth_token (String): OAuth 2.0 token for the current user. - :pretty_print (Boolean): Returns response with indentations and line breaks. - :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. Overrides userIp if both are provided. - :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits. ## Returns {:ok, %GoogleApi.Compute.V1.Model.SslCertificate{}} on success {:error, info} on failure """ @spec compute_ssl_certificates_get(Tesla.Env.client, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.SslCertificate.t} | {:error, Tesla.Env.t} def compute_ssl_certificates_get(connection, project, ssl_certificate, opts \\ []) do optional_params = %{ :"alt" => :query, :"fields" => :query, :"key" => :query, :"oauth_token" => :query, :"prettyPrint" => :query, :"quotaUser" => :query, :"userIp" => :query } %{} |> method(:get) |> url("/#{project}/global/sslCertificates/#{ssl_certificate}") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.SslCertificate{}) end @doc """ Creates a SslCertificate resource in the specified project using the data included in the request. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - opts (KeywordList): [optional] Optional parameters - :alt (String): Data format for the response. - :fields (String): Selector specifying which fields to include in a partial response. - :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. - :oauth_token (String): OAuth 2.0 token for the current user. - :pretty_print (Boolean): Returns response with indentations and line breaks. - :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. Overrides userIp if both are provided. - :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :request_id (String): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). - :body (SslCertificate): ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_ssl_certificates_insert(Tesla.Env.client, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t} | {:error, Tesla.Env.t} def compute_ssl_certificates_insert(connection, project, opts \\ []) do optional_params = %{ :"alt" => :query, :"fields" => :query, :"key" => :query, :"oauth_token" => :query, :"prettyPrint" => :query, :"quotaUser" => :query, :"userIp" => :query, :"requestId" => :query, :"body" => :body } %{} |> method(:post) |> url("/#{project}/global/sslCertificates") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.Operation{}) end @doc """ Retrieves the list of SslCertificate resources available to the specified project. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - opts (KeywordList): [optional] Optional parameters - :alt (String): Data format for the response. - :fields (String): Selector specifying which fields to include in a partial response. - :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. - :oauth_token (String): OAuth 2.0 token for the current user. - :pretty_print (Boolean): Returns response with indentations and line breaks. - :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. Overrides userIp if both are provided. - :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :filter (String): Sets a filter {expression} for filtering listed resources. Your {expression} must be in the format: field_name comparison_string literal_string. The field_name is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The comparison_string must be either eq (equals) or ne (not equals). The literal_string is the string value to filter to. The literal value must be valid for the type of field you are filtering by (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, to filter for instances that do not have a name of example-instance, you would use name ne example-instance. You can filter on nested fields. For example, you could filter on instances that have set the scheduling.automaticRestart field to true. Use filtering on nested fields to take advantage of labels to organize and search for results based on label values. To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple expressions are treated as AND expressions, meaning that resources must match all expressions to pass the filters. - :max_results (Integer): The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) - :order_by (String): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy&#x3D;\&quot;creationTimestamp desc\&quot;. This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported. - :page_token (String): Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. ## Returns {:ok, %GoogleApi.Compute.V1.Model.SslCertificateList{}} on success {:error, info} on failure """ @spec compute_ssl_certificates_list(Tesla.Env.client, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.SslCertificateList.t} | {:error, Tesla.Env.t} def compute_ssl_certificates_list(connection, project, opts \\ []) do optional_params = %{ :"alt" => :query, :"fields" => :query, :"key" => :query, :"oauth_token" => :query, :"prettyPrint" => :query, :"quotaUser" => :query, :"userIp" => :query, :"filter" => :query, :"maxResults" => :query, :"orderBy" => :query, :"pageToken" => :query } %{} |> method(:get) |> url("/#{project}/global/sslCertificates") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.SslCertificateList{}) end end
61.947368
1,327
0.721634
ff4f8061bf371b39307f171c43dc93ca61bd371e
12,455
ex
Elixir
lib/elixir/lib/code/typespec.ex
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
19,291
2015-01-01T02:42:49.000Z
2022-03-31T21:01:40.000Z
lib/elixir/lib/code/typespec.ex
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
8,082
2015-01-01T04:16:23.000Z
2022-03-31T22:08:02.000Z
lib/elixir/lib/code/typespec.ex
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
3,472
2015-01-03T04:11:56.000Z
2022-03-29T02:07:30.000Z
defmodule Code.Typespec do @moduledoc false @doc """ Converts a spec clause back to Elixir quoted expression. """ @spec spec_to_quoted(atom, tuple) :: {atom, keyword, [Macro.t()]} def spec_to_quoted(name, spec) def spec_to_quoted(name, {:type, anno, :fun, [{:type, _, :product, args}, result]}) when is_atom(name) do meta = meta(anno) body = {name, meta, Enum.map(args, &typespec_to_quoted/1)} vars = for type_expr <- args ++ [result], var <- collect_vars(type_expr), uniq: true, do: {var, {:var, meta, nil}} spec = {:"::", meta, [body, typespec_to_quoted(result)]} if vars == [] do spec else {:when, meta, [spec, vars]} end end def spec_to_quoted(name, {:type, anno, :fun, []}) when is_atom(name) do meta = meta(anno) {:"::", meta, [{name, meta, []}, quote(do: term)]} end def spec_to_quoted(name, {:type, anno, :bounded_fun, [type, constrs]}) when is_atom(name) do meta = meta(anno) {:type, _, :fun, [{:type, _, :product, args}, result]} = type guards = for {:type, _, :constraint, [{:atom, _, :is_subtype}, [{:var, _, var}, type]]} <- constrs do {erl_to_ex_var(var), typespec_to_quoted(type)} end ignore_vars = Keyword.keys(guards) vars = for type_expr <- args ++ [result], var <- collect_vars(type_expr), var not in ignore_vars, uniq: true, do: {var, {:var, meta, nil}} args = for arg <- args, do: typespec_to_quoted(arg) when_args = [ {:"::", meta, [{name, meta, args}, typespec_to_quoted(result)]}, guards ++ vars ] {:when, meta, when_args} end @doc """ Converts a type clause back to Elixir AST. """ def type_to_quoted(type) def type_to_quoted({{:record, record}, fields, args}) when is_atom(record) do fields = for field <- fields, do: typespec_to_quoted(field) args = for arg <- args, do: typespec_to_quoted(arg) type = {:{}, [], [record | fields]} quote(do: unquote(record)(unquote_splicing(args)) :: unquote(type)) end def type_to_quoted({name, type, args}) when is_atom(name) do args = for arg <- args, do: typespec_to_quoted(arg) quote(do: unquote(name)(unquote_splicing(args)) :: unquote(typespec_to_quoted(type))) end @doc """ Returns all types available from the module's BEAM code. The result is returned as a list of tuples where the first element is the type (`:typep`, `:type` and `:opaque`). The module must have a corresponding BEAM file which can be located by the runtime system. The types will be in the Erlang Abstract Format. """ @spec fetch_types(module | binary) :: {:ok, [tuple]} | :error def fetch_types(module) when is_atom(module) or is_binary(module) do case typespecs_abstract_code(module) do {:ok, abstract_code} -> exported_types = for {:attribute, _, :export_type, types} <- abstract_code, do: types exported_types = List.flatten(exported_types) types = for {:attribute, _, kind, {name, _, args} = type} <- abstract_code, kind in [:opaque, :type] do cond do kind == :opaque -> {:opaque, type} {name, length(args)} in exported_types -> {:type, type} true -> {:typep, type} end end {:ok, types} _ -> :error end end @doc """ Returns all specs available from the module's BEAM code. The result is returned as a list of tuples where the first element is spec name and arity and the second is the spec. The module must have a corresponding BEAM file which can be located by the runtime system. The types will be in the Erlang Abstract Format. """ @spec fetch_specs(module) :: {:ok, [tuple]} | :error def fetch_specs(module) when is_atom(module) or is_binary(module) do case typespecs_abstract_code(module) do {:ok, abstract_code} -> {:ok, for({:attribute, _, :spec, value} <- abstract_code, do: value)} :error -> :error end end @doc """ Returns all callbacks available from the module's BEAM code. The result is returned as a list of tuples where the first element is spec name and arity and the second is the spec. The module must have a corresponding BEAM file which can be located by the runtime system. The types will be in the Erlang Abstract Format. """ @spec fetch_callbacks(module) :: {:ok, [tuple]} | :error def fetch_callbacks(module) when is_atom(module) or is_binary(module) do case typespecs_abstract_code(module) do {:ok, abstract_code} -> {:ok, for({:attribute, _, :callback, value} <- abstract_code, do: value)} :error -> :error end end defp typespecs_abstract_code(module) do with {module, binary} <- get_module_and_beam(module), {:ok, {_, [debug_info: {:debug_info_v1, backend, data}]}} <- :beam_lib.chunks(binary, [:debug_info]) do case data do {:elixir_v1, %{}, specs} -> # Fast path to avoid translation to Erlang from Elixir. {:ok, specs} _ -> case backend.debug_info(:erlang_v1, module, data, []) do {:ok, abstract_code} -> {:ok, abstract_code} _ -> :error end end else _ -> :error end end defp get_module_and_beam(module) when is_atom(module) do case :code.get_object_code(module) do {^module, beam, _filename} -> {module, beam} :error -> :error end end defp get_module_and_beam(beam) when is_binary(beam) do case :beam_lib.info(beam) do [_ | _] = info -> {info[:module], beam} _ -> :error end end ## To AST conversion defp collect_vars({:ann_type, _anno, args}) when is_list(args) do [] end defp collect_vars({:type, _anno, _kind, args}) when is_list(args) do Enum.flat_map(args, &collect_vars/1) end defp collect_vars({:remote_type, _anno, args}) when is_list(args) do Enum.flat_map(args, &collect_vars/1) end defp collect_vars({:typed_record_field, _anno, type}) do collect_vars(type) end defp collect_vars({:paren_type, _anno, [type]}) do collect_vars(type) end defp collect_vars({:var, _anno, var}) do [erl_to_ex_var(var)] end defp collect_vars(_) do [] end defp typespec_to_quoted({:user_type, anno, name, args}) do args = for arg <- args, do: typespec_to_quoted(arg) {name, meta(anno), args} end defp typespec_to_quoted({:type, anno, :tuple, :any}) do {:tuple, meta(anno), []} end defp typespec_to_quoted({:type, anno, :tuple, args}) do args = for arg <- args, do: typespec_to_quoted(arg) {:{}, meta(anno), args} end defp typespec_to_quoted({:type, _anno, :list, [{:type, _, :union, unions} = arg]}) do case unpack_typespec_kw(unions, []) do {:ok, ast} -> ast :error -> [typespec_to_quoted(arg)] end end defp typespec_to_quoted({:type, anno, :list, []}) do {:list, meta(anno), []} end defp typespec_to_quoted({:type, _anno, :list, [arg]}) do [typespec_to_quoted(arg)] end defp typespec_to_quoted({:type, anno, :nonempty_list, []}) do [{:..., meta(anno), nil}] end defp typespec_to_quoted({:type, anno, :nonempty_list, [arg]}) do [typespec_to_quoted(arg), {:..., meta(anno), nil}] end defp typespec_to_quoted({:type, anno, :map, :any}) do {:map, meta(anno), []} end defp typespec_to_quoted({:type, anno, :map, fields}) do fields = Enum.map(fields, fn {:type, _, :map_field_assoc, :any} -> {{:optional, [], [{:any, [], []}]}, {:any, [], []}} {:type, _, :map_field_exact, [{:atom, _, k}, v]} -> {k, typespec_to_quoted(v)} {:type, _, :map_field_exact, [k, v]} -> {{:required, [], [typespec_to_quoted(k)]}, typespec_to_quoted(v)} {:type, _, :map_field_assoc, [k, v]} -> {{:optional, [], [typespec_to_quoted(k)]}, typespec_to_quoted(v)} end) case List.keytake(fields, :__struct__, 0) do {{:__struct__, struct}, fields_pruned} when is_atom(struct) and struct != nil -> map_pruned = {:%{}, meta(anno), fields_pruned} {:%, meta(anno), [struct, map_pruned]} _ -> {:%{}, meta(anno), fields} end end defp typespec_to_quoted({:type, anno, :binary, [arg1, arg2]}) do [arg1, arg2] = for arg <- [arg1, arg2], do: typespec_to_quoted(arg) line = meta(anno)[:line] case {typespec_to_quoted(arg1), typespec_to_quoted(arg2)} do {arg1, 0} -> quote(line: line, do: <<_::unquote(arg1)>>) {0, arg2} -> quote(line: line, do: <<_::_*unquote(arg2)>>) {arg1, arg2} -> quote(line: line, do: <<_::unquote(arg1), _::_*unquote(arg2)>>) end end defp typespec_to_quoted({:type, anno, :union, args}) do args = for arg <- args, do: typespec_to_quoted(arg) Enum.reduce(Enum.reverse(args), fn arg, expr -> {:|, meta(anno), [arg, expr]} end) end defp typespec_to_quoted({:type, anno, :fun, [{:type, _, :product, args}, result]}) do args = for arg <- args, do: typespec_to_quoted(arg) [{:->, meta(anno), [args, typespec_to_quoted(result)]}] end defp typespec_to_quoted({:type, anno, :fun, [args, result]}) do [{:->, meta(anno), [[typespec_to_quoted(args)], typespec_to_quoted(result)]}] end defp typespec_to_quoted({:type, anno, :fun, []}) do typespec_to_quoted({:type, anno, :fun, [{:type, anno, :any}, {:type, anno, :any, []}]}) end defp typespec_to_quoted({:type, anno, :range, [left, right]}) do {:.., meta(anno), [typespec_to_quoted(left), typespec_to_quoted(right)]} end defp typespec_to_quoted({:type, _anno, nil, []}) do [] end defp typespec_to_quoted({:type, anno, name, args}) do args = for arg <- args, do: typespec_to_quoted(arg) {name, meta(anno), args} end defp typespec_to_quoted({:var, anno, var}) do {erl_to_ex_var(var), meta(anno), nil} end defp typespec_to_quoted({:op, anno, op, arg}) do {op, meta(anno), [typespec_to_quoted(arg)]} end defp typespec_to_quoted({:remote_type, anno, [mod, name, args]}) do remote_type(anno, mod, name, args) end defp typespec_to_quoted({:ann_type, anno, [var, type]}) do {:"::", meta(anno), [typespec_to_quoted(var), typespec_to_quoted(type)]} end defp typespec_to_quoted( {:typed_record_field, {:record_field, anno1, {:atom, anno2, name}}, type} ) do typespec_to_quoted({:ann_type, anno1, [{:var, anno2, name}, type]}) end defp typespec_to_quoted({:type, _, :any}) do quote(do: ...) end defp typespec_to_quoted({:paren_type, _, [type]}) do typespec_to_quoted(type) end defp typespec_to_quoted({type, _anno, atom}) when is_atom(type) do atom end defp typespec_to_quoted(other), do: other ## Helpers defp remote_type(anno, {:atom, _, :elixir}, {:atom, _, :charlist}, []) do typespec_to_quoted({:type, anno, :charlist, []}) end defp remote_type(anno, {:atom, _, :elixir}, {:atom, _, :nonempty_charlist}, []) do typespec_to_quoted({:type, anno, :nonempty_charlist, []}) end defp remote_type(anno, {:atom, _, :elixir}, {:atom, _, :struct}, []) do typespec_to_quoted({:type, anno, :struct, []}) end defp remote_type(anno, {:atom, _, :elixir}, {:atom, _, :as_boolean}, [arg]) do typespec_to_quoted({:type, anno, :as_boolean, [arg]}) end defp remote_type(anno, {:atom, _, :elixir}, {:atom, _, :keyword}, args) do typespec_to_quoted({:type, anno, :keyword, args}) end defp remote_type(anno, mod, name, args) do args = for arg <- args, do: typespec_to_quoted(arg) dot = {:., meta(anno), [typespec_to_quoted(mod), typespec_to_quoted(name)]} {dot, meta(anno), args} end defp erl_to_ex_var(var) do case Atom.to_string(var) do <<"_", c::utf8, rest::binary>> -> String.to_atom("_#{String.downcase(<<c::utf8>>)}#{rest}") <<c::utf8, rest::binary>> -> String.to_atom("#{String.downcase(<<c::utf8>>)}#{rest}") end end defp unpack_typespec_kw([{:type, _, :tuple, [{:atom, _, atom}, type]} | t], acc) do unpack_typespec_kw(t, [{atom, typespec_to_quoted(type)} | acc]) end defp unpack_typespec_kw([], acc) do {:ok, Enum.reverse(acc)} end defp unpack_typespec_kw(_, _acc) do :error end defp meta(anno), do: [line: :erl_anno.line(anno)] end
29.514218
98
0.61381
ff4faeaa7e167b5844ec08d3f1043e4fcc698f6f
1,418
ex
Elixir
priv/templates/lib/web/controllers/veil/user_controller.ex
hassan/veil
345b5d3539ccaba7e51b4e83583e9d15d8379fd4
[ "MIT" ]
164
2018-02-10T21:33:40.000Z
2022-03-15T06:10:50.000Z
priv/templates/lib/web/controllers/veil/user_controller.ex
hassan/veil
345b5d3539ccaba7e51b4e83583e9d15d8379fd4
[ "MIT" ]
21
2018-02-15T02:31:40.000Z
2021-04-04T07:16:43.000Z
priv/templates/lib/web/controllers/veil/user_controller.ex
hassan/veil
345b5d3539ccaba7e51b4e83583e9d15d8379fd4
[ "MIT" ]
14
2018-03-24T11:15:07.000Z
2020-06-28T12:33:38.000Z
defmodule <%= web_module %>.Veil.UserController do use <%= web_module %>, :controller alias <%= main_module %>.Veil alias <%= main_module %>.Veil.User action_fallback(<%= web_module %>.Veil.FallbackController) <%= if html? do %> plug(:scrub_params, "user" when action in [:create]) @doc """ Shows the sign in form """ def new(conn, _params) do render(conn, "new.html", changeset: User.changeset(%User{})) end <% end %> @doc """ If needed, creates a new user, otherwise finds the existing one. Creates a new request and emails the unique id to the user. """ <%= if html? do %> def create(conn, %{"user" => %{"email" => email}}) when not is_nil(email) do <% else %> def create(conn, %{"email" => email}) when not is_nil(email) do <% end %> if user = Veil.get_user_by_email(email) do sign_and_email(conn, user) else with {:ok, user} <- Veil.create_user(email) do sign_and_email(conn, user) else error -> error end end end defp sign_and_email(conn, %User{} = user) do with {:ok, request} <- Veil.create_request(conn, user), {:ok, email} <- Veil.send_login_email(conn, user, request) do <%= if html? do %> render(conn, "show.html", user: user, email: email) <% else %> render(conn, "ok.json") <% end %> else error -> error end end end
26.259259
78
0.589563
ff4ff3db4913fa91029ffe27bad1e489bc5af48e
1,107
exs
Elixir
c_src/membrane_rtmp_plugin/sink/rtmp_sink.spec.exs
membraneframework/membrane_rtmp_plugin
ff4b1ff25b7d67c896b6db523517f795c30b6f52
[ "Apache-2.0" ]
10
2021-11-05T10:19:43.000Z
2022-03-04T18:42:41.000Z
c_src/membrane_rtmp_plugin/sink/rtmp_sink.spec.exs
membraneframework/membrane_rtmp_plugin
ff4b1ff25b7d67c896b6db523517f795c30b6f52
[ "Apache-2.0" ]
5
2021-11-23T12:10:48.000Z
2022-01-04T06:57:31.000Z
c_src/membrane_rtmp_plugin/sink/rtmp_sink.spec.exs
membraneframework/membrane_rtmp_plugin
ff4b1ff25b7d67c896b6db523517f795c30b6f52
[ "Apache-2.0" ]
null
null
null
module Membrane.RTMP.Sink.Native state_type "State" interface [NIF] spec create(rtmp_url :: string) :: {:ok :: label, state} | {:error :: label, reason :: string} # WARN: connect will conflict with POSIX function name spec try_connect(state) :: (:ok :: label) | {:error :: label, :econnrefused :: label} | {:error :: label, reason :: string} spec finalize_stream(state) :: :ok :: label spec init_video_stream(state, width :: int, height :: int, avc_config :: payload) :: {:ok :: label, ready :: bool, state} | {:error :: label, :caps_resent :: label} spec write_video_frame(state, frame :: payload, dts :: int64, is_key_frame :: bool) :: {:ok :: label, state} | {:error :: label, reason :: string} spec init_audio_stream(state, channels :: int, sample_rate :: int, aac_config :: payload) :: {:ok :: label, ready :: bool, state} | {:error :: label, :caps_resent :: label} spec write_audio_frame(state, frame :: payload, pts :: int64) :: {:ok :: label, state} | {:error :: label, reason :: string} dirty :io, write_video_frame: 4, write_audio_frame: 3
39.535714
94
0.636856
ff5008a24d5bdeb3835959e37fa665b749dc60e1
16,952
ex
Elixir
lib/cubdb/btree.ex
meyercm/cubdb
ed6bd87abd25d6d053b08a4b0a01defd57a5bbac
[ "Apache-2.0" ]
null
null
null
lib/cubdb/btree.ex
meyercm/cubdb
ed6bd87abd25d6d053b08a4b0a01defd57a5bbac
[ "Apache-2.0" ]
null
null
null
lib/cubdb/btree.ex
meyercm/cubdb
ed6bd87abd25d6d053b08a4b0a01defd57a5bbac
[ "Apache-2.0" ]
null
null
null
defmodule CubDB.Btree do @moduledoc false # `CubDB.Btree` is the internal module implementing the fundamental data # structure for CubDB: an append-only, copy-on-write B+tree. # # Operations on Btree generally return another modified Btree, similarly to # immutable data structures like maps. The new Btree points to the updated # root, while the "old" Btree still points to the old one, effectively # maintaining an immutable snapshot. # # Updates are not committed, and will not be visible after a restart, until # `commit/1` is explicitly called. Also, they may not be durable until # `sync/1` is called (although the OS will eventually sync changes to disk # even if `sync/1` is not explicitly called). @leaf :l @branch :b @value :v @deleted :d require Record Record.defrecord(:leaf, @leaf, children: []) Record.defrecord(:branch, @branch, children: []) Record.defrecord(:value, @value, val: nil) @type key :: CubDB.key() @type val :: CubDB.value() @type btree_size :: non_neg_integer @type dirt :: non_neg_integer @type location :: non_neg_integer @type capacity :: pos_integer @type child_pointer :: {key, location} @type leaf_node :: record(:leaf, children: [child_pointer]) @type branch_node :: record(:branch, children: [child_pointer]) @type value_node :: record(:value, val: val) @type deleted_node :: :d @type internal_node :: leaf_node | branch_node @type terminal_node :: value_node | deleted_node @type btree_node :: leaf_node | branch_node | value_node | deleted_node @type btree_header :: {btree_size, location, dirt} @type node_type :: :l | :b | :v | :d alias CubDB.Store alias CubDB.Btree @type t :: %Btree{ root: branch_node | leaf_node, root_loc: location, size: btree_size, store: Store.t(), capacity: non_neg_integer } @default_capacity 32 @enforce_keys [:root, :root_loc, :size, :store, :capacity] defstruct root: nil, root_loc: nil, size: 0, dirt: 0, store: nil, capacity: @default_capacity @spec new(Store.t(), pos_integer) :: Btree.t() def new(store, cap \\ @default_capacity) do case Store.get_latest_header(store) do {_, {s, loc, dirt}} -> root = Store.get_node(store, loc) %Btree{root: root, root_loc: loc, dirt: dirt, size: s, capacity: cap, store: store} nil -> root = leaf() loc = Store.put_node(store, root) Store.put_header(store, {0, loc, 0}) %Btree{root: root, root_loc: loc, size: 0, capacity: cap, store: store} end end @spec load(Enumerable.t(), Store.t(), pos_integer) :: Btree.t() # `load/3` takes an enumerable of `{key, value}` entries that should be # strictly sorted by key and an empty store, and creates a Btree with those # entries by writing them into the store. It is used primarily for compaction # operations, where the enumerable is the `Btree` to be compacted. The fact # that the enumerable is sorted by key, allows using a specific algorithm to # create the Btree in a much faster way than with normal inserts. def load(enum, store, cap \\ @default_capacity) do unless Store.blank?(store), do: raise(ArgumentError, message: "cannot load into non-empty store") {st, count} = Enum.reduce(enum, {[], 0}, fn {k, v}, {st, count} -> {load_node(store, k, value(val: v), st, 1, cap), count + 1} end) if count == 0 do new(store, cap) else {root, root_loc} = finalize_load(store, st, 1, cap) Store.put_header(store, {count, root_loc, 0}) %Btree{root: root, root_loc: root_loc, capacity: cap, store: store, size: count} end end @spec fetch(Btree.t(), key) :: {:ok, val} | :error # `fetch/2` returns `{:ok, value}` if an entry with key `key` is present # in the Btree, or `:error` otherwise. def fetch(%Btree{root: root, store: store}, key) do {{@leaf, children}, _} = lookup_leaf(root, store, key, []) case Enum.find(children, &match?({^key, _}, &1)) do nil -> :error {_, loc} -> case Store.get_node(store, loc) do {@value, value} -> {:ok, value} @deleted -> :error end end end @spec insert(Btree.t(), key, val) :: Btree.t() # `insert/3` writes an entry in the Btree, updating the previous one with the # same key if existing. It does not commit the operation, so `commit/1` must # be explicitly called to commit the insertion. def insert(btree, key, value) do insert_terminal_node(btree, key, value(val: value)) end @spec insert_new(Btree.t(), key, val) :: Btree.t() | {:error, :exists} # `insert_new/3` writes an entry in the Btree, only if it is not yet present # in the database. It does not commit the operation, so `commit/1` must be # explicitly called to commit the insertion. def insert_new(btree, key, value) do insert_terminal_node(btree, key, value(val: value), false) end @spec delete(Btree.t(), key) :: Btree.t() # `delete/2` deletes the entry associated to `key` in the Btree, if existing. # It does not commit the operation, so `commit/1` must be explicitly called to # commit the deletion. def delete(btree, key) do %Btree{root: root, store: store, capacity: cap, size: s, dirt: dirt} = btree {leaf = {@leaf, children}, path} = lookup_leaf(root, store, key, []) case List.keyfind(children, key, 0) do {^key, loc} -> size = case Store.get_node(store, loc) do @deleted -> s _ -> s - 1 end {root_loc, new_root} = build_up(store, leaf, [], [key], path, cap) %Btree{ root: new_root, root_loc: root_loc, capacity: cap, store: store, size: size, dirt: dirt + 1 } nil -> btree end end @spec mark_deleted(Btree.t(), key) :: Btree.t() # `mark_deleted/2` deletes an entry by marking it as deleted, as opposed to # `delete/2`, that simply removes it. It is necessary to use `mark_deleted/2` # instead of `delete/2` while a compaction operation is running in the # background. This is so that, after the compaction is done, the compacted # Btree can catch-up with updates performed after compaction started, # including deletions, that would otherwise not be enumerated by Btree.Diff. # Similar to `update/3` and `delete/3`, it does not commit the operation, so # `commit/1` must be explicitly called to commit the deletion. def mark_deleted(btree, key) do case fetch(btree, key) do {:ok, _} -> insert_terminal_node(btree, key, @deleted) :error -> btree end end @spec commit(Btree.t()) :: Btree.t() # `commit/1` writes the header to the store, committing all updates performed # after the previous call to `commit/1`. This is primarily used to control # atomicity of updates: if a batch of updates is to be performed atomically, # `commit/1` must be called once, after all updates. # If one or more updates are performed, but `commit/1` is not called, the # updates won't be committed to the database and will be lost in case of a # restart. def commit(tree = %Btree{store: store, size: size, root_loc: root_loc, dirt: dirt}) do Store.put_header(store, {size, root_loc, dirt + 1}) tree end @spec key_range(Btree.t(), Btree.KeyRange.bound(), Btree.KeyRange.bound(), boolean) :: Btree.KeyRange.t() # `key_range/4` returns a `Btree.KeyRange` `Enumerable` that can be used to # iterate through a range of entries with key between `min_key` and `max_key`. def key_range(tree, min_key \\ nil, max_key \\ nil, reverse \\ false) do Btree.KeyRange.new(tree, min_key, max_key, reverse) end @spec dirt_factor(Btree.t()) :: float # `dirt_factor/1` returns a flating point number between 0 and 1 giving an # indication of how much overhead due to old entries (that were rewritten or # deleted and are therefore unreachable) and headers is present in the Btree. # The dirt factor is used to estimate when a compaction operation is # necessary. def dirt_factor(%Btree{size: size, dirt: dirt}) do dirt / (1 + size + dirt) end @spec sync(Btree.t()) :: Btree.t() # `sync/1` performs a file sync on the store, and is used to ensure durability # of updates. def sync(btree = %Btree{store: store}) do :ok = Store.sync(store) btree end @spec stop(Btree.t()) :: :ok def stop(%Btree{store: store}) do Store.close(store) end @spec alive?(Btree.t()) :: boolean def alive?(%Btree{store: store}) do Store.open?(store) end def __leaf__, do: @leaf def __branch__, do: @branch def __value__, do: @value def __deleted__, do: @deleted @spec insert_terminal_node(Btree.t(), key, terminal_node, boolean) :: Btree.t() | {:error, :exists} defp insert_terminal_node(btree, key, terminal_node, overwrite \\ true) do %Btree{root: root, store: store, capacity: cap, size: s, dirt: dirt} = btree {leaf = {@leaf, children}, path} = lookup_leaf(root, store, key, []) was_set = child_is_set?(store, children, key) if overwrite == false && was_set do {:error, :exists} else {root_loc, new_root} = build_up(store, leaf, [{key, terminal_node}], [], path, cap) size = case {terminal_node, was_set} do {{@value, _}, true} -> s {{@value, _}, false} -> s + 1 {@deleted, true} -> s - 1 {@deleted, false} -> s end %Btree{ root: new_root, root_loc: root_loc, capacity: cap, store: store, size: size, dirt: dirt + 1 } end end @spec child_is_set?(Store.t(), [child_pointer], key) :: boolean defp child_is_set?(store, children, key) do case List.keyfind(children, key, 0) do nil -> false {_, pos} -> Store.get_node(store, pos) != @deleted end end @spec load_node(Store.t(), key, btree_node, [btree_node], pos_integer, capacity) :: [ [child_pointer] ] defp load_node(store, key, node, [], _, _) do loc = Store.put_node(store, node) [[{key, loc}]] end defp load_node(store, key, node, [children | rest], level, cap) do loc = Store.put_node(store, node) children = [{key, loc} | children] if length(children) == cap do parent = make_node(children, level) parent_key = List.last(keys(children)) [[] | load_node(store, parent_key, parent, rest, level + 1, cap)] else [children | rest] end end @spec finalize_load(Store.t(), [[child_pointer]], pos_integer, capacity) :: {btree_node, location} defp finalize_load(store, [children], level, _) do case children do [{_, loc}] when level > 1 -> {Store.get_node(store, loc), loc} _ -> node = make_node(children, level) {node, Store.put_node(store, node)} end end defp finalize_load(store, [children | rest], level, cap) do case children do [] -> finalize_load(store, rest, level + 1, cap) _ -> node = make_node(children, level) key = List.last(keys(children)) stack = load_node(store, key, node, rest, level + 1, cap) finalize_load(store, stack, level + 1, cap) end end @spec make_node([child_pointer], pos_integer) :: internal_node defp make_node(children, level) do children = Enum.reverse(children) if level == 1, do: leaf(children: children), else: branch(children: children) end @spec lookup_leaf(internal_node, Store.t(), key, [internal_node]) :: {leaf_node, [internal_node]} defp lookup_leaf(branch = {@branch, children}, store, key, path) do loc = Enum.reduce_while(children, nil, fn {_, loc}, nil -> {:cont, loc} {k, loc}, acc -> if k <= key, do: {:cont, loc}, else: {:halt, acc} end) child = Store.get_node(store, loc) lookup_leaf(child, store, key, [branch | path]) end defp lookup_leaf(leaf = {@leaf, _}, _, _, path) do {leaf, path} end @spec build_up(Store.t(), internal_node, [{key, val}], [key], [internal_node], capacity) :: {location, internal_node} defp build_up(store, node, to_merge, to_delete, [], cap) do to_merge_locs = store_nodes(store, to_merge) case replace_node(store, node, to_merge_locs, to_delete, nil, cap) do [] -> root = leaf() {Store.put_node(store, root), root} [{_, {@branch, [{_, loc}]}}] -> {loc, Store.get_node(store, loc)} [{_, node}] -> {Store.put_node(store, node), node} new_nodes -> new_locs = store_nodes(store, new_nodes) root = branch(children: new_locs) {Store.put_node(store, root), root} end end defp build_up(store, node, to_merge, to_delete, [parent | up], cap) do to_merge_locs = store_nodes(store, to_merge) new_nodes = replace_node(store, node, to_merge_locs, to_delete, parent, cap) deleted = keys(elem(node, 1)) -- keys(new_nodes) build_up(store, parent, new_nodes, deleted, up, cap) end @spec store_nodes(Store.t(), [{key, btree_node}]) :: [{key, location}] defp store_nodes(store, nodes) do Enum.map(nodes, fn {k, v} -> {k, Store.put_node(store, v)} end) end @spec replace_node( Store.t(), internal_node, [{key, location}], [key], internal_node | nil, capacity ) :: [btree_node] defp replace_node(store, node, merge, delete, parent, cap) do {type, children} = node children |> update_children(merge, delete) |> split_merge(store, node, parent, cap) |> wrap_nodes(type) end @spec update_children([child_pointer], [{key, location}], [key]) :: [child_pointer] defp update_children(children, merge, delete) do merged = Enum.reduce(merge, children, fn kv = {k, _}, acc -> List.keystore(acc, k, 0, kv) end) Enum.reduce(delete, merged, fn k, acc -> List.keydelete(acc, k, 0) end) |> List.keysort(0) end @spec wrap_nodes([[{key, any}]], node_type) :: [{key, btree_node}] defp wrap_nodes(chunks, type) do for chunk = [{k, _} | _] <- chunks do {k, {type, chunk}} end end @spec split_merge( [child_pointer], Store.t(), internal_node | nil, internal_node | nil, capacity ) :: [[child_pointer]] defp split_merge(children, store, old_node, parent, cap) do size = length(children) cond do size > cap -> split(children, cap) size < div(cap + 1, 2) and parent != nil and old_node != nil -> merge(store, children, old_node, parent, cap) true -> [children] end end @spec split([child_pointer], capacity) :: [[child_pointer]] defp split(children, cap) do children |> Enum.split(div(cap + 1, 2)) |> Tuple.to_list() end @spec merge(Store.t(), [child_pointer], internal_node, internal_node, capacity) :: [ [child_pointer] ] defp merge(store, children, {_, old_children}, parent, cap) do key = min_key(keys(old_children), keys(children)) (left_sibling(store, parent, key) ++ children) |> split_merge(store, nil, parent, cap) end @spec left_sibling(Store.t(), branch_node, key) :: [child_pointer] defp left_sibling(store, {@branch, children}, key) do left = children |> Enum.take_while(fn {k, _} -> k < key end) |> List.last() case left do {_, loc} -> {_, children} = Store.get_node(store, loc) children nil -> [] end end @spec keys([{key, any}]) :: [key] defp keys(tuples) do Enum.map(tuples, &elem(&1, 0)) end @spec min_key([key], [key]) :: key defp min_key([], ks2), do: List.first(ks2) defp min_key(ks1, []), do: List.first(ks1) defp min_key(ks1, ks2), do: min(List.first(ks1), List.first(ks2)) end defimpl Enumerable, for: CubDB.Btree do # `Btree` implements `Enumerable`, and can be iterated (or streamed) yielding # entries sorted by key. alias CubDB.Btree alias CubDB.Store @value Btree.__value__() @deleted Btree.__deleted__() def reduce(btree, cmd_acc, fun) do Btree.Enumerable.reduce(btree, cmd_acc, fun, &get_children/2) end def count(%Btree{size: size}), do: {:ok, size} def member?(btree, {key, value}) do case Btree.fetch(btree, key) do {:ok, ^value} -> {:ok, true} _ -> {:ok, false} end end def member?(_, _), do: {:ok, false} def slice(_), do: {:error, __MODULE__} @spec get_children(Btree.btree_node(), Store.t()) :: any defp get_children({@value, v}, _), do: v defp get_children({_, locs}, store) do locs |> Enum.map(fn {k, loc} -> {k, Store.get_node(store, loc)} end) |> Enum.filter(fn {_, node} -> node != @deleted end) end end
30.217469
95
0.622758
ff50139c045d3b01f54d8bb17277b510dd8ed8dc
2,446
ex
Elixir
clients/analytics_data/lib/google_api/analytics_data/v1alpha/model/date_range.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/analytics_data/lib/google_api/analytics_data/v1alpha/model/date_range.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/analytics_data/lib/google_api/analytics_data/v1alpha/model/date_range.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.AnalyticsData.V1alpha.Model.DateRange do @moduledoc """ A contiguous set of days: startDate, startDate + 1, ..., endDate. Requests are allowed up to 4 date ranges. ## Attributes * `endDate` (*type:* `String.t`, *default:* `nil`) - The inclusive end date for the query in the format `YYYY-MM-DD`. Cannot be before `start_date`. The format `NdaysAgo`, `yesterday`, or `today` is also accepted, and in that case, the date is inferred based on the property's reporting time zone. * `name` (*type:* `String.t`, *default:* `nil`) - Assigns a name to this date range. The dimension `dateRange` is valued to this name in a report response. If set, cannot begin with `date_range_` or `RESERVED_`. If not set, date ranges are named by their zero based index in the request: `date_range_0`, `date_range_1`, etc. * `startDate` (*type:* `String.t`, *default:* `nil`) - The inclusive start date for the query in the format `YYYY-MM-DD`. Cannot be after `end_date`. The format `NdaysAgo`, `yesterday`, or `today` is also accepted, and in that case, the date is inferred based on the property's reporting time zone. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :endDate => String.t() | nil, :name => String.t() | nil, :startDate => String.t() | nil } field(:endDate) field(:name) field(:startDate) end defimpl Poison.Decoder, for: GoogleApi.AnalyticsData.V1alpha.Model.DateRange do def decode(value, options) do GoogleApi.AnalyticsData.V1alpha.Model.DateRange.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AnalyticsData.V1alpha.Model.DateRange do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
46.150943
328
0.719133
ff5014140b53c5db856e3e38821183c9ef62a77d
1,926
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/model/subscription_content_details.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/you_tube/lib/google_api/you_tube/v3/model/subscription_content_details.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/you_tube/lib/google_api/you_tube/v3/model/subscription_content_details.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.YouTube.V3.Model.SubscriptionContentDetails do @moduledoc """ Details about the content to witch a subscription refers. ## Attributes * `activityType` (*type:* `String.t`, *default:* `nil`) - The type of activity this subscription is for (only uploads, everything). * `newItemCount` (*type:* `integer()`, *default:* `nil`) - The number of new items in the subscription since its content was last read. * `totalItemCount` (*type:* `integer()`, *default:* `nil`) - The approximate number of items that the subscription points to. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :activityType => String.t() | nil, :newItemCount => integer() | nil, :totalItemCount => integer() | nil } field(:activityType) field(:newItemCount) field(:totalItemCount) end defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.SubscriptionContentDetails do def decode(value, options) do GoogleApi.YouTube.V3.Model.SubscriptionContentDetails.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.SubscriptionContentDetails do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.339623
139
0.726376
ff50280ce95e0d11930350697c1fab0f265350df
2,828
ex
Elixir
lib/mimicry/mock_api.ex
mimicry-tech/mimicry
08a28fb08a7f02fbbb0a2bc2724a08a0b0b41cd9
[ "MIT" ]
4
2021-06-18T17:47:32.000Z
2022-01-04T22:41:36.000Z
lib/mimicry/mock_api.ex
mimicry-tech/mimicry
08a28fb08a7f02fbbb0a2bc2724a08a0b0b41cd9
[ "MIT" ]
56
2021-06-14T19:04:35.000Z
2022-03-24T04:18:58.000Z
lib/mimicry/mock_api.ex
mimicry-tech/mimicry
08a28fb08a7f02fbbb0a2bc2724a08a0b0b41cd9
[ "MIT" ]
1
2021-06-13T13:44:35.000Z
2021-06-13T13:44:35.000Z
defmodule Mimicry.MockAPI do @moduledoc """ contains functions for pretending to be a functional API based on a spec """ require Logger alias Mimicry.OpenAPI.{Example, Path, Response, Specification} import Plug.Conn, only: [get_req_header: 2] @doc """ main entry point for responses. Essentially tries to infer the path used and respond with an example from the spec """ @spec respond(Plug.Conn.t(), Specification.t() | nil) :: map() def respond( conn = %Plug.Conn{method: method, request_path: request_path}, spec = %Specification{} ) do expected_code = conn |> get_req_header("x-mimicry-expect-status") |> List.first() # TODO: For JSON, all keys are strings, always |> ensure_numerical() |> fallback("default") expected_example = conn |> get_req_header("x-mimicry-example") |> List.first() |> fallback(:random) content_type = conn |> get_req_header("Accept") |> List.first() |> fallback("application/json") response = spec |> Path.extract_response(method, request_path, expected_code, content_type) case response do {:ok, response = %Response{}} -> example = response |> Example.choose(expected_example, spec) request_path |> respond_with(response, method, example) {:error, :not_found} -> %{ status: :not_found, headers: default_headers(request_path, method), body: %{} } {:error, :no_examples} -> %{ status: :not_implemented, headers: default_headers(request_path, method), body: %{} } end end def respond(%Plug.Conn{request_path: path, method: method}, nil) do %{status: :internal_error, headers: default_headers([], method, path), body: %{}} end defp default_headers(path, method, headers \\ []) do [ {"x-mimicry-path", path}, {"x-mimicry-method", method} ] |> Enum.concat(headers) end defp fallback(nil, fb), do: fb defp fallback(value, _), do: value defp respond_with(path, _, method, {:error, :no_examples}) do %{ status: :not_implemented, headers: default_headers(path, method), body: %{ error: "No examples for this response found" } } end defp respond_with(path, response, method, {:ok, %{"value" => value} = _example}) do headers = [ {"x-mimicry-description", response.description}, {"content-type", response.content_type} ] %{ status: response.status, headers: default_headers(path, method, headers), body: value } end defp ensure_numerical(nil), do: nil defp ensure_numerical(maybe_number) do case Integer.parse(maybe_number) do :error -> nil {number, _} -> number end end end
26.429907
86
0.617044
ff5029bc269d7b8e71406725a20f17b8625198f4
2,839
ex
Elixir
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_rbm_card_content_rbm_media.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_rbm_card_content_rbm_media.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_rbm_card_content_rbm_media.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2021-03-04T13:43:47.000Z
2021-03-04T13:43:47.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.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia do @moduledoc """ Rich Business Messaging (RBM) Media displayed in Cards The following media-types are currently supported: Image Types * image/jpeg * image/jpg' * image/gif * image/png Video Types * video/h263 * video/m4v * video/mp4 * video/mpeg * video/mpeg4 * video/webm ## Attributes * `fileUri` (*type:* `String.t`, *default:* `nil`) - Required. Publicly reachable URI of the file. The RBM platform determines the MIME type of the file from the content-type field in the HTTP headers when the platform fetches the file. The content-type field must be present and accurate in the HTTP response from the URL. * `height` (*type:* `String.t`, *default:* `nil`) - Required for cards with vertical orientation. The height of the media within a rich card with a vertical layout. For a standalone card with horizontal layout, height is not customizable, and this field is ignored. * `thumbnailUri` (*type:* `String.t`, *default:* `nil`) - Optional. Publicly reachable URI of the thumbnail.If you don't provide a thumbnail URI, the RBM platform displays a blank placeholder thumbnail until the user's device downloads the file. Depending on the user's setting, the file may not download automatically and may require the user to tap a download button. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :fileUri => String.t(), :height => String.t(), :thumbnailUri => String.t() } field(:fileUri) field(:height) field(:thumbnailUri) end defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia do def decode(value, options) do GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
47.316667
373
0.749912
ff5030b71aa292613e25397359dd4115b2cf31fe
2,837
ex
Elixir
clients/ad_sense_host/lib/google_api/ad_sense_host/v41/model/ad_unit.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/ad_sense_host/lib/google_api/ad_sense_host/v41/model/ad_unit.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/ad_sense_host/lib/google_api/ad_sense_host/v41/model/ad_unit.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.AdSenseHost.V41.Model.AdUnit do @moduledoc """ ## Attributes - code (String): Identity code of this ad unit, not necessarily unique across ad clients. Defaults to: `null`. - contentAdsSettings (AdUnitContentAdsSettings): Defaults to: `null`. - customStyle (AdStyle): Custom style information specific to this ad unit. Defaults to: `null`. - id (String): Unique identifier of this ad unit. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. Defaults to: `null`. - kind (String): Kind of resource this is, in this case adsensehost#adUnit. Defaults to: `null`. - mobileContentAdsSettings (AdUnitMobileContentAdsSettings): Defaults to: `null`. - name (String): Name of this ad unit. Defaults to: `null`. - status (String): Status of this ad unit. Possible values are: NEW: Indicates that the ad unit was created within the last seven days and does not yet have any activity associated with it. ACTIVE: Indicates that there has been activity on this ad unit in the last seven days. INACTIVE: Indicates that there has been no activity on this ad unit in the last seven days. Defaults to: `null`. """ defstruct [ :"code", :"contentAdsSettings", :"customStyle", :"id", :"kind", :"mobileContentAdsSettings", :"name", :"status" ] end defimpl Poison.Decoder, for: GoogleApi.AdSenseHost.V41.Model.AdUnit do import GoogleApi.AdSenseHost.V41.Deserializer def decode(value, options) do value |> deserialize(:"contentAdsSettings", :struct, GoogleApi.AdSenseHost.V41.Model.AdUnitContentAdsSettings, options) |> deserialize(:"customStyle", :struct, GoogleApi.AdSenseHost.V41.Model.AdStyle, options) |> deserialize(:"mobileContentAdsSettings", :struct, GoogleApi.AdSenseHost.V41.Model.AdUnitMobileContentAdsSettings, options) end end defimpl Poison.Encoder, for: GoogleApi.AdSenseHost.V41.Model.AdUnit do def encode(value, options) do GoogleApi.AdSenseHost.V41.Deserializer.serialize_non_nil(value, options) end end
44.328125
393
0.746563
ff503b8a5bebf9ba6e768ea18da3d519451b4de9
16,583
ex
Elixir
lib/ex_unit/lib/ex_unit/callbacks.ex
irisTa56/elixir
0a953d75fb2cbdc6f3d33040aa60738d85512a1f
[ "Apache-2.0" ]
null
null
null
lib/ex_unit/lib/ex_unit/callbacks.ex
irisTa56/elixir
0a953d75fb2cbdc6f3d33040aa60738d85512a1f
[ "Apache-2.0" ]
null
null
null
lib/ex_unit/lib/ex_unit/callbacks.ex
irisTa56/elixir
0a953d75fb2cbdc6f3d33040aa60738d85512a1f
[ "Apache-2.0" ]
null
null
null
defmodule ExUnit.Callbacks do @moduledoc ~S""" Defines ExUnit callbacks. This module defines the `setup/1`, `setup/2`, `setup_all/1`, and `setup_all/2` callbacks, as well as the `on_exit/2`, `start_supervised/2` and `stop_supervised/1` functions. The setup callbacks are defined via macros and each one can optionally receive a map with test state and metadata, usually referred to as `context`. The context to be used in the tests can be optionally extended by the setup callbacks by returning a properly structured value (see below). The `setup_all` callbacks are invoked only once per module, before any test is run. All `setup` callbacks are run before each test. No callback is run if the test case has no tests or all tests have been filtered out. `setup` and `setup_all` callbacks can be defined by a block, by passing an atom naming a one-arity function, or by passing a list of such atoms. Both can opt to receive the current context by specifying it as parameter if defined by a block. Functions used to define a test setup must accept the context as single argument. A test module can define multiple `setup` and `setup_all` callbacks, and they are invoked in order of appearance. `start_supervised/2` is used to start processes under a supervisor. The supervisor is linked to the current test process. The supervisor as well as all child processes are guaranteed to terminate before any `on_exit/2` callback runs. `on_exit/2` callbacks are registered on demand, usually to undo an action performed by a setup callback. `on_exit/2` may also take a reference, allowing the callback to be overridden in the future. A registered `on_exit/2` callback will always run, while failures in `setup` and `setup_all` will stop all remaining setup callbacks from executing. Finally, `setup_all` callbacks run in a separate process per module, while all `setup` callbacks run in the same process as the test itself. `on_exit/2` callbacks always run in a separate process, as implied by their name. The test process always exits with reason `:shutdown`, which means any process linked to the test process will also exit, although asynchronously. Therefore it is preferred to use `start_supervised/2` to guarantee synchronous termination. Here is a rundown of the life-cycle of the test process: 1. the test process is spawned 2. it runs `setup/2` callbacks 3. it runs the test itself 4. it stops all supervised processes 5. the test process exits with reason `:shutdown` 6. `on_exit/2` callbacks are executed in a separate process ## Context If `setup_all` or `setup` return a keyword list, a map, or a tuple in the shape of `{:ok, keyword() | map()}`, the keyword list or map will be merged into the current context and will be available in all subsequent `setup_all`, `setup`, and the `test` itself. Returning `:ok` leaves the context unchanged (in `setup` and `setup_all` callbacks). Returning anything else from `setup_all` will force all tests to fail, while a bad response from `setup` causes the current test to fail. ## Examples defmodule AssertionTest do use ExUnit.Case, async: true # "setup_all" is called once per module before any test runs setup_all do IO.puts("Starting AssertionTest") # Context is not updated here :ok end # "setup" is called before each test setup do IO.puts("This is a setup callback for #{inspect(self())}") on_exit(fn -> IO.puts("This is invoked once the test is done. Process: #{inspect(self())}") end) # Returns extra metadata to be merged into context [hello: "world"] # Similarly, any of the following would work: # {:ok, [hello: "world"]} # %{hello: "world"} # {:ok, %{hello: "world"}} end # Same as above, but receives the context as argument setup context do IO.puts("Setting up: #{context.test}") :ok end # Setups can also invoke a local or imported function that returns a context setup :invoke_local_or_imported_function test "always pass" do assert true end test "uses metadata from setup", context do assert context[:hello] == "world" assert context[:from_named_setup] == true end defp invoke_local_or_imported_function(context) do [from_named_setup: true] end end """ @doc false defmacro __using__(_) do quote do @ex_unit_describe nil @ex_unit_setup [] @ex_unit_setup_all [] @before_compile unquote(__MODULE__) import unquote(__MODULE__) end end @doc false defmacro __before_compile__(env) do [compile_callbacks(env, :setup), compile_callbacks(env, :setup_all)] end @doc """ Defines a callback to be run before each test in a case. Accepts a block or the name of a one-arity function in the form of an atom, or a list of such atoms. Can return values to be merged into the context, to set up the state for tests. For more details, see the "Context" section shown above. ## Examples def clean_up_tmp_directory(context) do # perform setup :ok end setup :clean_up_tmp_directory setup do [conn: Plug.Conn.build_conn()] end """ defmacro setup(block) do if Keyword.keyword?(block) do do_setup(quote(do: _), block) else quote do @ex_unit_setup ExUnit.Callbacks.__callback__(unquote(block), @ex_unit_describe) ++ @ex_unit_setup end end end @doc """ Defines a callback to be run before each test in a case. Accepts a block or the name of a one-arity function in the form of an atom, or a list of such atoms. Can return values to be merged into the `context`, to set up the state for tests. For more details, see the "Context" section shown above. ## Examples setup context do [conn: Plug.Conn.build_conn()] end """ defmacro setup(context, block) do do_setup(context, block) end defp do_setup(context, block) do quote bind_quoted: [context: escape(context), block: escape(block)] do name = :"__ex_unit_setup_#{length(@ex_unit_setup)}" defp unquote(name)(unquote(context)), unquote(block) @ex_unit_setup [{name, @ex_unit_describe} | @ex_unit_setup] end end @doc """ Defines a callback to be run before all tests in a case. Accepts a block or the name of a one-arity function in the form of an atom, or a list of such atoms. Can return values to be merged into the `context`, to set up the state for tests. For more details, see the "Context" section shown above. ## Examples def clean_up_tmp_directory(context) do # perform setup :ok end # block setup_all do [conn: Plug.Conn.build_conn()] end # one-arity function name setup_all :clean_up_tmp_directory """ defmacro setup_all(block) do if Keyword.keyword?(block) do do_setup_all(quote(do: _), block) else quote do @ex_unit_describe && raise "cannot invoke setup_all/1 inside describe as setup_all/1 " <> "always applies to all tests in a module" @ex_unit_setup_all ExUnit.Callbacks.__callback__(unquote(block), nil) ++ @ex_unit_setup_all end end end @doc """ Defines a callback to be run before all tests in a case. Accepts a block or the name of a one-arity function in the form of an atom, or a list of such atoms. Can return values to be merged into the `context`, to set up the state for tests. For more details, see the "Context" section shown above. ## Examples setup_all context do [conn: Plug.Conn.build_conn()] end """ defmacro setup_all(context, block) do do_setup_all(context, block) end defp do_setup_all(context, block) do quote bind_quoted: [context: escape(context), block: escape(block)] do @ex_unit_describe && raise "cannot invoke setup_all/2 inside describe" name = :"__ex_unit_setup_all_#{length(@ex_unit_setup_all)}" defp unquote(name)(unquote(context)), unquote(block) @ex_unit_setup_all [{name, nil} | @ex_unit_setup_all] end end @doc """ Defines a callback that runs once the test exits. `callback` is a function that receives no arguments and runs in a separate process than the caller. `on_exit/2` is usually called from `setup` and `setup_all` callbacks, often to undo the action performed during the setup. However, `on_exit/2` may also be called dynamically, where a reference can be used to guarantee the callback will be invoked only once. """ @spec on_exit(term, (() -> term)) :: :ok def on_exit(name_or_ref \\ make_ref(), callback) when is_function(callback, 0) do case ExUnit.OnExitHandler.add(self(), name_or_ref, callback) do :ok -> :ok :error -> raise ArgumentError, "on_exit/2 callback can only be invoked from the test process" end end @supervisor_opts [strategy: :one_for_one, max_restarts: 1_000_000, max_seconds: 1] @doc """ Starts a child process under the test supervisor. It expects a child specification or a module, similar to the ones given to `Supervisor.start_link/2`. For example, if your application starts a supervision tree by running: Supervisor.start_link([MyServer, {OtherSupervisor, ...}], ...) You can start those processes under test in isolation by running: start_supervised(MyServer) start_supervised({OtherSupervisor, :initial_value}) A keyword list can also be given if there is a need to change the child specification for the given child process: start_supervised({MyServer, :initial_value}, restart: :temporary) See the `Supervisor` module for a discussion on child specifications and the available specification keys. The advantage of starting a process under the test supervisor is that it is guaranteed to exit before the next test starts. Therefore, you don't need to remove the process at the end of your tests via `stop_supervised/1`. You only need to use `stop_supervised/1 ` if you want to remove a process from the supervision tree in the middle of a test, as simply shutting down the process would cause it to be restarted according to its `:restart` value. This function returns `{:ok, pid}` in case of success, otherwise it returns `{:error, reason}`. """ @doc since: "1.5.0" @spec start_supervised(Supervisor.child_spec() | module | {module, term}, keyword) :: Supervisor.on_start_child() def start_supervised(child_spec_or_module, opts \\ []) do sup = case ExUnit.OnExitHandler.get_supervisor(self()) do {:ok, nil} -> {:ok, sup} = Supervisor.start_link([], @supervisor_opts) ExUnit.OnExitHandler.put_supervisor(self(), sup) sup {:ok, sup} -> sup :error -> raise ArgumentError, "start_supervised/2 can only be invoked from the test process" end child_spec = Supervisor.child_spec(child_spec_or_module, opts) case Supervisor.start_child(sup, child_spec) do {:error, {:already_started, _pid}} -> {:error, {:duplicate_child_name, child_spec.id}} other -> other end end @doc """ Same as `start_supervised/2` but returns the PID on success and raises if not started properly. """ @doc since: "1.6.0" @spec start_supervised!(Supervisor.child_spec() | module | {module, term}, keyword) :: pid def start_supervised!(child_spec_or_module, opts \\ []) do case start_supervised(child_spec_or_module, opts) do {:ok, pid} -> pid {:ok, pid, _info} -> pid {:error, reason} -> raise "failed to start child with the spec #{inspect(child_spec_or_module)}.\n" <> "Reason: #{start_supervised_error(reason)}" end end defp start_supervised_error({{:EXIT, reason}, info}) when is_tuple(info), do: Exception.format_exit(reason) defp start_supervised_error({reason, info}) when is_tuple(info), do: Exception.format_exit(reason) defp start_supervised_error(reason), do: Exception.format_exit({:start_spec, reason}) @doc """ Stops a child process started via `start_supervised/2`. This function expects the `id` in the child specification. For example: {:ok, _} = start_supervised(MyServer) :ok = stop_supervised(MyServer) It returns `:ok` if there is a supervised process with such `id`, `{:error, :not_found}` otherwise. """ @doc since: "1.5.0" @spec stop_supervised(id :: term()) :: :ok | {:error, :not_found} def stop_supervised(id) do case ExUnit.OnExitHandler.get_supervisor(self()) do {:ok, nil} -> {:error, :not_found} {:ok, sup} -> with :ok <- Supervisor.terminate_child(sup, id), :ok <- Supervisor.delete_child(sup, id), do: :ok :error -> raise ArgumentError, "stop_supervised/1 can only be invoked from the test process" end end @doc """ Same as `stop_supervised/1` but raises if it cannot be stopped. """ @doc since: "1.10.0" @spec stop_supervised!(id :: term()) :: :ok def stop_supervised!(id) do case stop_supervised(id) do :ok -> :ok {:error, :not_found} -> raise "could not stop child ID #{inspect(id)} because it was not found" end end ## Helpers @reserved [:case, :file, :line, :test, :async, :registered, :describe] @doc false def __callback__(callback, describe) do for k <- List.wrap(callback) do if not is_atom(k) do raise ArgumentError, "setup/setup_all expect a callback name as an atom or " <> "a list of callback names, got: #{inspect(k)}" end {k, describe} end |> Enum.reverse() end @doc false def __merge__(mod, context, value) do merge(mod, context, value, value) end defp merge(_mod, context, :ok, _original_value) do context end defp merge(mod, context, {:ok, value}, original_value) do merge(mod, context, value, original_value) end defp merge(mod, _context, %_{}, original_value) do raise_merge_failed!(mod, original_value) end defp merge(mod, context, data, original_value) when is_list(data) do merge(mod, context, Map.new(data), original_value) end defp merge(mod, context, data, _original_value) when is_map(data) do context_merge(mod, context, data) end defp merge(mod, _, _return_value, original_value) do raise_merge_failed!(mod, original_value) end defp context_merge(mod, context, data) do Map.merge(context, data, fn k, v1, v2 when k in @reserved -> if v1 == v2, do: v1, else: raise_merge_reserved!(mod, k, v2) _, _, v -> v end) end defp raise_merge_failed!(mod, return_value) do raise "expected ExUnit callback in #{inspect(mod)} to return :ok | keyword | map, " <> "got #{inspect(return_value)} instead" end defp raise_merge_reserved!(mod, key, value) do raise "ExUnit callback in #{inspect(mod)} is trying to set " <> "reserved field #{inspect(key)} to #{inspect(value)}" end defp escape(contents) do Macro.escape(contents, unquote: true) end defp compile_callbacks(env, kind) do callbacks = Module.get_attribute(env.module, :"ex_unit_#{kind}") |> Enum.reverse() acc = case callbacks do [] -> quote(do: context) [h | t] -> Enum.reduce(t, compile_merge(h), fn callback_describe, acc -> quote do context = unquote(acc) unquote(compile_merge(callback_describe)) end end) end quote do def __ex_unit__(unquote(kind), context) do describe = Map.get(context, :describe, nil) unquote(acc) end end end defp compile_merge({callback, nil}) do quote do unquote(__MODULE__).__merge__(__MODULE__, context, unquote(callback)(context)) end end defp compile_merge({callback, {_line, describe}}) do quote do if unquote(describe) == describe do unquote(compile_merge({callback, nil})) else context end end end end
30.595941
93
0.663511
ff5087e53f22e77f92e1ad1e80d8451a1e01bc4f
276
ex
Elixir
test/examples/conditional/cond.ex
Fl4m3Ph03n1x/gradient
60d7d3fe2ebdf68747325c1e852959f8b92fdcee
[ "Apache-2.0" ]
75
2021-11-17T11:55:13.000Z
2022-03-28T04:35:04.000Z
test/examples/conditional/cond.ex
Fl4m3Ph03n1x/gradient
60d7d3fe2ebdf68747325c1e852959f8b92fdcee
[ "Apache-2.0" ]
48
2021-11-15T13:56:14.000Z
2022-03-31T15:55:47.000Z
test/examples/conditional/cond.ex
Fl4m3Ph03n1x/gradient
60d7d3fe2ebdf68747325c1e852959f8b92fdcee
[ "Apache-2.0" ]
6
2021-12-22T20:41:27.000Z
2022-03-09T09:07:38.000Z
defmodule Conditional.Cond do def cond_(a), do: (cond do a == :ok -> :ok a > 5 -> :ok true -> :error end) def cond_block do a = 5 cond do a == :ok -> :ok a > 5 -> :ok true -> :error end end end
13.8
29
0.413043
ff50a504d841d9ca0018d4ee6da3420e9c86308c
80
ex
Elixir
lib/scratch_phoenix/repo.ex
w0rd-driven/scratch_phoenix
465e01af6e7d649bfb308edf91247e9d6c6a5876
[ "MIT" ]
null
null
null
lib/scratch_phoenix/repo.ex
w0rd-driven/scratch_phoenix
465e01af6e7d649bfb308edf91247e9d6c6a5876
[ "MIT" ]
null
null
null
lib/scratch_phoenix/repo.ex
w0rd-driven/scratch_phoenix
465e01af6e7d649bfb308edf91247e9d6c6a5876
[ "MIT" ]
null
null
null
defmodule ScratchPhoenix.Repo do use Ecto.Repo, otp_app: :scratch_phoenix end
20
42
0.8125
ff50a64990040111bc50342cf06fa3d89d494b50
3,502
ex
Elixir
clients/service_management/lib/google_api/service_management/v1/model/quota.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/service_management/lib/google_api/service_management/v1/model/quota.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/service_management/lib/google_api/service_management/v1/model/quota.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "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.ServiceManagement.V1.Model.Quota do @moduledoc """ Quota configuration helps to achieve fairness and budgeting in service usage. The quota configuration works this way: - The service configuration defines a set of metrics. - For API calls, the quota.metric_rules maps methods to metrics with corresponding costs. - The quota.limits defines limits on the metrics, which will be used for quota checks at runtime. An example quota configuration in yaml format: quota: - name: apiWriteQpsPerProject metric: library.googleapis.com/write_calls unit: \&quot;1/min/{project}\&quot; # rate limit for consumer projects values: STANDARD: 10000 # The metric rules bind all methods to the read_calls metric, # except for the UpdateBook and DeleteBook methods. These two methods # are mapped to the write_calls metric, with the UpdateBook method # consuming at twice rate as the DeleteBook method. metric_rules: - selector: \&quot;*\&quot; metric_costs: library.googleapis.com/read_calls: 1 - selector: google.example.library.v1.LibraryService.UpdateBook metric_costs: library.googleapis.com/write_calls: 2 - selector: google.example.library.v1.LibraryService.DeleteBook metric_costs: library.googleapis.com/write_calls: 1 Corresponding Metric definition: metrics: - name: library.googleapis.com/read_calls display_name: Read requests metric_kind: DELTA value_type: INT64 - name: library.googleapis.com/write_calls display_name: Write requests metric_kind: DELTA value_type: INT64 ## Attributes - limits ([QuotaLimit]): List of &#x60;QuotaLimit&#x60; definitions for the service. Defaults to: `null`. - metricRules ([MetricRule]): List of &#x60;MetricRule&#x60; definitions, each one mapping a selected method to one or more metrics. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :limits => list(GoogleApi.ServiceManagement.V1.Model.QuotaLimit.t()), :metricRules => list(GoogleApi.ServiceManagement.V1.Model.MetricRule.t()) } field(:limits, as: GoogleApi.ServiceManagement.V1.Model.QuotaLimit, type: :list) field(:metricRules, as: GoogleApi.ServiceManagement.V1.Model.MetricRule, type: :list) end defimpl Poison.Decoder, for: GoogleApi.ServiceManagement.V1.Model.Quota do def decode(value, options) do GoogleApi.ServiceManagement.V1.Model.Quota.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceManagement.V1.Model.Quota do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
68.666667
1,615
0.73044
ff50d7bc37c4c417c7d4bdb015d5d4ab1f63edad
1,587
ex
Elixir
Microsoft.Azure.Management.Advisor/lib/microsoft/azure/management/advisor/connection.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.Advisor/lib/microsoft/azure/management/advisor/connection.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
Microsoft.Azure.Management.Advisor/lib/microsoft/azure/management/advisor/connection.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.Advisor.Connection do @moduledoc """ Handle Tesla connections for Microsoft.Azure.Management.Advisor. """ use Tesla # Add any middleware here (authentication) plug Tesla.Middleware.BaseUrl, "https://management.azure.com" plug Tesla.Middleware.Headers, %{"User-Agent" => "Elixir"} plug Tesla.Middleware.EncodeJson @scopes [ "user_impersonation" # impersonate your user account ] @doc """ Configure a client connection using a provided OAuth2 token as a Bearer token ## Parameters - token (String): Bearer token ## Returns Tesla.Env.client """ @spec new(String.t) :: Tesla.Env.client def new(token) when is_binary(token) do Tesla.build_client([ {Tesla.Middleware.Headers, %{"Authorization" => "Bearer #{token}"}} ]) end @doc """ Configure a client connection using a function which yields a Bearer token. ## Parameters - token_fetcher (function arity of 1): Callback which provides an OAuth2 token given a list of scopes ## Returns Tesla.Env.client """ @spec new(((list(String.t)) -> String.t)) :: Tesla.Env.client def new(token_fetcher) when is_function(token_fetcher) do token_fetcher.(@scopes) |> new end @doc """ Configure an authless client connection # Returns Tesla.Env.client """ @spec new() :: Tesla.Env.client def new do Tesla.build_client([]) end end
23.338235
80
0.694392
ff50dbe12d7882d2a2bd8bd57ce086c502689c1c
1,563
ex
Elixir
lib/mix/lib/mix/state.ex
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
19,291
2015-01-01T02:42:49.000Z
2022-03-31T21:01:40.000Z
lib/mix/lib/mix/state.ex
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
8,082
2015-01-01T04:16:23.000Z
2022-03-31T22:08:02.000Z
lib/mix/lib/mix/state.ex
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
3,472
2015-01-03T04:11:56.000Z
2022-03-29T02:07:30.000Z
defmodule Mix.State do @moduledoc false @name __MODULE__ @timeout :infinity use Agent def start_link(_opts) do Agent.start_link(__MODULE__, :init, [], name: @name) end def init() do %{ shell: Mix.Shell.IO, env: from_env("MIX_ENV", :dev), target: from_env("MIX_TARGET", :host), scm: [Mix.SCM.Git, Mix.SCM.Path], cache: :ets.new(@name, [:public, :set, :named_table, read_concurrency: true]) } end defp from_env(varname, default) do case System.get_env(varname) do nil -> default "" -> default value -> String.to_atom(value) end end def fetch(key) do Agent.get(@name, Map, :fetch, [key], @timeout) end def get(key, default \\ nil) do Agent.get(@name, Map, :get, [key, default], @timeout) end def put(key, value) do Agent.update(@name, Map, :put, [key, value], @timeout) end def prepend_scm(value) do Agent.update( @name, fn state -> update_in(state.scm, &[value | List.delete(&1, value)]) end, @timeout ) end def append_scm(value) do Agent.update( @name, fn state -> update_in(state.scm, &(List.delete(&1, value) ++ [value])) end, @timeout ) end def read_cache(key) do case :ets.lookup(@name, key) do [{^key, value}] -> value [] -> nil end end def write_cache(key, value) do :ets.insert(@name, {key, value}) value end def delete_cache(key) do :ets.delete(@name, key) end def clear_cache do :ets.delete_all_objects(@name) end end
20.038462
83
0.595649
ff51295b621bb59d5657d0dc445324a818b280f0
1,342
exs
Elixir
mix.exs
Schultzer/timezone
ea252e87b99e07226cd45cda902489255c8c54b4
[ "MIT", "Unlicense" ]
2
2017-07-16T13:39:53.000Z
2018-01-17T15:53:29.000Z
mix.exs
Schultzer/timezone
ea252e87b99e07226cd45cda902489255c8c54b4
[ "MIT", "Unlicense" ]
null
null
null
mix.exs
Schultzer/timezone
ea252e87b99e07226cd45cda902489255c8c54b4
[ "MIT", "Unlicense" ]
null
null
null
defmodule Timezone.Mixfile do use Mix.Project @version "0.2.2" def project do [app: :timezone, version: @version, elixir: "~> 1.5", name: "Timezone", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps(), # Hex description: description(), package: package(), docs: docs() ] end def application do [extra_applications: [:logger]] end defp deps do [{:httpoison, "~> 0.13"}, {:poison, "~> 3.1"}, {:decimal, "~> 1.4", optional: true}, {:ex_doc, "~> 0.18", override: true, only: :dev}] end defp description do """ Simple wrapper around Google Maps Time Zone API """ end defp package do [name: :timezone, maintainers: ["Benjamin Schultzer"], licenses: ["MIT"], links: links(), files: ["lib", "config", "mix.exs", "README*", "CHANGELOG*", "LICENSE*"] ] end defp docs do [ source_ref: "v#{@version}", main: "readme", extras: ["README.md", "CHANGELOG.md"] ] end defp links do %{ "GitHub" => "https://github.com/schultzer/timezone", "Readme" => "https://github.com/schultzer/timezone/blob/v#{@version}/README.md", "Changelog" => "https://github.com/schultzer/timezone/blob/v#{@version}/CHANGELOG.md" } end end
20.96875
91
0.564083
ff518300a3fe2e148462ed6e89d738cf5be2a1ca
1,010
exs
Elixir
test/render_test.exs
augnustin/ex_admin
218d0094de8186808924dcca6157875a7bb382c9
[ "MIT" ]
2
2019-12-21T12:59:19.000Z
2020-04-01T15:27:12.000Z
test/render_test.exs
augnustin/ex_admin
218d0094de8186808924dcca6157875a7bb382c9
[ "MIT" ]
null
null
null
test/render_test.exs
augnustin/ex_admin
218d0094de8186808924dcca6157875a7bb382c9
[ "MIT" ]
1
2020-02-29T22:13:24.000Z
2020-02-29T22:13:24.000Z
defmodule ExAdminTest.Render do use ExUnit.Case, async: true alias ExAdmin.Render test "string" do assert Render.to_string("test") == "test" end test "integer" do assert Render.to_string(123) == "123" end test "float" do assert Render.to_string(10.99) == "10.99" end test "atom" do assert Render.to_string(:test) == "test" end test "list" do assert Render.to_string([:one, :two]) == ~s/["one","two"]/ end test "map" do assert Render.to_string(%{one: 1, two: 2}) == ~s/{"two":2,"one":1}/ end test "Decimal" do assert Render.to_string(Decimal.new(10.99)) == "10.99" end test "Date" do assert Render.to_string(~D[2016-10-10]) == "2016-10-10" end test "Time" do assert Render.to_string(~T[15:30:00]) == "15:30:00" end test "DateTime" do dt = DateTime.from_unix!(1_464_096_368) result = Render.to_string(dt) assert String.starts_with?(result, "2016-05-24 ") assert String.ends_with?(result, ":26:08") end end
21.041667
71
0.626733
ff518d3e8c665cf4c599de6c1b718fbda60168bd
1,720
ex
Elixir
clients/cloud_tasks/lib/google_api/cloud_tasks/v2/model/set_iam_policy_request.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/cloud_tasks/lib/google_api/cloud_tasks/v2/model/set_iam_policy_request.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/cloud_tasks/lib/google_api/cloud_tasks/v2/model/set_iam_policy_request.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "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.CloudTasks.V2.Model.SetIamPolicyRequest do @moduledoc """ Request message for `SetIamPolicy` method. ## Attributes * `policy` (*type:* `GoogleApi.CloudTasks.V2.Model.Policy.t`, *default:* `nil`) - REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Google Cloud services (such as Projects) might reject them. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :policy => GoogleApi.CloudTasks.V2.Model.Policy.t() | nil } field(:policy, as: GoogleApi.CloudTasks.V2.Model.Policy) end defimpl Poison.Decoder, for: GoogleApi.CloudTasks.V2.Model.SetIamPolicyRequest do def decode(value, options) do GoogleApi.CloudTasks.V2.Model.SetIamPolicyRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudTasks.V2.Model.SetIamPolicyRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.595745
308
0.748256
ff51c40a6060f7e315cc2496115eb7ed7b6d2a6f
1,412
ex
Elixir
lib/codes/codes_p19.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_p19.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_p19.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_P19 do alias IcdCode.ICDCode def _P190 do %ICDCode{full_code: "P190", category_code: "P19", short_code: "0", full_name: "Metabolic acidemia in newborn first noted before onset of labor", short_name: "Metabolic acidemia in newborn first noted before onset of labor", category_name: "Metabolic acidemia in newborn first noted before onset of labor" } end def _P191 do %ICDCode{full_code: "P191", category_code: "P19", short_code: "1", full_name: "Metabolic acidemia in newborn first noted during labor", short_name: "Metabolic acidemia in newborn first noted during labor", category_name: "Metabolic acidemia in newborn first noted during labor" } end def _P192 do %ICDCode{full_code: "P192", category_code: "P19", short_code: "2", full_name: "Metabolic acidemia noted at birth", short_name: "Metabolic acidemia noted at birth", category_name: "Metabolic acidemia noted at birth" } end def _P199 do %ICDCode{full_code: "P199", category_code: "P19", short_code: "9", full_name: "Metabolic acidemia, unspecified", short_name: "Metabolic acidemia, unspecified", category_name: "Metabolic acidemia, unspecified" } end end
32.837209
90
0.635977
ff51deeeb925d1103807dfb10515b1dcd886b4ce
2,779
ex
Elixir
lib/console/runbooks/action.ex
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
6
2021-11-17T21:10:49.000Z
2022-02-16T19:45:28.000Z
lib/console/runbooks/action.ex
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
18
2021-11-25T04:31:06.000Z
2022-03-27T04:54:00.000Z
lib/console/runbooks/action.ex
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
null
null
null
defprotocol Console.Runbooks.Action do @spec enact(struct, Console.Runbooks.Actor.t) :: {:ok | :error, any} def enact(action, struct) end defmodule Console.Runbooks.Actor do alias Console.Runbooks.Action, as: ActionImpl alias Kube.Runbook.{Action, ConfigurationAction} defstruct [:ctx, :repo, :actor] @type t :: %__MODULE__{} def build(repo, ctx, actor), do: %__MODULE__{ctx: ctx, repo: repo, actor: actor} def enact(%Action{configuration: %ConfigurationAction{} = act}, actor) do ActionImpl.enact(act, actor) end end defimpl Console.Runbooks.Action, for: Kube.Runbook.ConfigurationAction do alias Console.Services.Plural alias Console.Runbooks.Actor alias Console.Services.Builds alias Kube.{Runbook, StatefulSetResize} def enact(%{updates: updates, stateful_sets: ss}, %Actor{ctx: ctx, repo: repo, actor: actor}) do with {:ok, vals} <- Plural.values_file(repo), {:ok, map} <- YamlElixir.read_from_string(vals), map <- make_updates(updates, map, ctx), {:ok, doc} <- Ymlr.document(map), :ok <- maybe_resize(ss, repo, ctx), _ <- Console.Deployer.update(repo, String.trim_leading(doc, "---\n"), :helm) do Builds.create(%{ type: :deploy, repository: repo, message: "updated configuration" }, actor) end end defp make_updates(updates, values, map) do Enum.reduce(updates, values, fn %Runbook.PathUpdate{path: path, value_from: from}, acc -> case map[from] do nil -> acc val -> Console.put_path(acc, path, val) end end) end defp maybe_resize([statefulset | rest], repo, ctx) do resize = %StatefulSetResize{ spec: %StatefulSetResize.Spec{ name: statefulset.name, persistent_volume: statefulset.persistent_volume, size: ctx[statefulset.value_from] } } namespace = Console.namespace(repo) name = "resize-#{statefulset.name}-#{statefulset.persistent_volume}" with {:val, val} when not is_nil(val) <- {:val, ctx[statefulset.value_from]}, {:ok, _} <- Kube.Client.create_statefulset_resize(namespace, name, resize), :ok <- poll_resize(namespace, name) do maybe_resize(rest, repo, ctx) else {:val, _} -> {:error, "#{statefulset.value_from} not set"} error -> error end end defp maybe_resize(_, _, _), do: :ok defp poll_resize(namespace, name, attempts \\ 0) defp poll_resize(_, _, attempts) when attempts >= 3, do: {:error, "statefulset resize in hung state"} defp poll_resize(namespace, name, attempts) do case Kube.Client.get_statefulset_resize(namespace, name) do {:ok, _} -> :timer.sleep(300) poll_resize(namespace, name, attempts + 1) _ -> :ok end end end
31.579545
98
0.653113
ff51f051dd0bbcb962bf3d79e5fd65715dbdc7b7
64
ex
Elixir
web/views/login_view.ex
shawn-mcginty/phoenix-webpack-skeleton
311559c860da97157d643d06cd2601aee81c6a3a
[ "MIT" ]
null
null
null
web/views/login_view.ex
shawn-mcginty/phoenix-webpack-skeleton
311559c860da97157d643d06cd2601aee81c6a3a
[ "MIT" ]
null
null
null
web/views/login_view.ex
shawn-mcginty/phoenix-webpack-skeleton
311559c860da97157d643d06cd2601aee81c6a3a
[ "MIT" ]
null
null
null
defmodule TimeVoice.LoginView do use TimeVoice.Web, :view end
16
32
0.796875
ff521993e9634a6d41dfe3541596e5ad75d0f17c
292
exs
Elixir
config/test.exs
aquamatt/ex_gdax
f3baf6aba40215b21e70712b89add30df7a873de
[ "MIT" ]
11
2017-08-31T01:18:17.000Z
2021-02-12T04:09:12.000Z
config/test.exs
aquamatt/ex_gdax
f3baf6aba40215b21e70712b89add30df7a873de
[ "MIT" ]
5
2017-10-27T20:03:00.000Z
2019-02-07T05:19:30.000Z
config/test.exs
aquamatt/ex_gdax
f3baf6aba40215b21e70712b89add30df7a873de
[ "MIT" ]
9
2017-08-31T01:14:29.000Z
2020-05-28T12:33:56.000Z
use Mix.Config config :ex_gdax, api_key: {:system, "GDAX_TEST_API_KEY"}, # Base.encode64("GDAX_TEST_API_SECRET") api_secret: {:system, "R0RBWF9URVNUX0FQSV9TRUNSRVQ="}, api_passphrase: {:system, "GDAX_TEST_API_PASSPHRASE"}, api_url: {:system, "https://api-public.sandbox.gdax.com"}
32.444444
59
0.736301
ff5225f3392892025062c905e5caa26da56dc324
519
exs
Elixir
test/ex_polygon/rest/stock_splits_test.exs
aai/ex_polygon
3bd6d8d0f1fbe4cd3fa939751c5ff00813eeeba3
[ "MIT" ]
null
null
null
test/ex_polygon/rest/stock_splits_test.exs
aai/ex_polygon
3bd6d8d0f1fbe4cd3fa939751c5ff00813eeeba3
[ "MIT" ]
null
null
null
test/ex_polygon/rest/stock_splits_test.exs
aai/ex_polygon
3bd6d8d0f1fbe4cd3fa939751c5ff00813eeeba3
[ "MIT" ]
null
null
null
defmodule ExPolygon.Rest.StockSplitsTest do use ExUnit.Case, async: false use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney doctest ExPolygon.Rest.HTTPClient setup_all do HTTPoison.start() :ok end @api_key System.get_env("POLYGON_API_KEY") test ".query returns an ok tuple with a list of splits" do use_cassette "rest/stock_splits/query_ok" do assert {:ok, splits} = ExPolygon.Rest.StockSplits.query("AAPL", @api_key) assert [%ExPolygon.Split{} = _ | _] = splits end end end
25.95
79
0.709056
ff5253ccf9f67c6b724dc921565657b247dfaa1f
656
ex
Elixir
lib/starship/handlers/wildcard/http/redirect.ex
probably-not/starship
aaa107bb0efec06fc841b0cae99cb69294887337
[ "MIT" ]
2
2019-10-22T08:22:22.000Z
2019-11-18T07:24:39.000Z
lib/starship/handlers/wildcard/http/redirect.ex
coby-spotim/starship
aaa107bb0efec06fc841b0cae99cb69294887337
[ "MIT" ]
null
null
null
lib/starship/handlers/wildcard/http/redirect.ex
coby-spotim/starship
aaa107bb0efec06fc841b0cae99cb69294887337
[ "MIT" ]
null
null
null
defmodule Starship.Handler.Wildcard.Http.Redirect do @moduledoc """ A simple wildcard handler for redirecting HTTP requests from non-secured to secured endpoints. """ alias Starship.Reactor.Conn @spec http(Conn.t(), map) :: {non_neg_integer, Conn.headers(), binary, map} def http(%Conn{} = conn, config) do {_, host} = List.keyfind(conn.headers, "host", 0) query = Enum.reduce(conn.query, "", fn {k, v}, a -> "#{a}&#{k}=#{v}" end) query = if byte_size(query) > 0, do: "?#{String.trim_leading(query, "&")}", else: "" ssl_path = "https://#{host}/#{conn.path}#{query}" {301, [{"Location", ssl_path}], "", config} end end
34.526316
96
0.628049
ff5262cfa371cc19a941f6a09aea1e519603c577
485
ex
Elixir
lib/gaga_web/views/error_view.ex
madvoidhq/gaga
1a539edc327135c7910a51bffd6824bddcba5f7d
[ "MIT" ]
13
2020-11-22T18:43:21.000Z
2022-02-12T00:57:45.000Z
lib/gaga_web/views/error_view.ex
madvoidhq/gaga
1a539edc327135c7910a51bffd6824bddcba5f7d
[ "MIT" ]
2
2020-11-25T16:58:15.000Z
2021-06-21T12:02:41.000Z
lib/gaga_web/views/error_view.ex
madvoidhq/gaga
1a539edc327135c7910a51bffd6824bddcba5f7d
[ "MIT" ]
4
2020-11-23T08:14:03.000Z
2022-01-25T08:18:41.000Z
defmodule GagaWeb.ErrorView do use GagaWeb, :view # If you want to customize a particular status code # for a certain format, you may uncomment below. # def render("500.html", _assigns) do # "Internal Server Error" # end # By default, Phoenix returns the status message from # the template name. For example, "404.html" becomes # "Not Found". def template_not_found(template, _assigns) do Phoenix.Controller.status_message_from_template(template) end end
28.529412
61
0.731959
ff527ad150161bfaa658a6b103f6476f362800be
11,187
exs
Elixir
apps/site/test/upcoming_route_departures_test.exs
paulswartz/dotcom
73e43e7c61afd96b1928608ce8316a7ed0eb1440
[ "MIT" ]
null
null
null
apps/site/test/upcoming_route_departures_test.exs
paulswartz/dotcom
73e43e7c61afd96b1928608ce8316a7ed0eb1440
[ "MIT" ]
65
2021-05-06T18:38:33.000Z
2022-03-28T20:50:04.000Z
apps/site/test/upcoming_route_departures_test.exs
paulswartz/dotcom
73e43e7c61afd96b1928608ce8316a7ed0eb1440
[ "MIT" ]
null
null
null
defmodule UpcomingRouteDeparturesTest do use ExUnit.Case, async: true import UpcomingRouteDepartures alias Routes.Route alias Schedules.{Schedule, Trip} alias Predictions.Prediction @time ~N[2017-01-01T22:30:00] @stop %Stops.Stop{id: 1} @schedules [ %Schedule{ route: %Route{id: "CR-1", type: 2}, stop: @stop, trip: %Trip{id: "CR-TRIP-1", headsign: "HS-1", direction_id: 0}, time: Timex.shift(@time, minutes: 5), pickup_type: 2, stop_sequence: 1 }, %Schedule{ route: %Route{id: "CR-1", type: 2}, stop: @stop, trip: %Trip{id: "CR-TRIP-2", headsign: "HS-2", direction_id: 0}, time: Timex.shift(@time, minutes: 5), pickup_type: 2, stop_sequence: 1 }, %Schedule{ route: %Route{id: "CR-1", type: 2}, stop: @stop, trip: %Trip{id: "CR-TRIP-3", headsign: "HS-2", direction_id: 0}, time: Timex.shift(@time, minutes: 20), pickup_type: 2, stop_sequence: 1 }, %Schedule{ route: %Route{id: "CR-1", type: 2}, stop: @stop, trip: %Trip{id: "Early Schedule", headsign: "HS-2", direction_id: 0}, time: Timex.shift(@time, minutes: -20), pickup_type: 2, stop_sequence: 1 }, %Schedule{ route: %Route{id: "CR-2", type: 2}, stop: @stop, trip: %Trip{id: "CR-TRIP-4", headsign: "HS-1", direction_id: 1}, time: Timex.shift(@time, minutes: 20), pickup_type: 2, stop_sequence: 1 }, %Schedule{ route: %Route{id: "Non departure", type: 2}, stop: @stop, trip: %Trip{id: "CR-TRIP-5", headsign: "HS-1", direction_id: 1}, time: Timex.shift(@time, minutes: 20), pickup_type: 1, stop_sequence: 1 }, %Schedule{ route: %Route{id: "Green-B", type: 0}, stop: @stop, trip: %Trip{id: "GREEN-1", headsign: "GREEN-1", direction_id: 0}, time: Timex.shift(@time, minutes: 5), pickup_type: 2, stop_sequence: 1 }, %Schedule{ route: %Route{id: "66", type: 3, name: "66"}, stop: @stop, trip: %Trip{id: "BUS-66-1", headsign: "BUS-HS-1", direction_id: 0}, time: Timex.shift(@time, minutes: 5), pickup_type: 2, stop_sequence: 1 }, %Schedule{ route: %Route{id: "9", type: 3, name: "9"}, stop: @stop, trip: %Trip{id: "BUS-9-1", headsign: "BUS-HS-2", direction_id: 0}, time: Timex.shift(@time, minutes: 5), pickup_type: 2, stop_sequence: 1 }, %Schedule{ route: %Route{id: "742", type: 3, name: "SL1"}, stop: @stop, trip: %Trip{id: "BUS-SL1-1", headsign: "BUS-HS-4", direction_id: 0}, time: Timex.shift(@time, minutes: 5), pickup_type: 2, stop_sequence: 1 } ] @predictions [ %Prediction{ route: %Route{id: "CR-1", type: 2}, id: 1, direction_id: 0, stop: @stop, trip: %Trip{id: "CR-TRIP-1", headsign: "HS-1", direction_id: 0}, time: Timex.shift(@time, minutes: 4), departing?: true, stop_sequence: 1 }, %Prediction{ route: %Route{id: "CR-2", type: 2}, direction_id: 1, id: 2, stop: @stop, trip: %Trip{id: "CR-TRIP-4", headsign: "HS-1", direction_id: 1}, time: Timex.shift(@time, minutes: 20), departing?: true, stop_sequence: 1 }, %Prediction{ route: %Route{id: "Green-B", type: 0}, direction_id: 0, id: 3, stop: @stop, trip: %Trip{id: "GREEN-1", headsign: "GREEN-1", direction_id: 0}, time: Timex.shift(@time, minutes: 4), departing?: true, stop_sequence: 1 }, %Prediction{ route: %Route{id: "Non departure", type: 2}, direction_id: 0, stop: @stop, trip: %Trip{id: "CR-TRIP-5", headsign: "HS-1", direction_id: 0}, time: Timex.shift(@time, minutes: 20), departing?: false, stop_sequence: 1 }, %Prediction{ direction_id: 1, route: %Route{id: "Early Prediction Route", type: 2}, stop: @stop, trip: %Trip{id: "Early Prediction Trip", headsign: "HS-1", direction_id: 1}, time: Timex.shift(@time, minutes: 20), departing?: true, stop_sequence: 1 } ] @green_line_schedules [ %Schedule{ route: %Route{id: "Green-E", type: 0}, stop: @stop, trip: %Trip{id: "GREEN-1", headsign: "Heath Street", direction_id: 0}, time: Timex.shift(@time, minutes: 5) }, %Schedule{ route: %Route{id: "Green-B", type: 0}, stop: @stop, trip: %Trip{id: "GREEN-2", headsign: "Boston College", direction_id: 0}, time: Timex.shift(@time, minutes: 5), stop_sequence: 1 } ] @green_line_predictions [ %Prediction{ id: "Green-Prediction-1", direction_id: 0, route: %Route{id: "Green-E", type: 0}, status: "Boarding", departing?: true, stop: @stop, stop_sequence: 1 }, %Prediction{ id: "Green-Prediction-2", direction_id: 0, route: %Route{id: "Green-E", type: 0}, status: "3 stops away", departing?: true, stop: @stop, stop_sequence: 1 }, %Prediction{ id: "Green-Prediction-3", direction_id: 0, route: %Route{id: "Green-E", type: 0}, status: "6 stops away", departing?: true, stop: @stop, stop_sequence: 1 }, %Prediction{ id: "Green-Prediction-4", direction_id: 0, route: %Route{id: "Green-B", type: 0}, status: "1 stop away", departing?: true, stop: @stop, stop_sequence: 1 }, %Prediction{ id: "Green-Prediction-5", direction_id: 0, route: %Route{id: "Green-B", type: 0}, trip: %Trip{id: "GREEN-2", headsign: "Boston College", direction_id: 0}, stop: @stop, time: Timex.shift(@time, minutes: 5), stop_sequence: 1, departing?: true }, %Prediction{ id: "Green-Prediction-6", status: "1 stop away", departing?: true, direction_id: 0, route: %Route{id: "Green-C", type: 0}, stop: @stop, stop_sequence: 1 }, %Prediction{ id: "Green-Prediction-5", status: "Approaching", departing?: true, direction_id: 0, route: %Route{id: "Green-C", type: 0}, stop: @stop, stop_sequence: 1 }, %Prediction{ id: "Green-Prediction-8", status: "Boarding", departing?: true, direction_id: 0, route: %Route{id: "Green-C", type: 0}, stop: @stop, stop_sequence: 1 } ] describe "build_mode_list/3" do test "PredictedSchedules are grouped by mode" do mode_map = @predictions |> build_mode_list(@schedules, @time) |> Map.new() for type_integer_val <- [0, 2, 3] do for route_time <- mode_map[Route.type_atom(type_integer_val)] do assert route_time.route.type == type_integer_val end end end test "UpcomingRouteDepartures are grouped by headsign" do mode_map = @predictions |> build_mode_list(@schedules, @time) |> Map.new() commuter_route_times = mode_map[:commuter_rail] for route_time <- commuter_route_times do for {headsign, predicted_schedules} <- route_time.departures do Enum.all?(predicted_schedules, &(PredictedSchedule.trip(&1).headsign == headsign)) end end end test "Only upcoming times are returned" do for {_mode, route_times} <- build_mode_list(@predictions, @schedules, @time) do for route_time <- route_times do for {_headsign, predicted_schedules} <- route_time.departures do for predicted_schedule <- predicted_schedules do assert Timex.after?(PredictedSchedule.time(predicted_schedule), @time) end end end end end test "Bus routes are sorted in increasing route number" do mode_map = @predictions |> build_mode_list(@schedules, @time) |> Map.new() bus_route_names = mode_map[:bus] |> Enum.map(& &1.route.name) assert bus_route_names == ["SL1", "9", "66"] end test "Only departing predicted_schedules are returned" do mode_map = @predictions |> build_mode_list(@schedules, @time) |> Map.new() commuter_route_times = mode_map[:commuter_rail] refute Enum.find(commuter_route_times, &(&1.route.id == "Non departure")) end test "Same headsign can occur in separate routes" do mode_map = @predictions |> build_mode_list(@schedules, @time) |> Map.new() commuter_route_times = mode_map[:commuter_rail] route1 = Enum.find(commuter_route_times, &(&1.route.id == "CR-1")) route2 = Enum.find(commuter_route_times, &(&1.route.id == "CR-2")) route1_headsigns = route1.departures |> Enum.map(&elem(&1, 0)) route2_headsigns = route2.departures |> Enum.map(&elem(&1, 0)) assert "HS-1" in route1_headsigns assert "HS-1" in route2_headsigns end test "Subway departures do not contain scheduled times" do mode_map = @predictions |> build_mode_list(@schedules, @time) |> Map.new() subway_route_times = mode_map[:subway] for route_departure <- subway_route_times do for {_headsign, departures} <- route_departure.departures do Enum.all?(departures, &is_nil(&1.schedule)) end end end end describe "Green line predictions" do test "Multiple greenline status predictions can be shown on single route" do mode_map = @green_line_predictions |> build_mode_list(@green_line_schedules, @time) |> Map.new() upcoming_e_line = mode_map[:subway] |> Enum.find(&(&1.route.id == "Green-E")) for {_headsign, departures} <- upcoming_e_line.departures do assert Enum.count(departures) > 1 for departure <- departures, departure.prediction do assert departure.prediction.status end end end test "are sorted by status" do status_extractor = fn {_headsign, deps} -> Enum.map(deps, & &1.prediction.status) end mode_map = @green_line_predictions |> build_mode_list(@green_line_schedules, @time) |> Map.new() upcoming_c_line = mode_map[:subway] |> Enum.find(&(&1.route.id == "Green-C")) c_line_statuses = upcoming_c_line.departures |> Enum.flat_map(status_extractor) assert c_line_statuses == ["Boarding", "Approaching", "1 stop away"] end test "are sorted by status then time" do id_extractor = fn {_headsign, deps} -> Enum.map(deps, & &1.prediction.id) end mode_map = @green_line_predictions |> build_mode_list(@green_line_schedules, @time) |> Map.new() upcoming_b_line = mode_map[:subway] |> Enum.find(&(&1.route.id == "Green-B")) b_line_ids = upcoming_b_line.departures |> Enum.flat_map(id_extractor) assert b_line_ids == ["Green-Prediction-4", "Green-Prediction-5"] end test "status-only predictions shown without related schedules" do mode_map = @green_line_predictions |> build_mode_list(@green_line_schedules, @time) |> Map.new() assert mode_map[:subway] |> Enum.find(&(&1.route.id == "Green-C")) end end end
31.691218
93
0.594082
ff5297dff4631c3216e96ca813891aad6a867b0a
1,018
ex
Elixir
test/support/apps/phx1_6/lib/phx1_6/application.ex
infinitered/torch
ea55326f9c3521933c86af398bfea584e7ffe1ed
[ "MIT" ]
203
2016-10-28T00:37:15.000Z
2019-01-21T16:33:42.000Z
test/support/apps/phx1_6/lib/phx1_6/application.ex
jamonholmgren/torch
ea55326f9c3521933c86af398bfea584e7ffe1ed
[ "MIT" ]
61
2016-11-01T02:29:22.000Z
2019-01-01T22:35:21.000Z
test/support/apps/phx1_6/lib/phx1_6/application.ex
jamonholmgren/torch
ea55326f9c3521933c86af398bfea584e7ffe1ed
[ "MIT" ]
37
2016-11-01T18:13:55.000Z
2019-01-07T00:35:48.000Z
defmodule Phx16.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application @impl true def start(_type, _args) do children = [ # Start the Ecto repository Phx16.Repo, # Start the Telemetry supervisor Phx16Web.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: Phx16.PubSub}, # Start the Endpoint (http/https) Phx16Web.Endpoint # Start a worker by calling: Phx16.Worker.start_link(arg) # {Phx16.Worker, arg} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Phx16.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. @impl true def config_change(changed, _new, removed) do Phx16Web.Endpoint.config_change(changed, removed) :ok end end
27.513514
63
0.694499
ff52a591961324d61a7d6a367d3017acf11d7c6c
720
ex
Elixir
lib/ex_config_eldap/helpers.ex
sega-yarkin/ex_config_eldap
0f91ce0814f37d76b7637dccbab3e4f51872b597
[ "MIT" ]
null
null
null
lib/ex_config_eldap/helpers.ex
sega-yarkin/ex_config_eldap
0f91ce0814f37d76b7637dccbab3e4f51872b597
[ "MIT" ]
null
null
null
lib/ex_config_eldap/helpers.ex
sega-yarkin/ex_config_eldap
0f91ce0814f37d76b7637dccbab3e4f51872b597
[ "MIT" ]
null
null
null
defmodule ExConfigEldap.Helpers do @moduledoc """ A set of helpers for `:eldap` library. """ @doc """ A small helper to clarify which format is needed by `:eldap` to work correctly with UTF8 strings. """ @spec string_to_list(String.t) :: [byte] def string_to_list(str) when is_binary(str), do: :binary.bin_to_list(str) @compile {:inline, string_to_list: 1} @doc """ Helper for ExConfig to transform Elixir string value to valid `:eldap` string. """ @spec from_string(ExConfig.Param.t | map) :: ExConfig.Param.t | map def from_string(%ExConfig.Param{data: data} = param) when is_binary(data) do %{param | data: string_to_list(data)} end def from_string(param = %{}), do: param end
31.304348
80
0.688889
ff52a9c3721cb1b294edd5fa672a69b94d79ea6b
1,275
ex
Elixir
clients/firestore/lib/google_api/firestore/v1beta1/connection.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/firestore/lib/google_api/firestore/v1beta1/connection.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/firestore/lib/google_api/firestore/v1beta1/connection.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.Firestore.V1beta1.Connection do @moduledoc """ Handle Tesla connections for GoogleApi.Firestore.V1beta1. """ @type t :: Tesla.Env.client() use GoogleApi.Gax.Connection, scopes: [ # See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account. "https://www.googleapis.com/auth/cloud-platform", # View and manage your Google Cloud Datastore data "https://www.googleapis.com/auth/datastore" ], otp_app: :google_api_firestore, base_url: "https://firestore.googleapis.com/" end
35.416667
114
0.736471
ff52be2fece81134ba761aaf9caaecf9a1d68a4c
4,477
ex
Elixir
clients/slides/lib/google_api/slides/v1/model/paragraph_style.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/slides/lib/google_api/slides/v1/model/paragraph_style.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/slides/lib/google_api/slides/v1/model/paragraph_style.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.Slides.V1.Model.ParagraphStyle do @moduledoc """ Styles that apply to a whole paragraph. If this text is contained in a shape with a parent placeholder, then these paragraph styles may be inherited from the parent. Which paragraph styles are inherited depend on the nesting level of lists: * A paragraph not in a list will inherit its paragraph style from the paragraph at the 0 nesting level of the list inside the parent placeholder. * A paragraph in a list will inherit its paragraph style from the paragraph at its corresponding nesting level of the list inside the parent placeholder. Inherited paragraph styles are represented as unset fields in this message. ## Attributes * `alignment` (*type:* `String.t`, *default:* `nil`) - The text alignment for this paragraph. * `direction` (*type:* `String.t`, *default:* `nil`) - The text direction of this paragraph. If unset, the value defaults to LEFT_TO_RIGHT since text direction is not inherited. * `indentEnd` (*type:* `GoogleApi.Slides.V1.Model.Dimension.t`, *default:* `nil`) - The amount indentation for the paragraph on the side that corresponds to the end of the text, based on the current text direction. If unset, the value is inherited from the parent. * `indentFirstLine` (*type:* `GoogleApi.Slides.V1.Model.Dimension.t`, *default:* `nil`) - The amount of indentation for the start of the first line of the paragraph. If unset, the value is inherited from the parent. * `indentStart` (*type:* `GoogleApi.Slides.V1.Model.Dimension.t`, *default:* `nil`) - The amount indentation for the paragraph on the side that corresponds to the start of the text, based on the current text direction. If unset, the value is inherited from the parent. * `lineSpacing` (*type:* `number()`, *default:* `nil`) - The amount of space between lines, as a percentage of normal, where normal is represented as 100.0. If unset, the value is inherited from the parent. * `spaceAbove` (*type:* `GoogleApi.Slides.V1.Model.Dimension.t`, *default:* `nil`) - The amount of extra space above the paragraph. If unset, the value is inherited from the parent. * `spaceBelow` (*type:* `GoogleApi.Slides.V1.Model.Dimension.t`, *default:* `nil`) - The amount of extra space below the paragraph. If unset, the value is inherited from the parent. * `spacingMode` (*type:* `String.t`, *default:* `nil`) - The spacing mode for the paragraph. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :alignment => String.t() | nil, :direction => String.t() | nil, :indentEnd => GoogleApi.Slides.V1.Model.Dimension.t() | nil, :indentFirstLine => GoogleApi.Slides.V1.Model.Dimension.t() | nil, :indentStart => GoogleApi.Slides.V1.Model.Dimension.t() | nil, :lineSpacing => number() | nil, :spaceAbove => GoogleApi.Slides.V1.Model.Dimension.t() | nil, :spaceBelow => GoogleApi.Slides.V1.Model.Dimension.t() | nil, :spacingMode => String.t() | nil } field(:alignment) field(:direction) field(:indentEnd, as: GoogleApi.Slides.V1.Model.Dimension) field(:indentFirstLine, as: GoogleApi.Slides.V1.Model.Dimension) field(:indentStart, as: GoogleApi.Slides.V1.Model.Dimension) field(:lineSpacing) field(:spaceAbove, as: GoogleApi.Slides.V1.Model.Dimension) field(:spaceBelow, as: GoogleApi.Slides.V1.Model.Dimension) field(:spacingMode) end defimpl Poison.Decoder, for: GoogleApi.Slides.V1.Model.ParagraphStyle do def decode(value, options) do GoogleApi.Slides.V1.Model.ParagraphStyle.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Slides.V1.Model.ParagraphStyle do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
63.056338
618
0.726603
ff52c8b81cfd4859a78d7f24e06a71c23b9cb923
205
ex
Elixir
web/views/current_user_view.ex
nsarno/winter
a65a6aa61d2b1af39277338277f8b3f479643939
[ "MIT" ]
3
2015-08-24T11:44:19.000Z
2016-10-01T21:37:05.000Z
web/views/current_user_view.ex
nsarno/winter
a65a6aa61d2b1af39277338277f8b3f479643939
[ "MIT" ]
null
null
null
web/views/current_user_view.ex
nsarno/winter
a65a6aa61d2b1af39277338277f8b3f479643939
[ "MIT" ]
null
null
null
defmodule Storm.CurrentUserView do use Storm.Web, :view def render("index.json", %{current_user: current_user}) do %{current_user: render_one(current_user, Storm.UserView, "user.json")} end end
25.625
74
0.736585
ff52de9ef1e59cd0989b1ab052c5c7424b4c8798
2,912
exs
Elixir
day18_test.exs
hermanstehouwer/adventofcode2021
9000f0d3d96825f9ca1bb047cd7530e336022a16
[ "CC0-1.0" ]
null
null
null
day18_test.exs
hermanstehouwer/adventofcode2021
9000f0d3d96825f9ca1bb047cd7530e336022a16
[ "CC0-1.0" ]
null
null
null
day18_test.exs
hermanstehouwer/adventofcode2021
9000f0d3d96825f9ca1bb047cd7530e336022a16
[ "CC0-1.0" ]
null
null
null
ExUnit.start() defmodule Testing do use ExUnit.Case, async: true test "test_explode" do pairs = [ {[[[[[9,8],1],2],3],4], [[[[0,9],2],3],4]}, {[7,[6,[5,[4,[3,2]]]]], [7,[6,[5,[7,0]]]]}, {[[6,[5,[4,[3,2]]]],1], [[6,[5,[7,0]]],3]}, {[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]], [[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]}, {[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]], [[3,[2,[8,0]]],[9,[5,[7,0]]]]} ] for {a,b} <- pairs do {true, snail_num, _la, _ra} = Snails.snail_explode(a, 0) assert snail_num == b end end test "test_addition" do #NOTE: snail_add is a reducer, so the left element is the to_process thing and the right the acumulator assert Snails.snail_add([1,1],[[[[4,3],4],4],[7,[[8,4],9]]]) == [[[[0,7],4],[[7,8],[6,0]]],[8,1]] end test "test_full_small" do added = [[1,1], [2,2], [3,3], [4,4]] |> Enum.reduce(&Snails.snail_add/2) assert added == [[[[1,1],[2,2]],[3,3]],[4,4]] end test "test_full_2" do added = [[1,1], [2,2], [3,3], [4,4], [5,5]] |> Enum.reduce(&Snails.snail_add/2) assert added == [[[[3,0],[5,3]],[4,4]],[5,5]] end test "test_full_3" do added = [[1,1], [2,2], [3,3], [4,4], [5,5], [6,6]] |> Enum.reduce(&Snails.snail_add/2) assert added == [[[[5,0],[7,4]],[5,5]],[6,6]] end test "test_full_large" do added = [[[[0,[4,5]],[0,0]],[[[4,5],[2,6]],[9,5]]], [7,[[[3,7],[4,3]],[[6,3],[8,8]]]], [[2,[[0,8],[3,4]]],[[[6,7],1],[7,[1,6]]]], [[[[2,4],7],[6,[0,5]]],[[[6,8],[2,8]],[[2,1],[4,5]]]], [7,[5,[[3,8],[1,4]]]], [[2,[2,2]],[8,[8,1]]], [2,9], [1,[[[9,3],9],[[9,0],[0,7]]]], [[[5,[7,4]],7],1], [[[[4,2],2],6],[8,7]]] |> Enum.reduce(&Snails.snail_add/2) assert added == [[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]] end test "test_magnitudes" do pairs = [ {[[1,2],[[3,4],5]], 143}, {[[[[0,7],4],[[7,8],[6,0]]],[8,1]], 1384}, {[[[[1,1],[2,2]],[3,3]],[4,4]], 445}, {[[[[3,0],[5,3]],[4,4]],[5,5]], 791}, {[[[[5,0],[7,4]],[5,5]],[6,6]], 1137}, {[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]], 3488} ] for {a,b} <- pairs do assert Snails.magnitude(a) == b end end test "final test" do input = [[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]], [[[5,[2,8]],4],[5,[[9,9],0]]], [6,[[[6,2],[5,6]],[[7,6],[4,7]]]], [[[6,[0,7]],[0,9]],[4,[9,[9,0]]]], [[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]], [[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]], [[[[5,4],[7,7]],8],[[8,3],8]], [[9,3],[[9,9],[6,[4,9]]]], [[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]], [[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]]] |> Enum.reduce(&Snails.snail_add/2) assert input == [[[[6,6],[7,6]],[[7,7],[7,0]]],[[[7,7],[7,7]],[[7,8],[9,9]]]] assert Snails.magnitude(input) == 4140 end end
27.733333
107
0.380495
ff5313187efa59c26fdb8979a7b11208f495827d
2,993
ex
Elixir
apps/astarte_appengine_api/lib/astarte_appengine_api_web/controllers/interface_values_controller.ex
matt-mazzucato/astarte
34d84941a5019efc42321052f7f34b7d907a38f2
[ "Apache-2.0" ]
4
2018-03-15T14:26:43.000Z
2019-12-20T15:07:10.000Z
apps/astarte_appengine_api/lib/astarte_appengine_api_web/controllers/interface_values_controller.ex
matt-mazzucato/astarte
34d84941a5019efc42321052f7f34b7d907a38f2
[ "Apache-2.0" ]
27
2018-06-28T16:00:07.000Z
2019-12-19T10:05:36.000Z
apps/astarte_appengine_api/lib/astarte_appengine_api_web/controllers/interface_values_controller.ex
matt-mazzucato/astarte
34d84941a5019efc42321052f7f34b7d907a38f2
[ "Apache-2.0" ]
2
2018-03-16T09:37:29.000Z
2019-11-18T17:37:42.000Z
# # This file is part of Astarte. # # Copyright 2017 Ispirata Srl # # 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. defmodule Astarte.AppEngine.APIWeb.InterfaceValuesController do use Astarte.AppEngine.APIWeb, :controller alias Astarte.AppEngine.API.Device alias Astarte.AppEngine.API.Device.InterfaceValues plug Astarte.AppEngine.APIWeb.Plug.JoinPath plug Astarte.AppEngine.APIWeb.Plug.LogDeviceId plug Astarte.AppEngine.APIWeb.Plug.LogInterface plug Astarte.AppEngine.APIWeb.Plug.LogPath action_fallback Astarte.AppEngine.APIWeb.FallbackController def index(conn, %{"realm_name" => realm_name, "device_id" => device_id}) do with {:ok, interfaces} <- Device.list_interfaces(realm_name, device_id) do render(conn, "index.json", interfaces: interfaces) end end def show( conn, %{ "realm_name" => realm_name, "device_id" => device_id, "interface" => interface, "path" => path } = parameters ) do with {:ok, %InterfaceValues{} = interface_values} <- Device.get_interface_values!(realm_name, device_id, interface, path, parameters) do render(conn, "show.json", interface_values: interface_values) end end def show( conn, %{"realm_name" => realm_name, "device_id" => device_id, "interface" => interface} = parameters ) do with {:ok, %InterfaceValues{} = interface_values} <- Device.get_interface_values!(realm_name, device_id, interface, parameters) do render(conn, "show.json", interface_values: interface_values) end end def update( conn, %{ "realm_name" => realm_name, "device_id" => device_id, "interface" => interface, "path" => path, "data" => value } = parameters ) do with {:ok, %InterfaceValues{} = interface_values} <- Device.update_interface_values!( realm_name, device_id, interface, path, value, parameters ) do render(conn, "show.json", interface_values: interface_values) end end def delete(conn, %{ "realm_name" => realm_name, "device_id" => device_id, "interface" => interface, "path" => path }) do with :ok <- Device.delete_interface_values(realm_name, device_id, interface, path) do send_resp(conn, :no_content, "") end end end
31.177083
94
0.646843
ff532eba1f05f4fe5f440830d24285717ee3b24e
1,279
ex
Elixir
lib/tinkoff_invest/model/order_book.ex
reetou/tinkoff-invest-elixir
5eeb27a89c65be6cb2b34d965332bbcc17f3f244
[ "MIT" ]
1
2021-05-26T11:38:42.000Z
2021-05-26T11:38:42.000Z
lib/tinkoff_invest/model/order_book.ex
reetou/tinkoff-invest-elixir
5eeb27a89c65be6cb2b34d965332bbcc17f3f244
[ "MIT" ]
null
null
null
lib/tinkoff_invest/model/order_book.ex
reetou/tinkoff-invest-elixir
5eeb27a89c65be6cb2b34d965332bbcc17f3f244
[ "MIT" ]
null
null
null
defmodule TinkoffInvest.Model.OrderBook do use TypedStruct alias TinkoffInvest.Model.OrderBook.Bid alias TinkoffInvest.Model.OrderBook.Ask typedstruct enforce: true do field(:figi, String.t()) field(:trade_status, String.t()) field(:depth, integer()) field(:min_price_increment, float()) field(:face_value, float()) field(:last_price, float()) field(:close_price, float()) field(:limit_up, float()) field(:limit_down, float()) field(:bids, list(Bid.t())) field(:asks, list(Ask.t())) end def new( %{ "figi" => figi, "tradeStatus" => trade_status, "depth" => depth, "minPriceIncrement" => min_price_increment, "lastPrice" => last_price, "closePrice" => close_price, "bids" => bids, "asks" => asks } = params ) do %__MODULE__{ figi: figi, trade_status: trade_status, depth: depth, min_price_increment: min_price_increment, face_value: Map.get(params, "faceValue"), last_price: last_price, close_price: close_price, limit_up: Map.get(params, "limitUp"), limit_down: Map.get(params, "limitDown"), bids: Bid.new(bids), asks: Ask.new(asks) } end end
27.212766
53
0.602033
ff533715966253f81f392f662ecf20c694d12cbb
519
ex
Elixir
ex/apps/corals/lib/corals/server.ex
limadelic/corals
be1730551ce7420f12b3b689c79ebd7571892d53
[ "MIT" ]
null
null
null
ex/apps/corals/lib/corals/server.ex
limadelic/corals
be1730551ce7420f12b3b689c79ebd7571892d53
[ "MIT" ]
null
null
null
ex/apps/corals/lib/corals/server.ex
limadelic/corals
be1730551ce7420f12b3b689c79ebd7571892d53
[ "MIT" ]
null
null
null
defmodule Corals.Server do use GenServer alias Corals.Rules import Corals.Resolver def start_link name, spec do GenServer.start_link __MODULE__, spec, name: name end def init spec do {:ok, spec} end def handle_call {:resolve, opts, user_opts}, _, %{require: deps, rules: rules} = spec do {:reply, {:ok, resolve(opts, user_opts, deps, rules)}, spec} end defp resolve opts, user_opts, deps, rules do opts |> Rules.resolve_raw(deps, user_opts) |> resolve_raw(rules, user_opts) end end
24.714286
90
0.701349
ff533a08aca45d92b424312d828039ac38ff8c36
1,048
exs
Elixir
daily_meals/config/config.exs
joabehenrique/daily-meals
ea8919a45dc155046289c96854348bd7ed89c1fb
[ "MIT" ]
null
null
null
daily_meals/config/config.exs
joabehenrique/daily-meals
ea8919a45dc155046289c96854348bd7ed89c1fb
[ "MIT" ]
null
null
null
daily_meals/config/config.exs
joabehenrique/daily-meals
ea8919a45dc155046289c96854348bd7ed89c1fb
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. # General application configuration use Mix.Config config :daily_meals, ecto_repos: [DailyMeals.Repo] # Configures the endpoint config :daily_meals, DailyMealsWeb.Endpoint, url: [host: "localhost"], secret_key_base: "FtuR11z012ulOcsoBe4Mfq1wwzeHcCIXGjbZOR0QZEpbJ5YjplmQDNyRFi5A5xJw", render_errors: [view: DailyMealsWeb.ErrorView, accepts: ~w(json), layout: false], pubsub_server: DailyMeals.PubSub, live_view: [signing_salt: "hAWCA7KP"] # 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 "#{Mix.env()}.exs"
32.75
86
0.775763
ff53563ab0a493f3944888ae413f19b0f9fd2761
900
ex
Elixir
lib/randpass.ex
marioluigiman/elixirpasswordgen
93f815e5741ae2cc839e0f254f4449dbc8481491
[ "MIT" ]
null
null
null
lib/randpass.ex
marioluigiman/elixirpasswordgen
93f815e5741ae2cc839e0f254f4449dbc8481491
[ "MIT" ]
null
null
null
lib/randpass.ex
marioluigiman/elixirpasswordgen
93f815e5741ae2cc839e0f254f4449dbc8481491
[ "MIT" ]
null
null
null
:random.seed(:os.timestamp) defmodule RandPass do def randomascii() do asciilist = Enum.to_list(48 .. 57) asciilist = Enum.concat(asciilist, Enum.to_list(65 .. 90)) asciilist = Enum.concat(asciilist, Enum.to_list(97 .. 122)) IO.chardata_to_string([Enum.random(asciilist)]) end def randomstring(str \\ "",length) do if (length > 0) do randomstring(str <> randomascii(), length - 1) else str end end def randomlist(str \\ "", lines, length) do if (lines > 0) do randomlist(str <> randomstring(length) <> "\n", lines - 1, length) else str end end def writetoList(filename, lines \\ 3, length \\ 12) do {:ok, file} = File.open(filename, [:write]) str = randomlist(lines, length) IO.binwrite(file, str) File.close file str end def generatePassword(length) do randomstring(length) end end
20.930233
72
0.626667
ff535f933d79a1d8a5b647f1190328c130f29b04
1,517
ex
Elixir
clients/dataflow/lib/google_api/dataflow/v1b3/model/parameter.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/dataflow/lib/google_api/dataflow/v1b3/model/parameter.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/parameter.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # 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 elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.Dataflow.V1b3.Model.Parameter do @moduledoc """ Structured data associated with this message. ## Attributes * `key` (*type:* `String.t`, *default:* `nil`) - Key or name for this parameter. * `value` (*type:* `any()`, *default:* `nil`) - Value for this parameter. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :key => String.t(), :value => any() } field(:key) field(:value) end defimpl Poison.Decoder, for: GoogleApi.Dataflow.V1b3.Model.Parameter do def decode(value, options) do GoogleApi.Dataflow.V1b3.Model.Parameter.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dataflow.V1b3.Model.Parameter do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
30.34
84
0.71325
ff53781b92b359bf9f2b976c105e2e9d53a845e5
163
exs
Elixir
project/gamenect/priv/repo/migrations/20160930150225_remove_user_join_date.exs
daemonfire300/learning_phoenix
0ab0cb1feacda4ec5c0ab0a5324835a150db22ab
[ "MIT" ]
null
null
null
project/gamenect/priv/repo/migrations/20160930150225_remove_user_join_date.exs
daemonfire300/learning_phoenix
0ab0cb1feacda4ec5c0ab0a5324835a150db22ab
[ "MIT" ]
null
null
null
project/gamenect/priv/repo/migrations/20160930150225_remove_user_join_date.exs
daemonfire300/learning_phoenix
0ab0cb1feacda4ec5c0ab0a5324835a150db22ab
[ "MIT" ]
null
null
null
defmodule Gamenect.Repo.Migrations.RemoveUserJoinDate do use Ecto.Migration def change do alter table(:users) do remove :joindate end end end
16.3
56
0.723926
ff53ca2e2c4c2d444d02315ef981b500dfeaca69
2,141
ex
Elixir
clients/app_engine/lib/google_api/app_engine/v1/model/network_utilization.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/app_engine/lib/google_api/app_engine/v1/model/network_utilization.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/app_engine/lib/google_api/app_engine/v1/model/network_utilization.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "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.AppEngine.V1.Model.NetworkUtilization do @moduledoc """ Target scaling by network usage. Only applicable in the App Engine flexible environment. ## Attributes - targetReceivedBytesPerSecond (integer()): Target bytes received per second. Defaults to: `null`. - targetReceivedPacketsPerSecond (integer()): Target packets received per second. Defaults to: `null`. - targetSentBytesPerSecond (integer()): Target bytes sent per second. Defaults to: `null`. - targetSentPacketsPerSecond (integer()): Target packets sent per second. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :targetReceivedBytesPerSecond => any(), :targetReceivedPacketsPerSecond => any(), :targetSentBytesPerSecond => any(), :targetSentPacketsPerSecond => any() } field(:targetReceivedBytesPerSecond) field(:targetReceivedPacketsPerSecond) field(:targetSentBytesPerSecond) field(:targetSentPacketsPerSecond) end defimpl Poison.Decoder, for: GoogleApi.AppEngine.V1.Model.NetworkUtilization do def decode(value, options) do GoogleApi.AppEngine.V1.Model.NetworkUtilization.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AppEngine.V1.Model.NetworkUtilization do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.561404
104
0.752452
ff53e403c4a854693c9ca092610c5c5e50fce22c
17
exs
Elixir
config/test.exs
NeoAlchemist/ex_nexmo
e4f8d56e1b9fe3b57f352c540936e77eb31a5f76
[ "MIT" ]
30
2017-07-03T23:53:37.000Z
2021-03-14T21:27:14.000Z
config/test.exs
NeoAlchemist/ex_nexmo
e4f8d56e1b9fe3b57f352c540936e77eb31a5f76
[ "MIT" ]
4
2016-09-26T20:00:20.000Z
2018-09-04T01:34:34.000Z
config/test.exs
NeoAlchemist/ex_nexmo
e4f8d56e1b9fe3b57f352c540936e77eb31a5f76
[ "MIT" ]
7
2017-02-02T01:32:52.000Z
2021-09-04T00:26:45.000Z
use Mix.Config
4.25
14
0.705882
ff5401d3d90865979fac8c4ce0410995c18d4edb
57
ex
Elixir
lib/fotd_web/views/layout_view.ex
aesmail/fotd
03bc3f145ed2aa30bafa25198570c380a8d0ad31
[ "Apache-2.0" ]
1
2018-11-24T12:01:30.000Z
2018-11-24T12:01:30.000Z
lib/fotd_web/views/layout_view.ex
wojtekmach/fotd
f485b6b8d4d9e7b3385699f6175d1bc61d13035a
[ "Apache-2.0" ]
null
null
null
lib/fotd_web/views/layout_view.ex
wojtekmach/fotd
f485b6b8d4d9e7b3385699f6175d1bc61d13035a
[ "Apache-2.0" ]
null
null
null
defmodule FotdWeb.LayoutView do use FotdWeb, :view end
14.25
31
0.789474