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
03ad30def2a88183197f09f337c269dcfd06b95f
626
exs
Elixir
functions/fizzbuzz.exs
hckrtst/elixir-kata
6bee22e46443207aee77418e62ceec2569fffdba
[ "MIT" ]
1
2016-09-22T03:48:10.000Z
2016-09-22T03:48:10.000Z
functions/fizzbuzz.exs
hckrtst/elixir-kata
6bee22e46443207aee77418e62ceec2569fffdba
[ "MIT" ]
null
null
null
functions/fizzbuzz.exs
hckrtst/elixir-kata
6bee22e46443207aee77418e62ceec2569fffdba
[ "MIT" ]
null
null
null
# Write a function that takes three arguments. If the first two are zero, return “FizzBuzz.” If the first is zero, return “Fizz.” # If the second is zero, return “Buzz.” Otherwise return the third argument. fizzy = fn #explicitly defining for context a=0,b=0,c=_ -> "FizzBuzz" # this is way cleaner 0,_,_ -> "Fizz" _,0,_ -> "Buzz" _,_,c -> c end fizzy.(0,0,3) |> IO.puts fizzy.(0,1,3) |> IO.puts fizzy.(1,0,1) |> IO.puts fizzy.(1,1,4) |> IO.puts remmy = fn n -> fizzy.(rem(n,3), rem(n,5), n) end [remmy.(10), remmy.(11), remmy.(12), remmy.(13), remmy.(14), remmy.(15), remmy.(16)] |> inspect |> IO.puts
31.3
130
0.616613
03adfebec5c2f0aa983ebe35b8982a81f43cd9e8
132
exs
Elixir
test/mapsi_test.exs
hergetto/mapsi
115440f770afc5f5d19ad9c9a68dac6e2f5abf8d
[ "MIT" ]
1
2022-02-03T12:23:29.000Z
2022-02-03T12:23:29.000Z
test/mapsi_test.exs
hergetto/mapsi
115440f770afc5f5d19ad9c9a68dac6e2f5abf8d
[ "MIT" ]
null
null
null
test/mapsi_test.exs
hergetto/mapsi
115440f770afc5f5d19ad9c9a68dac6e2f5abf8d
[ "MIT" ]
null
null
null
defmodule MapsiTest do use ExUnit.Case doctest Mapsi test "greets the world" do assert Mapsi.hello() == :world end end
14.666667
34
0.69697
03ae16cb88623847ecb91d9e43d7ea2fb7f0af33
502
ex
Elixir
apps/admin_app/lib/admin_app/calculator/calculator_context.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
456
2018-09-20T02:40:59.000Z
2022-03-07T08:53:48.000Z
apps/admin_app/lib/admin_app/calculator/calculator_context.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
273
2018-09-19T06:43:43.000Z
2021-08-07T12:58:26.000Z
apps/admin_app/lib/admin_app/calculator/calculator_context.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
122
2018-09-26T16:32:46.000Z
2022-03-13T11:44:19.000Z
defmodule AdminApp.Promotion.CalculatorContext do @moduledoc false def preferences(calculator, params) do changeset = calculator.changeset(struct!(calculator), %{}) data = changeset.types |> Stream.filter(fn {_data, type} -> type != :binary_id end) |> Enum.map(fn {data, type} -> %{key: data, type: get_data_type(type), value: params[to_string(data)]} end) %{name: calculator, data: data} end def get_data_type(:decimal) do "input" end end
23.904762
79
0.64741
03ae578f8ca092434d358d7a89f1c9038421a5ae
1,636
ex
Elixir
clients/manufacturers/lib/google_api/manufacturers/v1/model/count.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/manufacturers/lib/google_api/manufacturers/v1/model/count.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/manufacturers/lib/google_api/manufacturers/v1/model/count.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.Manufacturers.V1.Model.Count do @moduledoc """ The number of products in a single package. For more information, see https://support.google.com/manufacturers/answer/6124116#count. ## Attributes * `unit` (*type:* `String.t`, *default:* `nil`) - The unit in which these products are counted. * `value` (*type:* `String.t`, *default:* `nil`) - The numeric value of the number of products in a package. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :unit => String.t(), :value => String.t() } field(:unit) field(:value) end defimpl Poison.Decoder, for: GoogleApi.Manufacturers.V1.Model.Count do def decode(value, options) do GoogleApi.Manufacturers.V1.Model.Count.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Manufacturers.V1.Model.Count do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.72
134
0.720049
03ae719366e03d40a99e677aa13fc2003241934b
561
ex
Elixir
lib/nidavellir/supervisor.ex
GabrielMalakias/nidavellir
9e786f6813aa3e014f44bdedbf88a7c8259fe1f9
[ "MIT" ]
1
2021-01-20T04:15:01.000Z
2021-01-20T04:15:01.000Z
lib/nidavellir/supervisor.ex
GabrielMalakias/nidavellir
9e786f6813aa3e014f44bdedbf88a7c8259fe1f9
[ "MIT" ]
null
null
null
lib/nidavellir/supervisor.ex
GabrielMalakias/nidavellir
9e786f6813aa3e014f44bdedbf88a7c8259fe1f9
[ "MIT" ]
null
null
null
defmodule Nidavellir.Supervisor do @moduledoc """ It just creates the supervisor tree for this project """ use Supervisor def start_link(opts) do Supervisor.start_link(__MODULE__, :ok, opts) end def init(:ok) do children = [ worker(Nidavellir.Mqtt.Connection, [%{}, [name: :mqtt]]), worker(Nidavellir.Mqtt.ReconnectServer, [[]])#, # Plug.Adapters.Cowboy.child_spec(scheme: :http, plug: Nidavellir.Router, options: [port: 4001]) ] opts = [strategy: :one_for_one] supervise(children, opts) end end
22.44
107
0.659537
03aec8ffb07ff93a6e0f4a0be530de6b2261a6cf
25,058
ex
Elixir
lib/cldr/backend/cldr.ex
kianmeng/cldr
d0510a55b5406e4604d8823a98ff6b6aea2bb397
[ "Apache-2.0" ]
null
null
null
lib/cldr/backend/cldr.ex
kianmeng/cldr
d0510a55b5406e4604d8823a98ff6b6aea2bb397
[ "Apache-2.0" ]
null
null
null
lib/cldr/backend/cldr.ex
kianmeng/cldr
d0510a55b5406e4604d8823a98ff6b6aea2bb397
[ "Apache-2.0" ]
null
null
null
defmodule Cldr.Backend do @moduledoc false def define_backend_functions(config) do backend = config.backend quote location: :keep, bind_quoted: [config: Macro.escape(config), backend: backend] do @doc """ Returns a list of the known locale names. Known locales are those locales which are the subset of all CLDR locales that have been configured for use either in this module or in `Gettext`. """ alias Cldr.{Locale, Config, LanguageTag} @omit_locales [Config.root_locale_name()] @known_locale_names Locale.Loader.known_locale_names(config) -- @omit_locales def known_locale_names do @known_locale_names end @doc """ Returns the default `locale`. ## Example iex> #{inspect(__MODULE__)}.default_locale() %Cldr.LanguageTag{ backend: #{inspect(__MODULE__)}, canonical_locale_name: "en-001", cldr_locale_name: :"en-001", language_subtags: [], extensions: %{}, gettext_locale_name: "en", language: "en", locale: %{}, private_use: [], rbnf_locale_name: :en, requested_locale_name: "en-001", script: :Latn, territory: :"001", transform: %{}, language_variants: [] } """ @default_locale config |> Config.default_locale_name() |> Config.language_tag() |> Map.put(:backend, __MODULE__) @compile {:inline, default_locale: 0} @spec default_locale :: LanguageTag.t() | no_return() def default_locale do Cldr.Locale.put_gettext_locale_name(@default_locale) end @doc """ Returns the default territory when a locale does not specify one and none can be inferred. ## Example iex> #{inspect(__MODULE__)}.default_territory() :"001" """ @spec default_territory() :: Locale.territory_code() def default_territory do Cldr.Locale.territory_from_locale(@default_locale) end @doc """ Returns a list of the locales names that are configured, but not known in CLDR. Since there is a compile-time exception raised if there are any unknown locales this function should always return an empty list. """ @unknown_locale_names Config.unknown_locale_names(config) @spec unknown_locale_names() :: [Locale.locale_name()] def unknown_locale_names do @unknown_locale_names end @doc """ Returns a list of locale names which have rules-based number formats (RBNF). """ @known_rbnf_locale_names Locale.Loader.known_rbnf_locale_names(config) @spec known_rbnf_locale_names() :: [Locale.locale_name()] def known_rbnf_locale_names do @known_rbnf_locale_names end @doc """ Returns a list of GetText locale names but in CLDR format with underscore replaced by hyphen in order to facilitate comparisons with `Cldr` locale names. """ @known_gettext_locale_names Config.known_gettext_locale_names(config) @spec known_gettext_locale_names() :: [String.t()] def known_gettext_locale_names do @known_gettext_locale_names end @doc """ Returns a boolean indicating if the specified locale name is configured and available in Cldr. ## Arguments * `locale` is any valid locale name returned by `#{inspect(__MODULE__)}.known_locale_names/0` ## Examples iex> #{inspect(__MODULE__)}.known_locale_name?(:en) true iex> #{inspect(__MODULE__)}.known_locale_name?(:"!!") false """ @spec known_locale_name?(Locale.locale_name()) :: boolean def known_locale_name?(locale_name) when is_atom(locale_name) do locale_name in known_locale_names() end @doc """ Returns a boolean indicating if the specified locale name is configured and available in Cldr and supports rules based number formats (RBNF). ## Arguments * `locale` is any valid locale name returned by `#{inspect(__MODULE__)}.known_locale_names/0` ## Examples iex> #{inspect(__MODULE__)}.known_rbnf_locale_name?(:en) true iex> #{inspect(__MODULE__)}.known_rbnf_locale_name?(:"!!") false """ @spec known_rbnf_locale_name?(Locale.locale_name()) :: boolean def known_rbnf_locale_name?(locale_name) when is_atom(locale_name) do locale_name in known_rbnf_locale_names() end @doc """ Returns a boolean indicating if the specified locale name is configured and available in Gettext. ## Arguments * `locale` is any valid locale name returned by `#{inspect(__MODULE__)}.known_locale_names/0` ## Examples iex> #{inspect(__MODULE__)}.known_gettext_locale_name?("en") true iex> #{inspect(__MODULE__)}.known_gettext_locale_name?("!!") false """ @spec known_gettext_locale_name?(String.t()) :: boolean def known_gettext_locale_name?(locale_name) when is_binary(locale_name) do locale_name in known_gettext_locale_names() end @doc """ Returns either the `locale_name` or `false` based upon whether the locale name is configured in `Cldr`. This is helpful when building a list of `or` expressions to return the first known locale name from a list. ## Arguments * `locale` is any valid locale name returned by `#{inspect(__MODULE__)}.known_locale_names/0` ## Examples iex> #{inspect(__MODULE__)}.known_locale_name :"en-AU" :"en-AU" iex> #{inspect(__MODULE__)}.known_locale_name :"en-SA" false """ @spec known_locale_name(Locale.locale_name()) :: String.t() | false def known_locale_name(locale_name) when is_atom(locale_name) do if known_locale_name?(locale_name) do locale_name else false end end @doc """ Returns either the RBNF `locale_name` or `false` based upon whether the locale name is configured in `Cldr` and has RBNF rules defined. ## Arguments * `locale` is any valid locale name returned by `#{inspect(__MODULE__)}.known_locale_names/0` ## Examples iex> #{inspect(__MODULE__)}.known_rbnf_locale_name :en :en iex> #{inspect(__MODULE__)}.known_rbnf_locale_name :"en-SA" false """ @spec known_rbnf_locale_name(Locale.locale_name()) :: String.t() | false def known_rbnf_locale_name(locale_name) when is_atom(locale_name) do if known_rbnf_locale_name?(locale_name) do locale_name else false end end @doc """ Returns either the Gettext `locale_name` in Cldr format or `false` based upon whether the locale name is configured in `Gettext`. ## Arguments * `locale` is any valid locale name returned by `#{inspect(__MODULE__)}.known_gettext_locale_names/0` ## Examples iex> #{inspect(__MODULE__)}.known_gettext_locale_name "en" "en" iex> #{inspect(__MODULE__)}.known_gettext_locale_name "en-SA" false """ @spec known_gettext_locale_name(String.t()) :: String.t() | false def known_gettext_locale_name(locale_name) when is_binary(locale_name) do if known_gettext_locale_name?(locale_name) do locale_name else false end end @doc """ Return the current locale to be used for `Cldr` functions that take an optional locale parameter for which a locale is not supplied. ## Example iex> #{inspect(__MODULE__)}.put_locale("pl") iex> #{inspect(__MODULE__)}.get_locale %Cldr.LanguageTag{ backend: #{__MODULE__}, canonical_locale_name: "pl", cldr_locale_name: :pl, extensions: %{}, language: "pl", locale: %{}, private_use: [], rbnf_locale_name: :pl, territory: :PL, requested_locale_name: "pl", script: :Latn, transform: %{}, language_variants: [] } """ @spec get_locale :: LanguageTag.t() def get_locale do Cldr.get_locale(__MODULE__) end @doc """ Set the current locale to be used for `Cldr` functions that take an optional locale parameter for which a locale is not supplied. ## Arguments * `locale` is any valid locale name returned by `#{inspect(__MODULE__)}.known_locale_names/0` or a `t:Cldr.LanguageTag` struct returned by `#{inspect(__MODULE__)}.Locale.new!/1` See [rfc5646](https://tools.ietf.org/html/rfc5646) for the specification of a language tag. ## Examples iex> #{inspect(__MODULE__)}.put_locale("en") {:ok, %Cldr.LanguageTag{ backend: #{inspect(__MODULE__)}, canonical_locale_name: "en", cldr_locale_name: :en, language_subtags: [], extensions: %{}, gettext_locale_name: "en", language: "en", locale: %{}, private_use: [], rbnf_locale_name: :en, requested_locale_name: "en", script: :Latn, territory: :US, transform: %{}, language_variants: [] }} iex> #{inspect(__MODULE__)}.put_locale("invalid-locale!") {:error, {Cldr.LanguageTag.ParseError, "Expected a BCP47 language tag. Could not parse the remaining \\"!\\" starting at position 15"}} """ @spec put_locale(Locale.locale_name() | LanguageTag.t()) :: {:ok, LanguageTag.t()} | {:error, {module(), String.t()}} def put_locale(locale_name) do with {:ok, locale} <- validate_locale(locale_name) do Cldr.put_locale(__MODULE__, locale) end end @doc """ Add locale-specific quotation marks around a string. ## Arguments * `string` is any valid Elixir string * `options` is a keyword list of options ## Options * `locale` is any valid locale name returned by `Cldr.known_locale_names/1`. The default is `Cldr.get_locale/0` ## Examples iex> #{inspect(__MODULE__)}.quote "Quoted String" "“Quoted String”" iex> #{inspect(__MODULE__)}.quote "Quoted String", locale: :ja "「Quoted String」" """ @spec quote(String.t(), Keyword.t()) :: String.t() def quote(string, options \\ []) when is_binary(string) and is_list(options) do locale = options[:locale] || Cldr.get_locale() with {:ok, %LanguageTag{cldr_locale_name: locale_name}} <- validate_locale(locale) do marks = quote_marks_for(locale_name) marks[:quotation_start] <> string <> marks[:quotation_end] end end @doc """ Add locale-specific ellipsis to a string. ## Arguments * `string` is any `String.t` or a 2-element list of `String.t` between which the ellipsis is inserted. * `backend` is any module that includes `use Cldr` and therefore is a `Cldr` backend module. The default is `Cldr.default_backend!/0`. Note that `Cldr.default_backend!/0` will raise an exception if no `:default_backend` is configured under the `:ex_cldr` key in `config.exs`. * `options` is a keyword list of options ## Options * `:locale` is any valid locale name returned by `Cldr.known_locale_names/1`. The default is `Cldr.get_locale/0`. * `:location` determines where to place the ellipsis. The options are `:after` (the default for a single string argument), `:between` (the default and only valid location for an argument that is a list of two strings) and `:before`. * `:format` formats based upon whether the ellipsis is inserted between words or sentences. The valid options are `:word` or `:sentence`. The default is `:sentence`. ## Examples iex> #{inspect(__MODULE__)}.ellipsis "And furthermore" "And furthermore…" iex> #{inspect(__MODULE__)}.ellipsis ["And furthermore", "there is much to be done"], locale: :ja "And furthermore…there is much to be done" iex> #{inspect(__MODULE__)}.ellipsis "And furthermore", format: :word "And furthermore …" iex> #{inspect(__MODULE__)}.ellipsis ["And furthermore", "there is much to be done"], locale: :ja, format: :word "And furthermore … there is much to be done" """ @spec ellipsis(String.t() | list(String.t()), Keyword.t()) :: String.t() def ellipsis(string, options \\ []) when is_list(options) do locale = options[:locale] || Cldr.get_locale() format = options[:format] || :sentence location = options[:location] || :between with {:ok, %LanguageTag{cldr_locale_name: locale_name}} <- validate_locale(locale) do ellipsis(string, ellipsis_chars(locale_name), location, format) end end # For the :word format defp ellipsis([string_1, string_2], %{word_medial: medial}, _, :word) when is_binary(string_1) and is_binary(string_2) do [string_1, string_2] |> Cldr.Substitution.substitute(medial) |> :erlang.iolist_to_binary() end defp ellipsis(string, %{word_final: final}, :after, :word) when is_binary(string) do string |> Cldr.Substitution.substitute(final) |> :erlang.iolist_to_binary() end defp ellipsis(string, %{word_initial: initial}, :before, :word) when is_binary(string) do string |> Cldr.Substitution.substitute(initial) |> :erlang.iolist_to_binary() end defp ellipsis(string, %{word_final: final}, _, :word) when is_binary(string) do string |> Cldr.Substitution.substitute(final) |> :erlang.iolist_to_binary() end # For the :sentence format defp ellipsis([string_1, string_2], %{medial: medial}, _, _) when is_binary(string_1) and is_binary(string_2) do [string_1, string_2] |> Cldr.Substitution.substitute(medial) |> :erlang.iolist_to_binary() end defp ellipsis(string, %{final: final}, :after, _) when is_binary(string) do string |> Cldr.Substitution.substitute(final) |> :erlang.iolist_to_binary() end defp ellipsis(string, %{initial: initial}, :before, _) when is_binary(string) do string |> Cldr.Substitution.substitute(initial) |> :erlang.iolist_to_binary() end defp ellipsis(string, %{final: final}, _, _) when is_binary(string) do string |> Cldr.Substitution.substitute(final) |> :erlang.iolist_to_binary() end @doc """ Normalise and validate a locale name. ## Arguments * `locale` is any valid locale name returned by `#{inspect(__MODULE__)}.known_locale_names/0` or a `Cldr.LanguageTag` struct returned by `#{inspect(__MODULE__)}.Locale.new!/1` ## Returns * `{:ok, language_tag}` * `{:error, reason}` ## Notes See [rfc5646](https://tools.ietf.org/html/rfc5646) for the specification of a language tag. ## Examples iex> #{inspect(__MODULE__)}.validate_locale(:en) {:ok, %Cldr.LanguageTag{ backend: #{inspect(__MODULE__)}, canonical_locale_name: "en", cldr_locale_name: :en, extensions: %{}, gettext_locale_name: "en", language: "en", locale: %{}, private_use: [], rbnf_locale_name: :en, requested_locale_name: "en", script: :Latn, territory: :US, transform: %{}, language_variants: [] }} iex> #{inspect(__MODULE__)}.validate_locale #{inspect(__MODULE__)}.default_locale() {:ok, %Cldr.LanguageTag{ backend: #{inspect(__MODULE__)}, canonical_locale_name: "en-001", cldr_locale_name: :"en-001", extensions: %{}, gettext_locale_name: "en", language: "en", locale: %{}, private_use: [], rbnf_locale_name: :en, requested_locale_name: "en-001", script: :Latn, territory: :"001", transform: %{}, language_variants: [] }} iex> #{inspect(__MODULE__)}.validate_locale("zzz") {:error, {Cldr.InvalidLanguageError, "The language \\"zzz\\" is invalid"}} """ @spec validate_locale(Locale.locale_name() | LanguageTag.t() | String.t()) :: {:ok, LanguageTag.t()} | {:error, {module(), String.t()}} def validate_locale(%LanguageTag{cldr_locale_name: nil} = locale) do {:error, Locale.locale_error(locale)} end def validate_locale(%LanguageTag{} = language_tag) do {:ok, language_tag} end def validate_locale(locale_name) when is_binary(locale_name) do locale = locale_name |> String.downcase() |> Cldr.Locale.locale_name_from_posix() |> do_validate_locale case locale do {:error, {Cldr.UnknownLocaleError, _}} -> {:error, Locale.locale_error(locale_name)} {:error, reason} -> {:error, reason} {:ok, locale} -> {:ok, locale} end end def validate_locale(locale_name) when is_atom(locale_name) do locale = locale_name |> Atom.to_string() |> validate_locale case locale do {:error, {Cldr.UnknownLocaleError, _}} -> {:error, Locale.locale_error(locale_name)} {:error, reason} -> {:error, reason} {:ok, locale} -> {:ok, locale} end end def validate_locale(locale) do {:error, Locale.locale_error(locale)} end @doc """ Normalizes a string by applying transliteration of common symbols in numbers, currencies and dates """ def normalize_lenient_parse(string, scope, locale \\ get_locale()) do with {:ok, locale} <- validate_locale(locale) do locale_name = locale.cldr_locale_name Enum.reduce(lenient_parse_map(scope, locale_name), string, fn {replacement, regex}, acc -> String.replace(acc, regex, replacement) end) end end @doc false # We make two adjustments to the character classes # in CLDR # # 1. Adjust the escaping of "\" to suit # 2. Remove compound patterns like `{Rs}` which # are not supported in Erlang's re @remove_compounds Regex.compile!("{.*}", [:ungreedy]) for locale_name <- Cldr.Locale.Loader.known_locale_names(config) do lenient_parse = locale_name |> Cldr.Locale.Loader.get_locale(config) |> Map.get(:lenient_parse) |> Cldr.Map.deep_map( fn {k, v} -> regex = v |> String.replace("\x5c\x5c", "\x5c") |> String.replace(@remove_compounds, "") {k, Regex.compile!(regex, "u")} end, level: 2 ) |> Cldr.Map.atomize_keys(level: 1) |> Map.new() for {scope, map} <- lenient_parse do def lenient_parse_map(unquote(scope), unquote(locale_name)) do unquote(Macro.escape(map)) end end end # When validating known locale names we memoize the # parsed language tag for performance reasons and only # add the gettext locale name (if there is one) and the # backend module. for locale_name <- Cldr.Locale.Loader.known_locale_names(config), not is_nil(Cldr.Config.language_tag(locale_name)) do language_tag = locale_name |> Cldr.Config.language_tag() |> Cldr.Locale.put_gettext_locale_name(config) |> Map.put(:backend, __MODULE__) locale_name = locale_name |> Atom.to_string() |> String.downcase() defp do_validate_locale(unquote(locale_name)) do {:ok, unquote(Macro.escape(language_tag))} end end for locale_name <- Cldr.Locale.Loader.known_locale_names(config) do delimiters = locale_name |> Cldr.Locale.Loader.get_locale(config) |> Map.get(:delimiters) defp quote_marks_for(unquote(locale_name)) do unquote(Macro.escape(delimiters)) end ellipsis = locale_name |> Cldr.Locale.Loader.get_locale(config) |> Map.get(:ellipsis) @doc false def ellipsis_chars(unquote(locale_name)) do unquote(Macro.escape(ellipsis)) end end # It's not a well known locale so we need to # parse and validate defp do_validate_locale(locale_name) do with {:ok, locale} <- Cldr.Locale.new(locale_name, unquote(backend)), {:ok, locale} <- known_cldr_locale(locale, locale_name), {:ok, locale} <- known_cldr_territory(locale) do {:ok, locale} end end defp known_cldr_locale(%LanguageTag{cldr_locale_name: nil}, locale_name) do {:error, Cldr.Locale.locale_error(locale_name)} end defp known_cldr_locale(%LanguageTag{} = locale, _locale_name) do {:ok, locale} end defp known_cldr_territory(%LanguageTag{territory: territory} = language_tag) do if territory in Cldr.known_territories() do {:ok, language_tag} else {:error, Cldr.unknown_territory_error(territory)} end end @doc """ Returns a list of atoms representing the number systems types known to `Cldr`. ## Example iex> #{inspect(__MODULE__)}.known_number_system_types [:default, :finance, :native, :traditional] """ @known_number_system_types Cldr.Config.known_number_system_types(config) def known_number_system_types do @known_number_system_types end @doc """ Normalise and validate a number system type. ## Arguments * `number_system_type` is any number system type returned by `Cldr.known_number_system_types/1` ## Returns * `{:ok, normalized_number_system_type}` or * `{:error, {exception, message}}` ## Examples iex> #{inspect(__MODULE__)}.validate_number_system_type :default {:ok, :default} iex> #{inspect(__MODULE__)}.validate_number_system_type :traditional {:ok, :traditional} iex> #{inspect(__MODULE__)}.validate_number_system_type :latn { :error, {Cldr.UnknownNumberSystemTypeError, "The number system type :latn is unknown"} } iex> #{inspect(__MODULE__)}.validate_number_system_type "bork" { :error, {Cldr.UnknownNumberSystemTypeError, "The number system type \\"bork\\" is invalid"} } """ @spec validate_number_system_type(String.t() | atom()) :: {:ok, atom()} | {:error, {module(), String.t()}} def validate_number_system_type(number_system_type) when is_atom(number_system_type) do if number_system_type in known_number_system_types() do {:ok, number_system_type} else {:error, Cldr.unknown_number_system_type_error(number_system_type)} end end def validate_number_system_type(number_system_type) when is_binary(number_system_type) do number_system_type |> String.downcase() |> String.to_existing_atom() |> validate_number_system_type rescue ArgumentError -> {:error, Cldr.unknown_number_system_type_error(to_string(number_system_type))} end defdelegate available_locale_name?(locale_name), to: Cldr defdelegate known_calendars(), to: Cldr defdelegate known_territories(), to: Cldr defdelegate known_currencies(), to: Cldr defdelegate known_number_systems(), to: Cldr defdelegate validate_calendar(calendar), to: Cldr defdelegate validate_territory(territory), to: Cldr defdelegate validate_currency(currency), to: Cldr defdelegate validate_number_system(number_system), to: Cldr end end end
30.974042
122
0.598611
03aeef12e2fd4f7ad0e4990c2db0bfd7a9cc34e0
2,370
ex
Elixir
onboarding/service/web/models/merchant.ex
FoxComm/highlander
1aaf8f9e5353b94c34d574c2a92206a1c363b5be
[ "MIT" ]
10
2018-04-12T22:29:52.000Z
2021-10-18T17:07:45.000Z
onboarding/service/web/models/merchant.ex
FoxComm/highlander
1aaf8f9e5353b94c34d574c2a92206a1c363b5be
[ "MIT" ]
null
null
null
onboarding/service/web/models/merchant.ex
FoxComm/highlander
1aaf8f9e5353b94c34d574c2a92206a1c363b5be
[ "MIT" ]
1
2018-07-06T18:42:05.000Z
2018-07-06T18:42:05.000Z
defmodule OnboardingService.Merchant do use OnboardingService.Web, :model schema "merchants" do field :name, :string field :business_name, :string field :phone_number, :string field :email_address, :string field :description, :string field :site_url, :string field :state, :string, default: "new" field :scope_id, :integer #Scopes live in Permissions/Solomon field :organization_id, :integer #Organizations live in Permissions/Solomon timestamps has_one :merchant_application, OnboardingService.MerchantApplication has_many :merchant_addresses, OnboardingService.MerchantAddress has_many :merchant_accounts, OnboardingService.MerchantAccount has_one :merchant_social_profile, OnboardingService.MerchantSocialProfile has_one :merchant_business_profile, OnboardingService.MerchantBusinessProfile has_one :social_profile, through: [:merchant_social_profile, :social_profile] has_one :business_profile, through: [:merchant_business_profile, :business_profile] has_one :merchant_products_feed, OnboardingService.MerchantProductsFeed has_one :products_feed, through: [:merchant_products_feed, :products_feed] has_one :merchant_products_upload, OnboardingService.MerchantProductsUpload has_one :products_upload, through: [:merchant_products_upload, :products_upload] end @states ~w(new approved suspended cancelled activated)s @required_fields ~w(business_name phone_number email_address site_url state)a @optional_fields ~w(name description scope_id organization_id)a def changeset(model, params \\ :empty) do model |> cast(params, @required_fields ++ @optional_fields) |> validate_required_code(@required_fields) |> validate_inclusion_code(:state, @states) |> validate_phone_number(:phone_number) |> validate_uri(:site_url) |> validate_email(:email_address) |> unique_constraint_code(:email_address, name: :merchant_email) end def update_changeset(model, params \\ :empty) do model |> cast(params, @required_fields ++ @optional_fields) |> validate_required_code(@required_fields) |> validate_inclusion_code(:state, @states) |> validate_phone_number(:phone_number) |> validate_uri(:site_url) |> validate_email(:email_address) |> unique_constraint_code(:email_address, name: :merchant_email) end end
41.578947
87
0.76962
03af0809d5fe314d17972a95443b94a1a51941c0
1,316
ex
Elixir
template/$PROJECT_NAME$/apps/$PROJECT_NAME$/lib/$PROJECT_NAME$/notifications/email.ex
fadeojo/mithril
d84ff2d42f895c27c46c0feb09b70ccbac5827ac
[ "MIT" ]
54
2018-01-24T00:22:57.000Z
2019-01-15T20:03:52.000Z
template/$PROJECT_NAME$/apps/$PROJECT_NAME$/lib/$PROJECT_NAME$/notifications/email.ex
infinitered/mithril
0bbad29f86c63d9a827dcaaf6fed78a176ab90d7
[ "MIT" ]
3
2018-02-05T18:00:39.000Z
2018-05-04T00:05:20.000Z
template/$PROJECT_NAME$/apps/$PROJECT_NAME$/lib/$PROJECT_NAME$/notifications/email.ex
fadeojo/mithril
d84ff2d42f895c27c46c0feb09b70ccbac5827ac
[ "MIT" ]
3
2019-07-12T11:16:42.000Z
2020-06-08T15:03:36.000Z
defmodule <%= @project_name_camel_case %>.Notifications.Email do @moduledoc false import Swoosh.Email alias <%= @project_name_camel_case %>.Notifications.Email.Template <%= if assigns[:accounts] do %> @doc """ Builds a forgot password email. """ @spec forgot_password(String.t, <%= @project_name_camel_case %>.Accounts.user_token) :: Swoosh.Email.t def forgot_password(email, token) do url = Application.get_env(:<%= @project_name %>, :reset_password_url) <> "?token=#{token}" new() |> to(email) |> from({"<%= @project_name_camel_case %>", "no-reply@<%= @project_name %>.com"}) |> subject("Reset Your Password") |> html_body(Template.render("forgot_password.html", %{url: url})) |> text_body(Template.render("forgot_password.text", %{url: url})) end <% else %> @doc """ A sample email function definition. See `<%= @project_name_camel_case %>.Notifications.notify_sample/2` to see how it can be used. """ def sample(name, to_email) do new() |> to({name, to_email}) |> from({"<%= @project_name_camel_case %>", "no-reply@<%= @project_name %>.com"}) |> subject("Sample Notification Email") |> html_body(Template.render("sample.html", %{name: name})) |> text_body(Template.render("sample.text", %{name: name})) end <% end %> end
35.567568
105
0.650456
03af3265f86bfd39f9a00d282f37888dd9084486
4,169
ex
Elixir
lib/changelog/buffer/content.ex
theafricanengineer/changelog.com
4954d0df516c0a325667ec6c1fbbf02d68c9b953
[ "MIT" ]
null
null
null
lib/changelog/buffer/content.ex
theafricanengineer/changelog.com
4954d0df516c0a325667ec6c1fbbf02d68c9b953
[ "MIT" ]
null
null
null
lib/changelog/buffer/content.ex
theafricanengineer/changelog.com
4954d0df516c0a325667ec6c1fbbf02d68c9b953
[ "MIT" ]
null
null
null
defmodule Changelog.Buffer.Content do alias Changelog.{Episode, ListKit, NewsItem} alias ChangelogWeb.{Endpoint, NewsItemView, Router} def episode_link(nil), do: nil def episode_link(item), do: item.url def episode_text(nil), do: "" def episode_text(item) do item = item |> NewsItem.preload_all() |> NewsItem.load_object() episode = item.object people = Episode.participants(episode) meta = [ title_meta(episode), featuring_meta(people), topic_meta(item.topics) ] |> Enum.reject(&is_nil/1) if Enum.any?(meta) do """ #{episode_emoji()} New episode of #{episode.podcast.name}! #{Enum.join(meta, "\n")} 💚 #{episode_link(item)} """ else """ #{episode_emoji()} New episode of #{episode.podcast.name}! 💚 #{episode_link(item)} """ end end def news_item_image(nil), do: nil def news_item_image(%{image: nil}), do: nil def news_item_image(item), do: NewsItemView.image_url(item, :original) def news_item_link(nil), do: nil def news_item_link(item) do Router.Helpers.news_item_url(Endpoint, :show, NewsItemView.hashid(item)) end def news_item_text(nil), do: "" def news_item_text(item) do item = NewsItem.preload_all(item) if length(item.topics) >= 2 do news_item_verbose_text(item) else news_item_terse_text(item) end end defp news_item_terse_text(item) do [news_item_headline(item), news_item_byline(item), news_item_link(item)] |> ListKit.compact_join("\n") end defp news_item_verbose_text(item) do [news_item_headline(item), news_item_meta(item), news_item_link(item)] |> ListKit.compact_join("\n\n") end def post_link(nil), do: nil def post_link(item), do: item.url def post_text(nil), do: "" def post_text(item), do: news_item_text(item) defp news_item_headline(item = %{type: :video}), do: "#{video_emoji()} #{item.headline}" defp news_item_headline(item), do: item.headline defp news_item_byline(%{author: author, source: source}) when is_map(author) and is_map(source) do "#{author_emoji()} by #{twitterized(author)} via #{twitterized(source)}" end defp news_item_byline(%{author: author}) when is_map(author) do "#{author_emoji()} by #{twitterized(author)}" end defp news_item_byline(_item), do: nil defp news_item_meta(item) do meta = [ author_meta(item), source_meta(item), topic_meta(item.topics) ] |> Enum.reject(&is_nil/1) if Enum.any?(meta) do Enum.join(meta, "\n") else nil end end defp author_emoji, do: ~w(✍ 🖋 📝 🗣) |> Enum.random() defp episode_emoji, do: ~w(🙌 🎉 📢 🔥 🎧 🎁 💥) |> Enum.random() defp featuring_emoji, do: ~w(🌟 🎙 ✨ ⚡️ 💫) |> Enum.random() defp source_emoji, do: ~w(📨 📡 📢 🔊) |> Enum.random() defp title_emoji, do: ~w(🗣 💬) |> Enum.random() defp topic_emoji, do: ~w(🏷 💭 🗂 ) |> Enum.random() defp video_emoji, do: ~w(🎞 📽 🎬 🍿) |> Enum.random() defp author_meta(%{author: nil}), do: nil defp author_meta(%{author: %{twitter_handle: nil}}), do: nil defp author_meta(%{author: %{twitter_handle: handle}}), do: "#{author_emoji()} by @#{handle}" defp featuring_meta([]), do: nil defp featuring_meta(people), do: "#{featuring_emoji()} #{twitter_list(people, ", ")}" defp source_meta(%{source: nil}), do: nil defp source_meta(%{source: %{twitter_handle: nil}}), do: nil defp source_meta(%{source: %{twitter_handle: handle}}), do: "#{source_emoji()} via @#{handle}" defp title_meta(episode), do: "#{title_emoji()} #{episode.title}" defp topic_meta([]), do: nil defp topic_meta(topics) do "#{topic_emoji()} #{twitter_list(topics)}" end defp twitter_list(list, delimiter \\ " ") when is_list(list) do list |> Enum.map(&twitterized/1) |> Enum.join(delimiter) end defp twitterized(%{slug: "go"}), do: "#golang" defp twitterized(%{twitter_handle: nil, slug: slug}) when is_binary(slug), do: "#" <> String.replace(slug, "-", "") defp twitterized(%{twitter_handle: handle}) when is_binary(handle), do: "@" <> handle defp twitterized(%{name: name}), do: name end
29.992806
117
0.64308
03af3a2ed58bbf0afd0b984c6168ee1235fbf5e2
95
ex
Elixir
lib/he_broker/pry/message_relayed.ex
HackerExperience/HEBroker
2a653a43b512c6392f55508dfc1be8463a845b31
[ "BSD-3-Clause" ]
5
2017-02-15T18:25:35.000Z
2018-03-29T16:36:31.000Z
lib/he_broker/pry/message_relayed.ex
HackerExperience/HeBroker
2a653a43b512c6392f55508dfc1be8463a845b31
[ "BSD-3-Clause" ]
null
null
null
lib/he_broker/pry/message_relayed.ex
HackerExperience/HeBroker
2a653a43b512c6392f55508dfc1be8463a845b31
[ "BSD-3-Clause" ]
null
null
null
defmodule HeBroker.Pry.MessageRelayed do defstruct [:topic, :message, :request, :moment] end
23.75
49
0.768421
03af72c697b5cf07c5e7471ce53189be8fb74f75
1,775
exs
Elixir
discuss/mix.exs
hiroshisiq/elixir-sandbox
3f014d2f15ae1eeda1c22db30ef111cbc22e9afc
[ "MIT" ]
null
null
null
discuss/mix.exs
hiroshisiq/elixir-sandbox
3f014d2f15ae1eeda1c22db30ef111cbc22e9afc
[ "MIT" ]
null
null
null
discuss/mix.exs
hiroshisiq/elixir-sandbox
3f014d2f15ae1eeda1c22db30ef111cbc22e9afc
[ "MIT" ]
null
null
null
defmodule Discuss.MixProject do use Mix.Project def project do [ app: :discuss, version: "0.1.0", elixir: "~> 1.5", elixirc_paths: elixirc_paths(Mix.env()), compilers: [:phoenix, :gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps() ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {Discuss.Application, []}, extra_applications: [:logger, :runtime_tools, :ueberauth, :ueberauth_github] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:phoenix, "~> 1.4.10"}, {:phoenix_pubsub, "~> 1.1"}, {:phoenix_ecto, "~> 4.0"}, {:ecto_sql, "~> 3.1"}, {:postgrex, ">= 0.0.0"}, {:phoenix_html, "~> 2.11"}, {:phoenix_live_reload, "~> 1.2", only: :dev}, {:gettext, "~> 0.11"}, {:jason, "~> 1.0"}, {:plug_cowboy, "~> 2.0"}, {:ueberauth, "~> 0.6"}, {:ueberauth_github, "~> 0.7"}, {:poison, "~> 3.1"} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to create, migrate and run the seeds file at once: # # $ mix ecto.setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate", "test"] ] end end
26.893939
82
0.571268
03af83afdf7a97f200d8887861f8a6730d9e82af
1,917
exs
Elixir
clients/cloud_resource_manager/mix.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/mix.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/mix.exs
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.CloudResourceManager.Mixfile do use Mix.Project @version "0.28.0" def project() do [ app: :google_api_cloud_resource_manager, 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/cloud_resource_manager" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.2"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Cloud Resource Manager API client library. Creates, reads, and updates metadata for Google Cloud Platform resource containers. """ 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/cloud_resource_manager", "Homepage" => "https://cloud.google.com/resource-manager" } ] end end
28.61194
130
0.66771
03afa26cc9009fe65a2baba2d511bbd4c5a080d6
1,419
ex
Elixir
lib/fusion_auth/plugs/refresh_jwt.ex
Cogility/fusion_auth
bb765849d6e1d6bc105c2316ea5fe5dd792bd49e
[ "MIT" ]
10
2020-11-13T08:33:22.000Z
2021-08-09T17:37:09.000Z
lib/fusion_auth/plugs/refresh_jwt.ex
Cogility/fusion_auth
bb765849d6e1d6bc105c2316ea5fe5dd792bd49e
[ "MIT" ]
11
2021-01-06T21:30:14.000Z
2021-09-08T09:04:51.000Z
lib/fusion_auth/plugs/refresh_jwt.ex
Cogility/fusion_auth
bb765849d6e1d6bc105c2316ea5fe5dd792bd49e
[ "MIT" ]
null
null
null
defmodule FusionAuth.Plugs.RefreshJWT do @moduledoc """ The `FusionAuth.Plugs.RefreshJWT` module provides functionality to return a new refresh token and JWT back to the client after the request is processed. ## Examples ``` config/{env}.exs config :fusion_auth, token_header_key: "authorization", refresh_header_key: "refresh", ``` ``` lib/my_web_server/router.ex defmodule MyWebServer.Router do use MyWebServer, :router pipeline :protected do plug(FusionAuth.Plugs.RefreshJWT) end end ``` ## Plug Options - client :: FusionAuth.client(String.t(), String.t(), String.t()) // default FusionAuth.client() """ alias FusionAuth.Utils @spec init(keyword()) :: keyword() def init(opts \\ []), do: opts @spec call(%Plug.Conn{}, keyword()) :: %Plug.Conn{} def call(conn, opts \\ []) do client = opts[:client] || FusionAuth.client() Plug.Conn.register_before_send(conn, fn conn -> with {:ok, token} <- Utils.fetch_token(conn), {:ok, refresh} <- Utils.fetch_refresh(conn), {:ok, %{"token" => new_token}, _} <- FusionAuth.JWT.refresh_jwt(client, refresh, token) do conn |> Plug.Conn.put_resp_header( Application.get_env(:fusion_auth, :token_header_key), new_token ) else _ -> conn end end) end end
24.894737
103
0.610994
03afa7a1273068d2287188f748132c29f32ec319
438
ex
Elixir
lib/some_weather/noaa.ex
anthonyoconnor/some_weather
edd3c07115b4f76c0531dd9f4586bd8a13fb369f
[ "MIT" ]
1
2016-05-25T04:03:34.000Z
2016-05-25T04:03:34.000Z
lib/some_weather/noaa.ex
anthonyoconnor/some_weather
edd3c07115b4f76c0531dd9f4586bd8a13fb369f
[ "MIT" ]
null
null
null
lib/some_weather/noaa.ex
anthonyoconnor/some_weather
edd3c07115b4f76c0531dd9f4586bd8a13fb369f
[ "MIT" ]
null
null
null
defmodule SomeWeather.NOAA do @user_agent [{"User-agent", "Elixir test program"}] def fetch(id) do url(id) |> HTTPoison.get(@user_agent) |> handle_reponse end def url(id) do "http://w1.weather.gov/xml/current_obs/#{id}.xml" end def handle_reponse({:ok, %{status_code: 200, body: body}}) do {:ok, body} end def handle_reponse({_, %{status_code: _, body: body}}) do {:error, body} end end
18.25
63
0.623288
03afb2297c501e302bcf72d0371ae6045bf338b6
1,475
ex
Elixir
lib/xdr/void.ex
kommitters/xdr
41f8bcbb62c70a37a8ae7e861a473053f712fb67
[ "MIT" ]
7
2020-06-30T22:52:23.000Z
2022-02-18T22:13:43.000Z
lib/xdr/void.ex
kommitters/xdr
41f8bcbb62c70a37a8ae7e861a473053f712fb67
[ "MIT" ]
22
2020-05-22T15:24:52.000Z
2021-09-01T16:56:53.000Z
lib/xdr/void.ex
kommitters/xdr
41f8bcbb62c70a37a8ae7e861a473053f712fb67
[ "MIT" ]
1
2021-08-17T12:34:15.000Z
2021-08-17T12:34:15.000Z
defmodule XDR.Void do @moduledoc """ This module manages the `Void` type based on the RFC4506 XDR Standard. """ @behaviour XDR.Declaration alias XDR.VoidError defstruct [:void] @typedoc """ `XDR.Void` struct type specification. """ @type t :: %XDR.Void{void: nil} @doc """ Create a new `XDR.Void` structure from the `value` passed. """ @spec new(value :: nil) :: t() def new(value \\ nil) when is_nil(value), do: %XDR.Void{} @doc """ Encode a `XDR.Void` structure into a XDR format. """ @impl true def encode_xdr(%XDR.Void{void: nil}), do: {:ok, <<>>} def encode_xdr(_), do: {:error, :not_void} @doc """ Encode a `XDR.Void` structure into a XDR format. If the structure received is not `XDR.Void`, an exception is raised. """ @impl true def encode_xdr!(void) do case encode_xdr(void) do {:ok, result} -> result {:error, reason} -> raise(VoidError, reason) end end @doc """ Decode the XDR format to a void format. """ @impl true def decode_xdr(bytes, _void \\ nil) def decode_xdr(<<rest::binary>>, _), do: {:ok, {nil, rest}} def decode_xdr(_, _), do: {:error, :not_binary} @doc """ Decode the XDR format to a void format. If the binary is not a valid void, an exception is raised. """ @impl true def decode_xdr!(bytes, _void \\ nil) do case decode_xdr(bytes) do {:ok, result} -> result {:error, reason} -> raise(VoidError, reason) end end end
23.790323
72
0.621695
03afb3b8554ea070f0fe9770dc0be515516641fb
3,502
exs
Elixir
test/phoenix_ecto/sql/sandbox_test.exs
Sightsource/phoenix_ecto
4753a803059aa4108e76fe570674d1b419a61458
[ "MIT" ]
null
null
null
test/phoenix_ecto/sql/sandbox_test.exs
Sightsource/phoenix_ecto
4753a803059aa4108e76fe570674d1b419a61458
[ "MIT" ]
null
null
null
test/phoenix_ecto/sql/sandbox_test.exs
Sightsource/phoenix_ecto
4753a803059aa4108e76fe570674d1b419a61458
[ "MIT" ]
null
null
null
defmodule PhoenixEcto.SQL.SandboxTest do use ExUnit.Case, async: true use Plug.Test alias Phoenix.Ecto.SQL.Sandbox defmodule MockSandbox do def checkout(repo, opts) do send opts[:client], {:checkout, repo} :ok end def checkin(repo, opts) do send opts[:client], {:checkin, repo} :ok end def allow(repo, owner, _allowed) do send owner, {:allowed, repo} end end defp call_plug_with_checkout(conn, opts \\ []) do opts = Keyword.merge([at: "/sandbox", repo: MyRepo], opts) call_plug(conn, opts) end defp call_plug(conn, opts \\ []) do opts = opts |> Keyword.put_new(:sandbox, MockSandbox) |> Sandbox.init() Sandbox.call(conn, opts) end defp add_metadata(conn, metadata, header_key) do encoded = {:v1, metadata} |> :erlang.term_to_binary |> Base.url_encode64() put_req_header(conn, header_key, "PhoenixEcto/BeamMetadata (#{encoded})") end test "allows sandbox access to single repository" do metadata = Sandbox.metadata_for(MyRepo, self()) assert metadata == %{repo: MyRepo, owner: self()} _conn = conn(:get, "/") |> add_metadata(metadata, "user-agent") |> call_plug() assert_receive {:allowed, MyRepo} end test "allows sandbox access to multiple repositories" do repos = [MyRepoOne, MyRepoTwo] metadata = Sandbox.metadata_for(repos, self()) assert metadata == %{repo: repos, owner: self()} _conn = conn(:get, "/") |> add_metadata(metadata, "user-agent") |> call_plug() assert_receive {:allowed, MyRepoOne} assert_receive {:allowed, MyRepoTwo} end test "allows customized header" do metadata = Sandbox.metadata_for(MyRepo, self()) assert metadata == %{repo: MyRepo, owner: self()} _conn = conn(:get, "/") |> add_metadata(metadata, "x-custom") |> call_plug(header: "x-custom") assert_receive {:allowed, MyRepo} end test "does not allow sandbox access without metadata" do conn(:get, "/") |> call_plug() refute_receive {:allowed, _} end test "encodes and decodes metadata" do metadata = Sandbox.metadata_for(MyRepo, self()) encoded_meta = Sandbox.encode_metadata(metadata) assert "BeamMetadata " <> _ = encoded_meta assert metadata == Sandbox.decode_metadata(encoded_meta) end test "checks out/in connection through sandbox owner at path" do # start new sandbox owner conn = call_plug_with_checkout(conn(:post, "/sandbox")) assert "BeamMetadata" <> _ = user_agent = conn.resp_body assert conn.halted assert conn.status == 200 assert_receive {:checkout, MyRepo} # no allow with missing header conn = call_plug_with_checkout(conn(:get, "/")) refute conn.halted refute_receive {:allowed, MyRepo} # allows new request with metadata in header conn = conn(:get, "/") |> put_req_header("user-agent", user_agent) |> call_plug_with_checkout() refute conn.halted assert_receive {:allowed, MyRepo} # checks in request with metadata conn = conn(:delete, "/sandbox") |> put_req_header("user-agent", user_agent) |> call_plug_with_checkout() assert conn.status == 200 assert conn.halted # old user agent refuses owner who has been checked in _conn = conn(:get, "/") |> put_req_header("user-agent", user_agent) |> call_plug_with_checkout() refute_receive {:allowed, MyRepo} end end
25.940741
78
0.650771
03afe2db8d3a74afabde9b4df2680912814aade9
4,634
ex
Elixir
lib/serve_elm_web/worker.ex
robotarmy/serve_elm
931787a55acbe076eac0c0b199c5cfc63425197e
[ "MIT" ]
null
null
null
lib/serve_elm_web/worker.ex
robotarmy/serve_elm
931787a55acbe076eac0c0b199c5cfc63425197e
[ "MIT" ]
null
null
null
lib/serve_elm_web/worker.ex
robotarmy/serve_elm
931787a55acbe076eac0c0b199c5cfc63425197e
[ "MIT" ]
null
null
null
defmodule ServeElmWeb.Worker do use GenServer # Public Impl def get_or_render(key) do case GenServer.call(__MODULE__, {:get, key}) do {:missing, nil} -> case ServeElmWeb.Worker.render(key) do {:ok, result } -> {:ok, result } {:error, e } -> {:error, e} end {:ok, x} -> {:ok, x} end end def render(key) do GenServer.call(__MODULE__, {:render, key}) end # GenServer Impl def start_link() do GenServer.start_link(__MODULE__, :ok, name: __MODULE__) end def init(:ok) do {:ok , %{}} end def handle_call({:get, name}, _from_pid, state) do ret = case Map.get(state, name) do nil -> {:missing, nil} x -> {:ok, x} end {:reply, ret, state} end def handle_call({:render, name}, _from_pid, state) do {status, value} = execute_render(name) age = DateTime.utc_now() |> DateTime.to_unix() data = {name, value, age} new_state = Map.put(state, name, data) {:reply, {status, data } , new_state} end def execute_render(_name) do json_output = run_elm_program() result = cond do json_output["error"] != nil -> {:error, json_output["error"]} json_output["error"] == nil -> {:ok, json_output["html"]} end end def run_elm_program do generate_model() |> Poison.encode! |> render_template |> Execjs.compile |> Execjs.call("ElmRender", []) end def generate_contacts do [ #Elm : Model.Contact %{ id: 333, first_name: "Robot Army", last_name: "Made", gender: 3, birth_date: "11/20/1979", location: "home", phone_number: "222-222-2222", email: "robotarmy@ram9.cc", headline: "RAM9.CC", picture: "https://avatars0.githubusercontent.com/u/178963?s=400&v=4" }, %{ id: 123, first_name: "Jaine", last_name: "Smitherson", gender: 3, birth_date: "11/20/1983", location: "mt rushmore", phone_number: "333-333-3333", email: "js@rushmore.com", headline: "Nice Person", picture: "https://t6.rbxcdn.com/cd18c724efadc4e7a3220c2f098b6420" }, %{ id: 1333, first_name: "Toodles", last_name: "Kapital", gender: 3, birth_date: "11/20/1983", location: "wiggle", phone_number: "444-333-3333", email: "cat@kap.com", headline: "Cat Sitter", picture: "https://t6.rbxcdn.com/cd18c724efadc4e7a3220c2f098b6420" }, %{ id: 1311, first_name: "Boosh", last_name: "Sop", gender: 3, birth_date: "11/20/1983", location: "Dartmouth", phone_number: "444-55-3331", email: "boo@sop.net", headline: "Bitcoin Collector", picture: "https://t6.rbxcdn.com/cd18c724efadc4e7a3220c2f098b6420" } ] end def generate_model do contacts = generate_contacts() %{ # Elm List (Model.Contact) entries: contacts, page_number: 1, total_entries: length(contacts), total_pages: 1 } end def render_template(model_as_json_string) do elm_static_html_lib_path = Path.expand("../../node_modules/elm-static-html-lib", __DIR__) serve_elm_dir = Path.expand("../../",__DIR__) js_elm_render_function = "StaticMain.view" js_elm_decode_function = "StaticMain.decodeModel" """ const elmStaticHtml = require("#{elm_static_html_lib_path}").default; async function __elm_render__() { // // Contruct a representation for location // // global.document = global.document || {}; global.document.location = global.document.location || { hash: "", host: "", hostname: "", href: "", origin: "", pathname: "", port: "", protocol: "", search: "", }; const options = { model: #{model_as_json_string} , decoder: "#{js_elm_decode_function}" }; let myerror = null; let result = "empty"; try { result = await new Promise( function(resolve, reject) { elmStaticHtml("#{serve_elm_dir}", "#{js_elm_render_function}", options).then(function(html) { resolve(html); }); } ); } catch(error) { myerror = error; console.log("ERROR:"+error) } return {error: myerror, html:result}; } function ElmRender() { return __elm_render__(); } """ end end
23.40404
93
0.552438
03b03fe37a051c9d98ba8df605eb042813b86830
1,094
ex
Elixir
lib/circular_web/channels/user_socket.ex
cblock/circular
fb784d638bde2b1f125a03c403783f93533f5892
[ "Apache-2.0" ]
null
null
null
lib/circular_web/channels/user_socket.ex
cblock/circular
fb784d638bde2b1f125a03c403783f93533f5892
[ "Apache-2.0" ]
3
2020-09-04T09:32:55.000Z
2022-03-06T02:17:06.000Z
lib/circular_web/channels/user_socket.ex
cblock/circular
fb784d638bde2b1f125a03c403783f93533f5892
[ "Apache-2.0" ]
null
null
null
defmodule CircularWeb.UserSocket do use Phoenix.Socket ## Channels # channel "room:*", CircularWeb.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. @impl true def connect(_params, socket, _connect_info) 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: # # CircularWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. @impl true def id(_socket), do: nil end
30.388889
83
0.695612
03b07a018f074ae0b06cde58861aa39e41d75395
4,615
ex
Elixir
lib/mix/lib/mix/tasks/archive.install.ex
fmterrorf/elixir
eafb7b87756179adac5dc2bc11edcb04c1f187cc
[ "Apache-2.0" ]
1
2022-03-28T12:04:08.000Z
2022-03-28T12:04:08.000Z
lib/mix/lib/mix/tasks/archive.install.ex
fmterrorf/elixir
eafb7b87756179adac5dc2bc11edcb04c1f187cc
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/tasks/archive.install.ex
fmterrorf/elixir
eafb7b87756179adac5dc2bc11edcb04c1f187cc
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Archive.Install do use Mix.Task @shortdoc "Installs an archive locally" @moduledoc """ Installs an archive locally. If no argument is supplied but there is an archive in the project's root directory (created with `mix archive.build`), then the archive will be installed locally. For example: mix do archive.build + archive.install If an argument is provided, it should be a local path to a prebuilt archive, a Git repository, a GitHub repository, or a Hex package. mix archive.install archive.ez mix archive.install path/to/archive.ez mix archive.install git https://path/to/git/repo mix archive.install git https://path/to/git/repo branch git_branch mix archive.install git https://path/to/git/repo tag git_tag mix archive.install git https://path/to/git/repo ref git_ref mix archive.install github user/project mix archive.install github user/project branch git_branch mix archive.install github user/project tag git_tag mix archive.install github user/project ref git_ref mix archive.install hex hex_package mix archive.install hex hex_package 1.2.3 After installation, the tasks in the archive are available locally: mix some_task Note that installing via Git, GitHub, or Hex fetches the source of the archive and builds it, while using local path uses a pre-built archive. ## Command line options * `--sha512` - checks the archive matches the given SHA-512 checksum. Only applies to installations via a local path * `--force` - forces installation without a shell prompt; primarily intended for automation in build systems like Make * `--submodules` - fetches repository submodules before building archive from Git or GitHub * `--app` - specifies a custom app name to be used for building the archive from Git, GitHub, or Hex * `--organization` - set this for Hex private packages belonging to an organization * `--repo` - set this for self-hosted Hex instances, defaults to `hexpm` """ @behaviour Mix.Local.Installer @switches [ force: :boolean, sha512: :string, submodules: :boolean, app: :string, organization: :string, repo: :string, timeout: :integer ] @impl true def run(argv) do Mix.Local.Installer.install(__MODULE__, argv, @switches) end @impl true def check_install_spec({:local, path} = _install_spec, _opts) do check_extname(path) end def check_install_spec({:url, url} = _install_spec, _opts) do check_extname(url) end def check_install_spec(_, _), do: :ok defp check_extname(path_or_url) do if Path.extname(path_or_url) == ".ez" do :ok else {:error, "Expected a local file path ending in \".ez\"."} end end @impl true def find_previous_versions(src) do app = src |> Mix.Local.archive_name() |> String.split("-") |> List.first() if app do archives(app) ++ archives(app <> "-*") else [] end end @impl true def install(basename, contents, previous) do ez_path = Path.join(Mix.path_for(:archives), basename) dir_dest = resolve_destination(ez_path, contents) remove_previous_versions(previous) File.mkdir_p!(dir_dest) {:ok, _} = :zip.extract(contents, cwd: to_charlist(dir_dest)) Mix.shell().info([:green, "* creating ", :reset, Path.relative_to_cwd(dir_dest)]) ebin = Mix.Local.archive_ebin(dir_dest) Mix.Local.check_elixir_version_in_ebin(ebin) true = Code.append_path(ebin) :ok end @impl true def build(_install_spec, _opts) do src = Mix.Local.name_for(:archives, Mix.Project.config()) previous = find_previous_versions(src) Enum.each(previous, fn path -> Code.delete_path(Mix.Local.archive_ebin(path)) end) Mix.Task.run("loadconfig") Mix.Task.run("archive.build", []) src end ### Private helpers defp resolve_destination(ez_path, contents) do with {:ok, [_comment, zip_first_file | _]} <- :zip.list_dir(contents), {:zip_file, zip_first_path, _, _, _, _} = zip_first_file, [zip_root_dir | _] = Path.split(zip_first_path) do Path.join(Path.dirname(ez_path), zip_root_dir) else _ -> Mix.raise("Installation failed: invalid archive file") end end defp archives(name) do Mix.path_for(:archives) |> Path.join(name) |> Path.wildcard() end defp remove_previous_versions([]), do: :ok defp remove_previous_versions(previous), do: Enum.each(previous, &File.rm_rf!/1) end
28.140244
85
0.681473
03b07dea78b6991409d93f1202d8b07501480d59
11,208
ex
Elixir
lib/ex_doc/retriever.ex
bdanklin/ex_doc
21b32dd2e501723bec1a7ab004e813f9745cff0d
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
lib/ex_doc/retriever.ex
bdanklin/ex_doc
21b32dd2e501723bec1a7ab004e813f9745cff0d
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
lib/ex_doc/retriever.ex
bdanklin/ex_doc
21b32dd2e501723bec1a7ab004e813f9745cff0d
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
defmodule ExDoc.Retriever do # Functions to extract documentation information from modules. @moduledoc false defmodule Error do @moduledoc false defexception [:message] end alias ExDoc.{DocAST, GroupMatcher, Refs} alias ExDoc.Retriever.Error @doc """ Extract documentation from all modules in the specified directory or directories. """ @spec docs_from_dir(Path.t() | [Path.t()], ExDoc.Config.t()) :: [ExDoc.ModuleNode.t()] def docs_from_dir(dir, config) when is_binary(dir) do files = Path.wildcard(Path.expand("*.beam", dir)) docs_from_files(files, config) end def docs_from_dir(dirs, config) when is_list(dirs) do Enum.flat_map(dirs, &docs_from_dir(&1, config)) end @doc """ Extract documentation from all modules in the specified list of files """ @spec docs_from_files([Path.t()], ExDoc.Config.t()) :: [ExDoc.ModuleNode.t()] def docs_from_files(files, config) when is_list(files) do files |> Enum.map(&filename_to_module(&1)) |> docs_from_modules(config) end @doc """ Extract documentation from all modules in the list `modules` """ @spec docs_from_modules([atom], ExDoc.Config.t()) :: [ExDoc.ModuleNode.t()] def docs_from_modules(modules, config) when is_list(modules) do modules |> Enum.flat_map(&get_module(&1, config)) |> Enum.sort_by(fn module -> {GroupMatcher.group_index(config.groups_for_modules, module.group), module.nested_context, module.nested_title, module.id} end) end defp filename_to_module(name) do name = Path.basename(name, ".beam") String.to_atom(name) end defp get_module(module, config) do with {:docs_v1, _, language, _, _, metadata, _} = docs_chunk <- docs_chunk(module), true <- config.filter_modules.(module, metadata), {:ok, language} <- ExDoc.Language.get(language, module), %{} = module_data <- language.module_data(module, docs_chunk, config) do [generate_node(module, module_data, config)] else _ -> [] end end defp docs_chunk(module) do result = Code.fetch_docs(module) Refs.insert_from_chunk(module, result) case result do {:docs_v1, _, _, _, :hidden, _, _} -> false {:docs_v1, _, _, _, _, _, _} = docs -> case Code.ensure_loaded(module) do {:module, _} -> docs {:error, reason} -> IO.warn("skipping module #{inspect(module)}, reason: #{reason}", []) false end {:error, :chunk_not_found} -> false {:error, :module_not_found} -> unless Code.ensure_loaded?(module) do raise Error, "module #{inspect(module)} is not defined/available" end {:error, _} = error -> raise Error, "error accessing #{inspect(module)}: #{inspect(error)}" _ -> raise Error, "unknown format in Docs chunk. This likely means you are running on " <> "a more recent Elixir version that is not supported by ExDoc. Please update." end end defp generate_node(module, module_data, config) do source_url = config.source_url_pattern source_path = source_path(module, config) source = %{url: source_url, path: source_path} {doc_line, moduledoc, metadata} = get_module_docs(module_data, source_path) # TODO: The default function groups must be returned by the language groups_for_functions = config.groups_for_functions ++ [Callbacks: & &1[:__callback__], Functions: fn _ -> true end] function_groups = Enum.map(groups_for_functions, &elem(&1, 0)) function_docs = get_docs(module_data, source, groups_for_functions) docs = function_docs ++ get_callbacks(module_data, source, groups_for_functions) types = get_types(module_data, source) metadata = Map.put(metadata, :__type__, module_data.type) group = GroupMatcher.match_module(config.groups_for_modules, module, module_data.id, metadata) {nested_title, nested_context} = module_data.nesting_info || {nil, nil} %ExDoc.ModuleNode{ id: module_data.id, title: module_data.title, nested_title: nested_title, nested_context: nested_context, group: group, module: module, type: module_data.type, deprecated: metadata[:deprecated], function_groups: function_groups, docs: Enum.sort_by(docs, &sort_key(&1.name, &1.arity)), doc: moduledoc, doc_line: doc_line, typespecs: Enum.sort_by(types, &{&1.name, &1.arity}), source_path: source_path, source_url: source_link(source, module_data.line), language: module_data.language, annotations: List.wrap(metadata[:tags]) } end defp sort_key(name, arity) do first = name |> Atom.to_charlist() |> hd() {first in ?a..?z, name, arity} end defp doc_ast(format, %{"en" => doc_content}, options) do DocAST.parse!(doc_content, format, options) end defp doc_ast(_, _, _options) do nil end # Module Helpers defp get_module_docs(module_data, source_path) do {:docs_v1, anno, _, content_type, moduledoc, metadata, _} = module_data.docs doc_line = anno_line(anno) options = [file: source_path, line: doc_line + 1] {doc_line, doc_ast(content_type, moduledoc, options), metadata} end ## Function helpers defp get_docs(module_data, source, groups_for_functions) do {:docs_v1, _, _, _, _, _, doc_elements} = module_data.docs nodes = Enum.flat_map(doc_elements, fn doc_element -> case module_data.language.function_data(doc_element, module_data) do :skip -> [] function_data -> [get_function(doc_element, function_data, source, module_data, groups_for_functions)] end end) filter_defaults(nodes) end defp get_function(doc_element, function_data, source, module_data, groups_for_functions) do {:docs_v1, _, _, content_type, _, _, _} = module_data.docs {{type, name, arity}, anno, signature, doc_content, metadata} = doc_element doc_line = anno_line(anno) annotations = annotations_from_metadata(metadata) ++ function_data.extra_annotations line = function_data.line || doc_line defaults = get_defaults(name, arity, Map.get(metadata, :defaults, 0)) doc_ast = (doc_content && doc_ast(content_type, doc_content, file: source.path, line: doc_line + 1)) || function_data.doc_fallback.() group = GroupMatcher.match_function(groups_for_functions, metadata) %ExDoc.FunctionNode{ id: "#{name}/#{arity}", name: name, arity: arity, deprecated: metadata[:deprecated], doc: doc_ast, doc_line: doc_line, defaults: Enum.sort_by(defaults, fn {name, arity} -> sort_key(name, arity) end), signature: signature(signature), specs: function_data.specs, source_path: source.path, source_url: source_link(source, line), type: type, group: group, annotations: annotations, route: metadata[:route], method: metadata[:method], permissions: metadata[:permissions], events: metadata[:events], audit_log: metadata[:audit_log] } end defp get_defaults(_name, _arity, 0), do: [] defp get_defaults(name, arity, defaults) do for default <- (arity - defaults)..(arity - 1), do: {name, default} end defp filter_defaults(nodes) do Enum.map(nodes, &filter_defaults(&1, nodes)) end defp filter_defaults(node, nodes) do update_in(node.defaults, fn defaults -> Enum.reject(defaults, fn {name, arity} -> Enum.any?(nodes, &match?(%{name: ^name, arity: ^arity}, &1)) end) end) end ## Callback helpers defp get_callbacks(%{type: :behaviour} = module_data, source, groups_for_functions) do {:docs_v1, _, _, _, _, _, docs} = module_data.docs for {{kind, _, _}, _, _, _, _} = doc <- docs, kind in module_data.callback_types do get_callback(doc, source, groups_for_functions, module_data) end end defp get_callbacks(_, _, _), do: [] defp get_callback(callback, source, groups_for_functions, module_data) do callback_data = module_data.language.callback_data(callback, module_data) {:docs_v1, _, _, content_type, _, _, _} = module_data.docs {{kind, name, arity}, anno, _signature, doc, metadata} = callback doc_line = anno_line(anno) signature = signature(callback_data.signature) specs = callback_data.specs annotations = callback_data.extra_annotations ++ annotations_from_metadata(metadata) doc_ast = doc_ast(content_type, doc, file: source.path, line: doc_line + 1) metadata = Map.put(metadata, :__callback__, true) group = GroupMatcher.match_function(groups_for_functions, metadata) %ExDoc.FunctionNode{ id: "c:#{name}/#{arity}", name: name, arity: arity, deprecated: metadata[:deprecated], doc: doc_ast, doc_line: doc_line, signature: signature, specs: specs, source_path: source.path, source_url: source_link(source, callback_data.line), type: kind, annotations: annotations, group: group } end ## Typespecs defp get_types(module_data, source) do {:docs_v1, _, _, _, _, _, docs} = module_data.docs for {{:type, _, _}, _, _, content, _} = doc <- docs, content != :hidden do get_type(doc, source, module_data) end end defp get_type(type_entry, source, module_data) do {:docs_v1, _, _, content_type, _, _, _} = module_data.docs {{_, name, arity}, anno, _signature, doc, metadata} = type_entry doc_line = anno_line(anno) annotations = annotations_from_metadata(metadata) type_data = module_data.language.type_data(type_entry, module_data) signature = signature(type_data.signature) annotations = if type_data.type == :opaque, do: ["opaque" | annotations], else: annotations doc_ast = doc_ast(content_type, doc, file: source.path) %ExDoc.TypeNode{ id: "t:#{name}/#{arity}", name: name, arity: arity, type: type_data.type, spec: type_data.spec, deprecated: metadata[:deprecated], doc: doc_ast, doc_line: doc_line, signature: signature, source_path: source.path, source_url: source_link(source, type_data.line), annotations: annotations } end ## General helpers defp signature([]), do: nil defp signature(list) when is_list(list), do: Enum.join(list, " ") defp annotations_from_metadata(metadata) do annotations = [] annotations = if since = metadata[:since] do ["since #{since}" | annotations] else annotations end annotations end defp anno_line(line) when is_integer(line), do: abs(line) defp anno_line(anno), do: anno |> :erl_anno.line() |> abs() defp source_link(%{path: _, url: nil}, _line), do: nil defp source_link(source, line) do source_url = Regex.replace(~r/%{path}/, source.url, source.path) Regex.replace(~r/%{line}/, source_url, to_string(line)) end defp source_path(module, _config) do module.module_info(:compile)[:source] |> String.Chars.to_string() |> Path.relative_to(File.cwd!()) end end
31.750708
99
0.661224
03b0841ec7e79661d2fc4e04b9cd51fa5d380bc8
455
ex
Elixir
backend/lib/backend/users/category.ex
ericgroom/gatorgoods
c78af60f463c6c8c6762101a2d8e7102d43bd804
[ "MIT" ]
null
null
null
backend/lib/backend/users/category.ex
ericgroom/gatorgoods
c78af60f463c6c8c6762101a2d8e7102d43bd804
[ "MIT" ]
9
2020-02-12T00:40:03.000Z
2021-12-09T01:11:33.000Z
backend/lib/backend/users/category.ex
ericgroom/gatorgoods
c78af60f463c6c8c6762101a2d8e7102d43bd804
[ "MIT" ]
null
null
null
defmodule Backend.Users.Category do @moduledoc """ Backend Category """ use Ecto.Schema import Ecto.Changeset use BackendWeb, :model schema "categories" do field :name, :string, default: "NONE SELECTED" has_many :items, Backend.Users.Item end @required_fields ~w(name) @optional_fields ~w() def changeset(model, params \\ :empty) do model |> cast(params, @required_fields) |> validate_required([:name]) end end
20.681818
50
0.685714
03b08c2728232b6443b551256ee4fefd4bb53c72
1,664
ex
Elixir
clients/drive/lib/google_api/drive/v3/model/file_content_hints_thumbnail.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/drive/lib/google_api/drive/v3/model/file_content_hints_thumbnail.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/drive/lib/google_api/drive/v3/model/file_content_hints_thumbnail.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.Drive.V3.Model.FileContentHintsThumbnail do @moduledoc """ A thumbnail for the file. This will only be used if Google Drive cannot generate a standard thumbnail. ## Attributes * `image` (*type:* `String.t`, *default:* `nil`) - The thumbnail data encoded with URL-safe Base64 (RFC 4648 section 5). * `mimeType` (*type:* `String.t`, *default:* `nil`) - The MIME type of the thumbnail. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :image => String.t(), :mimeType => String.t() } field(:image) field(:mimeType) end defimpl Poison.Decoder, for: GoogleApi.Drive.V3.Model.FileContentHintsThumbnail do def decode(value, options) do GoogleApi.Drive.V3.Model.FileContentHintsThumbnail.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Drive.V3.Model.FileContentHintsThumbnail do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.28
124
0.727163
03b09dc8d8e0b47ed48e48cb171c1fa8d030cace
1,234
exs
Elixir
mix.exs
derek-zhou/ueberauth_wordpress
299d56c6728aeecc3a21c4b171a4bb0e61b843cd
[ "MIT" ]
null
null
null
mix.exs
derek-zhou/ueberauth_wordpress
299d56c6728aeecc3a21c4b171a4bb0e61b843cd
[ "MIT" ]
null
null
null
mix.exs
derek-zhou/ueberauth_wordpress
299d56c6728aeecc3a21c4b171a4bb0e61b843cd
[ "MIT" ]
1
2022-02-25T23:47:11.000Z
2022-02-25T23:47:11.000Z
defmodule UeberauthWordpress.MixProject do use Mix.Project def project do [ app: :ueberauth_wordpress, version: "0.1.0", name: "Ueberauth Wordpress Strategy", package: package(), elixir: "~> 1.10", build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, description: description(), deps: deps(), docs: docs() ] 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 [ {:oauth2, "~> 1.0 or ~> 2.0"}, {:ueberauth, "~> 0.6.3"}, {:credo, ">= 0.0.0", only: [:dev, :test], runtime: false}, {:ex_doc, ">= 0.0.0", only: [:dev], runtime: false}, {:mock, "~> 0.3", only: :test} ] end defp docs do [extras: ["README.md"]] end defp description do "An Uberauth strategy for Wordpress authentication." end defp package do [ files: ["lib", "mix.exs", "README.md", "LICENSE"], maintainers: ["Derek Zhou"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/derek-zhou/ueberauth_wordpress"} ] end end
22.851852
79
0.56483
03b0b6e732c279e87e47eb19912bebdfcb10c7fa
15,708
ex
Elixir
lib/bamboo/adapters/smtp_adapter.ex
wingyplus/bamboo_smtp
ab73a194d6d8a130d499058a4ca52da150e3f206
[ "MIT" ]
null
null
null
lib/bamboo/adapters/smtp_adapter.ex
wingyplus/bamboo_smtp
ab73a194d6d8a130d499058a4ca52da150e3f206
[ "MIT" ]
null
null
null
lib/bamboo/adapters/smtp_adapter.ex
wingyplus/bamboo_smtp
ab73a194d6d8a130d499058a4ca52da150e3f206
[ "MIT" ]
null
null
null
defmodule Bamboo.SMTPAdapter do @moduledoc """ Sends email using SMTP. Use this adapter to send emails through SMTP. This adapter requires that some settings are set in the config. See the example section below. *Sensitive credentials should not be committed to source control and are best kept in environment variables. Using `{:system, "ENV_NAME"}` configuration is read from the named environment variable at runtime.* ## Example config # In config/config.exs, or config.prod.exs, etc. config :my_app, MyApp.Mailer, adapter: Bamboo.SMTPAdapter, server: "smtp.domain", hostname: "www.mydomain.com", port: 1025, username: "your.name@your.domain", # or {:system, "SMTP_USERNAME"} password: "pa55word", # or {:system, "SMTP_PASSWORD"} tls: :if_available, # can be `:always` or `:never` allowed_tls_versions: [:"tlsv1", :"tlsv1.1", :"tlsv1.2"], # or {":system", ALLOWED_TLS_VERSIONS"} w/ comma seprated values (e.g. "tlsv1.1,tlsv1.2") ssl: false, # can be `true`, retries: 1, no_mx_lookups: false, # can be `true` auth: :if_available # can be `:always`. If your smtp relay requires authentication set it to `:always`. # Define a Mailer. Maybe in lib/my_app/mailer.ex defmodule MyApp.Mailer do use Bamboo.Mailer, otp_app: :my_app end """ @behaviour Bamboo.Adapter require Logger @required_configuration [:server, :port] @default_configuration %{ tls: :if_available, ssl: false, retries: 1, transport: :gen_smtp_client, auth: :if_available } @tls_versions ~w(tlsv1 tlsv1.1 tlsv1.2) defmodule SMTPError do @moduledoc false defexception [:message, :raw] def exception(raw = {reason, detail}) do message = """ There was a problem sending the email through SMTP. The error is #{inspect(reason)} More detail below: #{inspect(detail)} """ %SMTPError{message: message, raw: raw} end end def deliver(email, config) do gen_smtp_config = config |> to_gen_smtp_server_config response = try do email |> Bamboo.Mailer.normalize_addresses() |> to_gen_smtp_message |> config[:transport].send_blocking(gen_smtp_config) catch e -> raise SMTPError, {:not_specified, e} end handle_response(response) end @doc false def handle_config(config) do config |> check_required_configuration |> put_default_configuration end @doc false def supports_attachments?, do: true defp handle_response({:error, :no_credentials = reason}) do raise SMTPError, {reason, "Username and password were not provided for authentication."} end defp handle_response({:error, reason, detail}) do raise SMTPError, {reason, detail} end defp handle_response({:error, detail}) do raise SMTPError, {:not_specified, detail} end defp handle_response(response) do {:ok, response} end defp add_bcc(body, %Bamboo.Email{bcc: []}) do body end defp add_bcc(body, %Bamboo.Email{bcc: recipients}) do add_smtp_header_line(body, :bcc, format_email_as_string(recipients, :bcc)) end defp add_cc(body, %Bamboo.Email{cc: []}) do body end defp add_cc(body, %Bamboo.Email{cc: recipients}) do add_smtp_header_line(body, :cc, format_email_as_string(recipients, :cc)) end defp add_custom_header(body, {key, value}) do add_smtp_header_line(body, key, value) end defp add_custom_headers(body, %Bamboo.Email{headers: headers}) do Enum.reduce(headers, body, &add_custom_header(&2, &1)) end defp add_ending_header(body) do add_smtp_line(body, "") end defp add_ending_multipart(body, delimiter) do add_smtp_line(body, "--#{delimiter}--") end defp add_html_body(body, %Bamboo.Email{html_body: html_body}, _multi_part_delimiter) when html_body == nil do body end defp add_html_body(body, %Bamboo.Email{html_body: html_body}, multi_part_delimiter) do base64_html_body = base64_and_split(html_body) body |> add_multipart_delimiter(multi_part_delimiter) |> add_smtp_header_line("Content-Type", "text/html;charset=UTF-8") |> add_smtp_line("Content-Transfer-Encoding: base64") |> add_smtp_line("") |> add_smtp_line(base64_html_body) end defp add_from(body, %Bamboo.Email{from: from}) do add_smtp_header_line(body, :from, format_email_as_string(from, :from)) end defp add_mime_header(body) do add_smtp_header_line(body, "MIME-Version", "1.0") end defp add_multipart_delimiter(body, delimiter) do add_smtp_line(body, "--#{delimiter}") end defp add_multipart_header(body, delimiter) do add_smtp_header_line(body, "Content-Type", ~s(multipart/alternative; boundary="#{delimiter}")) end defp add_multipart_mixed_header(body, delimiter) do add_smtp_header_line(body, "Content-Type", ~s(multipart/mixed; boundary="#{delimiter}")) end defp add_smtp_header_line(body, type, content) when is_list(content) do Enum.reduce(content, body, &add_smtp_header_line(&2, type, &1)) end defp add_smtp_header_line(body, type, content) when is_atom(type) do add_smtp_header_line(body, String.capitalize(to_string(type)), content) end defp add_smtp_header_line(body, type, content) when is_binary(type) do add_smtp_line(body, "#{type}: #{content}") end defp add_smtp_line(body, content), do: body <> content <> "\r\n" defp add_subject(body, %Bamboo.Email{subject: subject}) when is_nil(subject) do add_smtp_header_line(body, :subject, "") end defp add_subject(body, %Bamboo.Email{subject: subject}) do add_smtp_header_line(body, :subject, rfc822_encode(subject)) end defp rfc822_encode(content) do "=?UTF-8?B?#{Base.encode64(content)}?=" end def base64_and_split(data) do data |> Base.encode64() |> Stream.unfold(&String.split_at(&1, 76)) |> Enum.take_while(&(&1 != "")) |> Enum.join("\r\n") end defp add_text_body(body, %Bamboo.Email{text_body: text_body}, _multi_part_delimiter) when text_body == nil do body end defp add_text_body(body, %Bamboo.Email{text_body: text_body}, multi_part_delimiter) do body |> add_multipart_delimiter(multi_part_delimiter) |> add_smtp_header_line("Content-Type", "text/plain;charset=UTF-8") |> add_smtp_line("") |> add_smtp_line(text_body) end defp add_attachment_header(body, attachment) do case attachment.content_id do nil -> add_common_attachment_header(body, attachment) cid -> body |> add_common_attachment_header(attachment) |> add_smtp_line("Content-ID: <#{cid}>") end end defp add_common_attachment_header(body, %{content_type: content_type} = attachment) when content_type == "message/rfc822" do <<random::size(32)>> = :crypto.strong_rand_bytes(4) body |> add_smtp_line("Content-Type: #{attachment.content_type}; name=\"#{attachment.filename}\"") |> add_smtp_line("Content-Disposition: attachment; filename=\"#{attachment.filename}\"") |> add_smtp_line("X-Attachment-Id: #{random}") end defp add_common_attachment_header(body, attachment) do <<random::size(32)>> = :crypto.strong_rand_bytes(4) body |> add_smtp_line("Content-Type: #{attachment.content_type}; name=\"#{attachment.filename}\"") |> add_smtp_line("Content-Disposition: attachment; filename=\"#{attachment.filename}\"") |> add_smtp_line("Content-Transfer-Encoding: base64") |> add_smtp_line("X-Attachment-Id: #{random}") end defp add_attachment_body(body, data) do data = if String.contains?(body, "Content-Type: message/rfc822") do data else base64_and_split(data) end add_smtp_line(body, data) end defp add_attachment(nil, _), do: "" defp add_attachment(attachment, multi_part_mixed_delimiter) do "" |> add_multipart_delimiter(multi_part_mixed_delimiter) |> add_attachment_header(attachment) |> add_smtp_line("") |> add_attachment_body(attachment.data) end defp add_attachments(body, %Bamboo.Email{attachments: nil}, _), do: body defp add_attachments(body, %Bamboo.Email{attachments: attachments}, multi_part_mixed_delimiter) do attachment_part = attachments |> Enum.map(fn attachment -> add_attachment(attachment, multi_part_mixed_delimiter) end) "#{body}#{attachment_part}" end defp add_to(body, %Bamboo.Email{to: recipients}) do add_smtp_header_line(body, :to, format_email_as_string(recipients, :to)) end defp aggregate_errors(config, key, errors) do config |> Map.fetch(key) |> build_error(key, errors) end defp apply_default_configuration({:ok, value}, _default, config) when value != nil do config end defp apply_default_configuration(_not_found_value, {key, default_value}, config) do Map.put_new(config, key, default_value) end defp generate_multi_part_delimiter do <<random1::size(32), random2::size(32), random3::size(32)>> = :crypto.strong_rand_bytes(12) "----=_Part_#{random1}_#{random2}.#{random3}" end defp body(email = %Bamboo.Email{}) do multi_part_delimiter = generate_multi_part_delimiter() multi_part_mixed_delimiter = generate_multi_part_delimiter() "" |> add_subject(email) |> add_from(email) |> add_bcc(email) |> add_cc(email) |> add_to(email) |> add_custom_headers(email) |> add_mime_header |> add_multipart_mixed_header(multi_part_mixed_delimiter) |> add_ending_header |> add_multipart_delimiter(multi_part_mixed_delimiter) |> add_multipart_header(multi_part_delimiter) |> add_ending_header |> add_text_body(email, multi_part_delimiter) |> add_html_body(email, multi_part_delimiter) |> add_ending_multipart(multi_part_delimiter) |> add_attachments(email, multi_part_mixed_delimiter) |> add_ending_multipart(multi_part_mixed_delimiter) end defp build_error({:ok, value}, _key, errors) when value != nil, do: errors defp build_error(_not_found_value, key, errors) do ["Key #{key} is required for SMTP Adapter" | errors] end defp check_required_configuration(config) do @required_configuration |> Enum.reduce([], &aggregate_errors(config, &1, &2)) |> raise_on_missing_configuration(config) end defp format_email({nil, email}, _format), do: email defp format_email({name, email}, true), do: "#{rfc822_encode(name)} <#{email}>" defp format_email({_name, email}, false), do: email defp format_email(emails, format) when is_list(emails) do Enum.map(emails, &format_email(&1, format)) end defp format_email(email, type, format \\ true) do email |> Bamboo.Formatter.format_email_address(type) |> format_email(format) end defp format_email_as_string(emails) when is_list(emails) do Enum.join(emails, ", ") end defp format_email_as_string(email) do email end defp format_email_as_string(email, type) do email |> format_email(type) |> format_email_as_string end defp from_without_format(%Bamboo.Email{from: from}) do from |> format_email(:from, false) end defp put_default_configuration(config) do @default_configuration |> Enum.reduce(config, &put_default_configuration(&2, &1)) end defp put_default_configuration(config, default = {key, _default_value}) do config |> Map.fetch(key) |> apply_default_configuration(default, config) end defp raise_on_missing_configuration([], config), do: config defp raise_on_missing_configuration(errors, config) do formatted_errors = errors |> Enum.map(&"* #{&1}") |> Enum.join("\n") raise ArgumentError, """ The following settings have not been found in your settings: #{formatted_errors} They are required to make the SMTP adapter work. Here you configuration: #{inspect(config)} """ end defp to_without_format(email = %Bamboo.Email{}) do email |> Bamboo.Email.all_recipients() |> format_email(:to, false) end defp to_gen_smtp_message(email = %Bamboo.Email{}) do {from_without_format(email), to_without_format(email), body(email)} end defp to_gen_smtp_server_config(config) do Enum.reduce(config, [], &to_gen_smtp_server_config/2) end defp to_gen_smtp_server_config({:server, value}, config) when is_binary(value) do [{:relay, value} | config] end defp to_gen_smtp_server_config({:username, value}, config) when is_binary(value) do [{:username, value} | config] end defp to_gen_smtp_server_config({:password, value}, config) when is_binary(value) do [{:password, value} | config] end defp to_gen_smtp_server_config({:tls, "if_available"}, config) do [{:tls, :if_available} | config] end defp to_gen_smtp_server_config({:tls, "always"}, config) do [{:tls, :always} | config] end defp to_gen_smtp_server_config({:tls, "never"}, config) do [{:tls, :never} | config] end defp to_gen_smtp_server_config({:tls, value}, config) when is_atom(value) do [{:tls, value} | config] end defp to_gen_smtp_server_config({:allowed_tls_versions, value}, config) when is_binary(value) do [{:tls_options, [{:versions, string_to_tls_versions(value)}]} | config] end defp to_gen_smtp_server_config({:allowed_tls_versions, value}, config) when is_list(value) do [{:tls_options, [{:versions, value}]} | config] end defp to_gen_smtp_server_config({:port, value}, config) when is_binary(value) do [{:port, String.to_integer(value)} | config] end defp to_gen_smtp_server_config({:port, value}, config) when is_integer(value) do [{:port, value} | config] end defp to_gen_smtp_server_config({:ssl, "true"}, config) do [{:ssl, true} | config] end defp to_gen_smtp_server_config({:ssl, "false"}, config) do [{:ssl, false} | config] end defp to_gen_smtp_server_config({:ssl, value}, config) when is_boolean(value) do [{:ssl, value} | config] end defp to_gen_smtp_server_config({:retries, value}, config) when is_binary(value) do [{:retries, String.to_integer(value)} | config] end defp to_gen_smtp_server_config({:retries, value}, config) when is_integer(value) do [{:retries, value} | config] end defp to_gen_smtp_server_config({:hostname, value}, config) when is_binary(value) do [{:hostname, value} | config] end defp to_gen_smtp_server_config({:no_mx_lookups, "true"}, config) do [{:no_mx_lookups, true} | config] end defp to_gen_smtp_server_config({:no_mx_lookups, "false"}, config) do [{:no_mx_lookups, false} | config] end defp to_gen_smtp_server_config({:no_mx_lookups, value}, config) when is_boolean(value) do [{:no_mx_lookups, value} | config] end defp to_gen_smtp_server_config({:auth, "if_available"}, config) do [{:auth, :if_available} | config] end defp to_gen_smtp_server_config({:auth, "always"}, config) do [{:auth, :always} | config] end defp to_gen_smtp_server_config({:auth, value}, config) when is_atom(value) do [{:auth, value} | config] end defp to_gen_smtp_server_config({:sockopts, value}, config) do [{:sockopts, value} | config] end defp to_gen_smtp_server_config({conf, {:system, var}}, config) do to_gen_smtp_server_config({conf, System.get_env(var)}, config) end defp to_gen_smtp_server_config({_key, _value}, config) do config end defp string_to_tls_versions(version_string) do version_string |> String.split(",") |> Enum.filter(&(&1 in @tls_versions)) |> Enum.map(&String.to_atom/1) end end
29.142857
111
0.692068
03b0c74f40d494ccae50fdb5e937869273ba6442
4,309
ex
Elixir
clients/policy_troubleshooter/lib/google_api/policy_troubleshooter/v1/model/google_iam_v1_binding.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/policy_troubleshooter/lib/google_api/policy_troubleshooter/v1/model/google_iam_v1_binding.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/policy_troubleshooter/lib/google_api/policy_troubleshooter/v1/model/google_iam_v1_binding.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.PolicyTroubleshooter.V1.Model.GoogleIamV1Binding do @moduledoc """ Associates `members` with a `role`. ## Attributes * `condition` (*type:* `GoogleApi.PolicyTroubleshooter.V1.Model.GoogleTypeExpr.t`, *default:* `nil`) - The condition that is associated with this binding. NOTE: An unsatisfied condition will not allow user access via current binding. Different bindings, including their conditions, are examined independently. * `members` (*type:* `list(String.t)`, *default:* `nil`) - Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: An email address that represents a Google group. For example, `admins@example.com`. * `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. * `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a service account that has been recently deleted. For example, `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted, this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`. If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that domain. For example, `google.com` or `example.com`. * `role` (*type:* `String.t`, *default:* `nil`) - Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :condition => GoogleApi.PolicyTroubleshooter.V1.Model.GoogleTypeExpr.t(), :members => list(String.t()), :role => String.t() } field(:condition, as: GoogleApi.PolicyTroubleshooter.V1.Model.GoogleTypeExpr) field(:members, type: :list) field(:role) end defimpl Poison.Decoder, for: GoogleApi.PolicyTroubleshooter.V1.Model.GoogleIamV1Binding do def decode(value, options) do GoogleApi.PolicyTroubleshooter.V1.Model.GoogleIamV1Binding.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.PolicyTroubleshooter.V1.Model.GoogleIamV1Binding do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
43.09
158
0.710374
03b0e714e6e7e0499fd29f01f35c4c4ea9337513
163
exs
Elixir
priv/repo/migrations/20211026050428_add_hls_path_to_media.exs
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
12
2021-09-30T20:51:49.000Z
2022-01-27T04:09:32.000Z
priv/repo/migrations/20211026050428_add_hls_path_to_media.exs
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
76
2021-10-01T05:45:11.000Z
2022-03-28T04:12:39.000Z
priv/repo/migrations/20211026050428_add_hls_path_to_media.exs
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
2
2021-10-04T19:27:28.000Z
2022-01-13T22:36:38.000Z
defmodule Ambry.Repo.Migrations.AddHlsPathToMedia do use Ecto.Migration def change do alter table(:media) do add :hls_path, :text end end end
16.3
52
0.705521
03b0f0ca02d202f354e8eaaf2282e02de84a97d9
3,698
ex
Elixir
clients/service_user/lib/google_api/service_user/v1/api/services.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/service_user/lib/google_api/service_user/v1/api/services.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/service_user/lib/google_api/service_user/v1/api/services.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.ServiceUser.V1.Api.Services do @moduledoc """ API calls for all endpoints tagged `Services`. """ alias GoogleApi.ServiceUser.V1.Connection import GoogleApi.ServiceUser.V1.RequestBuilder @doc """ Search available services. When no filter is specified, returns all accessible services. For authenticated users, also returns all services the calling user has \&quot;servicemanagement.services.bind\&quot; permission for. ## Parameters - connection (GoogleApi.ServiceUser.V1.Connection): Connection to server - opts (KeywordList): [optional] Optional parameters - :upload_protocol (String): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :pretty_print (Boolean): Returns response with indentations and line breaks. - :upload_type (String): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :fields (String): Selector specifying which fields to include in a partial response. - :__/xgafv (String): V1 error format. - :callback (String): JSONP - :alt (String): Data format for response. - :access_token (String): OAuth access token. - :key (String): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :quota_user (String): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :pp (Boolean): Pretty-print response. - :oauth_token (String): OAuth 2.0 token for the current user. - :bearer_token (String): OAuth bearer token. - :page_token (String): Token identifying which result to start with; returned by a previous list call. - :page_size (Integer): Requested size of the next page of data. ## Returns {:ok, %GoogleApi.ServiceUser.V1.Model.SearchServicesResponse{}} on success {:error, info} on failure """ @spec serviceuser_services_search(Tesla.Env.client, keyword()) :: {:ok, GoogleApi.ServiceUser.V1.Model.SearchServicesResponse.t} | {:error, Tesla.Env.t} def serviceuser_services_search(connection, opts \\ []) do optional_params = %{ :"upload_protocol" => :query, :"prettyPrint" => :query, :"uploadType" => :query, :"fields" => :query, :"$.xgafv" => :query, :"callback" => :query, :"alt" => :query, :"access_token" => :query, :"key" => :query, :"quotaUser" => :query, :"pp" => :query, :"oauth_token" => :query, :"bearer_token" => :query, :"pageToken" => :query, :"pageSize" => :query } %{} |> method(:get) |> url("/v1/services:search") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.ServiceUser.V1.Model.SearchServicesResponse{}) end end
43.505882
225
0.693618
03b103d2282a4b41343594617a3a2bc085a780ec
485
exs
Elixir
priv/repo/migrations/20181028010610_create_topic_for_contents.exs
DavidAlphaFox/coderplanets_server
3fd47bf3bba6cc04c9a34698201a60ad2f3e8254
[ "Apache-2.0" ]
1
2019-05-07T15:03:54.000Z
2019-05-07T15:03:54.000Z
priv/repo/migrations/20181028010610_create_topic_for_contents.exs
DavidAlphaFox/coderplanets_server
3fd47bf3bba6cc04c9a34698201a60ad2f3e8254
[ "Apache-2.0" ]
null
null
null
priv/repo/migrations/20181028010610_create_topic_for_contents.exs
DavidAlphaFox/coderplanets_server
3fd47bf3bba6cc04c9a34698201a60ad2f3e8254
[ "Apache-2.0" ]
null
null
null
defmodule MastaniServer.Repo.Migrations.CreateTopicForContents do use Ecto.Migration def change do create table(:topics) do # add(:community_id, references(:communities, on_delete: :delete_all), null: false) # add(:user_id, references(:users)) add(:thread, :string) add(:title, :string, default: "index") add(:raw, :string, default: "index") timestamps() end # create(unique_index(:topics, [:community, :part, :title])) end end
26.944444
89
0.661856
03b10df9c53640660fa806db37a1471b92b9d5cf
1,872
ex
Elixir
clients/android_publisher/lib/google_api/android_publisher/v2/model/bundle.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/android_publisher/lib/google_api/android_publisher/v2/model/bundle.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/android_publisher/lib/google_api/android_publisher/v2/model/bundle.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.AndroidPublisher.V2.Model.Bundle do @moduledoc """ ## Attributes * `sha1` (*type:* `String.t`, *default:* `nil`) - A sha1 hash of the upload payload, encoded as a hex string and matching the output of the sha1sum command. * `sha256` (*type:* `String.t`, *default:* `nil`) - A sha256 hash of the upload payload, encoded as a hex string and matching the output of the sha256sum command. * `versionCode` (*type:* `integer()`, *default:* `nil`) - The version code of the Android App Bundle. As specified in the Android App Bundle's base module APK manifest file. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :sha1 => String.t(), :sha256 => String.t(), :versionCode => integer() } field(:sha1) field(:sha256) field(:versionCode) end defimpl Poison.Decoder, for: GoogleApi.AndroidPublisher.V2.Model.Bundle do def decode(value, options) do GoogleApi.AndroidPublisher.V2.Model.Bundle.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidPublisher.V2.Model.Bundle do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.320755
177
0.715278
03b11244ca6fa8ef5293a4541429cb9b662d9d42
4,932
ex
Elixir
islands_engine/lib/islands_engine/game.ex
ipmsteven/rethink_webapp
ea906747e32baf0a6544cc33184cb55963cb25d1
[ "MIT" ]
null
null
null
islands_engine/lib/islands_engine/game.ex
ipmsteven/rethink_webapp
ea906747e32baf0a6544cc33184cb55963cb25d1
[ "MIT" ]
null
null
null
islands_engine/lib/islands_engine/game.ex
ipmsteven/rethink_webapp
ea906747e32baf0a6544cc33184cb55963cb25d1
[ "MIT" ]
null
null
null
defmodule IslandsEngine.Game do use GenServer, start: {__MODULE__, :start_link, []}, restart: :transient @timeout 15000 @players [:player1, :player2] alias IslandsEngine.{Board, Guesses, Rules, Island, Coordinate} def start_link(name) when is_binary(name) do GenServer.start_link(__MODULE__, name, name: via_tuple(name)) end def via_tuple(name), do: {:via, Registry, {Registry.Game, name}} def init(name) do send(self(), {:set_state, name}) {:ok, fresh_state(name)} end def handle_info({:set_state, name}, _state_data) do state_data = case :ets.lookup(:game_state, name) do [] -> fresh_state(name) [{_key, state}] -> state end :ets.insert(:game_state, {name, state_data}) {:noreply, state_data, @timeout} end def add_player(game, name) when is_binary(name) do GenServer.call(game, {:add_player, name}) end def handle_call({:add_player, name}, _from, state_data) do with {:ok, rules} <- Rules.check(state_data.rules, :add_player) do state_data |> update_player2_name(name) |> update_rules(rules) |> reply_success(:ok) else :error -> {:reply, :error, state_data} end end def position_island(game, player, key, row, col) when player in @players do GenServer.call(game, {:position_island, player, key, row, col}) end def handle_call({:position_island, player, key, row, col}, _from, state_data) do board = player_board(state_data, player) with {:ok, rules} <- Rules.check(state_data.rules, {:position_islands, player}), {:ok, coordinate} <- Coordinate.new(row, col), {:ok, island} <- Island.new(key, coordinate), %{} = board <- Board.position_island(board, key, island) do state_data |> update_board(player, board) |> update_rules(rules) |> reply_success(:ok) else :error -> {:reply, :error, state_data} {:error, :invalid_coordinate} -> {:reply, {:error, :invalid_coordinate}, state_data} {:error, :invalid_island_type} -> {:reply, {:error, :invalid_island_type}, state_data} end end def set_islands(game, player) when player in @players do GenServer.call(game, {:set_islands, player}) end def handle_call({:set_islands, player}, _from, state_data) do board = player_board(state_data, player) with {:ok, rules} <- Rules.check(state_data.rules, {:set_islands, player}), true <- Board.all_islands_positioned?(board) do state_data |> update_rules(rules) |> reply_success({:ok, board}) else :error -> {:reply, :error, state_data} false -> {:reply, {:error, :not_all_islands_positioned}, state_data} end end def guess_coordinate(game, player, row, col) when player in @players do GenServer.call(game, {:guess_coordinate, player, row, col}) end def handle_call({:guess_coordinate, player_key, row, col}, _from, state_data) do opponent_key = opponent(player_key) opponent_board = player_board(state_data, opponent_key) with {:ok, rules} <- Rules.check(state_data.rules, {:guess_coordinate, player_key}), {:ok, coordinate} <- Coordinate.new(row, col), {hit_or_miss, forested_island, win_status, opponent_board} <- Board.guess(opponent_board, coordinate), {:ok, rules} <- Rules.check(rules, {:win_check, win_status}) do state_data |> update_board(opponent_key, opponent_board) |> update_guesses(player_key, hit_or_miss, coordinate) |> update_rules(rules) |> reply_success({hit_or_miss, forested_island, win_status}) else :error -> {:reply, :error, state_data} {:error, :invalid_coordinate} -> {:reply, {:error, :invalid_coordinate}, state_data} end end def handle_info(:timeout, state_data) do {:stop, {:shutdown, :timeout}, state_data} end defp opponent(:player1), do: :player2 defp opponent(:player2), do: :player1 defp update_guesses(state_data, player_key, hit_or_miss, coordinate) do update_in(state_data[player_key].guesses, fn guesses -> Guesses.add(guesses, hit_or_miss, coordinate) end) end defp update_board(state_data, player, board) do Map.update!(state_data, player, fn player -> %{player | board: board} end) end defp player_board(state_data, player) do Map.get(state_data, player).board end defp update_player2_name(state_data, name) do put_in(state_data.player2.name, name) end defp update_rules(state_data, rules) do %{state_data | rules: rules} end defp reply_success(state_data, reply) do :ets.insert(:game_state, {state_data.player1.name, state_data}) {:reply, reply, state_data, @timeout} end defp fresh_state(name) do player1 = %{name: name, board: Board.new(), guesses: Guesses.new()} player2 = %{name: nil, board: Board.new(), guesses: Guesses.new()} %{player1: player1, player2: player2, rules: %Rules{}} end end
31.819355
129
0.671127
03b11a7b92efdbd328ec38622a43e4226dfcfa10
1,394
exs
Elixir
channel-sender/mix.exs
gabheadz/async-dataflow
7ca1f3087872b96c6f7f3b2c0f9aa102c74fdb38
[ "MIT" ]
null
null
null
channel-sender/mix.exs
gabheadz/async-dataflow
7ca1f3087872b96c6f7f3b2c0f9aa102c74fdb38
[ "MIT" ]
null
null
null
channel-sender/mix.exs
gabheadz/async-dataflow
7ca1f3087872b96c6f7f3b2c0f9aa102c74fdb38
[ "MIT" ]
1
2022-03-11T15:51:38.000Z
2022-03-11T15:51:38.000Z
defmodule ChannelSenderEx.MixProject do use Mix.Project def project do [ app: :channel_sender_ex, version: "0.1.0", elixir: "~> 1.10", start_permanent: Mix.env() == :prod, deps: deps(), aliases: aliases(), releases: [ channel_sender_ex: [ include_executables_for: [:unix], applications: [runtime_tools: :permanent], steps: [:assemble, :tar] ] ] ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger], mod: {ChannelSenderEx.Application, []} ] end # Run "mix help deps" to learn about dependencies. defp deps do [ # {:dep_from_hexpm, "~> 0.3.0"}, {:benchee, "~> 0.13", only: [:dev, :benchee]}, {:cowboy, "~> 2.8"}, {:cowlib, "~> 2.9", override: true}, {:plug_cowboy, "~> 2.0"}, {:elixir_uuid, "~> 1.2"}, {:gen_state_machine, "~> 2.1"}, {:jason, "~> 1.2"}, {:cors_plug, "~> 2.0"}, {:horde, "~> 0.8.3"}, {:hackney, "~> 1.2.0", only: :test}, {:plug_crypto, "~> 1.1"}, {:stream_data, "~> 0.4", only: [:test]}, {:gun, "~> 1.3", only: [:test, :benchee]} # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} ] end defp aliases do [test: "test --no-start"] end end
25.345455
87
0.515782
03b135c651a23d00925373020f6830114c61b8a4
1,112
ex
Elixir
test/support/channel_case.ex
vinolivae/daily_meals
8f375cbb7eaf54abfa6b683705bb8075067f9078
[ "MIT" ]
null
null
null
test/support/channel_case.ex
vinolivae/daily_meals
8f375cbb7eaf54abfa6b683705bb8075067f9078
[ "MIT" ]
null
null
null
test/support/channel_case.ex
vinolivae/daily_meals
8f375cbb7eaf54abfa6b683705bb8075067f9078
[ "MIT" ]
null
null
null
defmodule DailyMealsWeb.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 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 DailyMealsWeb.ChannelCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate alias Ecto.Adapters.SQL.Sandbox using do quote do # Import conveniences for testing with channels import Phoenix.ChannelTest import DailyMealsWeb.ChannelCase # The default endpoint for testing @endpoint DailyMealsWeb.Endpoint end end setup tags do pid = Sandbox.start_owner!(DailyMeals.Repo, shared: not tags[:async]) on_exit(fn -> Sandbox.stop_owner(pid) end) :ok end end
29.263158
73
0.739209
03b185dfbcf57ed908f547161db68a05696508f2
1,029
ex
Elixir
elixir/lib/junks/application.ex
crappygraphix/junks
a56b5b86e1a5cbcf0a71fc44d6292d6bcd525b76
[ "Apache-2.0" ]
1
2019-04-29T17:46:44.000Z
2019-04-29T17:46:44.000Z
elixir/lib/junks/application.ex
crappygraphix/junks
a56b5b86e1a5cbcf0a71fc44d6292d6bcd525b76
[ "Apache-2.0" ]
null
null
null
elixir/lib/junks/application.ex
crappygraphix/junks
a56b5b86e1a5cbcf0a71fc44d6292d6bcd525b76
[ "Apache-2.0" ]
null
null
null
defmodule Junks.Application do @moduledoc false use Application # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications def start(_type, _args) do import Supervisor.Spec # Define workers and child supervisors to be supervised children = [ # Start the Ecto repository supervisor(Junks.Repo, []), # Start the endpoint when the application starts supervisor(JunksWeb.Endpoint, []), # Start your own worker by calling: Junks.Worker.start_link(arg1, arg2, arg3) # worker(Junks.Worker, [arg1, arg2, arg3]), ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Junks.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do JunksWeb.Endpoint.config_change(changed, removed) :ok end end
30.264706
83
0.709427
03b18f2dc690de351ebefd2b063cd8e171b4c459
495
ex
Elixir
combo/phxexibee/lib/phxexibee_web/views/error_view.ex
exineris/shp_challenge2021
2a5447af681259d0ea699b670cf079bd31315cd8
[ "Apache-2.0" ]
null
null
null
combo/phxexibee/lib/phxexibee_web/views/error_view.ex
exineris/shp_challenge2021
2a5447af681259d0ea699b670cf079bd31315cd8
[ "Apache-2.0" ]
null
null
null
combo/phxexibee/lib/phxexibee_web/views/error_view.ex
exineris/shp_challenge2021
2a5447af681259d0ea699b670cf079bd31315cd8
[ "Apache-2.0" ]
null
null
null
defmodule PhxexibeeWeb.ErrorView do use PhxexibeeWeb, :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.117647
61
0.737374
03b1ad7927f7af7ab6eca4cf26fe950e87746c95
43,070
ex
Elixir
clients/compute/lib/google_api/compute/v1/api/instance_group_managers.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/instance_group_managers.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/instance_group_managers.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.InstanceGroupManagers do @moduledoc """ API calls for all endpoints tagged `InstanceGroupManagers`. """ alias GoogleApi.Compute.V1.Connection import GoogleApi.Compute.V1.RequestBuilder @doc """ Schedules a group action to remove the specified instances from the managed instance group. Abandoning an instance does not delete the instance, but it does remove the instance from any target pools that are applied by the managed instance group. This method reduces the targetSize of the managed instance group by the number of instances that you abandon. This operation is marked as DONE when the action is scheduled even if the instances have not yet been removed from the group. You must separately verify the status of the abandoning action with the listmanagedinstances method. If the group is part of a backend service that has enabled connection draining, it can take up to 60 seconds after the connection draining duration has elapsed before the VM instance is removed or deleted. You can specify a maximum of 1000 instances with this method per request. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - zone (String): The name of the zone where the managed instance group is located. - instance_group_manager (String): The name of the managed instance group. - 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 (InstanceGroupManagersAbandonInstancesRequest): ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_instance_group_managers_abandon_instances(Tesla.Env.client, String.t, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_abandon_instances(connection, project, zone, instance_group_manager, 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}/zones/#{zone}/instanceGroupManagers/#{instance_group_manager}/abandonInstances") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.Operation{}) end @doc """ Retrieves the list of managed instance groups and groups them by zone. ## 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.InstanceGroupManagerAggregatedList{}} on success {:error, info} on failure """ @spec compute_instance_group_managers_aggregated_list(Tesla.Env.client, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.InstanceGroupManagerAggregatedList.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_aggregated_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}/aggregated/instanceGroupManagers") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.InstanceGroupManagerAggregatedList{}) end @doc """ Deletes the specified managed instance group and all of the instances in that group. Note that the instance group must not belong to a backend service. Read Deleting an instance group for more information. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - zone (String): The name of the zone where the managed instance group is located. - instance_group_manager (String): The name of the managed instance group 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_instance_group_managers_delete(Tesla.Env.client, String.t, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_delete(connection, project, zone, instance_group_manager, 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}/zones/#{zone}/instanceGroupManagers/#{instance_group_manager}") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.Operation{}) end @doc """ Schedules a group action to delete the specified instances in the managed instance group. The instances are also removed from any target pools of which they were a member. This method reduces the targetSize of the managed instance group by the number of instances that you delete. This operation is marked as DONE when the action is scheduled even if the instances are still being deleted. You must separately verify the status of the deleting action with the listmanagedinstances method. If the group is part of a backend service that has enabled connection draining, it can take up to 60 seconds after the connection draining duration has elapsed before the VM instance is removed or deleted. You can specify a maximum of 1000 instances with this method per request. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - zone (String): The name of the zone where the managed instance group is located. - instance_group_manager (String): The name of the managed instance group. - 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 (InstanceGroupManagersDeleteInstancesRequest): ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_instance_group_managers_delete_instances(Tesla.Env.client, String.t, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_delete_instances(connection, project, zone, instance_group_manager, 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}/zones/#{zone}/instanceGroupManagers/#{instance_group_manager}/deleteInstances") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.Operation{}) end @doc """ Returns all of the details about the specified managed instance group. Get a list of available managed instance groups by making a list() request. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - zone (String): The name of the zone where the managed instance group is located. - instance_group_manager (String): The name of the managed instance group. - 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.InstanceGroupManager{}} on success {:error, info} on failure """ @spec compute_instance_group_managers_get(Tesla.Env.client, String.t, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.InstanceGroupManager.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_get(connection, project, zone, instance_group_manager, opts \\ []) do optional_params = %{ :"alt" => :query, :"fields" => :query, :"key" => :query, :"oauth_token" => :query, :"prettyPrint" => :query, :"quotaUser" => :query, :"userIp" => :query } %{} |> method(:get) |> url("/#{project}/zones/#{zone}/instanceGroupManagers/#{instance_group_manager}") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.InstanceGroupManager{}) end @doc """ Creates a managed instance group using the information that you specify in the request. After the group is created, it schedules an action to create instances in the group using the specified instance template. This operation is marked as DONE when the group is created even if the instances in the group have not yet been created. You must separately verify the status of the individual instances with the listmanagedinstances method. A managed instance group can have up to 1000 VM instances per group. Please contact Cloud Support if you need an increase in this limit. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - zone (String): The name of the zone where you want to create the managed instance group. - 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 (InstanceGroupManager): ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_instance_group_managers_insert(Tesla.Env.client, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_insert(connection, project, zone, 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}/zones/#{zone}/instanceGroupManagers") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.Operation{}) end @doc """ Retrieves a list of managed instance groups that are contained within the specified project and zone. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - zone (String): The name of the zone where the managed instance group is located. - 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.InstanceGroupManagerList{}} on success {:error, info} on failure """ @spec compute_instance_group_managers_list(Tesla.Env.client, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.InstanceGroupManagerList.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_list(connection, project, zone, 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}/zones/#{zone}/instanceGroupManagers") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.InstanceGroupManagerList{}) end @doc """ Lists all of the instances in the managed instance group. Each instance in the list has a currentAction, which indicates the action that the managed instance group is performing on the instance. For example, if the group is still creating an instance, the currentAction is CREATING. If a previous action failed, the list displays the errors for that failed action. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - zone (String): The name of the zone where the managed instance group is located. - instance_group_manager (String): The name of the managed instance group. - 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): - :max_results (Integer): - :order_by (String): - :page_token (String): ## Returns {:ok, %GoogleApi.Compute.V1.Model.InstanceGroupManagersListManagedInstancesResponse{}} on success {:error, info} on failure """ @spec compute_instance_group_managers_list_managed_instances(Tesla.Env.client, String.t, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.InstanceGroupManagersListManagedInstancesResponse.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_list_managed_instances(connection, project, zone, instance_group_manager, opts \\ []) do optional_params = %{ :"alt" => :query, :"fields" => :query, :"key" => :query, :"oauth_token" => :query, :"prettyPrint" => :query, :"quotaUser" => :query, :"userIp" => :query, :"filter" => :query, :"maxResults" => :query, :"order_by" => :query, :"pageToken" => :query } %{} |> method(:post) |> url("/#{project}/zones/#{zone}/instanceGroupManagers/#{instance_group_manager}/listManagedInstances") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.InstanceGroupManagersListManagedInstancesResponse{}) end @doc """ Schedules a group action to recreate the specified instances in the managed instance group. The instances are deleted and recreated using the current instance template for the managed instance group. This operation is marked as DONE when the action is scheduled even if the instances have not yet been recreated. You must separately verify the status of the recreating action with the listmanagedinstances method. If the group is part of a backend service that has enabled connection draining, it can take up to 60 seconds after the connection draining duration has elapsed before the VM instance is removed or deleted. You can specify a maximum of 1000 instances with this method per request. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - zone (String): The name of the zone where the managed instance group is located. - instance_group_manager (String): The name of the managed instance group. - 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 (InstanceGroupManagersRecreateInstancesRequest): ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_instance_group_managers_recreate_instances(Tesla.Env.client, String.t, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_recreate_instances(connection, project, zone, instance_group_manager, 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}/zones/#{zone}/instanceGroupManagers/#{instance_group_manager}/recreateInstances") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.Operation{}) end @doc """ Resizes the managed instance group. If you increase the size, the group creates new instances using the current instance template. If you decrease the size, the group deletes instances. The resize operation is marked DONE when the resize actions are scheduled even if the group has not yet added or deleted any instances. You must separately verify the status of the creating or deleting actions with the listmanagedinstances method. If the group is part of a backend service that has enabled connection draining, it can take up to 60 seconds after the connection draining duration has elapsed before the VM instance is removed or deleted. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - zone (String): The name of the zone where the managed instance group is located. - instance_group_manager (String): The name of the managed instance group. - size (Integer): The number of running instances that the managed instance group should maintain at any given time. The group automatically adds or removes instances to maintain the number of instances specified by this parameter. - 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_instance_group_managers_resize(Tesla.Env.client, String.t, String.t, String.t, Integer.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_resize(connection, project, zone, instance_group_manager, size, opts \\ []) do optional_params = %{ :"alt" => :query, :"fields" => :query, :"key" => :query, :"oauth_token" => :query, :"prettyPrint" => :query, :"quotaUser" => :query, :"userIp" => :query, :"requestId" => :query } %{} |> method(:post) |> url("/#{project}/zones/#{zone}/instanceGroupManagers/#{instance_group_manager}/resize") |> add_param(:query, :"size", size) |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.Operation{}) end @doc """ Specifies the instance template to use when creating new instances in this group. The templates for existing instances in the group do not change unless you recreate them. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - zone (String): The name of the zone where the managed instance group is located. - instance_group_manager (String): The name of the managed instance group. - 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 (InstanceGroupManagersSetInstanceTemplateRequest): ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_instance_group_managers_set_instance_template(Tesla.Env.client, String.t, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_set_instance_template(connection, project, zone, instance_group_manager, 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}/zones/#{zone}/instanceGroupManagers/#{instance_group_manager}/setInstanceTemplate") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.Operation{}) end @doc """ Modifies the target pools to which all instances in this managed instance group are assigned. The target pools automatically apply to all of the instances in the managed instance group. This operation is marked DONE when you make the request even if the instances have not yet been added to their target pools. The change might take some time to apply to all of the instances in the group depending on the size of the group. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String): Project ID for this request. - zone (String): The name of the zone where the managed instance group is located. - instance_group_manager (String): The name of the managed instance group. - 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 (InstanceGroupManagersSetTargetPoolsRequest): ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_instance_group_managers_set_target_pools(Tesla.Env.client, String.t, String.t, String.t, keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t} | {:error, Tesla.Env.t} def compute_instance_group_managers_set_target_pools(connection, project, zone, instance_group_manager, 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}/zones/#{zone}/instanceGroupManagers/#{instance_group_manager}/setTargetPools") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Compute.V1.Model.Operation{}) end end
72.386555
1,327
0.731577
03b1c0c72f786b86216038e8bffbe784016331c7
6,040
ex
Elixir
apps/ex_wire/lib/ex_wire/packet/capability/par/snapshot_data/state_chunk.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
152
2018-10-27T04:52:03.000Z
2022-03-26T10:34:00.000Z
apps/ex_wire/lib/ex_wire/packet/capability/par/snapshot_data/state_chunk.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
270
2018-04-14T07:34:57.000Z
2018-10-25T18:10:45.000Z
apps/ex_wire/lib/ex_wire/packet/capability/par/snapshot_data/state_chunk.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
25
2018-10-27T12:15:13.000Z
2022-01-25T20:31:14.000Z
defmodule ExWire.Packet.Capability.Par.SnapshotData.StateChunk do @moduledoc """ State chunks store the entire state of a given block. A "rich" account structure is used to save space. Each state chunk consists of a list of lists, each with two items: an address' sha3 hash and a rich account structure correlating with it. """ defmodule RichAccount do @moduledoc """ The rich account structure encodes the usual account data such as the nonce, balance, and code, as well as the full storage. Note: `code_flag` is a single byte which will determine what the `code` data will be: * if 0x00, the account has no code and code is the single byte 0x80, signifying RLP empty data. * if 0x01, the account has code, and code stores an arbitrary-length list of bytes containing the code. * if 0x02, the account has code, and code stores a 32-byte big-endian integer which is the hash of the code. The code’s hash must be substituted if and only if another account which has a smaller account entry has the same code. Note: `storage` is a list of the entire account’s storage, where the items are RLP lists of length two – the first item being sha3(key), and the second item being the storage value. This storage list must be sorted in ascending order by key-hash. Note: If `storage` is large enough that the rich account structure would bring the internal size (see the Validity section) of the chunk to over `CHUNK_SIZE`, only the prefix of storage that would keep the internal size of the chunk within `CHUNK_SIZE` will be included. We will call the unincluded remainder storage'. A new state chunk will begin with an account entry of the same account, but with storage set to the prefix of storage which will fit in the chunk, and so on. """ @type code_flag :: :no_code | :has_code | :has_repeat_code @type storage_tuple :: {EVM.hash(), <<_::256>>} @type t :: %__MODULE__{ nonce: EVM.hash(), balance: integer(), code_flag: code_flag(), code: binary(), storage: list(storage_tuple()) } defstruct [ :nonce, :balance, :code_flag, :code, :storage ] @spec decode_code_flag(0 | 1 | 2) :: code_flag() def decode_code_flag(0), do: :no_code def decode_code_flag(1), do: :has_code def decode_code_flag(2), do: :has_repeat_code @spec encode_code_flag(code_flag()) :: 0 | 1 | 2 def encode_code_flag(:no_code), do: 0 def encode_code_flag(:has_code), do: 1 def encode_code_flag(:has_repeat_code), do: 2 end @type account_entry :: { EVM.hash(), RichAccount.t() } @type t() :: %__MODULE__{ account_entries: list(account_entry()) } defstruct account_entries: [] @doc """ Given a `StateChunk`, serializes for transport within a SnapshotData packet. ## Examples iex> %ExWire.Packet.Capability.Par.SnapshotData.StateChunk{ ...> account_entries: [ ...> { ...> <<1::256>>, ...> %ExWire.Packet.Capability.Par.SnapshotData.StateChunk.RichAccount{ ...> nonce: 2, ...> balance: 3, ...> code_flag: :has_code, ...> code: <<5::256>>, ...> storage: [{<<1::256>>, <<2::256>>}] ...> } ...> } ...> ] ...> } ...> |> ExWire.Packet.Capability.Par.SnapshotData.StateChunk.serialize() [ [ <<1::256>>, [ 2, 3, 1, <<5::256>>, [[<<1::256>>, <<2::256>>]] ] ] ] """ @spec serialize(t()) :: ExRLP.t() def serialize(state_chunk = %__MODULE__{}) do for {hash, rich_account} <- state_chunk.account_entries do [ hash, [ rich_account.nonce, rich_account.balance, RichAccount.encode_code_flag(rich_account.code_flag), rich_account.code, for {key, val} <- rich_account.storage do [key, val] end ] ] end end @doc """ Given an RLP-encoded `StateChunk` from a SnapshotData packet, decodes into a `StateChunk` struct. ## Examples iex> [ ...> [ <<1::256>>, ...> [ ...> 2, ...> 3, ...> 1, ...> <<5::256>>, ...> [[<<1::256>>, <<2::256>>]] ...> ] ...> ] ...> ] ...> |> ExWire.Packet.Capability.Par.SnapshotData.StateChunk.deserialize() %ExWire.Packet.Capability.Par.SnapshotData.StateChunk{ account_entries: [ { <<1::256>>, %ExWire.Packet.Capability.Par.SnapshotData.StateChunk.RichAccount{ nonce: 2, balance: 3, code_flag: :has_code, code: <<5::256>>, storage: [{<<1::256>>, <<2::256>>}] } } ] } """ @spec deserialize(ExRLP.t()) :: t() def deserialize(rlp) do account_entries_rlp = rlp account_entries = for [hash, rich_account_rlp] <- account_entries_rlp do [ nonce, balance, encoded_code_flag, code, storage_rlp ] = rich_account_rlp storage = for [key, val] <- storage_rlp do {key, val} end {hash, %RichAccount{ nonce: Exth.maybe_decode_unsigned(nonce), balance: Exth.maybe_decode_unsigned(balance), code_flag: encoded_code_flag |> Exth.maybe_decode_unsigned() |> RichAccount.decode_code_flag(), code: code, storage: storage }} end %__MODULE__{ account_entries: account_entries } end end
30.351759
83
0.548013
03b1c13bee58d0e2789e3cbc01b5f3725e28b620
311
ex
Elixir
lib/imager_web/views/error.ex
appunite/imager
b41f76be975faf4d255ad0a5d8e972df1924356b
[ "MIT" ]
55
2018-10-02T14:56:04.000Z
2021-12-10T21:08:07.000Z
lib/imager_web/views/error.ex
appunite/imager
b41f76be975faf4d255ad0a5d8e972df1924356b
[ "MIT" ]
27
2018-10-02T14:57:09.000Z
2019-04-11T07:51:11.000Z
lib/imager_web/views/error.ex
appunite/imager
b41f76be975faf4d255ad0a5d8e972df1924356b
[ "MIT" ]
3
2018-10-12T18:31:41.000Z
2020-04-22T15:26:25.000Z
defmodule ImagerWeb.Views.Error do use Phoenix.View, root: "lib/imager_web/templates" @moduledoc false def render("500.json", _), do: %{error: "Internal server error"} def render("404.json", _), do: %{error: "Non existent page"} def render("422.json", _), do: %{error: "Cannot parse arguments"} end
31.1
67
0.684887
03b1e0d15f98ffe9fafe79f16e6e2be98d587de7
444
ex
Elixir
samples/client/petstore/elixir/lib/swagger_petstore/model/return.ex
bruceadams/swagger-codegen-1
2e5289c4d74eafd48e3a324ccdd9e39323b5fb06
[ "Apache-2.0" ]
null
null
null
samples/client/petstore/elixir/lib/swagger_petstore/model/return.ex
bruceadams/swagger-codegen-1
2e5289c4d74eafd48e3a324ccdd9e39323b5fb06
[ "Apache-2.0" ]
null
null
null
samples/client/petstore/elixir/lib/swagger_petstore/model/return.ex
bruceadams/swagger-codegen-1
2e5289c4d74eafd48e3a324ccdd9e39323b5fb06
[ "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 SwaggerPetstore.Model.Return do @moduledoc """ Model for testing reserved words """ @derive [Poison.Encoder] defstruct [ :"return" ] end defimpl Poison.Decoder, for: SwaggerPetstore.Model.Return do def decode(value, _options) do value end end
20.181818
75
0.727477
03b23c2f9121498d39abb25e2d53dd42c1bd54dd
2,640
ex
Elixir
lib/glimesh/subcategories/rawg_source.ex
Megami-Studios/glimesh.tv
57dde3a328fabdcc3305be48ae1b82df27b83c9b
[ "MIT" ]
328
2020-07-23T22:13:49.000Z
2022-03-31T21:22:28.000Z
lib/glimesh/subcategories/rawg_source.ex
Megami-Studios/glimesh.tv
57dde3a328fabdcc3305be48ae1b82df27b83c9b
[ "MIT" ]
362
2020-07-23T22:38:38.000Z
2022-03-24T02:11:16.000Z
lib/glimesh/subcategories/rawg_source.ex
Megami-Studios/glimesh.tv
57dde3a328fabdcc3305be48ae1b82df27b83c9b
[ "MIT" ]
72
2020-07-23T22:50:46.000Z
2022-02-02T11:59:32.000Z
defmodule Glimesh.Subcategories.RawgSource do @moduledoc """ Pull a list of games from Rawg to pre-fill our subcategory list for gaming. """ @source_name "rawg" def update_game_list do {:ok, games} = list_games() IO.puts("Loaded #{length(games)} games into the database") end defp create_subcategory_for_game(game, gaming_category_id) do case Glimesh.ChannelCategories.upsert_subcategory_from_source( @source_name, Integer.to_string(game["id"]), %{ name: game["name"], slug: game["slug"], user_created: false, category_id: gaming_category_id, background_image: background_image(game) } ) do {:ok, _game} -> IO.puts("Loaded: " <> game["name"]) {:error, _} -> IO.puts("Failed to Load: " <> game["name"]) end end defp background_image(%{"background_image" => image, "esrb_rating" => esrb_rating}) when is_binary(image) do if !is_nil(esrb_rating) and Map.get(esrb_rating, "slug", nil) == "adults-only" do "" else image end end defp background_image(_) do "" end defp list_games do params = URI.encode_query(%{ "key" => api_key(), "page_size" => "40", "ordering" => "-metacritic" }) %{id: gaming_id} = Glimesh.ChannelCategories.get_category("gaming") aggregate_page("https://api.rawg.io/api/games?#{params}", [], fn new_games -> # Loop through all of the games until we start getting unreviewed # games, then we know we're into the trash filtered = Enum.reject(new_games, fn x -> is_nil(x["metacritic"]) end) if filtered == [] do :stop else Enum.each(filtered, fn x -> create_subcategory_for_game(x, gaming_id) end) :ok end end) end defp aggregate_page(next_url, existing_list, save_games) do with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <- HTTPoison.get(next_url, [ {"Content-Type", "application/json"} ]), {:ok, %{"next" => next, "results" => games}} <- Jason.decode(body) do existing_list = existing_list ++ games case save_games.(games) do :ok -> aggregate_page(next, existing_list, save_games) :stop -> {:ok, existing_list} end else {:ok, %HTTPoison.Response{status_code: 404}} -> {:error, existing_list} _ -> {:error, existing_list} end end defp api_key do Application.get_env(:glimesh, Glimesh.Subcategories.RawgSource)[:api_key] end end
27.216495
85
0.596591
03b23e587f963c8594de809a56232603d26b9b08
253
ex
Elixir
lib/chatsnek.ex
xtagon/chatsnek
a2bc762da02467631d17ddc8b47217f4a49b740b
[ "MIT" ]
3
2020-12-13T15:24:40.000Z
2021-09-22T17:45:40.000Z
lib/chatsnek.ex
xtagon/chatsnek
a2bc762da02467631d17ddc8b47217f4a49b740b
[ "MIT" ]
8
2020-12-14T01:25:44.000Z
2021-10-03T16:12:23.000Z
lib/chatsnek.ex
xtagon/chatsnek
a2bc762da02467631d17ddc8b47217f4a49b740b
[ "MIT" ]
null
null
null
defmodule ChatSnek do @moduledoc """ ChatSnek keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
25.3
66
0.754941
03b25687bea4861766f9af28ffaa46c588f89795
2,129
ex
Elixir
lib/dlex/utils.ex
m0dnar/dlex
1a3d0216d0aabb8c1ab5c92c5e6847c140769201
[ "Apache-2.0" ]
1
2021-11-26T03:41:39.000Z
2021-11-26T03:41:39.000Z
lib/dlex/utils.ex
m0dnar/dlex
1a3d0216d0aabb8c1ab5c92c5e6847c140769201
[ "Apache-2.0" ]
null
null
null
lib/dlex/utils.ex
m0dnar/dlex
1a3d0216d0aabb8c1ab5c92c5e6847c140769201
[ "Apache-2.0" ]
null
null
null
defmodule Dlex.Utils do @doc """ Encode variables """ def encode_vars(vars) do for {key, value} <- vars, into: %{}, do: {key, to_string(value)} end @doc """ Add temporary blank ids to json object """ def add_blank_ids(statement, uid_key \\ "uid"), do: statement |> add_blank_ids(0, uid_key) |> elem(0) defp add_blank_ids(list, counter, uid_key) when is_list(list) do {list, counter} = Enum.reduce(list, {[], counter}, fn map, {acc, counter} -> {map, counter} = add_blank_ids(map, counter, uid_key) {[map | acc], counter} end) {Enum.reverse(list), counter} end defp add_blank_ids(map, counter, uid_key) when is_map(map) do cond do is_location?(map) or (Map.has_key?(map, :__struct__) and !Map.has_key?(map, :uid)) -> {map, counter} true -> map = Map.update(map, uid_key, "_:#{counter}", &(&1 || "_:#{counter}")) :maps.fold(&do_add_blank_ids(&1, &2, &3, uid_key), {%{}, counter + 1}, map) end end defp add_blank_ids(value, counter, _uid_key), do: {value, counter} defp do_add_blank_ids(key, value, {map, counter}, uid_key) do {value, counter} = add_blank_ids(value, counter, uid_key) {Map.put(map, key, value), counter} end defp is_location?(map) do map_size(map) == 2 and (match?(%{type: _, coordinates: _}, map) or match?(%{"type" => _, "coordinates" => _}, map)) end @doc """ Replace temporary blank ids to real ids """ def replace_ids(json, uids, uid_key \\ "uid") def replace_ids(json, uids, uid_key) when is_list(json), do: Enum.map(json, &replace_ids(&1, uids, uid_key)) def replace_ids(map, uids, uid_key) when is_map(map), do: :maps.fold(&replace_kv(&1, &2, &3, uids, uid_key), map, map) def replace_ids(value, _uids, _uid_key), do: value defp replace_kv(uid_key, "_:" <> blank_id, map, uids, uid_key), do: Map.put(map, uid_key, uids[blank_id]) defp replace_kv(key, value, map, uids, uid_key) do if is_map(value) or is_list(value), do: Map.put(map, key, replace_ids(value, uids, uid_key)), else: map end end
29.985915
98
0.621419
03b25c2ab00bb9e88595209335558b149741dbeb
15,748
exs
Elixir
test/phoenix/digester_test.exs
arjun810/phoenix
b50ca688e7b79423f3124af8778711bb1588947f
[ "MIT" ]
null
null
null
test/phoenix/digester_test.exs
arjun810/phoenix
b50ca688e7b79423f3124af8778711bb1588947f
[ "MIT" ]
null
null
null
test/phoenix/digester_test.exs
arjun810/phoenix
b50ca688e7b79423f3124af8778711bb1588947f
[ "MIT" ]
null
null
null
defmodule Phoenix.DigesterTest do use ExUnit.Case, async: true @output_path Path.join("tmp", "phoenix_digest") @fake_now 32_132_173 @hash_regex ~S"[a-fA-F\d]{32}" setup do File.rm_rf!(@output_path) :ok end describe "compile" do test "fails when the given paths are invalid" do assert {:error, :invalid_path} = Phoenix.Digester.compile("nonexistent path", "/ ?? /path") end test "digests and compress files" do input_path = "test/fixtures/digest/priv/static/" assert :ok = Phoenix.Digester.compile(input_path, @output_path) output_files = assets_files(@output_path) assert "phoenix.png" in output_files refute "phoenix.png.gz" in output_files assert "app.js" in output_files assert "app.js.gz" in output_files assert "css/app.css" in output_files assert "css/app.css.gz" in output_files assert "manifest.json" in output_files assert "manifest.json.gz" in output_files assert "cache_manifest.json" in output_files assert Enum.any?(output_files, &String.match?(&1, ~r/(phoenix-#{@hash_regex}\.png)/)) refute Enum.any?(output_files, &String.match?(&1, ~r/(phoenix-#{@hash_regex}\.png\.gz)/)) json = Path.join(@output_path, "cache_manifest.json") |> json_read!() assert json["latest"]["phoenix.png"] =~ ~r"phoenix-#{@hash_regex}.png" assert json["version"] == 1 end test "includes existing digests in new cache manifest" do source_path = "test/fixtures/digest/priv/static/" input_path = "tmp/digest/static" File.rm_rf!(input_path) :ok = File.mkdir_p!(@output_path) :ok = File.mkdir_p!(input_path) {:ok, _} = File.cp_r(source_path, input_path) :ok = File.cp( Path.join(source_path, "foo.css"), Path.join(@output_path, "foo-d978852bea6530fcd197b5445ed008fd.css") ) :ok = File.cp( "test/fixtures/digest/compile/cache_manifest.json", Path.join(@output_path, "cache_manifest.json") ) assert :ok = Phoenix.Digester.compile(input_path, @output_path) json = Path.join(@output_path, "cache_manifest.json") |> json_read!() # Keep old entries assert json["digests"]["foo-d978852bea6530fcd197b5445ed008fd.css"]["logical_path"] == "foo.css" # Update mtime assert_in_delta json["digests"]["foo-d978852bea6530fcd197b5445ed008fd.css"]["mtime"], now(), 2 # Add new entries key = Enum.find(Map.keys(json["digests"]), &(&1 =~ ~r"phoenix-#{@hash_regex}.png")) assert json["version"] == 1 assert is_integer(json["digests"][key]["mtime"]) assert json["digests"][key]["logical_path"] == "phoenix.png" assert json["digests"][key]["size"] == 13900 assert json["digests"][key]["digest"] =~ ~r"#{@hash_regex}" assert json["digests"][key]["sha512"] == "93pY5dBa8nHHi0Zfj75O/vXCBXb+UvEVCyU7Yd3pzOJ7o1wkYBWbvs3pVXhBChEmo8MDANT11vsggo2+bnYqoQ==" end test "old versions maintain their mtime" do source_path = "test/fixtures/digest/priv/static/" input_path = "tmp/digest/static" File.rm_rf!(input_path) :ok = File.mkdir_p!(@output_path) :ok = File.mkdir_p!(input_path) :ok = File.cp( Path.join(source_path, "foo.css"), Path.join(@output_path, "foo-d978852bea6530fcd197b5445ed008fd.css") ) :ok = File.cp( "test/fixtures/digest/compile/cache_manifest.json", Path.join(@output_path, "cache_manifest.json") ) File.write!(Path.join(input_path, "foo.css"), ".foo { background-color: blue }") assert :ok = Phoenix.Digester.compile(input_path, @output_path) json = Path.join(@output_path, "cache_manifest.json") |> json_read!() assert json["digests"]["foo-d978852bea6530fcd197b5445ed008fd.css"]["mtime"] == 32_132_171 assert_in_delta json["digests"]["foo-1198fd3c7ecf0e8f4a33a6e4fc5ae168.css"]["mtime"], now(), 2 end test "excludes files that no longer exist from cache manifest" do input_path = "tmp/digest/static" File.rm_rf!(input_path) :ok = File.mkdir_p!(input_path) :ok = File.cp( "test/fixtures/digest/compile/cache_manifest.json", Path.join(input_path, "cache_manifest.json") ) assert :ok = Phoenix.Digester.compile(input_path, input_path) json = Path.join(input_path, "cache_manifest.json") |> json_read!() assert json["digests"] == %{} end test "digests and compress nested files" do input_path = "test/fixtures/digest/priv/" assert :ok = Phoenix.Digester.compile(input_path, @output_path) output_files = assets_files(@output_path) assert "static/phoenix.png" in output_files refute "static/phoenix.png.gz" in output_files assert "cache_manifest.json" in output_files assert Enum.any?(output_files, &String.match?(&1, ~r/(phoenix-#{@hash_regex}\.png)/)) refute Enum.any?(output_files, &String.match?(&1, ~r/(phoenix-#{@hash_regex}\.png\.gz)/)) json = Path.join(@output_path, "cache_manifest.json") |> json_read!() assert json["latest"]["static/phoenix.png"] =~ ~r"static/phoenix-#{@hash_regex}\.png" end test "keeps old version in cache manifest when digesting twice" do input_path = Path.join("tmp", "phoenix_digest_twice") input_file = Path.join(input_path, "file.js") File.rm_rf!(input_path) File.mkdir_p!(input_path) File.mkdir_p!(@output_path) File.write!(input_file, "console.log('test');") assert :ok = Phoenix.Digester.compile(input_path, @output_path) json1 = Path.join(@output_path, "cache_manifest.json") |> json_read!() assert Enum.count(json1["digests"]) == 1 File.write!(input_file, "console.log('test2');") assert :ok = Phoenix.Digester.compile(input_path, @output_path) json2 = Path.join(@output_path, "cache_manifest.json") |> json_read!() assert Enum.count(json2["digests"]) == 2 end test "doesn't duplicate files when digesting and compressing twice" do input_path = Path.join("tmp", "phoenix_digest_twice") input_file = Path.join(input_path, "file.js") File.rm_rf!(input_path) File.mkdir_p!(input_path) File.write!(input_file, "console.log('test');") assert :ok = Phoenix.Digester.compile(input_path, input_path) assert :ok = Phoenix.Digester.compile(input_path, input_path) output_files = assets_files(input_path) refute "file.js.gz.gz" in output_files refute "cache_manifest.json.gz" in output_files refute Enum.any?(output_files, &(&1 =~ ~r/file-#{@hash_regex}.[\w|\d]*.[-#{@hash_regex}/)) end test "digests only absolute and relative asset paths found within stylesheets" do input_path = "test/fixtures/digest/priv/static/" assert :ok = Phoenix.Digester.compile(input_path, @output_path) digested_css_filename = assets_files(@output_path) |> Enum.find(&(&1 =~ ~r"app-#{@hash_regex}.css")) digested_css = Path.join(@output_path, digested_css_filename) |> File.read!() refute digested_css =~ ~r"/phoenix\.png" refute digested_css =~ ~r"\.\./images/relative\.png" assert digested_css =~ ~r"/phoenix-#{@hash_regex}\.png\?vsn=d" assert digested_css =~ ~r"\.\./images/relative-#{@hash_regex}\.png\?vsn=d" refute digested_css =~ ~r"http://www.phoenixframework.org/absolute-#{@hash_regex}.png" assert digested_css =~ ~r"http://www.phoenixframework.org/absolute.png" end test "sha512 matches content of digested file" do input_path = "test/fixtures/digest/priv/static/" assert :ok = Phoenix.Digester.compile(input_path, @output_path) digested_css_filename = assets_files(@output_path) |> Enum.find(&(&1 =~ ~r"app-#{@hash_regex}.css")) digested_css = Path.join(@output_path, digested_css_filename) |> File.read!() cache_manifest_file = @output_path |> assets_files() |> Enum.find(&(&1 =~ ~r"cache_manifest.json")) json = Path.join(@output_path, cache_manifest_file) |> json_read!() integrity = Base.encode64(:crypto.hash(:sha512, digested_css)) assert json["digests"][digested_css_filename]["sha512"] == integrity end test "digests sourceMappingURL asset paths found within javascript source files" do input_path = "test/fixtures/digest/priv/static/" assert :ok = Phoenix.Digester.compile(input_path, @output_path) digested_js_map_filename = assets_files(@output_path) |> Enum.find(&(&1 =~ ~r"app.js-#{@hash_regex}.map")) digested_js_filename = assets_files(@output_path) |> Enum.find(&(&1 =~ ~r"app-#{@hash_regex}.js")) digested_js = Path.join(@output_path, digested_js_filename) |> File.read!() refute digested_js =~ "app.js.map" assert digested_js =~ "#{digested_js_map_filename}" js = Path.join(@output_path, "app.js") |> File.read!() assert js =~ "app.js.map" refute js =~ "#{digested_js_map_filename}" end test "digests file url paths found within javascript mapping files" do input_path = "test/fixtures/digest/priv/static/" assert :ok = Phoenix.Digester.compile(input_path, @output_path) digested_js_map_filename = assets_files(@output_path) |> Enum.find(&(&1 =~ ~r"app.js-#{@hash_regex}.map")) digested_js_filename = assets_files(@output_path) |> Enum.find(&(&1 =~ ~r"app-#{@hash_regex}.js")) digested_js_map = Path.join(@output_path, digested_js_map_filename) |> File.read!() refute digested_js_map =~ ~r"\"file\":\"app.js\"" assert digested_js_map =~ ~r"#{digested_js_filename}" end test "does not digest assets within undigested files" do input_path = "test/fixtures/digest/priv/static/" assert :ok = Phoenix.Digester.compile(input_path, @output_path) undigested_css = Path.join(@output_path, "css/app.css") |> File.read!() assert undigested_css =~ ~r"/phoenix\.png" assert undigested_css =~ ~r"\.\./images/relative\.png" refute undigested_css =~ ~r"/phoenix-#{@hash_regex}\.png" refute undigested_css =~ ~r"\.\./images/relative-#{@hash_regex}\.png" end end describe "clean" do test "fails when the given path is invalid" do assert {:error, :invalid_path} = Phoenix.Digester.clean("nonexistent path", 3600, 2) end test "removes versions over the keep count" do manifest_path = "test/fixtures/digest/cleaner/cache_manifest.json" File.mkdir_p!(@output_path) File.cp(manifest_path, "#{@output_path}/cache_manifest.json") File.touch("#{@output_path}/app.css") File.touch("#{@output_path}/app-1.css") File.touch("#{@output_path}/app-1.css.gz") File.touch("#{@output_path}/app-2.css") File.touch("#{@output_path}/app-2.css.gz") File.touch("#{@output_path}/app-3.css") File.touch("#{@output_path}/app-3.css.gz") File.touch("#{@output_path}/manifest.json") File.touch("#{@output_path}/manifest.json.gz") File.touch("#{@output_path}/app.css") assert :ok = Phoenix.Digester.clean(@output_path, 3600, 1, @fake_now) output_files = assets_files(@output_path) assert "app.css" in output_files assert "app-3.css" in output_files assert "app-3.css.gz" in output_files assert "app-2.css" in output_files assert "app-2.css.gz" in output_files assert "manifest.json" in output_files assert "manifest.json.gz" in output_files refute "app-1.css" in output_files refute "app-1.css.gz" in output_files end test "removes files older than specified number of seconds" do manifest_path = "test/fixtures/digest/cleaner/cache_manifest.json" File.mkdir_p!(@output_path) File.cp(manifest_path, "#{@output_path}/cache_manifest.json") File.touch("#{@output_path}/app.css") File.touch("#{@output_path}/app-1.css") File.touch("#{@output_path}/app-1.css.gz") File.touch("#{@output_path}/app-2.css") File.touch("#{@output_path}/app-2.css.gz") File.touch("#{@output_path}/app-3.css") File.touch("#{@output_path}/app-3.css.gz") File.touch("#{@output_path}/manifest.json") File.touch("#{@output_path}/manifest.json.gz") File.touch("#{@output_path}/app.css") assert :ok = Phoenix.Digester.clean(@output_path, 1, 10, @fake_now) output_files = assets_files(@output_path) assert "app.css" in output_files assert "app-2.css" in output_files assert "app-2.css.gz" in output_files assert "app-3.css" in output_files assert "app-3.css.gz" in output_files assert "manifest.json" in output_files assert "manifest.json.gz" in output_files refute "app-1.css" in output_files refute "app-1.css.gz" in output_files end test "cleaning doesn't delete the latest even if the mtime is wrong" do manifest_path = "test/fixtures/digest/cleaner/latest_not_most_recent_cache_manifest.json" File.mkdir_p!(@output_path) File.cp(manifest_path, "#{@output_path}/cache_manifest.json") File.touch("#{@output_path}/app.css") File.touch("#{@output_path}/app-1.css") File.touch("#{@output_path}/app-1.css.gz") File.touch("#{@output_path}/app-2.css") File.touch("#{@output_path}/app-2.css.gz") File.touch("#{@output_path}/app-3.css") File.touch("#{@output_path}/app-3.css.gz") File.touch("#{@output_path}/manifest.json") File.touch("#{@output_path}/manifest.json.gz") File.touch("#{@output_path}/app.css") assert :ok = Phoenix.Digester.clean(@output_path, 3600, 1, @fake_now) output_files = assets_files(@output_path) assert "app.css" in output_files assert "app-3.css" in output_files assert "app-3.css.gz" in output_files assert "app-2.css" in output_files assert "app-2.css.gz" in output_files assert "manifest.json" in output_files assert "manifest.json.gz" in output_files refute "app-1.css" in output_files refute "app-1.css.gz" in output_files end test "cleaning updates cache manifest to remove cleaned files" do manifest_path = "test/fixtures/digest/cleaner/cache_manifest.json" File.mkdir_p!(@output_path) File.cp(manifest_path, "#{@output_path}/cache_manifest.json") File.touch("#{@output_path}/app.css") File.touch("#{@output_path}/app-1.css") File.touch("#{@output_path}/app-1.css.gz") File.touch("#{@output_path}/app-2.css") File.touch("#{@output_path}/app-2.css.gz") File.touch("#{@output_path}/app-3.css") File.touch("#{@output_path}/app-3.css.gz") File.touch("#{@output_path}/manifest.json") File.touch("#{@output_path}/manifest.json.gz") File.touch("#{@output_path}/app.css") assert :ok = Phoenix.Digester.clean(@output_path, 3600, 1, @fake_now) json = Path.join(@output_path, "cache_manifest.json") |> json_read!() refute json["digests"]["app-1.css"] end end defp assets_files(path) do path |> Path.join("**/*") |> Path.wildcard() |> Enum.filter(&(!File.dir?(&1))) |> Enum.map(&Path.relative_to(&1, path)) end defp now do :calendar.datetime_to_gregorian_seconds(:calendar.universal_time()) end defp json_read!(path) do path |> File.read!() |> Phoenix.json_library().decode!() end end
37.495238
105
0.643574
03b26693da25e364003cb3331445e816fe9d1fde
920
ex
Elixir
lib/glimesh/oauth/token_resolver.ex
Darkhax-Forked/glimesh.tv
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
[ "MIT" ]
1
2020-08-02T00:12:28.000Z
2020-08-02T00:12:28.000Z
lib/glimesh/oauth/token_resolver.ex
Darkhax-Forked/glimesh.tv
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
[ "MIT" ]
null
null
null
lib/glimesh/oauth/token_resolver.ex
Darkhax-Forked/glimesh.tv
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
[ "MIT" ]
null
null
null
defmodule Glimesh.Oauth.TokenResolver do @moduledoc """ Resolve a token into a user. """ alias Glimesh.Accounts.User alias Glimesh.Repo def resolve_user(nil) do {:error, "No token specified"} end def resolve_user(token) do config = [otp_app: :glimesh] ExOauth2Provider.authenticate_token(token, config) |> handle_authentication() end defp handle_authentication({:ok, %{resource_owner: %User{} = resource_owner}}) do {:ok, resource_owner} end defp handle_authentication({:ok, %{resource_owner: nil} = oauth_token}) do # Slightly more complicated, need to get the app owner when using Client Credentials Grant owner = oauth_token |> Repo.preload(:application) |> Map.get(:application) |> Repo.preload(:owner) |> Map.get(:owner) {:ok, owner} end defp handle_authentication({:error, reason}) do {:error, reason} end end
23
94
0.673913
03b274d8b6cdf1fa20f4c2465e49d29cd8e7fa27
1,108
ex
Elixir
web/elm-stuff/packages/simonh1000/elm-jwt/5.2.2/examples/phoenix/web/auth/auth.ex
Woody88/AnkiProject
91ce73e058e6d98678073d53a7b84c0b6571aacc
[ "BSD-3-Clause" ]
1
2018-02-21T20:01:51.000Z
2018-02-21T20:01:51.000Z
web/elm-stuff/packages/simonh1000/elm-jwt/5.2.2/examples/phoenix/web/auth/auth.ex
Woody88/AnkiProject
91ce73e058e6d98678073d53a7b84c0b6571aacc
[ "BSD-3-Clause" ]
1
2021-04-21T07:08:26.000Z
2021-04-21T07:08:26.000Z
examples/phoenix/web/auth/auth.ex
JonRowe/elm-jwt
54a65b33b362cb8daa2fcc4dd574aeec2d3c02b6
[ "MIT" ]
null
null
null
defmodule JwtExample.Auth do import Plug.Conn import Comeonin.Bcrypt, only: [ checkpw: 2, dummy_checkpw: 0 ] def init(opts) do Keyword.fetch!(opts, :repo) end def call(conn, repo) do user_id = get_session(conn, :user_id) user = user_id && repo.get(JwtExample.User, user_id) assign(conn, :current_user, user) end def login(conn, user) do conn |> assign(:current_user, user) |> put_session(:user_id, user.id) |> configure_session(renew: true) end def fail(conn) do conn |> assign(:current_user, "failed") end def login_by_username_and_pass(conn, email, given_pass, opts) do repo = Keyword.fetch!(opts, :repo) user = repo.get_by(JwtExample.User, email: email) cond do user && checkpw(given_pass, user.password_hash) -> {:ok, login(conn, user)} user -> {:error, :unauthorized, conn} true -> dummy_checkpw() {:error, :not_found, conn} end end end
26.380952
68
0.559567
03b2756449cc363e193832fce16dde995d61c123
396
exs
Elixir
test/cog/chat/slack/templates/embedded/help_command_documentation_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
1,003
2016-02-23T17:21:12.000Z
2022-02-20T14:39:35.000Z
test/cog/chat/slack/templates/embedded/help_command_documentation_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
906
2016-02-22T22:54:19.000Z
2022-03-11T15:19:43.000Z
test/cog/chat/slack/templates/embedded/help_command_documentation_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
95
2016-02-23T13:42:31.000Z
2021-11-30T14:39:55.000Z
defmodule Cog.Chat.Slack.Templates.Embedded.HelpCommandDocumentationTest do use Cog.TemplateCase test "help-command-documentation template" do data = %{"results" => [%{"documentation" => "big ol' doc string"}]} expected = """ ```big ol' doc string``` """ |> String.strip assert_rendered_template(:slack, :embedded, "help-command-documentation", data, expected) end end
33
93
0.691919
03b2ba24a27573af250c9c0f7f8535666491363a
1,448
ex
Elixir
priv/templates/coh.install/models/coherence/trackable.ex
thefuture2092/coherence
377d91ff01622773b5a9ec39fadf1f8c27328879
[ "MIT" ]
8
2019-01-15T08:57:07.000Z
2020-08-26T13:43:01.000Z
priv/templates/coh.install/models/coherence/trackable.ex
thefuture2092/coherence
377d91ff01622773b5a9ec39fadf1f8c27328879
[ "MIT" ]
2
2019-05-29T17:49:10.000Z
2019-06-18T21:39:22.000Z
priv/templates/coh.install/models/coherence/trackable.ex
thefuture2092/coherence
377d91ff01622773b5a9ec39fadf1f8c27328879
[ "MIT" ]
22
2018-12-10T02:15:18.000Z
2020-10-06T08:42:22.000Z
defmodule <%= base %>.Coherence.Trackable do @moduledoc """ Schema responsible for saving user tracking data for the --trackable-table option. """ use Ecto.Schema import Ecto.Changeset alias Coherence.Config @fields ~w(action sign_in_count current_sign_in_ip current_sign_in_at last_sign_in_ip last_sign_in_at user_id)a <%= if use_binary_id? do %> @primary_key {:id, :binary_id, autogenerate: true} @foreign_key_type :binary_id <% else %><% end %> schema "trackables" do field(:action, :string, null: false) field(:sign_in_count, :integer, default: 0) field(:current_sign_in_at, :naive_datetime) field(:last_sign_in_at, :naive_datetime) field(:current_sign_in_ip, :string) field(:last_sign_in_ip, :string) belongs_to(:user, Config.user_schema()<%= if use_binary_id?, do: ", type: :binary_id", else: "" %>) timestamps() end @doc """ Creates a changeset based on the `model` and `params`. If no params are provided, an invalid changeset is returned with no validation performed. """ @spec changeset(Ecto.Schema.t(), Map.t()) :: Ecto.Changeset.t() def changeset(model, params \\ %{}) do model |> cast(params, @fields) |> validate_required([:action, :user_id]) end @doc """ Creates a changeset for a new schema """ @spec new_changeset(Map.t()) :: Ecto.Changeset.t() def new_changeset(params \\ %{}) do changeset(%__MODULE__{}, params) end end
29.55102
113
0.685083
03b2c067fb12e62f086d29b4d6aa961c72377c17
1,046
ex
Elixir
web/models/item.ex
robot-overlord/todo-example
2877bf3dc94e857a576fdc922c040c6af2f68ec0
[ "MIT" ]
1
2017-07-20T17:41:13.000Z
2017-07-20T17:41:13.000Z
web/models/item.ex
robot-overlord/todo-example
2877bf3dc94e857a576fdc922c040c6af2f68ec0
[ "MIT" ]
null
null
null
web/models/item.ex
robot-overlord/todo-example
2877bf3dc94e857a576fdc922c040c6af2f68ec0
[ "MIT" ]
null
null
null
defmodule Todo.Item do @moduledoc """ Models a list item Backed by Ecto Completer --- Item >--- List (User) """ use Todo.Web, :model @type t :: %Todo.Item{ id: non_neg_integer(), name: String.t(), image_url: String.t(), completer: Todo.User.t() | nil, list: Todo.List.t(), inserted_at: Ecto.DateTime.t(), updated_at: Ecto.DateTime.t() } schema "items" do # ========== # Attributes # ========== field :name, :string field :image_url, :string timestamps() # ============ # Associations # ============ belongs_to :list, Todo.List belongs_to :completer, Todo.User end @allowed_fields ~W(name image_url completer_id list_id) @required_fields ~W(name list_id)a @spec changeset(t(), map()) :: Ecto.Changeset.t() def changeset(item, params \\ %{}) do item |> cast(params, @allowed_fields) |> validate_required(@required_fields) |> assoc_constraint(:completer) |> assoc_constraint(:list) end end
18.350877
57
0.575526
03b2c0a28bdbf648dfacb800408efc23576de6ce
109,241
ex
Elixir
lib/elixir/lib/enum.ex
bruteforcecat/elixir
2013b4dc34cd65953615f71e721e2e9c3949ec85
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/enum.ex
bruteforcecat/elixir
2013b4dc34cd65953615f71e721e2e9c3949ec85
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/enum.ex
bruteforcecat/elixir
2013b4dc34cd65953615f71e721e2e9c3949ec85
[ "Apache-2.0" ]
null
null
null
defprotocol Enumerable do @moduledoc """ Enumerable protocol used by `Enum` and `Stream` modules. When you invoke a function in the `Enum` module, the first argument is usually a collection that must implement this protocol. For example, the expression: Enum.map([1, 2, 3], &(&1 * 2)) invokes `Enumerable.reduce/3` to perform the reducing operation that builds a mapped list by calling the mapping function `&(&1 * 2)` on every element in the collection and consuming the element with an accumulated list. Internally, `Enum.map/2` is implemented as follows: def map(enumerable, fun) do reducer = fn x, acc -> {:cont, [fun.(x) | acc]} end Enumerable.reduce(enumerable, {:cont, []}, reducer) |> elem(1) |> :lists.reverse() end Notice the user-supplied function is wrapped into a `t:reducer/0` function. The `t:reducer/0` function must return a tagged tuple after each step, as described in the `t:acc/0` type. At the end, `Enumerable.reduce/3` returns `t:result/0`. This protocol uses tagged tuples to exchange information between the reducer function and the data type that implements the protocol. This allows enumeration of resources, such as files, to be done efficiently while also guaranteeing the resource will be closed at the end of the enumeration. This protocol also allows suspension of the enumeration, which is useful when interleaving between many enumerables is required (as in the `zip/1` and `zip/2` functions). This protocol requires four functions to be implemented, `reduce/3`, `count/1`, `member?/2`, and `slice/1`. The core of the protocol is the `reduce/3` function. All other functions exist as optimizations paths for data structures that can implement certain properties in better than linear time. """ @typedoc """ The accumulator value for each step. It must be a tagged tuple with one of the following "tags": * `:cont` - the enumeration should continue * `:halt` - the enumeration should halt immediately * `:suspend` - the enumeration should be suspended immediately Depending on the accumulator value, the result returned by `Enumerable.reduce/3` will change. Please check the `t:result/0` type documentation for more information. In case a `t:reducer/0` function returns a `:suspend` accumulator, it must be explicitly handled by the caller and never leak. """ @type acc :: {:cont, term} | {:halt, term} | {:suspend, term} @typedoc """ The reducer function. Should be called with the `enumerable` element and the accumulator contents. Returns the accumulator for the next enumeration step. """ @type reducer :: (term, term -> acc) @typedoc """ The result of the reduce operation. It may be *done* when the enumeration is finished by reaching its end, or *halted*/*suspended* when the enumeration was halted or suspended by the `t:reducer/0` function. In case a `t:reducer/0` function returns the `:suspend` accumulator, the `:suspended` tuple must be explicitly handled by the caller and never leak. In practice, this means regular enumeration functions just need to be concerned about `:done` and `:halted` results. Furthermore, a `:suspend` call must always be followed by another call, eventually halting or continuing until the end. """ @type result :: {:done, term} | {:halted, term} | {:suspended, term, continuation} @typedoc """ A partially applied reduce function. The continuation is the closure returned as a result when the enumeration is suspended. When invoked, it expects a new accumulator and it returns the result. A continuation can be trivially implemented as long as the reduce function is defined in a tail recursive fashion. If the function is tail recursive, all the state is passed as arguments, so the continuation is the reducing function partially applied. """ @type continuation :: (acc -> result) @typedoc """ A slicing function that receives the initial position and the number of elements in the slice. The `start` position is a number `>= 0` and guaranteed to exist in the `enumerable`. The length is a number `>= 1` in a way that `start + length <= count`, where `count` is the maximum amount of elements in the enumerable. The function should return a non empty list where the amount of elements is equal to `length`. """ @type slicing_fun :: (start :: non_neg_integer, length :: pos_integer -> [term()]) @doc """ Reduces the `enumerable` into an element. Most of the operations in `Enum` are implemented in terms of reduce. This function should apply the given `t:reducer/0` function to each element in the `enumerable` and proceed as expected by the returned accumulator. See the documentation of the types `t:result/0` and `t:acc/0` for more information. ## Examples As an example, here is the implementation of `reduce` for lists: def reduce(_list, {:halt, acc}, _fun), do: {:halted, acc} def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)} def reduce([], {:cont, acc}, _fun), do: {:done, acc} def reduce([head | tail], {:cont, acc}, fun), do: reduce(tail, fun.(head, acc), fun) """ @spec reduce(t, acc, reducer) :: result def reduce(enumerable, acc, fun) @doc """ Retrieves the number of elements in the `enumerable`. It should return `{:ok, count}` if you can count the number of elements in the `enumerable`. Otherwise it should return `{:error, __MODULE__}` and a default algorithm built on top of `reduce/3` that runs in linear time will be used. """ @spec count(t) :: {:ok, non_neg_integer} | {:error, module} def count(enumerable) @doc """ Checks if an `element` exists within the `enumerable`. It should return `{:ok, boolean}` if you can check the membership of a given element in the `enumerable` with `===/2` without traversing the whole enumerable. Otherwise it should return `{:error, __MODULE__}` and a default algorithm built on top of `reduce/3` that runs in linear time will be used. When not called whithin guards, the [`in`](`in/2`) and [`not in`](`in/2`) operators work by using this function. """ @spec member?(t, term) :: {:ok, boolean} | {:error, module} def member?(enumerable, element) @doc """ Returns a function that slices the data structure contiguously. It should return `{:ok, size, slicing_fun}` if the `enumerable` has a known bound and can access a position in the `enumerable` without traversing all previous elements. Otherwise it should return `{:error, __MODULE__}` and a default algorithm built on top of `reduce/3` that runs in linear time will be used. ## Differences to `count/1` The `size` value returned by this function is used for boundary checks, therefore it is extremely important that this function only returns `:ok` if retrieving the `size` of the `enumerable` is cheap, fast and takes constant time. Otherwise the simplest of operations, such as `Enum.at(enumerable, 0)`, will become too expensive. On the other hand, the `count/1` function in this protocol should be implemented whenever you can count the number of elements in the collection. """ @spec slice(t) :: {:ok, size :: non_neg_integer(), slicing_fun()} | {:error, module()} def slice(enumerable) end defmodule Enum do import Kernel, except: [max: 2, min: 2] @moduledoc """ Provides a set of algorithms to work with enumerables. In Elixir, an enumerable is any data type that implements the `Enumerable` protocol. `List`s (`[1, 2, 3]`), `Map`s (`%{foo: 1, bar: 2}`) and `Range`s (`1..3`) are common data types used as enumerables: iex> Enum.map([1, 2, 3], fn x -> x * 2 end) [2, 4, 6] iex> Enum.sum([1, 2, 3]) 6 iex> Enum.map(1..3, fn x -> x * 2 end) [2, 4, 6] iex> Enum.sum(1..3) 6 iex> map = %{"a" => 1, "b" => 2} iex> Enum.map(map, fn {k, v} -> {k, v * 2} end) [{"a", 2}, {"b", 4}] However, many other enumerables exist in the language, such as `MapSet`s and the data type returned by `File.stream!/3` which allows a file to be traversed as if it was an enumerable. The functions in this module work in linear time. This means that, the time it takes to perform an operation grows at the same rate as the length of the enumerable. This is expected on operations such as `Enum.map/2`. After all, if we want to traverse every element on a list, the longer the list, the more elements we need to traverse, and the longer it will take. This linear behaviour should also be expected on operations like `count/1`, `member?/2`, `at/2` and similar. While Elixir does allow data types to provide performant variants for such operations, you should not expect it to always be available, since the `Enum` module is meant to work with a large variety of data types and not all data types can provide optimized behaviour. Finally, note the functions in the `Enum` module are eager: they will traverse the enumerable as soon as they are invoked. This is particularly dangerous when working with infinite enumerables. In such cases, you should use the `Stream` module, which allows you to lazily express computations, without traversing collections, and work with possibly infinite collections. See the `Stream` module for examples and documentation. """ @compile :inline_list_funcs @type t :: Enumerable.t() @type acc :: any @type element :: any @typedoc "Zero-based index. It can also be a negative integer." @type index :: integer @type default :: any require Stream.Reducers, as: R defmacrop skip(acc) do acc end defmacrop next(_, entry, acc) do quote(do: [unquote(entry) | unquote(acc)]) end defmacrop acc(head, state, _) do quote(do: {unquote(head), unquote(state)}) end defmacrop next_with_acc(_, entry, head, state, _) do quote do {[unquote(entry) | unquote(head)], unquote(state)} end end @doc """ Returns `true` if `fun.(element)` is truthy for all elements in `enumerable`. Iterates over the `enumerable` and invokes `fun` on each element. When an invocation of `fun` returns a falsy value (`false` or `nil`) iteration stops immediately and `false` is returned. In all other cases `true` is returned. ## Examples iex> Enum.all?([2, 4, 6], fn x -> rem(x, 2) == 0 end) true iex> Enum.all?([2, 3, 4], fn x -> rem(x, 2) == 0 end) false iex> Enum.all?([], fn x -> x > 0 end) true If no function is given, the truthiness of each element is checked during iteration. When an element has a falsy value (`false` or `nil`) iteration stops immediately and `false` is returned. In all other cases `true` is returned. iex> Enum.all?([1, 2, 3]) true iex> Enum.all?([1, nil, 3]) false iex> Enum.all?([]) true """ @spec all?(t, (element -> as_boolean(term))) :: boolean def all?(enumerable, fun \\ fn x -> x end) def all?(enumerable, fun) when is_list(enumerable) do all_list(enumerable, fun) end def all?(enumerable, fun) do Enumerable.reduce(enumerable, {:cont, true}, fn entry, _ -> if fun.(entry), do: {:cont, true}, else: {:halt, false} end) |> elem(1) end @doc """ Returns `true` if `fun.(element)` is truthy for at least one element in `enumerable`. Iterates over the `enumerable` and invokes `fun` on each element. When an invocation of `fun` returns a truthy value (neither `false` nor `nil`) iteration stops immediately and `true` is returned. In all other cases `false` is returned. ## Examples iex> Enum.any?([2, 4, 6], fn x -> rem(x, 2) == 1 end) false iex> Enum.any?([2, 3, 4], fn x -> rem(x, 2) == 1 end) true iex> Enum.any?([], fn x -> x > 0 end) false If no function is given, the truthiness of each element is checked during iteration. When an element has a truthy value (neither `false` nor `nil`) iteration stops immediately and `true` is returned. In all other cases `false` is returned. iex> Enum.any?([false, false, false]) false iex> Enum.any?([false, true, false]) true iex> Enum.any?([]) false """ @spec any?(t, (element -> as_boolean(term))) :: boolean def any?(enumerable, fun \\ fn x -> x end) def any?(enumerable, fun) when is_list(enumerable) do any_list(enumerable, fun) end def any?(enumerable, fun) do Enumerable.reduce(enumerable, {:cont, false}, fn entry, _ -> if fun.(entry), do: {:halt, true}, else: {:cont, false} end) |> elem(1) end @doc """ Finds the element at the given `index` (zero-based). Returns `default` if `index` is out of bounds. A negative `index` can be passed, which means the `enumerable` is enumerated once and the `index` is counted from the end (for example, `-1` finds the last element). ## Examples iex> Enum.at([2, 4, 6], 0) 2 iex> Enum.at([2, 4, 6], 2) 6 iex> Enum.at([2, 4, 6], 4) nil iex> Enum.at([2, 4, 6], 4, :none) :none """ @spec at(t, index, default) :: element | default def at(enumerable, index, default \\ nil) when is_integer(index) do case slice_any(enumerable, index, 1) do [value] -> value [] -> default end end @doc false @deprecated "Use Enum.chunk_every/2 instead" def chunk(enumerable, count), do: chunk(enumerable, count, count, nil) @doc false @deprecated "Use Enum.chunk_every/3 instead" def chunk(enum, n, step) do chunk_every(enum, n, step, :discard) end @doc false @deprecated "Use Enum.chunk_every/4 instead" def chunk(enumerable, count, step, leftover) do chunk_every(enumerable, count, step, leftover || :discard) end @doc """ Shortcut to `chunk_every(enumerable, count, count)`. """ @doc since: "1.5.0" @spec chunk_every(t, pos_integer) :: [list] def chunk_every(enumerable, count), do: chunk_every(enumerable, count, count, []) @doc """ Returns list of lists containing `count` elements each, where each new chunk starts `step` elements into the `enumerable`. `step` is optional and, if not passed, defaults to `count`, i.e. chunks do not overlap. If the last chunk does not have `count` elements to fill the chunk, elements are taken from `leftover` to fill in the chunk. If `leftover` does not have enough elements to fill the chunk, then a partial chunk is returned with less than `count` elements. If `:discard` is given in `leftover`, the last chunk is discarded unless it has exactly `count` elements. ## Examples iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 2) [[1, 2], [3, 4], [5, 6]] iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, :discard) [[1, 2, 3], [3, 4, 5]] iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, [7]) [[1, 2, 3], [3, 4, 5], [5, 6, 7]] iex> Enum.chunk_every([1, 2, 3, 4], 3, 3, []) [[1, 2, 3], [4]] iex> Enum.chunk_every([1, 2, 3, 4], 10) [[1, 2, 3, 4]] iex> Enum.chunk_every([1, 2, 3, 4, 5], 2, 3, []) [[1, 2], [4, 5]] """ @doc since: "1.5.0" @spec chunk_every(t, pos_integer, pos_integer, t | :discard) :: [list] def chunk_every(enumerable, count, step, leftover \\ []) when is_integer(count) and count > 0 and is_integer(step) and step > 0 do R.chunk_every(&chunk_while/4, enumerable, count, step, leftover) end @doc """ Chunks the `enumerable` with fine grained control when every chunk is emitted. `chunk_fun` receives the current element and the accumulator and must return `{:cont, chunk, acc}` to emit the given chunk and continue with accumulator or `{:cont, acc}` to not emit any chunk and continue with the return accumulator. `after_fun` is invoked when iteration is done and must also return `{:cont, chunk, acc}` or `{:cont, acc}`. Returns a list of lists. ## Examples iex> chunk_fun = fn element, acc -> ...> if rem(element, 2) == 0 do ...> {:cont, Enum.reverse([element | acc]), []} ...> else ...> {:cont, [element | acc]} ...> end ...> end iex> after_fun = fn ...> [] -> {:cont, []} ...> acc -> {:cont, Enum.reverse(acc), []} ...> end iex> Enum.chunk_while(1..10, [], chunk_fun, after_fun) [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] """ @doc since: "1.5.0" @spec chunk_while( t, acc, (element, acc -> {:cont, chunk, acc} | {:cont, acc} | {:halt, acc}), (acc -> {:cont, chunk, acc} | {:cont, acc}) ) :: Enumerable.t() when chunk: any def chunk_while(enumerable, acc, chunk_fun, after_fun) do {_, {res, acc}} = Enumerable.reduce(enumerable, {:cont, {[], acc}}, fn entry, {buffer, acc} -> case chunk_fun.(entry, acc) do {:cont, emit, acc} -> {:cont, {[emit | buffer], acc}} {:cont, acc} -> {:cont, {buffer, acc}} {:halt, acc} -> {:halt, {buffer, acc}} end end) case after_fun.(acc) do {:cont, _acc} -> :lists.reverse(res) {:cont, elem, _acc} -> :lists.reverse([elem | res]) end end @doc """ Splits enumerable on every element for which `fun` returns a new value. Returns a list of lists. ## Examples iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1)) [[1], [2, 2], [3], [4, 4, 6], [7, 7]] """ @spec chunk_by(t, (element -> any)) :: [list] def chunk_by(enumerable, fun) do R.chunk_by(&chunk_while/4, enumerable, fun) end @doc """ Given an enumerable of enumerables, concatenates the `enumerables` into a single list. ## Examples iex> Enum.concat([1..3, 4..6, 7..9]) [1, 2, 3, 4, 5, 6, 7, 8, 9] iex> Enum.concat([[1, [2], 3], [4], [5, 6]]) [1, [2], 3, 4, 5, 6] """ @spec concat(t) :: t def concat(enumerables) do fun = &[&1 | &2] enumerables |> reduce([], &reduce(&1, &2, fun)) |> :lists.reverse() end @doc """ Concatenates the enumerable on the `right` with the enumerable on the `left`. This function produces the same result as the `Kernel.++/2` operator for lists. ## Examples iex> Enum.concat(1..3, 4..6) [1, 2, 3, 4, 5, 6] iex> Enum.concat([1, 2, 3], [4, 5, 6]) [1, 2, 3, 4, 5, 6] """ @spec concat(t, t) :: t def concat(left, right) when is_list(left) and is_list(right) do left ++ right end def concat(left, right) do concat([left, right]) end @doc """ Returns the size of the `enumerable`. ## Examples iex> Enum.count([1, 2, 3]) 3 """ @spec count(t) :: non_neg_integer def count(enumerable) when is_list(enumerable) do length(enumerable) end def count(enumerable) do case Enumerable.count(enumerable) do {:ok, value} when is_integer(value) -> value {:error, module} -> enumerable |> module.reduce({:cont, 0}, fn _, acc -> {:cont, acc + 1} end) |> elem(1) end end @doc """ Returns the count of elements in the `enumerable` for which `fun` returns a truthy value. ## Examples iex> Enum.count([1, 2, 3, 4, 5], fn x -> rem(x, 2) == 0 end) 2 """ @spec count(t, (element -> as_boolean(term))) :: non_neg_integer def count(enumerable, fun) do reduce(enumerable, 0, fn entry, acc -> if(fun.(entry), do: acc + 1, else: acc) end) end @doc """ Enumerates the `enumerable`, returning a list where all consecutive duplicated elements are collapsed to a single element. Elements are compared using `===/2`. If you want to remove all duplicated elements, regardless of order, see `uniq/1`. ## Examples iex> Enum.dedup([1, 2, 3, 3, 2, 1]) [1, 2, 3, 2, 1] iex> Enum.dedup([1, 1, 2, 2.0, :three, :three]) [1, 2, 2.0, :three] """ @spec dedup(t) :: list def dedup(enumerable) do dedup_by(enumerable, fn x -> x end) end @doc """ Enumerates the `enumerable`, returning a list where all consecutive duplicated elements are collapsed to a single element. The function `fun` maps every element to a term which is used to determine if two elements are duplicates. ## Examples iex> Enum.dedup_by([{1, :a}, {2, :b}, {2, :c}, {1, :a}], fn {x, _} -> x end) [{1, :a}, {2, :b}, {1, :a}] iex> Enum.dedup_by([5, 1, 2, 3, 2, 1], fn x -> x > 2 end) [5, 1, 3, 2] """ @spec dedup_by(t, (element -> term)) :: list def dedup_by(enumerable, fun) do {list, _} = reduce(enumerable, {[], []}, R.dedup(fun)) :lists.reverse(list) end @doc """ Drops the `amount` of elements from the `enumerable`. If a negative `amount` is given, the `amount` of last values will be dropped. The `enumerable` will be enumerated once to retrieve the proper index and the remaining calculation is performed from the end. ## Examples iex> Enum.drop([1, 2, 3], 2) [3] iex> Enum.drop([1, 2, 3], 10) [] iex> Enum.drop([1, 2, 3], 0) [1, 2, 3] iex> Enum.drop([1, 2, 3], -1) [1, 2] """ @spec drop(t, integer) :: list def drop(enumerable, amount) when is_list(enumerable) and is_integer(amount) and amount >= 0 do drop_list(enumerable, amount) end def drop(enumerable, amount) when is_integer(amount) and amount >= 0 do {result, _} = reduce(enumerable, {[], amount}, R.drop()) if is_list(result), do: :lists.reverse(result), else: [] end def drop(enumerable, amount) when is_integer(amount) and amount < 0 do {count, fun} = slice_count_and_fun(enumerable) amount = Kernel.min(amount + count, count) if amount > 0 do fun.(0, amount) else [] end end @doc """ Returns a list of every `nth` element in the `enumerable` dropped, starting with the first element. The first element is always dropped, unless `nth` is 0. The second argument specifying every `nth` element must be a non-negative integer. ## Examples iex> Enum.drop_every(1..10, 2) [2, 4, 6, 8, 10] iex> Enum.drop_every(1..10, 0) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] iex> Enum.drop_every([1, 2, 3], 1) [] """ @spec drop_every(t, non_neg_integer) :: list def drop_every(enumerable, nth) def drop_every(_enumerable, 1), do: [] def drop_every(enumerable, 0), do: to_list(enumerable) def drop_every([], nth) when is_integer(nth), do: [] def drop_every(enumerable, nth) when is_integer(nth) and nth > 1 do {res, _} = reduce(enumerable, {[], :first}, R.drop_every(nth)) :lists.reverse(res) end @doc """ Drops elements at the beginning of the `enumerable` while `fun` returns a truthy value. ## Examples iex> Enum.drop_while([1, 2, 3, 2, 1], fn x -> x < 3 end) [3, 2, 1] """ @spec drop_while(t, (element -> as_boolean(term))) :: list def drop_while(enumerable, fun) when is_list(enumerable) do drop_while_list(enumerable, fun) end def drop_while(enumerable, fun) do {res, _} = reduce(enumerable, {[], true}, R.drop_while(fun)) :lists.reverse(res) end @doc """ Invokes the given `fun` for each element in the `enumerable`. Returns `:ok`. ## Examples Enum.each(["some", "example"], fn x -> IO.puts(x) end) "some" "example" #=> :ok """ @spec each(t, (element -> any)) :: :ok def each(enumerable, fun) when is_list(enumerable) do :lists.foreach(fun, enumerable) :ok end def each(enumerable, fun) do reduce(enumerable, nil, fn entry, _ -> fun.(entry) nil end) :ok end @doc """ Determines if the `enumerable` is empty. Returns `true` if `enumerable` is empty, otherwise `false`. ## Examples iex> Enum.empty?([]) true iex> Enum.empty?([1, 2, 3]) false """ @spec empty?(t) :: boolean def empty?(enumerable) when is_list(enumerable) do enumerable == [] end def empty?(enumerable) do case Enumerable.slice(enumerable) do {:ok, value, _} -> value == 0 {:error, module} -> enumerable |> module.reduce({:cont, true}, fn _, _ -> {:halt, false} end) |> elem(1) end end @doc """ Finds the element at the given `index` (zero-based). Returns `{:ok, element}` if found, otherwise `:error`. A negative `index` can be passed, which means the `enumerable` is enumerated once and the `index` is counted from the end (for example, `-1` fetches the last element). ## Examples iex> Enum.fetch([2, 4, 6], 0) {:ok, 2} iex> Enum.fetch([2, 4, 6], -3) {:ok, 2} iex> Enum.fetch([2, 4, 6], 2) {:ok, 6} iex> Enum.fetch([2, 4, 6], 4) :error """ @spec fetch(t, index) :: {:ok, element} | :error def fetch(enumerable, index) when is_integer(index) do case slice_any(enumerable, index, 1) do [value] -> {:ok, value} [] -> :error end end @doc """ Finds the element at the given `index` (zero-based). Raises `OutOfBoundsError` if the given `index` is outside the range of the `enumerable`. ## Examples iex> Enum.fetch!([2, 4, 6], 0) 2 iex> Enum.fetch!([2, 4, 6], 2) 6 iex> Enum.fetch!([2, 4, 6], 4) ** (Enum.OutOfBoundsError) out of bounds error """ @spec fetch!(t, index) :: element def fetch!(enumerable, index) when is_integer(index) do case slice_any(enumerable, index, 1) do [value] -> value [] -> raise Enum.OutOfBoundsError end end @doc """ Filters the `enumerable`, i.e. returns only those elements for which `fun` returns a truthy value. See also `reject/2` which discards all elements where the function returns a truthy value. ## Examples iex> Enum.filter([1, 2, 3], fn x -> rem(x, 2) == 0 end) [2] Keep in mind that `filter` is not capable of filtering and transforming an element at the same time. If you would like to do so, consider using `flat_map/2`. For example, if you want to convert all strings that represent an integer and discard the invalid one in one pass: strings = ["1234", "abc", "12ab"] Enum.flat_map(strings, fn string -> case Integer.parse(string) do # transform to integer {int, _rest} -> [int] # skip the value :error -> [] end end) """ @spec filter(t, (element -> as_boolean(term))) :: list def filter(enumerable, fun) when is_list(enumerable) do filter_list(enumerable, fun) end def filter(enumerable, fun) do reduce(enumerable, [], R.filter(fun)) |> :lists.reverse() end @doc false @deprecated "Use Enum.filter/2 + Enum.map/2 or for comprehensions instead" def filter_map(enumerable, filter, mapper) when is_list(enumerable) do for element <- enumerable, filter.(element), do: mapper.(element) end def filter_map(enumerable, filter, mapper) do enumerable |> reduce([], R.filter_map(filter, mapper)) |> :lists.reverse() end @doc """ Returns the first element for which `fun` returns a truthy value. If no such element is found, returns `default`. ## Examples iex> Enum.find([2, 3, 4], fn x -> rem(x, 2) == 1 end) 3 iex> Enum.find([2, 4, 6], fn x -> rem(x, 2) == 1 end) nil iex> Enum.find([2, 4, 6], 0, fn x -> rem(x, 2) == 1 end) 0 """ @spec find(t, default, (element -> any)) :: element | default def find(enumerable, default \\ nil, fun) def find(enumerable, default, fun) when is_list(enumerable) do find_list(enumerable, default, fun) end def find(enumerable, default, fun) do Enumerable.reduce(enumerable, {:cont, default}, fn entry, default -> if fun.(entry), do: {:halt, entry}, else: {:cont, default} end) |> elem(1) end @doc """ Similar to `find/3`, but returns the index (zero-based) of the element instead of the element itself. ## Examples iex> Enum.find_index([2, 4, 6], fn x -> rem(x, 2) == 1 end) nil iex> Enum.find_index([2, 3, 4], fn x -> rem(x, 2) == 1 end) 1 """ @spec find_index(t, (element -> any)) :: non_neg_integer | nil def find_index(enumerable, fun) when is_list(enumerable) do find_index_list(enumerable, 0, fun) end def find_index(enumerable, fun) do result = Enumerable.reduce(enumerable, {:cont, {:not_found, 0}}, fn entry, {_, index} -> if fun.(entry), do: {:halt, {:found, index}}, else: {:cont, {:not_found, index + 1}} end) case elem(result, 1) do {:found, index} -> index {:not_found, _} -> nil end end @doc """ Similar to `find/3`, but returns the value of the function invocation instead of the element itself. The return value is considered to be found when the result is truthy (neither `nil` nor `false`). ## Examples iex> Enum.find_value([2, 3, 4], fn x -> ...> if x > 2, do: x * x ...> end) 9 iex> Enum.find_value([2, 4, 6], fn x -> rem(x, 2) == 1 end) nil iex> Enum.find_value([2, 3, 4], fn x -> rem(x, 2) == 1 end) true iex> Enum.find_value([1, 2, 3], "no bools!", &is_boolean/1) "no bools!" """ @spec find_value(t, any, (element -> any)) :: any | nil def find_value(enumerable, default \\ nil, fun) def find_value(enumerable, default, fun) when is_list(enumerable) do find_value_list(enumerable, default, fun) end def find_value(enumerable, default, fun) do Enumerable.reduce(enumerable, {:cont, default}, fn entry, default -> fun_entry = fun.(entry) if fun_entry, do: {:halt, fun_entry}, else: {:cont, default} end) |> elem(1) end @doc """ Maps the given `fun` over `enumerable` and flattens the result. This function returns a new enumerable built by appending the result of invoking `fun` on each element of `enumerable` together; conceptually, this is similar to a combination of `map/2` and `concat/1`. ## Examples iex> Enum.flat_map([:a, :b, :c], fn x -> [x, x] end) [:a, :a, :b, :b, :c, :c] iex> Enum.flat_map([{1, 3}, {4, 6}], fn {x, y} -> x..y end) [1, 2, 3, 4, 5, 6] iex> Enum.flat_map([:a, :b, :c], fn x -> [[x]] end) [[:a], [:b], [:c]] """ @spec flat_map(t, (element -> t)) :: list def flat_map(enumerable, fun) when is_list(enumerable) do flat_map_list(enumerable, fun) end def flat_map(enumerable, fun) do reduce(enumerable, [], fn entry, acc -> case fun.(entry) do list when is_list(list) -> :lists.reverse(list, acc) other -> reduce(other, acc, &[&1 | &2]) end end) |> :lists.reverse() end @doc """ Maps and reduces an `enumerable`, flattening the given results (only one level deep). It expects an accumulator and a function that receives each enumerable element, and must return a tuple containing a new enumerable (often a list) with the new accumulator or a tuple with `:halt` as first element and the accumulator as second. ## Examples iex> enumerable = 1..100 iex> n = 3 iex> Enum.flat_map_reduce(enumerable, 0, fn x, acc -> ...> if acc < n, do: {[x], acc + 1}, else: {:halt, acc} ...> end) {[1, 2, 3], 3} iex> Enum.flat_map_reduce(1..5, 0, fn x, acc -> {[[x]], acc + x} end) {[[1], [2], [3], [4], [5]], 15} """ @spec flat_map_reduce(t, acc, fun) :: {[any], acc} when fun: (element, acc -> {t, acc} | {:halt, acc}) def flat_map_reduce(enumerable, acc, fun) do {_, {list, acc}} = Enumerable.reduce(enumerable, {:cont, {[], acc}}, fn entry, {list, acc} -> case fun.(entry, acc) do {:halt, acc} -> {:halt, {list, acc}} {[], acc} -> {:cont, {list, acc}} {[entry], acc} -> {:cont, {[entry | list], acc}} {entries, acc} -> {:cont, {reduce(entries, list, &[&1 | &2]), acc}} end end) {:lists.reverse(list), acc} end @doc """ Returns a map with keys as unique elements of `enumerable` and values as the count of every element. ## Examples iex> Enum.frequencies(~w{ant buffalo ant ant buffalo dingo}) %{"ant" => 3, "buffalo" => 2, "dingo" => 1} """ @doc since: "1.10.0" @spec frequencies(t) :: map def frequencies(enumerable) do reduce(enumerable, %{}, fn key, acc -> case acc do %{^key => value} -> %{acc | key => value + 1} %{} -> Map.put(acc, key, 1) end end) end @doc """ Returns a map with keys as unique elements given by `key_fun` and values as the count of every element. ## Examples iex> Enum.frequencies_by(~w{aa aA bb cc}, &String.downcase/1) %{"aa" => 2, "bb" => 1, "cc" => 1} iex> Enum.frequencies_by(~w{aaa aA bbb cc c}, &String.length/1) %{3 => 2, 2 => 2, 1 => 1} """ @doc since: "1.10.0" @spec frequencies_by(t, (element -> any)) :: map def frequencies_by(enumerable, key_fun) when is_function(key_fun) do reduce(enumerable, %{}, fn entry, acc -> key = key_fun.(entry) case acc do %{^key => value} -> %{acc | key => value + 1} %{} -> Map.put(acc, key, 1) end end) end @doc """ Splits the `enumerable` into groups based on `key_fun`. The result is a map where each key is given by `key_fun` and each value is a list of elements given by `value_fun`. The order of elements within each list is preserved from the `enumerable`. However, like all maps, the resulting map is unordered. ## Examples iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length/1) %{3 => ["ant", "cat"], 5 => ["dingo"], 7 => ["buffalo"]} iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length/1, &String.first/1) %{3 => ["a", "c"], 5 => ["d"], 7 => ["b"]} """ @spec group_by(t, (element -> any), (element -> any)) :: map def group_by(enumerable, key_fun, value_fun \\ fn x -> x end) def group_by(enumerable, key_fun, value_fun) when is_function(key_fun) do reduce(reverse(enumerable), %{}, fn entry, acc -> key = key_fun.(entry) value = value_fun.(entry) case acc do %{^key => existing} -> Map.put(acc, key, [value | existing]) %{} -> Map.put(acc, key, [value]) end end) end def group_by(enumerable, dict, fun) do IO.warn( "Enum.group_by/3 with a map/dictionary as second element is deprecated. " <> "A map is used by default and it is no longer required to pass one to this function" ) # Avoid warnings about Dict dict_module = Dict reduce(reverse(enumerable), dict, fn entry, categories -> dict_module.update(categories, fun.(entry), [entry], &[entry | &1]) end) end @doc """ Intersperses `element` between each element of the enumeration. ## Examples iex> Enum.intersperse([1, 2, 3], 0) [1, 0, 2, 0, 3] iex> Enum.intersperse([1], 0) [1] iex> Enum.intersperse([], 0) [] """ @spec intersperse(t, element) :: list def intersperse(enumerable, element) do list = enumerable |> reduce([], fn x, acc -> [x, element | acc] end) |> :lists.reverse() # Head is a superfluous intersperser element case list do [] -> [] [_ | t] -> t end end @doc """ Inserts the given `enumerable` into a `collectable`. Note that passing a non-empty list as the `collectable` is deprecated. If you're collecting into a non-empty keyword list, consider using `Keyword.merge/2`. If you're collecting into a non-empty list, consider something like `to_list(enumerable) ++ collectable`. ## Examples iex> Enum.into([1, 2], []) [1, 2] iex> Enum.into([a: 1, b: 2], %{}) %{a: 1, b: 2} iex> Enum.into(%{a: 1}, %{b: 2}) %{a: 1, b: 2} iex> Enum.into([a: 1, a: 2], %{}) %{a: 2} """ @spec into(Enumerable.t(), Collectable.t()) :: Collectable.t() def into(enumerable, collectable) def into(enumerable, []) do to_list(enumerable) end def into(%_{} = enumerable, collectable) do into_protocol(enumerable, collectable) end def into(enumerable, %_{} = collectable) do into_protocol(enumerable, collectable) end def into(%{} = enumerable, %{} = collectable) do Map.merge(collectable, enumerable) end def into(enumerable, %{} = collectable) when is_list(enumerable) do Map.merge(collectable, :maps.from_list(enumerable)) end def into(enumerable, %{} = collectable) do reduce(enumerable, collectable, fn {key, val}, acc -> Map.put(acc, key, val) end) end def into(enumerable, collectable) do into_protocol(enumerable, collectable) end defp into_protocol(enumerable, collectable) do {initial, fun} = Collectable.into(collectable) into(enumerable, initial, fun, fn entry, acc -> fun.(acc, {:cont, entry}) end) end @doc """ Inserts the given `enumerable` into a `collectable` according to the transformation function. ## Examples iex> Enum.into([2, 3], [3], fn x -> x * 3 end) [3, 6, 9] iex> Enum.into(%{a: 1, b: 2}, %{c: 3}, fn {k, v} -> {k, v * 2} end) %{a: 2, b: 4, c: 3} """ @spec into(Enumerable.t(), Collectable.t(), (term -> term)) :: Collectable.t() def into(enumerable, collectable, transform) when is_list(collectable) do collectable ++ map(enumerable, transform) end def into(enumerable, collectable, transform) do {initial, fun} = Collectable.into(collectable) into(enumerable, initial, fun, fn entry, acc -> fun.(acc, {:cont, transform.(entry)}) end) end defp into(enumerable, initial, fun, callback) do try do reduce(enumerable, initial, callback) catch kind, reason -> fun.(initial, :halt) :erlang.raise(kind, reason, __STACKTRACE__) else acc -> fun.(acc, :done) end end @doc """ Joins the given `enumerable` into a string using `joiner` as a separator. If `joiner` is not passed at all, it defaults to an empty string. All elements in the `enumerable` must be convertible to a string, otherwise an error is raised. ## Examples iex> Enum.join([1, 2, 3]) "123" iex> Enum.join([1, 2, 3], " = ") "1 = 2 = 3" """ @spec join(t, String.t()) :: String.t() def join(enumerable, joiner \\ "") def join(enumerable, "") do enumerable |> map(&entry_to_string(&1)) |> IO.iodata_to_binary() end def join(enumerable, joiner) when is_binary(joiner) do reduced = reduce(enumerable, :first, fn entry, :first -> entry_to_string(entry) entry, acc -> [acc, joiner | entry_to_string(entry)] end) if reduced == :first do "" else IO.iodata_to_binary(reduced) end end @doc """ Returns a list where each element is the result of invoking `fun` on each corresponding element of `enumerable`. For maps, the function expects a key-value tuple. ## Examples iex> Enum.map([1, 2, 3], fn x -> x * 2 end) [2, 4, 6] iex> Enum.map([a: 1, b: 2], fn {k, v} -> {k, -v} end) [a: -1, b: -2] """ @spec map(t, (element -> any)) :: list def map(enumerable, fun) def map(enumerable, fun) when is_list(enumerable) do :lists.map(fun, enumerable) end def map(enumerable, fun) do reduce(enumerable, [], R.map(fun)) |> :lists.reverse() end @doc """ Returns a list of results of invoking `fun` on every `nth` element of `enumerable`, starting with the first element. The first element is always passed to the given function, unless `nth` is `0`. The second argument specifying every `nth` element must be a non-negative integer. If `nth` is `0`, then `enumerable` is directly converted to a list, without `fun` being ever applied. ## Examples iex> Enum.map_every(1..10, 2, fn x -> x + 1000 end) [1001, 2, 1003, 4, 1005, 6, 1007, 8, 1009, 10] iex> Enum.map_every(1..10, 3, fn x -> x + 1000 end) [1001, 2, 3, 1004, 5, 6, 1007, 8, 9, 1010] iex> Enum.map_every(1..5, 0, fn x -> x + 1000 end) [1, 2, 3, 4, 5] iex> Enum.map_every([1, 2, 3], 1, fn x -> x + 1000 end) [1001, 1002, 1003] """ @doc since: "1.4.0" @spec map_every(t, non_neg_integer, (element -> any)) :: list def map_every(enumerable, nth, fun) def map_every(enumerable, 1, fun), do: map(enumerable, fun) def map_every(enumerable, 0, _fun), do: to_list(enumerable) def map_every([], nth, _fun) when is_integer(nth) and nth > 1, do: [] def map_every(enumerable, nth, fun) when is_integer(nth) and nth > 1 do {res, _} = reduce(enumerable, {[], :first}, R.map_every(nth, fun)) :lists.reverse(res) end @doc """ Maps and intersperses the given enumerable in one pass. ## Examples iex> Enum.map_intersperse([1, 2, 3], :a, &(&1 * 2)) [2, :a, 4, :a, 6] """ @doc since: "1.10.0" @spec map_intersperse(t, element(), (element -> any())) :: list() def map_intersperse(enumerable, separator, mapper) def map_intersperse(enumerable, separator, mapper) when is_list(enumerable) do map_intersperse_list(enumerable, separator, mapper) end def map_intersperse(enumerable, separator, mapper) do reduced = reduce(enumerable, :first, fn entry, :first -> [mapper.(entry)] entry, acc -> [mapper.(entry), separator | acc] end) if reduced == :first do [] else :lists.reverse(reduced) end end @doc """ Maps and joins the given `enumerable` in one pass. If `joiner` is not passed at all, it defaults to an empty string. All elements returned from invoking the `mapper` must be convertible to a string, otherwise an error is raised. ## Examples iex> Enum.map_join([1, 2, 3], &(&1 * 2)) "246" iex> Enum.map_join([1, 2, 3], " = ", &(&1 * 2)) "2 = 4 = 6" """ @spec map_join(t, String.t(), (element -> String.Chars.t())) :: String.t() def map_join(enumerable, joiner \\ "", mapper) when is_binary(joiner) do enumerable |> map_intersperse(joiner, &entry_to_string(mapper.(&1))) |> IO.iodata_to_binary() end @doc """ Invokes the given function to each element in the `enumerable` to reduce it to a single element, while keeping an accumulator. Returns a tuple where the first element is the mapped enumerable and the second one is the final accumulator. The function, `fun`, receives two arguments: the first one is the element, and the second one is the accumulator. `fun` must return a tuple with two elements in the form of `{result, accumulator}`. For maps, the first tuple element must be a `{key, value}` tuple. ## Examples iex> Enum.map_reduce([1, 2, 3], 0, fn x, acc -> {x * 2, x + acc} end) {[2, 4, 6], 6} """ @spec map_reduce(t, acc, (element, acc -> {element, acc})) :: {list, acc} def map_reduce(enumerable, acc, fun) when is_list(enumerable) do :lists.mapfoldl(fun, acc, enumerable) end def map_reduce(enumerable, acc, fun) do {list, acc} = reduce(enumerable, {[], acc}, fn entry, {list, acc} -> {new_entry, acc} = fun.(entry, acc) {[new_entry | list], acc} end) {:lists.reverse(list), acc} end @doc false @spec max(t, (() -> empty_result)) :: element | empty_result when empty_result: any def max(enumerable, empty_fallback) when is_function(empty_fallback, 0) do max(enumerable, &>=/2, empty_fallback) end @doc """ Returns the maximal element in the `enumerable` according to Erlang's term ordering. By default, the comparison is done with the `>=` sorter function. If multiple elements are considered maximal, the first one that was found is returned. If you want the last element considered maximal to be returned, the sorter function should not return true for equal elements. If the enumerable is empty, the provided `empty_fallback` is called. The default `empty_fallback` raises `Enum.EmptyError`. ## Examples iex> Enum.max([1, 2, 3]) 3 The fact this function uses Erlang's term ordering means that the comparison is structural and not semantic. For example: iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]]) ~D[2017-03-31] In the example above, `max/2` returned March 31st instead of April 1st because the structural comparison compares the day before the year. For this reason, most structs provide a "compare" function, such as `Date.compare/2`, which receives two structs and returns `:lt` (less-than), `:eq` (equal to), and `:gt` (greater-than). If you pass a module as the sorting function, Elixir will automatically use the `compare/2` function of said module: iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]], Date) ~D[2017-04-01] Finally, if you don't want to raise on empty enumerables, you can pass the empty fallback: iex> Enum.max([], &>=/2, fn -> 0 end) 0 """ @spec max(t, (element, element -> boolean) | module()) :: element | empty_result when empty_result: any @spec max(t, (element, element -> boolean) | module(), (() -> empty_result)) :: element | empty_result when empty_result: any def max(enumerable, sorter \\ &>=/2, empty_fallback \\ fn -> raise Enum.EmptyError end) do aggregate(enumerable, max_sort_fun(sorter), empty_fallback) end defp max_sort_fun(sorter) when is_function(sorter, 2), do: sorter defp max_sort_fun(module) when is_atom(module), do: &(module.compare(&1, &2) != :lt) @doc false @spec max_by(t, (element -> any), (() -> empty_result)) :: element | empty_result when empty_result: any def max_by(enumerable, fun, empty_fallback) when is_function(fun, 1) and is_function(empty_fallback, 0) do max_by(enumerable, fun, &>=/2, empty_fallback) end @doc """ Returns the maximal element in the `enumerable` as calculated by the given `fun`. By default, the comparison is done with the `>=` sorter function. If multiple elements are considered maximal, the first one that was found is returned. If you want the last element considered maximal to be returned, the sorter function should not return true for equal elements. Calls the provided `empty_fallback` function and returns its value if `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`. ## Examples iex> Enum.max_by(["a", "aa", "aaa"], fn x -> String.length(x) end) "aaa" iex> Enum.max_by(["a", "aa", "aaa", "b", "bbb"], &String.length/1) "aaa" The fact this function uses Erlang's term ordering means that the comparison is structural and not semantic. Therefore, if you want to compare structs, most structs provide a "compare" function, such as `Date.compare/2`, which receives two structs and returns `:lt` (less-than), `:eq` (equal to), and `:gt` (greater-than). If you pass a module as the sorting function, Elixir will automatically use the `compare/2` function of said module: iex> users = [ ...> %{name: "Ellis", birthday: ~D[1943-05-11]}, ...> %{name: "Lovelace", birthday: ~D[1815-12-10]}, ...> %{name: "Turing", birthday: ~D[1912-06-23]} ...> ] iex> Enum.max_by(users, &(&1.birthday), Date) %{name: "Ellis", birthday: ~D[1943-05-11]} Finally, if you don't want to raise on empty enumerables, you can pass the empty fallback: iex> Enum.max_by([], &String.length/1, fn -> nil end) nil """ @spec max_by( t, (element -> any), (element, element -> boolean) | module() ) :: element | empty_result when empty_result: any @spec max_by( t, (element -> any), (element, element -> boolean) | module(), (() -> empty_result) ) :: element | empty_result when empty_result: any def max_by(enumerable, fun, sorter \\ &>=/2, empty_fallback \\ fn -> raise Enum.EmptyError end) when is_function(fun, 1) do aggregate_by(enumerable, fun, max_sort_fun(sorter), empty_fallback) end @doc """ Checks if `element` exists within the `enumerable`. Membership is tested with the match (`===/2`) operator. ## Examples iex> Enum.member?(1..10, 5) true iex> Enum.member?(1..10, 5.0) false iex> Enum.member?([1.0, 2.0, 3.0], 2) false iex> Enum.member?([1.0, 2.0, 3.0], 2.000) true iex> Enum.member?([:a, :b, :c], :d) false When not called whithin guards, the [`in`](`in/2`) and [`not in`](`in/2`) operators work by using this function. """ @spec member?(t, element) :: boolean def member?(enumerable, element) when is_list(enumerable) do :lists.member(element, enumerable) end def member?(enumerable, element) do case Enumerable.member?(enumerable, element) do {:ok, element} when is_boolean(element) -> element {:error, module} -> module.reduce(enumerable, {:cont, false}, fn v, _ when v === element -> {:halt, true} _, _ -> {:cont, false} end) |> elem(1) end end @doc false @spec min(t, (() -> empty_result)) :: element | empty_result when empty_result: any def min(enumerable, empty_fallback) when is_function(empty_fallback, 0) do min(enumerable, &<=/2, empty_fallback) end @doc """ Returns the minimal element in the `enumerable` according to Erlang's term ordering. By default, the comparison is done with the `<=` sorter function. If multiple elements are considered minimal, the first one that was found is returned. If you want the last element considered minimal to be returned, the sorter function should not return true for equal elements. If the enumerable is empty, the provided `empty_fallback` is called. The default `empty_fallback` raises `Enum.EmptyError`. ## Examples iex> Enum.min([1, 2, 3]) 1 The fact this function uses Erlang's term ordering means that the comparison is structural and not semantic. For example: iex> Enum.min([~D[2017-03-31], ~D[2017-04-01]]) ~D[2017-04-01] In the example above, `min/2` returned April 1st instead of March 31st because the structural comparison compares the day before the year. For this reason, most structs provide a "compare" function, such as `Date.compare/2`, which receives two structs and returns `:lt` (less-than), `:eq` (equal to), and `:gt` (greater-than). If you pass a module as the sorting function, Elixir will automatically use the `compare/2` function of said module: iex> Enum.min([~D[2017-03-31], ~D[2017-04-01]], Date) ~D[2017-03-31] Finally, if you don't want to raise on empty enumerables, you can pass the empty fallback: iex> Enum.min([], fn -> 0 end) 0 """ @spec min(t, (element, element -> boolean) | module()) :: element | empty_result when empty_result: any @spec min(t, (element, element -> boolean) | module(), (() -> empty_result)) :: element | empty_result when empty_result: any def min(enumerable, sorter \\ &<=/2, empty_fallback \\ fn -> raise Enum.EmptyError end) do aggregate(enumerable, min_sort_fun(sorter), empty_fallback) end defp min_sort_fun(sorter) when is_function(sorter, 2), do: sorter defp min_sort_fun(module) when is_atom(module), do: &(module.compare(&1, &2) != :gt) @doc false @spec min_by(t, (element -> any), (() -> empty_result)) :: element | empty_result when empty_result: any def min_by(enumerable, fun, empty_fallback) when is_function(fun, 1) and is_function(empty_fallback, 0) do min_by(enumerable, fun, &<=/2, empty_fallback) end @doc """ Returns the minimal element in the `enumerable` as calculated by the given `fun`. By default, the comparison is done with the `<=` sorter function. If multiple elements are considered minimal, the first one that was found is returned. If you want the last element considered minimal to be returned, the sorter function should not return true for equal elements. Calls the provided `empty_fallback` function and returns its value if `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`. ## Examples iex> Enum.min_by(["a", "aa", "aaa"], fn x -> String.length(x) end) "a" iex> Enum.min_by(["a", "aa", "aaa", "b", "bbb"], &String.length/1) "a" The fact this function uses Erlang's term ordering means that the comparison is structural and not semantic. Therefore, if you want to compare structs, most structs provide a "compare" function, such as `Date.compare/2`, which receives two structs and returns `:lt` (less-than), `:eq` (equal to), and `:gt` (greater-than). If you pass a module as the sorting function, Elixir will automatically use the `compare/2` function of said module: iex> users = [ ...> %{name: "Ellis", birthday: ~D[1943-05-11]}, ...> %{name: "Lovelace", birthday: ~D[1815-12-10]}, ...> %{name: "Turing", birthday: ~D[1912-06-23]} ...> ] iex> Enum.min_by(users, &(&1.birthday), Date) %{name: "Lovelace", birthday: ~D[1815-12-10]} Finally, if you don't want to raise on empty enumerables, you can pass the empty fallback: iex> Enum.min_by([], &String.length/1, fn -> nil end) nil """ @spec min_by( t, (element -> any), (element, element -> boolean) | module() ) :: element | empty_result when empty_result: any @spec min_by( t, (element -> any), (element, element -> boolean) | module(), (() -> empty_result) ) :: element | empty_result when empty_result: any def min_by(enumerable, fun, sorter \\ &<=/2, empty_fallback \\ fn -> raise Enum.EmptyError end) when is_function(fun, 1) do aggregate_by(enumerable, fun, min_sort_fun(sorter), empty_fallback) end @doc """ Returns a tuple with the minimal and the maximal elements in the enumerable according to Erlang's term ordering. If multiple elements are considered maximal or minimal, the first one that was found is returned. Calls the provided `empty_fallback` function and returns its value if `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`. ## Examples iex> Enum.min_max([2, 3, 1]) {1, 3} iex> Enum.min_max([], fn -> {nil, nil} end) {nil, nil} """ @spec min_max(t, (() -> empty_result)) :: {element, element} | empty_result when empty_result: any def min_max(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end) def min_max(first..last, empty_fallback) when is_function(empty_fallback, 0) do {Kernel.min(first, last), Kernel.max(first, last)} end def min_max(enumerable, empty_fallback) when is_function(empty_fallback, 0) do first_fun = &[&1 | &1] reduce_fun = fn entry, [min | max] -> [Kernel.min(min, entry) | Kernel.max(max, entry)] end case reduce_by(enumerable, first_fun, reduce_fun) do :empty -> empty_fallback.() [min | max] -> {min, max} end end @doc false @spec min_max_by(t, (element -> any), (() -> empty_result)) :: {element, element} | empty_result when empty_result: any def min_max_by(enumerable, fun, empty_fallback) when is_function(fun, 1) and is_function(empty_fallback, 0) do min_max_by(enumerable, fun, &</2, empty_fallback) end @doc """ Returns a tuple with the minimal and the maximal elements in the enumerable as calculated by the given function. If multiple elements are considered maximal or minimal, the first one that was found is returned. ## Examples iex> Enum.min_max_by(["aaa", "bb", "c"], fn x -> String.length(x) end) {"c", "aaa"} iex> Enum.min_max_by(["aaa", "a", "bb", "c", "ccc"], &String.length/1) {"a", "aaa"} iex> Enum.min_max_by([], &String.length/1, fn -> {nil, nil} end) {nil, nil} The fact this function uses Erlang's term ordering means that the comparison is structural and not semantic. Therefore, if you want to compare structs, most structs provide a "compare" function, such as `Date.compare/2`, which receives two structs and returns `:lt` (less-than), `:eq` (equal to), and `:gt` (greater-than). If you pass a module as the sorting function, Elixir will automatically use the `compare/2` function of said module: iex> users = [ ...> %{name: "Ellis", birthday: ~D[1943-05-11]}, ...> %{name: "Lovelace", birthday: ~D[1815-12-10]}, ...> %{name: "Turing", birthday: ~D[1912-06-23]} ...> ] iex> Enum.min_max_by(users, &(&1.birthday), Date) { %{name: "Lovelace", birthday: ~D[1815-12-10]}, %{name: "Ellis", birthday: ~D[1943-05-11]} } Finally, if you don't want to raise on empty enumerables, you can pass the empty fallback: iex> Enum.min_max_by([], &String.length/1, fn -> nil end) nil """ @spec min_max_by(t, (element -> any), (element, element -> boolean) | module()) :: {element, element} | empty_result when empty_result: any @spec min_max_by( t, (element -> any), (element, element -> boolean) | module(), (() -> empty_result) ) :: {element, element} | empty_result when empty_result: any def min_max_by( enumerable, fun, sorter_or_empty_fallback \\ &</2, empty_fallback \\ fn -> raise Enum.EmptyError end ) def min_max_by(enumerable, fun, sorter, empty_fallback) when is_function(fun, 1) and is_atom(sorter) and is_function(empty_fallback, 0) do min_max_by(enumerable, fun, min_max_by_sort_fun(sorter), empty_fallback) end def min_max_by(enumerable, fun, sorter, empty_fallback) when is_function(fun, 1) and is_function(sorter, 2) and is_function(empty_fallback, 0) do first_fun = fn entry -> fun_entry = fun.(entry) {entry, entry, fun_entry, fun_entry} end reduce_fun = fn entry, {prev_min, prev_max, fun_min, fun_max} = acc -> fun_entry = fun.(entry) cond do sorter.(fun_entry, fun_min) -> {entry, prev_max, fun_entry, fun_max} sorter.(fun_max, fun_entry) -> {prev_min, entry, fun_min, fun_entry} true -> acc end end case reduce_by(enumerable, first_fun, reduce_fun) do :empty -> empty_fallback.() {min, max, _, _} -> {min, max} end end defp min_max_by_sort_fun(module) when is_atom(module), do: &(module.compare(&1, &2) == :lt) @doc """ Splits the `enumerable` in two lists according to the given function `fun`. Splits the given `enumerable` in two lists by calling `fun` with each element in the `enumerable` as its only argument. Returns a tuple with the first list containing all the elements in `enumerable` for which applying `fun` returned a truthy value, and a second list with all the elements for which applying `fun` returned a falsy value (`false` or `nil`). The elements in both the returned lists are in the same relative order as they were in the original enumerable (if such enumerable was ordered, like a list). See the examples below. ## Examples iex> Enum.split_with([5, 4, 3, 2, 1, 0], fn x -> rem(x, 2) == 0 end) {[4, 2, 0], [5, 3, 1]} iex> Enum.split_with(%{a: 1, b: -2, c: 1, d: -3}, fn {_k, v} -> v < 0 end) {[b: -2, d: -3], [a: 1, c: 1]} iex> Enum.split_with(%{a: 1, b: -2, c: 1, d: -3}, fn {_k, v} -> v > 50 end) {[], [a: 1, b: -2, c: 1, d: -3]} iex> Enum.split_with(%{}, fn {_k, v} -> v > 50 end) {[], []} """ @doc since: "1.4.0" @spec split_with(t, (element -> as_boolean(term))) :: {list, list} def split_with(enumerable, fun) do {acc1, acc2} = reduce(enumerable, {[], []}, fn entry, {acc1, acc2} -> if fun.(entry) do {[entry | acc1], acc2} else {acc1, [entry | acc2]} end end) {:lists.reverse(acc1), :lists.reverse(acc2)} end @doc false @deprecated "Use Enum.split_with/2 instead" def partition(enumerable, fun) do split_with(enumerable, fun) end @doc """ Returns a random element of an `enumerable`. Raises `Enum.EmptyError` if `enumerable` is empty. This function uses Erlang's [`:rand` module](http://www.erlang.org/doc/man/rand.html) to calculate the random value. Check its documentation for setting a different random algorithm or a different seed. The implementation is based on the [reservoir sampling](https://en.wikipedia.org/wiki/Reservoir_sampling#Relation_to_Fisher-Yates_shuffle) algorithm. It assumes that the sample being returned can fit into memory; the input `enumerable` doesn't have to, as it is traversed just once. If a range is passed into the function, this function will pick a random value between the range limits, without traversing the whole range (thus executing in constant time and constant memory). ## Examples The examples below use the `:exrop` pseudorandom algorithm since it's the default from Erlang/OTP 20, however if you are using Erlang/OTP 22 or above then `:exsss` is the default algorithm. If you are using `:exsplus`, then please update, as this algorithm is deprecated since Erlang/OTP 20. # Although not necessary, let's seed the random algorithm iex> :rand.seed(:exrop, {101, 102, 103}) iex> Enum.random([1, 2, 3]) 3 iex> Enum.random([1, 2, 3]) 2 iex> Enum.random(1..1_000) 846 """ @spec random(t) :: element def random(enumerable) def random(enumerable) when is_list(enumerable) do case length(enumerable) do 0 -> raise Enum.EmptyError length -> enumerable |> drop_list(random_integer(0, length - 1)) |> hd() end end def random(enumerable) do result = case Enumerable.slice(enumerable) do {:ok, 0, _} -> [] {:ok, count, fun} when is_function(fun) -> fun.(random_integer(0, count - 1), 1) {:error, _} -> take_random(enumerable, 1) end case result do [] -> raise Enum.EmptyError [elem] -> elem end end @doc """ Invokes `fun` for each element in the `enumerable` with the accumulator. Raises `Enum.EmptyError` if `enumerable` is empty. The first element of the `enumerable` is used as the initial value of the accumulator. Then the function is invoked with the next element and the accumulator. The result returned by the function is used as the accumulator for the next iteration, recursively. When the `enumerable` is done, the last accumulator is returned. Since the first element of the enumerable is used as the initial value of the accumulator, `fun` will only be executed `n - 1` times where `n` is the length of the enumerable. This function won't call the specified function for enumerables that are one-element long. If you wish to use another value for the accumulator, use `Enum.reduce/3`. ## Examples iex> Enum.reduce([1, 2, 3, 4], fn x, acc -> x * acc end) 24 """ @spec reduce(t, (element, acc -> acc)) :: acc def reduce(enumerable, fun) def reduce([h | t], fun) do reduce(t, h, fun) end def reduce([], _fun) do raise Enum.EmptyError end def reduce(enumerable, fun) do Enumerable.reduce(enumerable, {:cont, :first}, fn x, {:acc, acc} -> {:cont, {:acc, fun.(x, acc)}} x, :first -> {:cont, {:acc, x}} end) |> elem(1) |> case do :first -> raise Enum.EmptyError {:acc, acc} -> acc end end @doc """ Invokes `fun` for each element in the `enumerable` with the accumulator. The initial value of the accumulator is `acc`. The function is invoked for each element in the enumerable with the accumulator. The result returned by the function is used as the accumulator for the next iteration. The function returns the last accumulator. ## Examples iex> Enum.reduce([1, 2, 3], 0, fn x, acc -> x + acc end) 6 ## Reduce as a building block Reduce (sometimes called `fold`) is a basic building block in functional programming. Almost all of the functions in the `Enum` module can be implemented on top of reduce. Those functions often rely on other operations, such as `Enum.reverse/1`, which are optimized by the runtime. For example, we could implement `map/2` in terms of `reduce/3` as follows: def my_map(enumerable, fun) do enumerable |> Enum.reduce([], fn x, acc -> [fun.(x) | acc] end) |> Enum.reverse() end In the example above, `Enum.reduce/3` accumulates the result of each call to `fun` into a list in reverse order, which is correctly ordered at the end by calling `Enum.reverse/1`. Implementing functions like `map/2`, `filter/2` and others are a good exercise for understanding the power behind `Enum.reduce/3`. When an operation cannot be expressed by any of the functions in the `Enum` module, developers will most likely resort to `reduce/3`. """ @spec reduce(t, any, (element, acc -> acc)) :: acc def reduce(enumerable, acc, fun) when is_list(enumerable) do :lists.foldl(fun, acc, enumerable) end def reduce(first..last, acc, fun) do if first <= last do reduce_range_inc(first, last, acc, fun) else reduce_range_dec(first, last, acc, fun) end end def reduce(%_{} = enumerable, acc, fun) do reduce_enumerable(enumerable, acc, fun) end def reduce(%{} = enumerable, acc, fun) do :maps.fold(fn k, v, acc -> fun.({k, v}, acc) end, acc, enumerable) end def reduce(enumerable, acc, fun) do reduce_enumerable(enumerable, acc, fun) end @doc """ Reduces `enumerable` until `fun` returns `{:halt, term}`. The return value for `fun` is expected to be * `{:cont, acc}` to continue the reduction with `acc` as the new accumulator or * `{:halt, acc}` to halt the reduction If `fun` returns `{:halt, acc}` the reduction is halted and the function returns `acc`. Otherwise, if the enumerable is exhausted, the function returns the accumulator of the last `{:cont, acc}`. ## Examples iex> Enum.reduce_while(1..100, 0, fn x, acc -> ...> if x < 5, do: {:cont, acc + x}, else: {:halt, acc} ...> end) 10 iex> Enum.reduce_while(1..100, 0, fn x, acc -> ...> if x > 0, do: {:cont, acc + x}, else: {:halt, acc} ...> end) 5050 """ @spec reduce_while(t, any, (element, any -> {:cont, any} | {:halt, any})) :: any def reduce_while(enumerable, acc, fun) do Enumerable.reduce(enumerable, {:cont, acc}, fun) |> elem(1) end @doc """ Returns a list of elements in `enumerable` excluding those for which the function `fun` returns a truthy value. See also `filter/2`. ## Examples iex> Enum.reject([1, 2, 3], fn x -> rem(x, 2) == 0 end) [1, 3] """ @spec reject(t, (element -> as_boolean(term))) :: list def reject(enumerable, fun) when is_list(enumerable) do reject_list(enumerable, fun) end def reject(enumerable, fun) do reduce(enumerable, [], R.reject(fun)) |> :lists.reverse() end @doc """ Returns a list of elements in `enumerable` in reverse order. ## Examples iex> Enum.reverse([1, 2, 3]) [3, 2, 1] """ @spec reverse(t) :: list def reverse(enumerable) def reverse([]), do: [] def reverse([_] = list), do: list def reverse([element1, element2]), do: [element2, element1] def reverse([element1, element2 | rest]), do: :lists.reverse(rest, [element2, element1]) def reverse(enumerable), do: reduce(enumerable, [], &[&1 | &2]) @doc """ Reverses the elements in `enumerable`, appends the `tail`, and returns it as a list. This is an optimization for `enumerable |> Enum.reverse() |> Enum.concat(tail)`. ## Examples iex> Enum.reverse([1, 2, 3], [4, 5, 6]) [3, 2, 1, 4, 5, 6] """ @spec reverse(t, t) :: list def reverse(enumerable, tail) when is_list(enumerable) do :lists.reverse(enumerable, to_list(tail)) end def reverse(enumerable, tail) do reduce(enumerable, to_list(tail), fn entry, acc -> [entry | acc] end) end @doc """ Reverses the `enumerable` in the range from initial `start_index` through `count` elements. If `count` is greater than the size of the rest of the `enumerable`, then this function will reverse the rest of the enumerable. ## Examples iex> Enum.reverse_slice([1, 2, 3, 4, 5, 6], 2, 4) [1, 2, 6, 5, 4, 3] """ @spec reverse_slice(t, non_neg_integer, non_neg_integer) :: list def reverse_slice(enumerable, start_index, count) when is_integer(start_index) and start_index >= 0 and is_integer(count) and count >= 0 do list = reverse(enumerable) length = length(list) count = Kernel.min(count, length - start_index) if count > 0 do reverse_slice(list, length, start_index + count, count, []) else :lists.reverse(list) end end @doc """ Applies the given function to each element in the `enumerable`, storing the result in a list and passing it as the accumulator for the next computation. Uses the first element in the `enumerable` as the starting value. ## Examples iex> Enum.scan(1..5, &(&1 + &2)) [1, 3, 6, 10, 15] """ @spec scan(t, (element, any -> any)) :: list def scan(enumerable, fun) do {res, _} = reduce(enumerable, {[], :first}, R.scan2(fun)) :lists.reverse(res) end @doc """ Applies the given function to each element in the `enumerable`, storing the result in a list and passing it as the accumulator for the next computation. Uses the given `acc` as the starting value. ## Examples iex> Enum.scan(1..5, 0, &(&1 + &2)) [1, 3, 6, 10, 15] """ @spec scan(t, any, (element, any -> any)) :: list def scan(enumerable, acc, fun) do {res, _} = reduce(enumerable, {[], acc}, R.scan3(fun)) :lists.reverse(res) end @doc """ Returns a list with the elements of `enumerable` shuffled. This function uses Erlang's [`:rand` module](http://www.erlang.org/doc/man/rand.html) to calculate the random value. Check its documentation for setting a different random algorithm or a different seed. ## Examples The examples below use the `:exrop` pseudorandom algorithm since it's the default from Erlang/OTP 20, however if you are using Erlang/OTP 22 or above then `:exsss` is the default algorithm. If you are using `:exsplus`, then please update, as this algorithm is deprecated since Erlang/OTP 20. # Although not necessary, let's seed the random algorithm iex> :rand.seed(:exrop, {1, 2, 3}) iex> Enum.shuffle([1, 2, 3]) [3, 1, 2] iex> Enum.shuffle([1, 2, 3]) [1, 3, 2] """ @spec shuffle(t) :: list def shuffle(enumerable) do randomized = reduce(enumerable, [], fn x, acc -> [{:rand.uniform(), x} | acc] end) shuffle_unwrap(:lists.keysort(1, randomized), []) end @doc """ Returns a subset list of the given `enumerable` by `index_range`. `index_range` must be a `Range`. Given an `enumerable`, it drops elements before `index_range.first` (zero-base), then takes elements until element `index_range.last` (inclusively). Indexes are normalized, meaning that negative indexes will be counted from the end (for example, `-1` means the last element of the `enumerable`). If `index_range.last` is out of bounds, then it is assigned as the index of the last element. If the normalized `index_range.first` is out of bounds of the given `enumerable`, or this one is greater than the normalized `index_range.last`, then `[]` is returned. ## Examples iex> Enum.slice(1..100, 5..10) [6, 7, 8, 9, 10, 11] iex> Enum.slice(1..10, 5..20) [6, 7, 8, 9, 10] # last five elements (negative indexes) iex> Enum.slice(1..30, -5..-1) [26, 27, 28, 29, 30] # last five elements (mixed positive and negative indexes) iex> Enum.slice(1..30, 25..-1) [26, 27, 28, 29, 30] # out of bounds iex> Enum.slice(1..10, 11..20) [] # first is greater than last iex> Enum.slice(1..10, 6..5) [] """ @doc since: "1.6.0" @spec slice(t, Range.t()) :: list def slice(enumerable, index_range) def slice(enumerable, first..last) when last >= first and last >= 0 do slice_any(enumerable, first, last - first + 1) end def slice(enumerable, first..last) do {count, fun} = slice_count_and_fun(enumerable) first = if first >= 0, do: first, else: first + count last = if last >= 0, do: last, else: last + count amount = last - first + 1 if first >= 0 and first < count and amount > 0 do fun.(first, Kernel.min(amount, count - first)) else [] end end @doc """ Returns a subset list of the given `enumerable`, from `start_index` (zero-based) with `amount` number of elements if available. Given an `enumerable`, it drops elements right before element `start_index`, then takes `amount` of elements, returning as many elements as possible if there are not enough elements. A negative `start_index` can be passed, which means the `enumerable` is enumerated once and the index is counted from the end (for example, `-1` starts slicing from the last element). It returns `[]` if `amount` is `0` or if `start_index` is out of bounds. ## Examples iex> Enum.slice(1..100, 5, 10) [6, 7, 8, 9, 10, 11, 12, 13, 14, 15] # amount to take is greater than the number of elements iex> Enum.slice(1..10, 5, 100) [6, 7, 8, 9, 10] iex> Enum.slice(1..10, 5, 0) [] # using a negative start index iex> Enum.slice(1..10, -6, 3) [5, 6, 7] # out of bound start index (positive) iex> Enum.slice(1..10, 10, 5) [] # out of bound start index (negative) iex> Enum.slice(1..10, -11, 5) [] """ @spec slice(t, index, non_neg_integer) :: list def slice(_enumerable, start_index, 0) when is_integer(start_index), do: [] def slice(enumerable, start_index, amount) when is_integer(start_index) and is_integer(amount) and amount >= 0 do slice_any(enumerable, start_index, amount) end @doc """ Sorts the `enumerable` according to Erlang's term ordering. This function uses the merge sort algorithm. Do not use this function to sort structs, see `sort/2` for more information. ## Examples iex> Enum.sort([3, 2, 1]) [1, 2, 3] """ @spec sort(t) :: list def sort(enumerable) when is_list(enumerable) do :lists.sort(enumerable) end def sort(enumerable) do sort(enumerable, &(&1 <= &2)) end @doc """ Sorts the `enumerable` by the given function. This function uses the merge sort algorithm. The given function should compare two arguments, and return `true` if the first argument precedes or is in the same place as the second one. ## Examples iex> Enum.sort([1, 2, 3], &(&1 >= &2)) [3, 2, 1] The sorting algorithm will be stable as long as the given function returns `true` for values considered equal: iex> Enum.sort(["some", "kind", "of", "monster"], &(byte_size(&1) <= byte_size(&2))) ["of", "some", "kind", "monster"] If the function does not return `true` for equal values, the sorting is not stable and the order of equal terms may be shuffled. For example: iex> Enum.sort(["some", "kind", "of", "monster"], &(byte_size(&1) < byte_size(&2))) ["of", "kind", "some", "monster"] ## Ascending and descending `sort/2` allows a developer to pass `:asc` or `:desc` as the sorting function, which is a convenience for `<=/2` and `>=/2` respectively. iex> Enum.sort([2, 3, 1], :asc) [1, 2, 3] iex> Enum.sort([2, 3, 1], :desc) [3, 2, 1] ## Sorting structs Do not use `</2`, `<=/2`, `>/2`, `>=/2` and friends when sorting structs. That's because the built-in operators above perform structural comparison and not a semantic one. Imagine we sort the following list of dates: iex> dates = [~D[2019-01-01], ~D[2020-03-02], ~D[2019-06-06]] iex> Enum.sort(dates) [~D[2019-01-01], ~D[2020-03-02], ~D[2019-06-06]] Notice the returned result is incorrect, because `sort/1` by default uses `<=/2`, which will compare their structure. When comparing structures, the fields are compared in alphabetical order, which means the dates above will be compared by `day`, `month` and then `year`, which is the opposite of what we want. For this reason, most structs provide a "compare" function, such as `Date.compare/2`, which receives two structs and returns `:lt` (less-than), `:eq` (equal to), and `:gt` (greater-than). If you pass a module as the sorting function, Elixir will automatically use the `compare/2` function of said module: iex> dates = [~D[2019-01-01], ~D[2020-03-02], ~D[2019-06-06]] iex> Enum.sort(dates, Date) [~D[2019-01-01], ~D[2019-06-06], ~D[2020-03-02]] To retrieve all dates in descending order, you can wrap the module in a tuple with `:asc` or `:desc` as first element: iex> dates = [~D[2019-01-01], ~D[2020-03-02], ~D[2019-06-06]] iex> Enum.sort(dates, {:asc, Date}) [~D[2019-01-01], ~D[2019-06-06], ~D[2020-03-02]] iex> dates = [~D[2019-01-01], ~D[2020-03-02], ~D[2019-06-06]] iex> Enum.sort(dates, {:desc, Date}) [~D[2020-03-02], ~D[2019-06-06], ~D[2019-01-01]] """ @spec sort( t, (element, element -> boolean) | :asc | :desc | module() | {:asc | :desc, module()} ) :: list def sort(enumerable, fun) when is_list(enumerable) do :lists.sort(to_sort_fun(fun), enumerable) end def sort(enumerable, fun) do fun = to_sort_fun(fun) reduce(enumerable, [], &sort_reducer(&1, &2, fun)) |> sort_terminator(fun) end defp to_sort_fun(sorter) when is_function(sorter, 2), do: sorter defp to_sort_fun(:asc), do: &<=/2 defp to_sort_fun(:desc), do: &>=/2 defp to_sort_fun(module) when is_atom(module), do: &(module.compare(&1, &2) != :gt) defp to_sort_fun({:asc, module}) when is_atom(module), do: &(module.compare(&1, &2) != :gt) defp to_sort_fun({:desc, module}) when is_atom(module), do: &(module.compare(&1, &2) != :lt) @doc """ Sorts the mapped results of the `enumerable` according to the provided `sorter` function. This function maps each element of the `enumerable` using the provided `mapper` function. The enumerable is then sorted by the mapped elements using the `sorter` function, which defaults to `Kernel.<=/2`. `sort_by/3` differs from `sort/2` in that it only calculates the comparison value for each element in the enumerable once instead of once for each element in each comparison. If the same function is being called on both elements, it's more efficient to use `sort_by/3`. ## Examples Using the default `sorter` of `<=/2`: iex> Enum.sort_by(["some", "kind", "of", "monster"], &byte_size/1) ["of", "some", "kind", "monster"] Sorting by multiple properties - first by size, then by first letter (this takes advantage of the fact that tuples are compared element-by-element): iex> Enum.sort_by(["some", "kind", "of", "monster"], &{byte_size(&1), String.first(&1)}) ["of", "kind", "some", "monster"] Similar to `sort/2`, you can pass a custom sorter: iex> Enum.sort_by(["some", "kind", "of", "monster"], &byte_size/1, &>=/2) ["monster", "some", "kind", "of"] Or use `:asc` and `:desc`: iex> Enum.sort_by(["some", "kind", "of", "monster"], &byte_size/1, :desc) ["monster", "some", "kind", "of"] As in `sort/2`, avoid using the default sorting function to sort structs, as by default it performs structural comparison instead of a semantic one. In such cases, you shall pass a sorting function as third element or any module that implements a `compare/2` function. For example, to sort users by their birthday in both ascending and descending order respectively: iex> users = [ ...> %{name: "Ellis", birthday: ~D[1943-05-11]}, ...> %{name: "Lovelace", birthday: ~D[1815-12-10]}, ...> %{name: "Turing", birthday: ~D[1912-06-23]} ...> ] iex> Enum.sort_by(users, &(&1.birthday), Date) [ %{name: "Lovelace", birthday: ~D[1815-12-10]}, %{name: "Turing", birthday: ~D[1912-06-23]}, %{name: "Ellis", birthday: ~D[1943-05-11]} ] iex> Enum.sort_by(users, &(&1.birthday), {:desc, Date}) [ %{name: "Ellis", birthday: ~D[1943-05-11]}, %{name: "Turing", birthday: ~D[1912-06-23]}, %{name: "Lovelace", birthday: ~D[1815-12-10]} ] """ @spec sort_by( t, (element -> mapped_element), (element, element -> boolean) | :asc | :desc | module() | {:asc | :desc, module()} ) :: list when mapped_element: element def sort_by(enumerable, mapper, sorter \\ &<=/2) do enumerable |> map(&{&1, mapper.(&1)}) |> sort(to_sort_by_fun(sorter)) |> map(&elem(&1, 0)) end defp to_sort_by_fun(sorter) when is_function(sorter, 2), do: &sorter.(elem(&1, 1), elem(&2, 1)) defp to_sort_by_fun(:asc), do: &(elem(&1, 1) <= elem(&2, 1)) defp to_sort_by_fun(:desc), do: &(elem(&1, 1) >= elem(&2, 1)) defp to_sort_by_fun(module) when is_atom(module), do: &(module.compare(elem(&1, 1), elem(&2, 1)) != :gt) defp to_sort_by_fun({:asc, module}) when is_atom(module), do: &(module.compare(elem(&1, 1), elem(&2, 1)) != :gt) defp to_sort_by_fun({:desc, module}) when is_atom(module), do: &(module.compare(elem(&1, 1), elem(&2, 1)) != :lt) @doc """ Splits the `enumerable` into two enumerables, leaving `count` elements in the first one. If `count` is a negative number, it starts counting from the back to the beginning of the `enumerable`. Be aware that a negative `count` implies the `enumerable` will be enumerated twice: once to calculate the position, and a second time to do the actual splitting. ## Examples iex> Enum.split([1, 2, 3], 2) {[1, 2], [3]} iex> Enum.split([1, 2, 3], 10) {[1, 2, 3], []} iex> Enum.split([1, 2, 3], 0) {[], [1, 2, 3]} iex> Enum.split([1, 2, 3], -1) {[1, 2], [3]} iex> Enum.split([1, 2, 3], -5) {[], [1, 2, 3]} """ @spec split(t, integer) :: {list, list} def split(enumerable, count) when is_list(enumerable) and is_integer(count) and count >= 0 do split_list(enumerable, count, []) end def split(enumerable, count) when is_integer(count) and count >= 0 do {_, list1, list2} = reduce(enumerable, {count, [], []}, fn entry, {counter, acc1, acc2} -> if counter > 0 do {counter - 1, [entry | acc1], acc2} else {counter, acc1, [entry | acc2]} end end) {:lists.reverse(list1), :lists.reverse(list2)} end def split(enumerable, count) when is_integer(count) and count < 0 do split_reverse_list(reverse(enumerable), -count, []) end @doc """ Splits enumerable in two at the position of the element for which `fun` returns a falsy value (`false` or `nil`) for the first time. It returns a two-element tuple with two lists of elements. The element that triggered the split is part of the second list. ## Examples iex> Enum.split_while([1, 2, 3, 4], fn x -> x < 3 end) {[1, 2], [3, 4]} iex> Enum.split_while([1, 2, 3, 4], fn x -> x < 0 end) {[], [1, 2, 3, 4]} iex> Enum.split_while([1, 2, 3, 4], fn x -> x > 0 end) {[1, 2, 3, 4], []} """ @spec split_while(t, (element -> as_boolean(term))) :: {list, list} def split_while(enumerable, fun) when is_list(enumerable) do split_while_list(enumerable, fun, []) end def split_while(enumerable, fun) do {list1, list2} = reduce(enumerable, {[], []}, fn entry, {acc1, []} -> if(fun.(entry), do: {[entry | acc1], []}, else: {acc1, [entry]}) entry, {acc1, acc2} -> {acc1, [entry | acc2]} end) {:lists.reverse(list1), :lists.reverse(list2)} end @doc """ Returns the sum of all elements. Raises `ArithmeticError` if `enumerable` contains a non-numeric value. ## Examples iex> Enum.sum([1, 2, 3]) 6 """ @spec sum(t) :: number def sum(enumerable) def sum(first..last) do div((last + first) * (abs(last - first) + 1), 2) end def sum(enumerable) do reduce(enumerable, 0, &+/2) end @doc """ Takes an `amount` of elements from the beginning or the end of the `enumerable`. If a positive `amount` is given, it takes the `amount` elements from the beginning of the `enumerable`. If a negative `amount` is given, the `amount` of elements will be taken from the end. The `enumerable` will be enumerated once to retrieve the proper index and the remaining calculation is performed from the end. If amount is `0`, it returns `[]`. ## Examples iex> Enum.take([1, 2, 3], 2) [1, 2] iex> Enum.take([1, 2, 3], 10) [1, 2, 3] iex> Enum.take([1, 2, 3], 0) [] iex> Enum.take([1, 2, 3], -1) [3] """ @spec take(t, integer) :: list def take(enumerable, amount) def take(_enumerable, 0), do: [] def take(enumerable, amount) when is_list(enumerable) and is_integer(amount) and amount > 0 do take_list(enumerable, amount) end def take(enumerable, amount) when is_integer(amount) and amount > 0 do {_, {res, _}} = Enumerable.reduce(enumerable, {:cont, {[], amount}}, fn entry, {list, n} -> case n do 1 -> {:halt, {[entry | list], n - 1}} _ -> {:cont, {[entry | list], n - 1}} end end) :lists.reverse(res) end def take(enumerable, amount) when is_integer(amount) and amount < 0 do {count, fun} = slice_count_and_fun(enumerable) first = Kernel.max(amount + count, 0) fun.(first, count - first) end @doc """ Returns a list of every `nth` element in the `enumerable`, starting with the first element. The first element is always included, unless `nth` is 0. The second argument specifying every `nth` element must be a non-negative integer. ## Examples iex> Enum.take_every(1..10, 2) [1, 3, 5, 7, 9] iex> Enum.take_every(1..10, 0) [] iex> Enum.take_every([1, 2, 3], 1) [1, 2, 3] """ @spec take_every(t, non_neg_integer) :: list def take_every(enumerable, nth) def take_every(enumerable, 1), do: to_list(enumerable) def take_every(_enumerable, 0), do: [] def take_every([], nth) when is_integer(nth) and nth > 1, do: [] def take_every(enumerable, nth) when is_integer(nth) and nth > 1 do {res, _} = reduce(enumerable, {[], :first}, R.take_every(nth)) :lists.reverse(res) end @doc """ Takes `count` random elements from `enumerable`. Notice this function will traverse the whole `enumerable` to get the random sublist. See `random/1` for notes on implementation and random seed. ## Examples # Although not necessary, let's seed the random algorithm iex> :rand.seed(:exrop, {1, 2, 3}) iex> Enum.take_random(1..10, 2) [7, 2] iex> Enum.take_random(?a..?z, 5) 'hypnt' """ @spec take_random(t, non_neg_integer) :: list def take_random(enumerable, count) def take_random(_enumerable, 0), do: [] def take_random([], _), do: [] def take_random([h | t], 1), do: take_random_list_one(t, h, 1) def take_random(enumerable, 1) do enumerable |> reduce([], fn x, [current | index] -> if :rand.uniform(index + 1) == 1 do [x | index + 1] else [current | index + 1] end x, [] -> [x | 1] end) |> case do [] -> [] [current | _index] -> [current] end end def take_random(enumerable, count) when is_integer(count) and count in 0..128 do sample = Tuple.duplicate(nil, count) reducer = fn elem, {idx, sample} -> jdx = random_integer(0, idx) cond do idx < count -> value = elem(sample, jdx) {idx + 1, put_elem(sample, idx, value) |> put_elem(jdx, elem)} jdx < count -> {idx + 1, put_elem(sample, jdx, elem)} true -> {idx + 1, sample} end end {size, sample} = reduce(enumerable, {0, sample}, reducer) sample |> Tuple.to_list() |> take(Kernel.min(count, size)) end def take_random(enumerable, count) when is_integer(count) and count >= 0 do reducer = fn elem, {idx, sample} -> jdx = random_integer(0, idx) cond do idx < count -> value = Map.get(sample, jdx) {idx + 1, Map.put(sample, idx, value) |> Map.put(jdx, elem)} jdx < count -> {idx + 1, Map.put(sample, jdx, elem)} true -> {idx + 1, sample} end end {size, sample} = reduce(enumerable, {0, %{}}, reducer) take_random(sample, Kernel.min(count, size), []) end defp take_random(_sample, 0, acc), do: acc defp take_random(sample, position, acc) do position = position - 1 take_random(sample, position, [Map.get(sample, position) | acc]) end defp take_random_list_one([h | t], current, index) do if :rand.uniform(index + 1) == 1 do take_random_list_one(t, h, index + 1) else take_random_list_one(t, current, index + 1) end end defp take_random_list_one([], current, _), do: [current] @doc """ Takes the elements from the beginning of the `enumerable` while `fun` returns a truthy value. ## Examples iex> Enum.take_while([1, 2, 3], fn x -> x < 3 end) [1, 2] """ @spec take_while(t, (element -> as_boolean(term))) :: list def take_while(enumerable, fun) when is_list(enumerable) do take_while_list(enumerable, fun) end def take_while(enumerable, fun) do {_, res} = Enumerable.reduce(enumerable, {:cont, []}, fn entry, acc -> if fun.(entry) do {:cont, [entry | acc]} else {:halt, acc} end end) :lists.reverse(res) end @doc """ Converts `enumerable` to a list. ## Examples iex> Enum.to_list(1..3) [1, 2, 3] """ @spec to_list(t) :: [element] def to_list(enumerable) when is_list(enumerable), do: enumerable def to_list(%_{} = enumerable), do: reverse(enumerable) |> :lists.reverse() def to_list(%{} = enumerable), do: Map.to_list(enumerable) def to_list(enumerable), do: reverse(enumerable) |> :lists.reverse() @doc """ Enumerates the `enumerable`, removing all duplicated elements. ## Examples iex> Enum.uniq([1, 2, 3, 3, 2, 1]) [1, 2, 3] """ @spec uniq(t) :: list def uniq(enumerable) do uniq_by(enumerable, fn x -> x end) end @doc false @deprecated "Use Enum.uniq_by/2 instead" def uniq(enumerable, fun) do uniq_by(enumerable, fun) end @doc """ Enumerates the `enumerable`, by removing the elements for which function `fun` returned duplicate elements. The function `fun` maps every element to a term. Two elements are considered duplicates if the return value of `fun` is equal for both of them. The first occurrence of each element is kept. ## Example iex> Enum.uniq_by([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end) [{1, :x}, {2, :y}] iex> Enum.uniq_by([a: {:tea, 2}, b: {:tea, 2}, c: {:coffee, 1}], fn {_, y} -> y end) [a: {:tea, 2}, c: {:coffee, 1}] """ @spec uniq_by(t, (element -> term)) :: list def uniq_by(enumerable, fun) when is_list(enumerable) do uniq_list(enumerable, %{}, fun) end def uniq_by(enumerable, fun) do {list, _} = reduce(enumerable, {[], %{}}, R.uniq_by(fun)) :lists.reverse(list) end @doc """ Opposite of `zip/2`. Extracts two-element tuples from the given `enumerable` and groups them together. It takes an `enumerable` with elements being two-element tuples and returns a tuple with two lists, each of which is formed by the first and second element of each tuple, respectively. This function fails unless `enumerable` is or can be converted into a list of tuples with *exactly* two elements in each tuple. ## Examples iex> Enum.unzip([{:a, 1}, {:b, 2}, {:c, 3}]) {[:a, :b, :c], [1, 2, 3]} iex> Enum.unzip(%{a: 1, b: 2}) {[:a, :b], [1, 2]} """ @spec unzip(t) :: {[element], [element]} def unzip(enumerable) do {list1, list2} = reduce(enumerable, {[], []}, fn {el1, el2}, {list1, list2} -> {[el1 | list1], [el2 | list2]} end) {:lists.reverse(list1), :lists.reverse(list2)} end @doc """ Returns the `enumerable` with each element wrapped in a tuple alongside its index. If an `offset` is given, we will index from the given offset instead of from zero. ## Examples iex> Enum.with_index([:a, :b, :c]) [a: 0, b: 1, c: 2] iex> Enum.with_index([:a, :b, :c], 3) [a: 3, b: 4, c: 5] """ @spec with_index(t, integer) :: [{element, index}] def with_index(enumerable, offset \\ 0) do enumerable |> to_list() |> do_with_index(offset) end @spec do_with_index(list, integer) :: [{element, index}] defp do_with_index([], _) do [] end defp do_with_index([head | tail], index) do [{head, index} | do_with_index(tail, index + 1)] end @doc """ Zips corresponding elements from two enumerables into one list of tuples. The zipping finishes as soon as any enumerable completes. ## Examples iex> Enum.zip([1, 2, 3], [:a, :b, :c]) [{1, :a}, {2, :b}, {3, :c}] iex> Enum.zip([1, 2, 3, 4, 5], [:a, :b, :c]) [{1, :a}, {2, :b}, {3, :c}] """ @spec zip(t, t) :: [{any, any}] def zip(enumerable1, enumerable2) when is_list(enumerable1) and is_list(enumerable2) do zip_list(enumerable1, enumerable2) end def zip(enumerable1, enumerable2) do zip([enumerable1, enumerable2]) end @doc """ Zips corresponding elements from a finite collection of enumerables into one list of tuples. The zipping finishes as soon as any enumerable in the given collection completes. ## Examples iex> Enum.zip([[1, 2, 3], [:a, :b, :c], ["foo", "bar", "baz"]]) [{1, :a, "foo"}, {2, :b, "bar"}, {3, :c, "baz"}] iex> Enum.zip([[1, 2, 3, 4, 5], [:a, :b, :c]]) [{1, :a}, {2, :b}, {3, :c}] """ @doc since: "1.4.0" @spec zip(enumerables) :: [tuple()] when enumerables: [t()] | t() def zip([]), do: [] def zip(enumerables) do Stream.zip(enumerables).({:cont, []}, &{:cont, [&1 | &2]}) |> elem(1) |> :lists.reverse() end ## Helpers @compile {:inline, entry_to_string: 1, reduce: 3, reduce_by: 3, reduce_enumerable: 3} defp entry_to_string(entry) when is_binary(entry), do: entry defp entry_to_string(entry), do: String.Chars.to_string(entry) defp aggregate([head | tail], fun, _empty) do aggregate_list(tail, head, fun) end defp aggregate([], _fun, empty) do empty.() end defp aggregate(first..last, fun, _empty) do case fun.(first, last) do true -> first false -> last end end defp aggregate(enumerable, fun, empty) do ref = make_ref() enumerable |> reduce(ref, fn element, ^ref -> element element, acc -> case fun.(acc, element) do true -> acc false -> element end end) |> case do ^ref -> empty.() result -> result end end defp aggregate_list([head | tail], acc, fun) do acc = case fun.(acc, head) do true -> acc false -> head end aggregate_list(tail, acc, fun) end defp aggregate_list([], acc, _fun), do: acc defp aggregate_by(enumerable, fun, sorter, empty_fallback) do first_fun = &[&1 | fun.(&1)] reduce_fun = fn entry, [_ | fun_ref] = old -> fun_entry = fun.(entry) case sorter.(fun_ref, fun_entry) do true -> old false -> [entry | fun_entry] end end case reduce_by(enumerable, first_fun, reduce_fun) do :empty -> empty_fallback.() [entry | _] -> entry end end defp reduce_by([head | tail], first, fun) do :lists.foldl(fun, first.(head), tail) end defp reduce_by([], _first, _fun) do :empty end defp reduce_by(enumerable, first, fun) do reduce(enumerable, :empty, fn element, :empty -> first.(element) element, acc -> fun.(element, acc) end) end defp random_integer(limit, limit) when is_integer(limit) do limit end defp random_integer(lower_limit, upper_limit) when upper_limit < lower_limit do random_integer(upper_limit, lower_limit) end defp random_integer(lower_limit, upper_limit) do lower_limit + :rand.uniform(upper_limit - lower_limit + 1) - 1 end ## Implementations ## all? defp all_list([h | t], fun) do if fun.(h) do all_list(t, fun) else false end end defp all_list([], _) do true end ## any? defp any_list([h | t], fun) do if fun.(h) do true else any_list(t, fun) end end defp any_list([], _) do false end ## drop defp drop_list(list, 0), do: list defp drop_list([_ | tail], counter), do: drop_list(tail, counter - 1) defp drop_list([], _), do: [] ## drop_while defp drop_while_list([head | tail], fun) do if fun.(head) do drop_while_list(tail, fun) else [head | tail] end end defp drop_while_list([], _) do [] end ## filter defp filter_list([head | tail], fun) do if fun.(head) do [head | filter_list(tail, fun)] else filter_list(tail, fun) end end defp filter_list([], _fun) do [] end ## find defp find_list([head | tail], default, fun) do if fun.(head) do head else find_list(tail, default, fun) end end defp find_list([], default, _) do default end ## find_index defp find_index_list([head | tail], counter, fun) do if fun.(head) do counter else find_index_list(tail, counter + 1, fun) end end defp find_index_list([], _, _) do nil end ## find_value defp find_value_list([head | tail], default, fun) do fun.(head) || find_value_list(tail, default, fun) end defp find_value_list([], default, _) do default end ## flat_map defp flat_map_list([head | tail], fun) do case fun.(head) do list when is_list(list) -> list ++ flat_map_list(tail, fun) other -> to_list(other) ++ flat_map_list(tail, fun) end end defp flat_map_list([], _fun) do [] end ## map_intersperse defp map_intersperse_list([], _, _), do: [] defp map_intersperse_list([last], _, mapper), do: [mapper.(last)] defp map_intersperse_list([head | rest], separator, mapper), do: [mapper.(head), separator | map_intersperse_list(rest, separator, mapper)] ## reduce defp reduce_range_inc(first, first, acc, fun) do fun.(first, acc) end defp reduce_range_inc(first, last, acc, fun) do reduce_range_inc(first + 1, last, fun.(first, acc), fun) end defp reduce_range_dec(first, first, acc, fun) do fun.(first, acc) end defp reduce_range_dec(first, last, acc, fun) do reduce_range_dec(first - 1, last, fun.(first, acc), fun) end defp reduce_enumerable(enumerable, acc, fun) do Enumerable.reduce(enumerable, {:cont, acc}, fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1) end ## reject defp reject_list([head | tail], fun) do if fun.(head) do reject_list(tail, fun) else [head | reject_list(tail, fun)] end end defp reject_list([], _fun) do [] end ## reverse_slice defp reverse_slice(rest, idx, idx, count, acc) do {slice, rest} = head_slice(rest, count, []) :lists.reverse(rest, :lists.reverse(slice, acc)) end defp reverse_slice([elem | rest], idx, start, count, acc) do reverse_slice(rest, idx - 1, start, count, [elem | acc]) end defp head_slice(rest, 0, acc), do: {acc, rest} defp head_slice([elem | rest], count, acc) do head_slice(rest, count - 1, [elem | acc]) end ## shuffle defp shuffle_unwrap([{_, h} | enumerable], t) do shuffle_unwrap(enumerable, [h | t]) end defp shuffle_unwrap([], t), do: t ## slice defp slice_any(enumerable, start, amount) when start < 0 do {count, fun} = slice_count_and_fun(enumerable) start = count + start if start >= 0 do fun.(start, Kernel.min(amount, count - start)) else [] end end defp slice_any(list, start, amount) when is_list(list) do list |> drop_list(start) |> take_list(amount) end defp slice_any(enumerable, start, amount) do case Enumerable.slice(enumerable) do {:ok, count, _} when start >= count -> [] {:ok, count, fun} when is_function(fun) -> fun.(start, Kernel.min(amount, count - start)) {:error, module} -> slice_enum(enumerable, module, start, amount) end end defp slice_enum(enumerable, module, start, amount) do {_, {_, _, slice}} = module.reduce(enumerable, {:cont, {start, amount, []}}, fn _entry, {start, amount, _list} when start > 0 -> {:cont, {start - 1, amount, []}} entry, {start, amount, list} when amount > 1 -> {:cont, {start, amount - 1, [entry | list]}} entry, {start, amount, list} -> {:halt, {start, amount, [entry | list]}} end) :lists.reverse(slice) end defp slice_count_and_fun(enumerable) when is_list(enumerable) do length = length(enumerable) {length, &Enumerable.List.slice(enumerable, &1, &2, length)} end defp slice_count_and_fun(enumerable) do case Enumerable.slice(enumerable) do {:ok, count, fun} when is_function(fun) -> {count, fun} {:error, module} -> {_, {list, count}} = module.reduce(enumerable, {:cont, {[], 0}}, fn elem, {acc, count} -> {:cont, {[elem | acc], count + 1}} end) {count, &Enumerable.List.slice(:lists.reverse(list), &1, &2, count)} end end ## sort defp sort_reducer(entry, {:split, y, x, r, rs, bool}, fun) do cond do fun.(y, entry) == bool -> {:split, entry, y, [x | r], rs, bool} fun.(x, entry) == bool -> {:split, y, entry, [x | r], rs, bool} r == [] -> {:split, y, x, [entry], rs, bool} true -> {:pivot, y, x, r, rs, entry, bool} end end defp sort_reducer(entry, {:pivot, y, x, r, rs, s, bool}, fun) do cond do fun.(y, entry) == bool -> {:pivot, entry, y, [x | r], rs, s, bool} fun.(x, entry) == bool -> {:pivot, y, entry, [x | r], rs, s, bool} fun.(s, entry) == bool -> {:split, entry, s, [], [[y, x | r] | rs], bool} true -> {:split, s, entry, [], [[y, x | r] | rs], bool} end end defp sort_reducer(entry, [x], fun) do {:split, entry, x, [], [], fun.(x, entry)} end defp sort_reducer(entry, acc, _fun) do [entry | acc] end defp sort_terminator({:split, y, x, r, rs, bool}, fun) do sort_merge([[y, x | r] | rs], fun, bool) end defp sort_terminator({:pivot, y, x, r, rs, s, bool}, fun) do sort_merge([[s], [y, x | r] | rs], fun, bool) end defp sort_terminator(acc, _fun) do acc end defp sort_merge(list, fun, true), do: reverse_sort_merge(list, [], fun, true) defp sort_merge(list, fun, false), do: sort_merge(list, [], fun, false) defp sort_merge([t1, [h2 | t2] | l], acc, fun, true), do: sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, false) | acc], fun, true) defp sort_merge([[h2 | t2], t1 | l], acc, fun, false), do: sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, false) | acc], fun, false) defp sort_merge([l], [], _fun, _bool), do: l defp sort_merge([l], acc, fun, bool), do: reverse_sort_merge([:lists.reverse(l, []) | acc], [], fun, bool) defp sort_merge([], acc, fun, bool), do: reverse_sort_merge(acc, [], fun, bool) defp reverse_sort_merge([[h2 | t2], t1 | l], acc, fun, true), do: reverse_sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, true) | acc], fun, true) defp reverse_sort_merge([t1, [h2 | t2] | l], acc, fun, false), do: reverse_sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, true) | acc], fun, false) defp reverse_sort_merge([l], acc, fun, bool), do: sort_merge([:lists.reverse(l, []) | acc], [], fun, bool) defp reverse_sort_merge([], acc, fun, bool), do: sort_merge(acc, [], fun, bool) defp sort_merge1([h1 | t1], h2, t2, m, fun, bool) do if fun.(h1, h2) == bool do sort_merge2(h1, t1, t2, [h2 | m], fun, bool) else sort_merge1(t1, h2, t2, [h1 | m], fun, bool) end end defp sort_merge1([], h2, t2, m, _fun, _bool), do: :lists.reverse(t2, [h2 | m]) defp sort_merge2(h1, t1, [h2 | t2], m, fun, bool) do if fun.(h1, h2) == bool do sort_merge2(h1, t1, t2, [h2 | m], fun, bool) else sort_merge1(t1, h2, t2, [h1 | m], fun, bool) end end defp sort_merge2(h1, t1, [], m, _fun, _bool), do: :lists.reverse(t1, [h1 | m]) ## split defp split_list([head | tail], counter, acc) when counter > 0 do split_list(tail, counter - 1, [head | acc]) end defp split_list(list, 0, acc) do {:lists.reverse(acc), list} end defp split_list([], _, acc) do {:lists.reverse(acc), []} end defp split_reverse_list([head | tail], counter, acc) when counter > 0 do split_reverse_list(tail, counter - 1, [head | acc]) end defp split_reverse_list(list, 0, acc) do {:lists.reverse(list), acc} end defp split_reverse_list([], _, acc) do {[], acc} end ## split_while defp split_while_list([head | tail], fun, acc) do if fun.(head) do split_while_list(tail, fun, [head | acc]) else {:lists.reverse(acc), [head | tail]} end end defp split_while_list([], _, acc) do {:lists.reverse(acc), []} end ## take defp take_list([head | _], 1), do: [head] defp take_list([head | tail], counter), do: [head | take_list(tail, counter - 1)] defp take_list([], _counter), do: [] ## take_while defp take_while_list([head | tail], fun) do if fun.(head) do [head | take_while_list(tail, fun)] else [] end end defp take_while_list([], _) do [] end ## uniq defp uniq_list([head | tail], set, fun) do value = fun.(head) case set do %{^value => true} -> uniq_list(tail, set, fun) %{} -> [head | uniq_list(tail, Map.put(set, value, true), fun)] end end defp uniq_list([], _set, _fun) do [] end ## zip defp zip_list([h1 | next1], [h2 | next2]) do [{h1, h2} | zip_list(next1, next2)] end defp zip_list(_, []), do: [] defp zip_list([], _), do: [] end defimpl Enumerable, for: List do def count(_list), do: {:error, __MODULE__} def member?(_list, _value), do: {:error, __MODULE__} def slice(_list), do: {:error, __MODULE__} def reduce(_list, {:halt, acc}, _fun), do: {:halted, acc} def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)} def reduce([], {:cont, acc}, _fun), do: {:done, acc} def reduce([head | tail], {:cont, acc}, fun), do: reduce(tail, fun.(head, acc), fun) @doc false def slice(_list, _start, 0, _size), do: [] def slice(list, start, count, size) when start + count == size, do: list |> drop(start) def slice(list, start, count, _size), do: list |> drop(start) |> take(count) defp drop(list, 0), do: list defp drop([_ | tail], count), do: drop(tail, count - 1) defp take(_list, 0), do: [] defp take([head | tail], count), do: [head | take(tail, count - 1)] end defimpl Enumerable, for: Map do def count(map) do {:ok, map_size(map)} end def member?(map, {key, value}) do {:ok, match?(%{^key => ^value}, map)} end def member?(_map, _other) do {:ok, false} end def slice(map) do size = map_size(map) {:ok, size, &Enumerable.List.slice(:maps.to_list(map), &1, &2, size)} end def reduce(map, acc, fun) do Enumerable.List.reduce(:maps.to_list(map), acc, fun) end end defimpl Enumerable, for: Function do def count(_function), do: {:error, __MODULE__} def member?(_function, _value), do: {:error, __MODULE__} def slice(_function), do: {:error, __MODULE__} def reduce(function, acc, fun) when is_function(function, 2), do: function.(acc, fun) def reduce(function, _acc, _fun) do raise Protocol.UndefinedError, protocol: @protocol, value: function, description: "only anonymous functions of arity 2 are enumerable" end end
28.604609
105
0.616563
03b2e2ce5fe64f1f22d9bb9f8c821e2cb6c71dbf
2,847
ex
Elixir
lib/workers/send_site_setup_emails.ex
wvffle/analytics
2c0fd55bc67f74af1fe1e2641678d44e9fee61d5
[ "MIT" ]
2
2020-05-16T13:48:44.000Z
2020-05-22T09:52:36.000Z
lib/workers/send_site_setup_emails.ex
wvffle/analytics
2c0fd55bc67f74af1fe1e2641678d44e9fee61d5
[ "MIT" ]
2
2020-07-09T21:44:35.000Z
2020-07-14T07:06:10.000Z
lib/workers/send_site_setup_emails.ex
wvffle/analytics
2c0fd55bc67f74af1fe1e2641678d44e9fee61d5
[ "MIT" ]
null
null
null
defmodule Plausible.Workers.SendSiteSetupEmails do use Plausible.Repo use Oban.Worker, queue: :site_setup_emails require Logger alias Plausible.Stats.Clickhouse, as: Stats @impl Oban.Worker def perform(_args, _job) do send_create_site_emails() send_setup_help_emails() send_setup_success_emails() :ok end defp send_create_site_emails() do q = from(s in Plausible.Auth.User, left_join: se in "create_site_emails", on: se.user_id == s.id, where: is_nil(se.id), where: s.inserted_at > fragment("(now() at time zone 'utc') - '72 hours'::interval") and s.inserted_at < fragment("(now() at time zone 'utc') - '48 hours'::interval"), preload: :sites ) for user <- Repo.all(q) do if Enum.count(user.sites) == 0 do send_create_site_email(user) end end end defp send_setup_help_emails() do q = from(s in Plausible.Site, left_join: se in "setup_help_emails", on: se.site_id == s.id, where: is_nil(se.id), where: s.inserted_at > fragment("(now() at time zone 'utc') - '72 hours'::interval"), preload: :members ) for site <- Repo.all(q) do owner = List.first(site.members) setup_completed = Stats.has_pageviews?(site) hours_passed = Timex.diff(Timex.now(), site.inserted_at, :hours) if !setup_completed && hours_passed > 47 do send_setup_help_email(owner, site) end end end defp send_setup_success_emails() do q = from(s in Plausible.Site, left_join: se in "setup_success_emails", on: se.site_id == s.id, where: is_nil(se.id), where: s.inserted_at > fragment("(now() at time zone 'utc') - '72 hours'::interval"), preload: :members ) for site <- Repo.all(q) do owner = List.first(site.members) if Stats.has_pageviews?(site) do send_setup_success_email(owner, site) end end end defp send_create_site_email(user) do PlausibleWeb.Email.create_site_email(user) |> Plausible.Mailer.send_email() Repo.insert_all("create_site_emails", [ %{ user_id: user.id, timestamp: NaiveDateTime.utc_now() } ]) end defp send_setup_success_email(user, site) do PlausibleWeb.Email.site_setup_success(user, site) |> Plausible.Mailer.send_email() Repo.insert_all("setup_success_emails", [ %{ site_id: site.id, timestamp: NaiveDateTime.utc_now() } ]) end defp send_setup_help_email(user, site) do PlausibleWeb.Email.site_setup_help(user, site) |> Plausible.Mailer.send_email() Repo.insert_all("setup_help_emails", [ %{ site_id: site.id, timestamp: NaiveDateTime.utc_now() } ]) end end
25.419643
93
0.623463
03b2eeb84f81f099006ee88883fc4990a0c18dbd
564
ex
Elixir
lib/bank_stone_web/views/changeset_view.ex
theguuholi/bank_stone
150a7c7ac9eb2d9bb977d1d784518b39df5c5ab5
[ "MIT" ]
3
2020-04-25T11:35:06.000Z
2021-10-06T19:59:47.000Z
lib/bank_stone_web/views/changeset_view.ex
theguuholi/bank_stone
150a7c7ac9eb2d9bb977d1d784518b39df5c5ab5
[ "MIT" ]
12
2019-11-04T11:06:37.000Z
2019-11-21T11:03:57.000Z
lib/bank_stone_web/views/changeset_view.ex
theguuholi/bank_stone
150a7c7ac9eb2d9bb977d1d784518b39df5c5ab5
[ "MIT" ]
1
2020-12-11T07:05:04.000Z
2020-12-11T07:05:04.000Z
defmodule BankStoneWeb.ChangesetView do use BankStoneWeb, :view @doc """ Traverses and translates changeset errors. See `Ecto.Changeset.traverse_errors/2` and `BankStoneWeb.ErrorHelpers.translate_error/1` for more details. """ def translate_errors(changeset) do Ecto.Changeset.traverse_errors(changeset, &translate_error/1) end def render("error.json", %{changeset: changeset}) do # When encoded, the changeset returns its errors # as a JSON object. So we just pass it forward. %{errors: translate_errors(changeset)} end end
28.2
65
0.741135
03b337aca5c39b8dc8df1d3afac177dc35372627
228
exs
Elixir
apps/data/priv/repo/migrations/20190118162555_add_last_seen_at_to_games.exs
sb8244/grapevine
effaaa01294d30114090c20f9cc40b8665d834f2
[ "MIT" ]
107
2018-10-05T18:20:32.000Z
2022-02-28T04:02:50.000Z
apps/data/priv/repo/migrations/20190118162555_add_last_seen_at_to_games.exs
sb8244/grapevine
effaaa01294d30114090c20f9cc40b8665d834f2
[ "MIT" ]
33
2018-10-05T14:11:18.000Z
2022-02-10T22:19:18.000Z
apps/data/priv/repo/migrations/20190118162555_add_last_seen_at_to_games.exs
sb8244/grapevine
effaaa01294d30114090c20f9cc40b8665d834f2
[ "MIT" ]
18
2019-02-03T03:08:20.000Z
2021-12-28T04:29:36.000Z
defmodule GrapevineData.Repo.Migrations.AddLastSeenAtToGames do use Ecto.Migration def change do alter table(:games) do add(:last_seen_at, :utc_datetime) end create index(:games, :last_seen_at) end end
19
63
0.72807
03b339f0c6ad66e354315c5bc1676d8ad078e7d1
2,351
exs
Elixir
test/mix/tasks/ecto.gen.migration_test.exs
michael-borisov/ecto_sql
86bcf507f026427211907b3c730dcc576721a421
[ "Apache-2.0" ]
null
null
null
test/mix/tasks/ecto.gen.migration_test.exs
michael-borisov/ecto_sql
86bcf507f026427211907b3c730dcc576721a421
[ "Apache-2.0" ]
null
null
null
test/mix/tasks/ecto.gen.migration_test.exs
michael-borisov/ecto_sql
86bcf507f026427211907b3c730dcc576721a421
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Ecto.Gen.MigrationTest do use ExUnit.Case, async: true import Support.FileHelpers import Mix.Tasks.Ecto.Gen.Migration, only: [run: 1] tmp_path = Path.join(tmp_path(), inspect(Ecto.Gen.Migration)) @migrations_path Path.join(tmp_path, "migrations") defmodule Repo do def __adapter__ do true end def config do [priv: "tmp/#{inspect(Ecto.Gen.Migration)}", otp_app: :ecto_sql] end end setup do File.rm_rf!(unquote(tmp_path)) :ok end test "generates a new migration" do [path] = run ["-r", to_string(Repo), "my_migration"] assert Path.dirname(path) == @migrations_path assert Path.basename(path) =~ ~r/^\d{14}_my_migration\.exs$/ assert_file path, fn file -> assert file =~ "defmodule Mix.Tasks.Ecto.Gen.MigrationTest.Repo.Migrations.MyMigration do" assert file =~ "use Ecto.Migration" assert file =~ "def change do" end end test "generates a new migration with Custom Migration Module" do Application.put_env(:ecto_sql, :migration_module, MyCustomApp.MigrationModule) [path] = run ["-r", to_string(Repo), "my_custom_migration"] Application.delete_env(:ecto_sql, :migration_module) assert Path.dirname(path) == @migrations_path assert Path.basename(path) =~ ~r/^\d{14}_my_custom_migration\.exs$/ assert_file path, fn file -> assert file =~ "defmodule Mix.Tasks.Ecto.Gen.MigrationTest.Repo.Migrations.MyCustomMigration do" assert file =~ "use MyCustomApp.MigrationModule" assert file =~ "def change do" end end test "underscores the filename when generating a migration" do run ["-r", to_string(Repo), "MyMigration"] assert [name] = File.ls!(@migrations_path) assert name =~ ~r/^\d{14}_my_migration\.exs$/ end test "underscores the filename when filename with spaces" do run ["-r", to_string(Repo), "My migration"] assert [name] = File.ls!(@migrations_path) assert name =~ ~r/^\d{14}_my_migration\.exs$/ end test "raises when existing migration exists" do run ["-r", to_string(Repo), "my_migration"] assert_raise Mix.Error, ~r"migration can't be created", fn -> run ["-r", to_string(Repo), "my_migration"] end end test "raises when missing file" do assert_raise Mix.Error, fn -> run ["-r", to_string(Repo)] end end end
32.652778
102
0.680987
03b39e1595e351d2aeca2522692f329cd0f878b2
1,330
ex
Elixir
lib/ex_sieve/node.ex
ppraisethesun/ex_sieve
17b9802281e13cc348621f519103f5e42fc0df87
[ "MIT" ]
null
null
null
lib/ex_sieve/node.ex
ppraisethesun/ex_sieve
17b9802281e13cc348621f519103f5e42fc0df87
[ "MIT" ]
null
null
null
lib/ex_sieve/node.ex
ppraisethesun/ex_sieve
17b9802281e13cc348621f519103f5e42fc0df87
[ "MIT" ]
null
null
null
defmodule ExSieve.Node do @moduledoc false alias ExSieve.Node.{Grouping, Sort} alias ExSieve.{Config, Utils} @typep error :: {:error, :attribute_not_found | :predicat_not_found | :direction_not_found} @spec call(%{(atom | binary) => term}, atom, Config.t) :: {:ok, Grouping.t, list(Sort.t)} | error def call(params_with_sort, schema, config) do params_with_sort = stringify_keys(params_with_sort) {params, sorts} = extract_sorts(params_with_sort, schema) grouping = Grouping.extract(params, schema, config) result(grouping, Utils.get_error(sorts, config)) end defp extract_sorts(params, schema) do {sorts, params} = Map.pop(params, "s", []) {params, sorts |> Sort.extract(schema)} end defp result({:error, reason}, _sorts), do: {:error, reason} defp result(_grouping, {:error, reason}), do: {:error, reason} defp result(grouping, sorts), do: {:ok, grouping, sorts} defp stringify_keys(nil), do: nil defp stringify_keys(%{__struct__: _struct} = value), do: Macro.escape(value) defp stringify_keys(map = %{}) do map |> Enum.map(fn {k, v} -> {to_string(k), stringify_keys(v)} end) |> Enum.into(%{}) end defp stringify_keys([head | rest]) do [stringify_keys(head) | stringify_keys(rest)] end defp stringify_keys(not_a_map) do not_a_map end end
33.25
99
0.682707
03b3a6cc1a71e28f81a2f52a839296723c7da9f2
2,651
ex
Elixir
clients/games/lib/google_api/games/v1/model/participant_result.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/games/lib/google_api/games/v1/model/participant_result.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/model/participant_result.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.Games.V1.Model.ParticipantResult do @moduledoc """ This is a JSON template for a result for a match participant. ## Attributes * `kind` (*type:* `String.t`, *default:* `games#participantResult`) - Uniquely identifies the type of this resource. Value is always the fixed string games#participantResult. * `participantId` (*type:* `String.t`, *default:* `nil`) - The ID of the participant. * `placing` (*type:* `integer()`, *default:* `nil`) - The placement or ranking of the participant in the match results; a number from one to the number of participants in the match. Multiple participants may have the same placing value in case of a type. * `result` (*type:* `String.t`, *default:* `nil`) - The result of the participant for this match. Possible values are: - "MATCH_RESULT_WIN" - The participant won the match. - "MATCH_RESULT_LOSS" - The participant lost the match. - "MATCH_RESULT_TIE" - The participant tied the match. - "MATCH_RESULT_NONE" - There was no winner for the match (nobody wins or loses this kind of game.) - "MATCH_RESULT_DISCONNECT" - The participant disconnected / left during the match. - "MATCH_RESULT_DISAGREED" - Different clients reported different results for this participant. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :kind => String.t(), :participantId => String.t(), :placing => integer(), :result => String.t() } field(:kind) field(:participantId) field(:placing) field(:result) end defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.ParticipantResult do def decode(value, options) do GoogleApi.Games.V1.Model.ParticipantResult.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.ParticipantResult do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.079365
258
0.712939
03b3b1a187e63aaa413d614cec901d177bd1a197
537
ex
Elixir
lib/rps_web/channels/user_socket.ex
cabol/rps
813028c4b7bb18f8c7cbcf4422249a81ccb9f059
[ "MIT" ]
3
2018-05-28T15:10:11.000Z
2020-08-02T21:14:25.000Z
lib/rps_web/channels/user_socket.ex
cabol/rps
813028c4b7bb18f8c7cbcf4422249a81ccb9f059
[ "MIT" ]
null
null
null
lib/rps_web/channels/user_socket.ex
cabol/rps
813028c4b7bb18f8c7cbcf4422249a81ccb9f059
[ "MIT" ]
null
null
null
defmodule RpsWeb.UserSocket do use Phoenix.Socket alias Rps.Accounts ## Channels channel "room:*", RpsWeb.RoomChannel ## Transports transport :websocket, Phoenix.Transports.WebSocket def connect(params, socket) do do_authorize(params, socket) end def id(_socket), do: nil defp do_authorize(params, socket) do case Accounts.authenticate_user(params) do {:ok, verified_user} -> {:ok, assign(socket, :user_id, verified_user.id)} {:error, _changeset} -> :error end end end
19.888889
57
0.67784
03b3c93147cf3f1457b56ce24976af09093120b8
1,188
exs
Elixir
clients/cloud_iot/mix.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/cloud_iot/mix.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/cloud_iot/mix.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
defmodule GoogleApi.CloudIot.V1.Mixfile do use Mix.Project @version "0.12.0" def project do [app: :google_api_cloud_iot, 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/cloud_iot" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.1.0"}, {:ex_doc, "~> 0.16", only: :dev}, {:dialyxir, "~> 0.5", only: [:dev], runtime: false} ] end defp description() do """ Registers and manages IoT (Internet of Things) devices that connect to the Google Cloud Platform. """ 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/cloud_iot", "Homepage" => "https://cloud.google.com/iot" } ] end end
24.244898
109
0.596801
03b3eebfa5562c887e374b55e7dcb4daeabcb3c1
1,589
exs
Elixir
test/define/tabular_test.exs
marick/flow_assertions
50936d03c7e0d482f13f94c96438627d344592c0
[ "Unlicense" ]
8
2020-09-04T19:38:41.000Z
2021-06-05T18:59:49.000Z
test/define/tabular_test.exs
marick/flow_assertions
50936d03c7e0d482f13f94c96438627d344592c0
[ "Unlicense" ]
null
null
null
test/define/tabular_test.exs
marick/flow_assertions
50936d03c7e0d482f13f94c96438627d344592c0
[ "Unlicense" ]
null
null
null
defmodule FlowAssertions.Define.TabularTests do use FlowAssertions.Case import FlowAssertions.Define.{Tabular,BodyParts} describe "fail" do test "variant argument lists" do a = assertion_runners_for(&assert_equal/2) msg = "Assertion with === failed" ["a", "b"] |> a.fail.(msg) ["a", "b"] |> a.fail.(left: "a", right: "b") ["a", "b"] |> a.fail.(message: msg, left: "a", right: "b") ["a", "b"] |> a.fail.(msg) |> a.plus.(left: "a", right: "b") # Note that left and right are not string versions [ ["a", "a"], "b"] |> a.fail.(message: msg, left: ["a", "a"]) # The message is always compared specially: [ ["a", "a"], "b"] |> a.fail.(message: ~r/with/, left: ["a", "a"]) end end describe "left_is_actual" do def bad_one_arg(_ ), do: elaborate_flunk("message", left: "weird") def bad_two_arg(_, _), do: elaborate_flunk("message", left: "weird") def fails(f) do assertion_fails("Field `:left` has the wrong value", [left: "weird", right: :error], f) end test "one argument asserter" do x = assertion_runners_for(&assert_equal/2) |> left_is_actual [1, 2] |> x.fail.("Assertion with === failed") a = assertion_runners_for(&bad_one_arg/1) |> left_is_actual fails(fn -> :error |> a.fail.("message") end) end test "two argument asserter" do a = assertion_runners_for(&bad_two_arg/2) |> left_is_actual fails(fn -> [:error, :other] |> a.fail.("message") end) end end end
29.981132
72
0.568282
03b3ffe73eb9502c9e058f15faa55eed2a3552e1
1,129
exs
Elixir
config/dev.exs
vertico/vertico-test
af68000ff99450cf5686d7c5b803931f267c8e19
[ "MIT" ]
3
2021-11-23T23:07:34.000Z
2021-11-24T01:40:01.000Z
config/dev.exs
vertico/vertico-test
af68000ff99450cf5686d7c5b803931f267c8e19
[ "MIT" ]
null
null
null
config/dev.exs
vertico/vertico-test
af68000ff99450cf5686d7c5b803931f267c8e19
[ "MIT" ]
1
2021-07-19T11:48:30.000Z
2021-07-19T11:48:30.000Z
import Mix.Config require Logger config :shikoba, Shikoba.Repo, database: "shikoba_dev", hostname: "localhost", show_sensitive_data_on_connection_error: true, pool_size: 10 config :shikoba, ShikobaWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false config :shikoba, ShikobaWeb.BasicAuth, username: "admin", password: "123123" # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime config :shikoba, Shikoba.Mailer, adapter: Bamboo.LocalAdapter config :shikoba, :environment, :dev if File.exists? "config/dev.secret.exs" do import_config "dev.secret.exs" else File.cp!("config/secret.example.exs", "config/dev.secret.exs") Logger.warn("config/dev.secret.exs created. Check your database configuration.") end
26.880952
82
0.765279
03b425c7e8e17f7660491cc245b31be36b83a8ff
2,525
exs
Elixir
config/config.exs
optikfluffel/radiator
b1a1b966296fa6bf123e3a2455009ff52099ace6
[ "MIT" ]
1
2021-03-02T16:59:40.000Z
2021-03-02T16:59:40.000Z
config/config.exs
optikfluffel/radiator
b1a1b966296fa6bf123e3a2455009ff52099ace6
[ "MIT" ]
null
null
null
config/config.exs
optikfluffel/radiator
b1a1b966296fa6bf123e3a2455009ff52099ace6
[ "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 :radiator, ecto_repos: [Radiator.Repo] # Configures the endpoint config :radiator, RadiatorWeb.Endpoint, url: [host: "localhost"], secret_key_base: "Ulfk2ILpLFu95vdZSe8Af8pjN9n516jHZXb7BUnPHU0xu8g/tyAdNzZBVGtMo0JH", render_errors: [view: RadiatorWeb.ErrorView, accepts: ~w(html json)], pubsub: [name: Radiator.PubSub, adapter: Phoenix.PubSub.PG2] config :radiator, Radiator.Auth.Guardian, issuer: "radiator", secret_key: "dev-only;I1B6O0dEt9sBw6531zH/vDHKEDTY64ohsPxLw5jvLtKaphKofVC/NM5nzkbyD4HW" config :radiator, storage_bucket: "radiator" config :radiator, :auth, email_from_name: "Radiator-Instance", email_from_email: "do_not_reply@radiator.local" config :radiator, Radiator.Mailer, adapter: Bamboo.SMTPAdapter, server: "smtp.domain", hostname: "your.domain", port: 1025, # or {:system, "SMTP_USERNAME"} username: "your.name@your.domain", # or {:system, "SMTP_PASSWORD"} password: "pa55word", # can be `:always` or `:never` tls: :if_available, # or {":system", ALLOWED_TLS_VERSIONS"} w/ comma seprated values (e.g. "tlsv1.1,tlsv1.2") allowed_tls_versions: [:tlsv1, :"tlsv1.1", :"tlsv1.2"], # can be `true` ssl: false, retries: 1, # can be `true` no_mx_lookups: false, # can be `always`. If your smtp relay requires authentication set it to `always`. auth: :if_available config :arc, # or Arc.Storage.Local storage: Arc.Storage.S3, # if using Amazon S3 bucket: "radiator", asset_host: System.get_env("STORAGE_ASSET_HOST") || "http://localhost:9000/radiator" config :ex_aws, access_key_id: "IEKAZMUY3KX32CRJPE9R", secret_access_key: "tXNYsfJyb8ctDgZSaIOYpndQwxOv8T+E+U0Rq3mN", json_codec: Jason config :ex_aws, :s3, scheme: "http://", host: System.get_env("STORAGE_HOST") || "localhost", port: 9000 config :ex_aws, :hackney_opts, follow_redirect: true, recv_timeout: 30_000 # 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"
30.059524
91
0.736634
03b42a8df3157dcfb696922c0bbd2843b42c4f1d
512
ex
Elixir
lib/utils.ex
alwayswimmin/Sue
33dfd860e7d5b6dce11e2dc202924efad6a9474c
[ "MIT" ]
1
2020-06-21T01:50:12.000Z
2020-06-21T01:50:12.000Z
lib/utils.ex
alwayswimmin/Sue
33dfd860e7d5b6dce11e2dc202924efad6a9474c
[ "MIT" ]
null
null
null
lib/utils.ex
alwayswimmin/Sue
33dfd860e7d5b6dce11e2dc202924efad6a9474c
[ "MIT" ]
null
null
null
defmodule Sue.Utils do @spec tokenize(String.t()) :: [String.t()] def tokenize(args) do cond do String.contains?(args, "\n") -> String.split(args, "\n") String.contains?(args, ",") -> String.split(args, ",", trim: true) true -> String.split(args, " ") end end @spec contains?(Enumerable.t(), any()) :: boolean() def contains?(enum, item) do item in enum end def unique_string() do ("Reference<" <> inspect(make_ref())) |> String.trim_trailing(">") end end
24.380952
72
0.591797
03b43c405c9ef3d4c6629c892ba370fc07da0045
894
ex
Elixir
debian/prerm.ex
sharkwouter/vaporos-flatpak-manager
da1dce2a806fdb51aa9366408ace50c28fbc3ff6
[ "MIT" ]
null
null
null
debian/prerm.ex
sharkwouter/vaporos-flatpak-manager
da1dce2a806fdb51aa9366408ace50c28fbc3ff6
[ "MIT" ]
21
2019-09-15T08:42:58.000Z
2021-08-28T16:48:54.000Z
debian/prerm.ex
sharkwouter/vaporos-flatpak-manager
da1dce2a806fdb51aa9366408ace50c28fbc3ff6
[ "MIT" ]
null
null
null
#!/bin/sh # prerm script for vaporos-flatpak-manager # # see: dh_installdeb(1) set -e # summary of how this script can be called: # * <prerm> `remove' # * <old-prerm> `upgrade' <new-version> # * <new-prerm> `failed-upgrade' <old-version> # * <conflictor's-prerm> `remove' `in-favour' <package> <new-version> # * <deconfigured's-prerm> `deconfigure' `in-favour' # <package-being-installed> <version> `removing' # <conflicting-package> <version> # for details, see https://www.debian.org/doc/debian-policy/ or # the debian-policy package case "$1" in remove|upgrade|deconfigure) ;; failed-upgrade) ;; *) echo "prerm called with unknown argument \`$1'" >&2 exit 1 ;; esac # dh_installdeb will replace this with shell code automatically # generated by other debhelper scripts. #DEBHELPER# exit 0
22.923077
76
0.630872
03b44d8e10a835af9bb7f7c804dfd4896e6d0ce0
4,400
exs
Elixir
test/mysimplelist/lists_test.exs
ScorpionResponse/mysimplelist
3c792373cc372ab5e196fe109b9dae68b97b7220
[ "Apache-2.0" ]
null
null
null
test/mysimplelist/lists_test.exs
ScorpionResponse/mysimplelist
3c792373cc372ab5e196fe109b9dae68b97b7220
[ "Apache-2.0" ]
null
null
null
test/mysimplelist/lists_test.exs
ScorpionResponse/mysimplelist
3c792373cc372ab5e196fe109b9dae68b97b7220
[ "Apache-2.0" ]
null
null
null
defmodule Mysimplelist.ListsTest do use Mysimplelist.DataCase alias Mysimplelist.Lists import Mysimplelist.Tests.Fixtures describe "lists" do alias Mysimplelist.Lists.List @valid_attrs %{name: "some name"} @update_attrs %{name: "some updated name"} @invalid_attrs %{name: nil, user_id: nil} test "list_lists/0 returns all lists" do list = list_fixture() assert Lists.list_lists() == [list] end test "get_list!/1 returns the list with given id" do list = list_fixture() assert Lists.get_list!(list.id) == list end test "create_list/1 with valid data creates a list" do user = user_fixture() assert {:ok, %List{} = list} = Lists.create_list(user, @valid_attrs) assert list.name == "some name" assert list.user_id == user.id end test "create_list/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Lists.create_list(nil, @invalid_attrs) end test "update_list/2 with valid data updates the list" do user = user_fixture() list = list_fixture(%{user: user}) assert {:ok, %List{} = list} = Lists.update_list(list, @update_attrs) assert list.name == "some updated name" assert list.user_id == user.id end test "update_list/2 with invalid data returns error changeset" do list = list_fixture() assert {:error, %Ecto.Changeset{}} = Lists.update_list(list, @invalid_attrs) assert list == Lists.get_list!(list.id) end test "delete_list/1 deletes the list" do list = list_fixture() assert {:ok, %List{}} = Lists.delete_list(list) assert_raise Ecto.NoResultsError, fn -> Lists.get_list!(list.id) end end test "change_list/1 returns a list changeset" do list = list_fixture() assert %Ecto.Changeset{} = Lists.change_list(list) end end describe "list_items" do alias Mysimplelist.Lists.ListItem @valid_attrs %{ title: "some title", details: "some details", complete: false } @update_attrs %{ title: "some updated title", details: "some updated details", complete: false } @invalid_attrs %{title: nil, details: nil, complete: nil} test "list_list_items/0 returns all list_items" do list_item = list_item_fixture() assert Map.delete(List.last(Lists.list_list_items()), :list) == Map.delete(list_item, :list) end test "get_list_item!/1 returns the list_item with given id" do list_item = list_item_fixture() assert Map.delete(Lists.get_list_item!(list_item.id), :list) == Map.delete(list_item, :list) end test "create_list_item/1 with valid data creates a list_item" do list = list_fixture() assert {:ok, %ListItem{} = list_item} = Lists.create_list_item(Map.put(@valid_attrs, :list_id, list.id)) assert list_item.details == "some details" assert list_item.title == "some title" assert list_item.complete == false assert list_item.list_id == list.id end test "create_list_item/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Lists.create_list_item(@invalid_attrs) end test "update_list_item/2 with valid data updates the list_item" do list = list_fixture() list_item = list_item_fixture(%{list: list}) assert {:ok, %ListItem{} = list_item} = Lists.update_list_item(list_item, @update_attrs) assert list_item.details == "some updated details" assert list_item.title == "some updated title" assert list_item.list_id == list.id end test "update_list_item/2 with invalid data returns error changeset" do list_item = list_item_fixture() assert {:error, %Ecto.Changeset{}} = Lists.update_list_item(list_item, @invalid_attrs) assert Map.delete(list_item, :list) == Map.delete(Lists.get_list_item!(list_item.id), :list) end test "delete_list_item/1 deletes the list_item" do list_item = list_item_fixture() assert {:ok, %ListItem{}} = Lists.delete_list_item(list_item) assert_raise Ecto.NoResultsError, fn -> Lists.get_list_item!(list_item.id) end end test "change_list_item/1 returns a list_item changeset" do list_item = list_item_fixture() assert %Ecto.Changeset{} = Lists.change_list_item(list_item) end end end
33.587786
98
0.672727
03b4a273b1a1f4f9b5df274d938fd337adf355c1
5,516
ex
Elixir
lib/grapevine/authorizations.ex
shanesveller/grapevine
fe74ade1adff88dfe4c1ab55fee3902dbb4664fe
[ "MIT" ]
null
null
null
lib/grapevine/authorizations.ex
shanesveller/grapevine
fe74ade1adff88dfe4c1ab55fee3902dbb4664fe
[ "MIT" ]
null
null
null
lib/grapevine/authorizations.ex
shanesveller/grapevine
fe74ade1adff88dfe4c1ab55fee3902dbb4664fe
[ "MIT" ]
null
null
null
defmodule Grapevine.Authorizations do @moduledoc """ Authorize remote logins """ import Ecto.Query alias Grapevine.Authorizations.AccessToken alias Grapevine.Authorizations.Authorization alias Grapevine.Games alias Grapevine.Repo @doc """ Check for a username before allowing oauth to proceed """ def check_for_username(user) do case is_nil(user.username) do true -> {:error, :no_username} false -> {:ok, user} end end @doc """ Start authorization Creates an authorization record """ def start_auth(user, game, params) do :telemetry.execute([:web, :oauth, :start], 1, %{user_id: user.id, game_id: game.id}) with {:ok, redirect_uri} <- Map.fetch(params, "redirect_uri") do scopes = params |> Map.get("scope", "") |> String.split(" ") |> Enum.sort() params = Map.put(params, "scopes", scopes) opts = [ user_id: user.id, game_id: game.id, redirect_uri: redirect_uri, active: true, scopes: scopes, ] case Repo.get_by(Authorization, opts) do nil -> create_authorization(user, game, params) authorization -> refresh_code(authorization) end else _ -> create_authorization(user, game, params) end end defp refresh_code(authorization) do changeset = authorization |> Authorization.refresh_code_changeset() case Repo.update(changeset) do {:ok, authorization} -> deactivate_all_tokens(authorization) {:ok, authorization} {:error, changeset} -> {:error, changeset} end end defp deactivate_all_tokens(authorization) do AccessToken |> where([at], at.authorization_id == ^authorization.id) |> Repo.update_all(set: [active: false]) end defp create_authorization(user, game, params) do user |> Ecto.build_assoc(:authorizations) |> Authorization.create_changeset(game, params) |> Repo.insert() end @doc """ Get a user's authorization record """ def get(user, id) do case Repo.get_by(Authorization, user_id: user.id, id: id) do nil -> {:error, :not_found} authorization -> {:ok, authorization} end end def get_token(token) do with {:ok, token} <- Ecto.UUID.cast(token) do case Repo.get_by(AccessToken, access_token: token) do nil -> {:error, :not_found} access_token -> {:ok, Repo.preload(access_token, [authorization: [:user]])} end else _ -> {:error, :not_found} end end @doc """ Authorize an authorization Marks it as active """ def authorize(authorization) do :telemetry.execute([:web, :oauth, :authorized], 1, %{user_id: authorization.user_id, game_id: authorization.game_id}) authorization |> Authorization.authorize_changeset() |> Repo.update() end @doc """ Deny an authorization Deletes the authorization record """ def deny(authorization) do :telemetry.execute([:web, :oauth, :denied], 1, %{user_id: authorization.user_id, game_id: authorization.game_id}) Repo.delete(authorization) end @doc """ Get an authorized redirect uri Includes the authorization code """ def authorized_redirect_uri(authorization) do uri = URI.parse(authorization.redirect_uri) query = URI.encode_query(%{code: authorization.code, state: authorization.state}) uri = %{uri | query: query} {:ok, URI.to_string(uri)} end @doc """ Get a denied redirect uri """ def denied_redirect_uri(authorization) do uri = URI.parse(authorization.redirect_uri) query = URI.encode_query(%{error: :access_denied, state: authorization.state}) uri = %{uri | query: query} {:ok, URI.to_string(uri)} end @doc """ Create an access token """ def create_token(client_id, redirect_uri, code) do with {:ok, client_id} <- Ecto.UUID.cast(client_id), {:ok, game} <- Games.get_by(client_id: client_id), {:ok, code} <- Ecto.UUID.cast(code) do case Repo.get_by(Authorization, game_id: game.id, redirect_uri: redirect_uri, code: code, active: true) do nil -> :telemetry.execute([:web, :oauth, :invalid_grant], 1, %{client_id: client_id}) {:error, :invalid_grant} authorization -> :telemetry.execute([:web, :oauth, :create_token], 1, %{user_id: authorization.user_id, game_id: authorization.game_id}) create_token(authorization) end else _ -> {:error, :invalid_grant} end end @doc false def create_token(authorization = %Authorization{}) do with {:ok, authorization} <- mark_as_used(authorization) do authorization |> Ecto.build_assoc(:access_tokens) |> AccessToken.create_changeset() |> Repo.insert() end end @doc false def mark_as_used(authorization) do authorization |> Authorization.used_changeset() |> Repo.update() end @doc """ Validate a token A token is valid if: - within expiration time - authorization is active """ def valid_token?(access_token) do access_token = Repo.preload(access_token, [:authorization]) case access_token.authorization.active do false -> false true -> valid_til = access_token.inserted_at |> Timex.shift(seconds: access_token.expires_in) access_token.active && Timex.before?(Timex.now(), valid_til) end end end
24.515556
129
0.637237
03b4af517983793f3ce3ec89dc78f8aed620691f
1,001
ex
Elixir
lib/danpay/application.ex
Nilomiranda/Danpay
1b6f05a8a5ce6b636241c369fca85f16b229bc82
[ "MIT" ]
null
null
null
lib/danpay/application.ex
Nilomiranda/Danpay
1b6f05a8a5ce6b636241c369fca85f16b229bc82
[ "MIT" ]
null
null
null
lib/danpay/application.ex
Nilomiranda/Danpay
1b6f05a8a5ce6b636241c369fca85f16b229bc82
[ "MIT" ]
null
null
null
defmodule Danpay.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do children = [ # Start the Ecto repository Danpay.Repo, # Start the Telemetry supervisor DanpayWeb.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: Danpay.PubSub}, # Start the Endpoint (http/https) DanpayWeb.Endpoint # Start a worker by calling: Danpay.Worker.start_link(arg) # {Danpay.Worker, arg} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Danpay.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do DanpayWeb.Endpoint.config_change(changed, removed) :ok end end
28.6
64
0.699301
03b4b4580687f7a60c916335e4267c9c2b2c70c9
1,100
exs
Elixir
test/chunk_test.exs
macoene/observables
6e43ab9b7ea2afa60160a13ef5c37eb20dc597b7
[ "MIT" ]
4
2018-04-16T20:43:37.000Z
2019-07-18T21:50:49.000Z
test/chunk_test.exs
macoene/observables
6e43ab9b7ea2afa60160a13ef5c37eb20dc597b7
[ "MIT" ]
null
null
null
test/chunk_test.exs
macoene/observables
6e43ab9b7ea2afa60160a13ef5c37eb20dc597b7
[ "MIT" ]
1
2021-03-18T18:37:11.000Z
2021-03-18T18:37:11.000Z
defmodule ChunkTest do use ExUnit.Case alias Observables.{Obs} require Logger @tag :chunk test "chunk" do testproc = self() start = 1 tend = 50 size = 5 # Create a range. Obs.range(start, tend, 100) # We should consume 5 values each time. |> Obs.chunk(size * 100 + 10) |> Obs.each(fn v -> Logger.debug("Sending #{inspect(v, charlists: :as_lists)}") send(testproc, v) end) # Receive all the values. Enum.chunk_every(1..50, size) |> Enum.map(fn list -> Logger.debug("Waiting for #{inspect(list, charlists: :as_lists)}") receive do ^list -> Logger.debug("Got list #{inspect(list, charlists: :as_lists)}") after 10000 -> assert "Did not receive list in time: #{inspect(list, charlists: :as_lists)}" == "" end end) # Receive no other values. receive do x -> Logger.error("Received another value, did not want") assert "received another value: #{inspect(x, charlists: :as_lists)} " == "" after 1000 -> :ok end end end
23.404255
93
0.58
03b4bcf5f7a8027334c903027268e96074000bb0
1,123
exs
Elixir
config/config.exs
zcking/ex_hash
5e70788bffd26961be059074bf15413fe0e2ee43
[ "MIT" ]
1
2018-11-04T14:45:36.000Z
2018-11-04T14:45:36.000Z
config/config.exs
zcking/ex_hash
5e70788bffd26961be059074bf15413fe0e2ee43
[ "MIT" ]
null
null
null
config/config.exs
zcking/ex_hash
5e70788bffd26961be059074bf15413fe0e2ee43
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :ex_hash, key: :value # # and access this configuration in your application as: # # Application.get_env(:ex_hash, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
36.225806
73
0.751558
03b4c0e7b786ca651f911f31facae41a7cf59d20
892
ex
Elixir
lib/astarte_rpc/protocol/realm_management.ex
Annopaolo/astarte_rpc
cd720004d225631f41d6f4d7f964aecb92b52849
[ "Apache-2.0" ]
3
2018-02-02T14:07:03.000Z
2020-02-10T07:12:39.000Z
lib/astarte_rpc/protocol/realm_management.ex
Annopaolo/astarte_rpc
cd720004d225631f41d6f4d7f964aecb92b52849
[ "Apache-2.0" ]
49
2018-02-02T10:00:30.000Z
2022-03-22T10:39:10.000Z
lib/astarte_rpc/protocol/realm_management.ex
Annopaolo/astarte_rpc
cd720004d225631f41d6f4d7f964aecb92b52849
[ "Apache-2.0" ]
5
2018-02-02T09:58:07.000Z
2021-04-07T08:53:44.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.RPC.Protocol.RealmManagement do @external_resource Path.expand("proto/realm_management", __DIR__) use Protobuf, from: Path.wildcard(Path.expand("proto/realm_management/*.proto", __DIR__)) use Astarte.RPC.Protocol, amqp_queue: "realm_management_rpc" end
35.68
91
0.769058
03b4eea915604d1ec1ac7d02d75b04deda19ae7e
456
ex
Elixir
platform/target/network/wait_for_time.ex
pdgonzalez872/farmbot_os
a444248f05ee8f4fe57f6a4865b942131960f76c
[ "MIT" ]
null
null
null
platform/target/network/wait_for_time.ex
pdgonzalez872/farmbot_os
a444248f05ee8f4fe57f6a4865b942131960f76c
[ "MIT" ]
null
null
null
platform/target/network/wait_for_time.ex
pdgonzalez872/farmbot_os
a444248f05ee8f4fe57f6a4865b942131960f76c
[ "MIT" ]
1
2020-12-16T16:39:32.000Z
2020-12-16T16:39:32.000Z
defmodule Farmbot.Target.Network.WaitForTime do use Farmbot.Logger def start_link(_, _) do :ok = wait_for_time() Logger.success 3, "Time seems to be set: #{:os.system_time(:seconds)} . Moving on." :ignore end defp wait_for_time do case :os.system_time(:seconds) do t when t > 1_474_929 -> :ok _ -> Process.sleep(1000) # Logger.warn "Waiting for time." wait_for_time() end end end
21.714286
87
0.618421
03b4f4bf9b852a716f8ab0f5c66df2ff53db49e8
277
ex
Elixir
lib/mix_test_watch/message_inbox.ex
gasparch/mix-test.watch
6be7f440bedb04ee191c187a6eeed433fd001572
[ "MIT" ]
1
2021-01-04T16:42:18.000Z
2021-01-04T16:42:18.000Z
lib/mix_test_watch/message_inbox.ex
mkaszubowski/mix-test.watch
6be7f440bedb04ee191c187a6eeed433fd001572
[ "MIT" ]
null
null
null
lib/mix_test_watch/message_inbox.ex
mkaszubowski/mix-test.watch
6be7f440bedb04ee191c187a6eeed433fd001572
[ "MIT" ]
null
null
null
defmodule MixTestWatch.MessageInbox do @moduledoc """ Helpers for managing process messages. """ @spec flush :: :ok @doc """ Clear the process inbox of all messages. """ def flush do receive do _ -> flush after 0 -> :ok end end end
16.294118
42
0.599278
03b5350d535404236bc9e8853a57709077f6b290
1,595
exs
Elixir
node_modules/@snyk/snyk-hex-plugin/elixirsrc/deps/json/mix.exs
muhamarief/cobafrappe
9f4c787338873e774d73779a8f1cee168daa2b62
[ "MIT" ]
165
2015-01-21T19:50:39.000Z
2021-11-05T12:31:23.000Z
node_modules/@snyk/snyk-hex-plugin/elixirsrc/deps/json/mix.exs
muhamarief/cobafrappe
9f4c787338873e774d73779a8f1cee168daa2b62
[ "MIT" ]
27
2015-05-08T14:03:17.000Z
2021-09-11T09:27:16.000Z
node_modules/@snyk/snyk-hex-plugin/elixirsrc/deps/json/mix.exs
muhamarief/cobafrappe
9f4c787338873e774d73779a8f1cee168daa2b62
[ "MIT" ]
28
2015-05-08T14:09:34.000Z
2021-06-20T13:48:52.000Z
defmodule ElixirJSON_140_SNAPSHOT.Mixfile do use Mix.Project @version "1.4.1" def project do [ app: :json, version: @version, elixir: "~> 1.7", deps: deps(Mix.env()), description: "The First Native Elixir library for JSON encoding and decoding", package: package(), source_url: "https://github.com/cblage/elixir-json", homepage_url: "https://hex.pm/packages/json", test_coverage: [tool: ExCoveralls], docs: docs(), preferred_cli_env: [ docs: :docs, coveralls: :test, test: :test ], dialyzer_ignored_warnings: [ {:warn_umatched_return, {:_, :_}, {:unmatched_return, :_}} ] ] end def application do [applications: applications(Mix.env())] end defp applications(:dev), do: [] ++ applications(:default) defp applications(_all), do: [:logger] def deps(_) do [ {:ex_doc, ">= 0.0.0", only: :dev, runtime: false}, {:credo, "~> 1.5", only: [:dev, :test], runtime: false}, {:dialyzex, "~> 1.2", only: [:dev]}, {:excoveralls, "~> 0.13.4", only: :test, optional: true, runtime: false} ] end defp docs() do [ main: "readme", name: "JSON", source_ref: "v#{@version}", canonical: "http://hexdocs.pm/json", source_url: "https://github.com/cblage/elixir-json", extras: [ "README.md" ] ] end def package do [ maintainers: ["cblage"], licenses: ["BSD 3-Clause"], links: %{"GitHub" => "https://github.com/cblage/elixir-json"} ] end end
24.166667
84
0.561129
03b5590e551276ba61c38303efba3c708bf9cb26
482
ex
Elixir
lib/elx_k8s/release.ex
adrianomota/elx-k8s
27c0f5c3099137041043d05e754b2b5eb7e0c0f9
[ "MIT" ]
null
null
null
lib/elx_k8s/release.ex
adrianomota/elx-k8s
27c0f5c3099137041043d05e754b2b5eb7e0c0f9
[ "MIT" ]
null
null
null
lib/elx_k8s/release.ex
adrianomota/elx-k8s
27c0f5c3099137041043d05e754b2b5eb7e0c0f9
[ "MIT" ]
null
null
null
defmodule ElxK8s.Release do @app :elx_k8s def migrate do load_app() for repo <- repos() do {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true)) end end def rollback(repo, version) do load_app() {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version)) end defp repos do Application.fetch_env!(@app, :ecto_repos) end defp load_app do Application.load(@app) end end
19.28
91
0.634855
03b55c9aafa3702cda2f322cbe443ec7ffffde04
1,071
ex
Elixir
lib/postgrex/extensions/jsonb.ex
enter-haken/postgrex
fb3438d4e6a56db81ddd0d578cdfc0484909c233
[ "Apache-2.0" ]
681
2016-06-16T12:28:22.000Z
2022-03-30T08:48:42.000Z
deps/postgrex/lib/postgrex/extensions/jsonb.ex
rwtrecs/rocketseat-nlw5-inmana
8ce8bc32e0bdd005c423394bb163945747b557e2
[ "MIT" ]
383
2016-06-17T14:49:41.000Z
2022-03-21T18:13:19.000Z
deps/postgrex/lib/postgrex/extensions/jsonb.ex
adrianomota/blog
ef3b2d2ed54f038368ead8234d76c18983caa75b
[ "MIT" ]
234
2016-06-16T16:14:47.000Z
2022-03-03T00:43:59.000Z
defmodule Postgrex.Extensions.JSONB do @moduledoc false import Postgrex.BinaryUtils, warn: false def init(opts) do json = Keyword.get_lazy(opts, :json, fn -> Application.get_env(:postgrex, :json_library, Jason) end) {json, Keyword.get(opts, :decode_binary, :copy)} end def matching({nil, _}), do: [] def matching(_), do: [type: "jsonb"] def format(_), do: :binary def encode({library, _}) do quote location: :keep do map -> data = unquote(library).encode_to_iodata!(map) [<<IO.iodata_length(data) + 1::int32, 1>> | data] end end def decode({library, :copy}) do quote location: :keep do <<len::int32, data::binary-size(len)>> -> <<1, json::binary>> = data json |> :binary.copy() |> unquote(library).decode!() end end def decode({library, :reference}) do quote location: :keep do <<len::int32, data::binary-size(len)>> -> <<1, json::binary>> = data unquote(library).decode!(json) end end end
21.42
60
0.578898
03b55ee12ab5f710b978199e7d1b91bd4fbeb6fb
247
ex
Elixir
plain-planner/elixir/lib/plain.ex
danielmarreirosdeoliveira/prototypes
047a7d0cae84b31213c06b45304e41a18e0678cb
[ "Apache-2.0" ]
null
null
null
plain-planner/elixir/lib/plain.ex
danielmarreirosdeoliveira/prototypes
047a7d0cae84b31213c06b45304e41a18e0678cb
[ "Apache-2.0" ]
1
2020-05-10T13:37:43.000Z
2020-05-10T13:37:43.000Z
plain-planner/elixir/lib/plain.ex
danielmarreirosdeoliveira/prototypes
047a7d0cae84b31213c06b45304e41a18e0678cb
[ "Apache-2.0" ]
null
null
null
defmodule Plain do @moduledoc """ Plain keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
24.7
66
0.748988
03b5698bef012babe8cb021e6a48139de9348ce9
9,474
exs
Elixir
apps/snitch_core/test/domain/splitters/weight_test.exs
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
456
2018-09-20T02:40:59.000Z
2022-03-07T08:53:48.000Z
apps/snitch_core/test/domain/splitters/weight_test.exs
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
273
2018-09-19T06:43:43.000Z
2021-08-07T12:58:26.000Z
apps/snitch_core/test/domain/splitters/weight_test.exs
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
122
2018-09-26T16:32:46.000Z
2022-03-13T11:44:19.000Z
defmodule Snitch.Domain.Splitter.WeightTest do use ExUnit.Case, async: true use Snitch.DataCase # TODO: Build the packages by hand, possibly using `Factory.Shipping.shipment!` # not using `Shipment.default_packages/1` import Mox, only: [expect: 4, verify_on_exit!: 1] import Snitch.Tools.Helper.{Order, Shipment, Stock, Zone} alias Snitch.Data.Schema.{Address, Order, StockItem, StockLocation, Product} alias Snitch.Domain.Shipment alias Snitch.Domain.Splitters.Weight, as: WeightSplitter @zone_manifest %{ "domestic" => %{zone_type: "S"}, "some_states" => %{zone_type: "S"} } @si_manifest %{ "default" => [ %{count_on_hand: 3, backorderable: true}, %{count_on_hand: 2, backorderable: true}, %{count_on_hand: 3, backorderable: true} ], "backup" => [ %{count_on_hand: 0}, %{count_on_hand: 0}, %{count_on_hand: 6} ], "origin" => [ %{count_on_hand: 3}, %{count_on_hand: 3}, %{count_on_hand: 3} ] } setup context do [india] = countries_with_manifest(~w(IN)) [ka, ap, tn, kl, _up, _mh] = states = states_with_manifest([ {"KA", "IN-KA", india}, {"AP", "IN-AP", india}, {"TN", "IN-TN", india}, {"KL", "IN-KL", india}, {"UP", "IN-UP", india}, {"MH", "IN-MH", india} ]) zones = [domestic, south_india] = zones_with_manifest(@zone_manifest) zone_members([ {domestic, states}, {south_india, [ka, ap, tn, kl]} ]) categories = [light, heavy, fragile] = shipping_categories_with_manifest(~w(light heavy fragile)) shipping_method_manifest = %{ "priority" => {zones, [light, fragile]}, "regular" => {zones, categories}, "hyperloop" => {[south_india], [light]} } methods = shipping_methods_with_manifest(shipping_method_manifest) variant_manifest = [ %{category: light}, %{category: fragile}, %{category: heavy} ] vs = variants_with_categories(variant_manifest, context) [ india: india, states: states, zones: zones, domestic: domestic, south_india: south_india, zones: zones, shipping_categories: categories, shipping_methods: methods, variants: vs ] end setup context do %{states: [ka, _, _, _, _, mh], india: india} = context manifest = %{ "default" => %{ default: true, state_id: ka.id, country_id: india.id, name: "default" }, "backup" => %{ state_id: ka.id, country_id: india.id, name: "default" }, "origin" => %{ state_id: mh.id, country_id: india.id, name: "default" } } [stock_locations: stock_locations(manifest)] end setup :stock_items setup :verify_on_exit! describe "split/1" do # Default Packages # # | Package | Item/Variant | Weight | Δ | Quantity | # |---------|--------------|--------|---|----------| # | 1 | 1 | 10 | 0 | 1 | # | 2 | 1 | 10 | 0 | 1 | # After Weight Splitting # # | Package | Item/Variant | Weight | Δ | Quantity | # |---------|--------------|--------|---|----------| # | 1 | 1 | 10 | 0 | 1 | # | 2 | 1 | 10 | 0 | 1 | @tag weights: [10.0], variant_count: 1, state_zone_count: 2 test "no package with weight over threshold", context do %{ variants: vs, states: [_, _, _, _, up, _], india: india } = context address = %Address{state_id: up.id, country_id: india.id} line_items = line_items_with_price(vs, [1]) order = %Order{id: 42, line_items: line_items, shipping_address: address} packages = order |> Shipment.default_packages() |> WeightSplitter.split() # Item {delta, quantity} packages_to_assert = [ [{0, 1}], [{0, 1}] ] assert length(packages) == 2 packages |> Enum.zip(packages_to_assert) |> Enum.map(&assert_package/1) end end # Default packages # # | Package | Item/Variant | Weight | Δ | Quantity | # |---------|--------------|--------|---|----------| # | 1 | 1 | 30 | 1 | 2 | # | 2 | 2 | 60 | 0 | 3 | # | 3 | 1 | 30 | 0 | 3 | # | 4 | 2 | 60 | 0 | 3 | # After weight splitting # # | Parent Package | Package | Item/Variant | Weight | Δ | Quantity | # +================+=========+==============+========+===+==========+ # | 1 | 1 | 1 | 90 | 1 | 2 | # +----------------+---------+--------------+--------+---+----------+ # | 2 | 2 | 2 | 60 | 0 | 1 | # | +---------+--------------+--------+---+----------+ # | | 3 | 2 | 120 | 0 | 2 | # +----------------+---------+--------------+--------+---+----------+ # | 3 | 4 | 1 | 90 | 0 | 3 | # +----------------+---------+--------------+--------+---+----------+ # | 4 | 5 | 2 | 60 | 0 | 1 | # | +---------+--------------+--------+---+----------+ # | | 6 | 2 | 120 | 0 | 2 | @tag weights: [60.0, 30.0], variant_count: 2, state_zone_count: 2 test "split package with more cumulative weight", context do %{ variants: vs, states: [_ka, _, _, _, up, _], india: india } = context address = %Address{state_id: up.id, country_id: india.id} line_items = line_items_with_price(vs, [3, 3]) order = %Order{id: 42, line_items: line_items, shipping_address: address} packages = order |> Shipment.default_packages() |> WeightSplitter.split() # Item {delta, quantity} packages_to_assert = [ [{1, 2}], [{0, 1}], [{0, 2}], [{0, 3}], [{0, 1}], [{0, 2}] ] assert length(packages) == 6 packages |> Enum.zip(packages_to_assert) |> Enum.map(&assert_package/1) end # Default packages # # | Package | Item/Variant | Weight | Δ | Quantity | # |---------|--------------|--------|---|----------| # | 1 | 2 | 40 | 4 | 2 | # | 2 | 1 | 10 | 0 | 2 | # | 3 | 1 | 10 | 0 | 2 | # After weight splitting # # | Parent Package | Package | Item/Variant | Weight | Δ | Quantity | # +================+=========+==============+========+===+==========+ # | 1 | 1 | 2 | 120 | 3 | 0 | # | +---------+--------------+--------+---+----------+ # | | 2 | 2 | 120 | 1 | 2 | # +----------------+---------+--------------+--------+---+----------+ # | 2 | 3 | 1 | 20 | 0 | 2 | # +----------------+---------+--------------+--------+---+----------+ # | 3 | 4 | 1 | 20 | 0 | 2 | @tag weights: [10.0, 40.0], variant_count: 2, state_zone_count: 2 test "split package with uneven weight", context do %{ variants: vs, states: [_, _, _, _, up, _], india: india } = context address = %Address{state_id: up.id, country_id: india.id} line_items = line_items_with_price(vs, [2, 6]) order = %Order{id: 42, line_items: line_items, shipping_address: address} packages = order |> Shipment.default_packages() |> WeightSplitter.split() # Item {delta, quantity} packages_to_assert = [ [{3, 0}], [{1, 2}], [{0, 2}], [{0, 2}] ] assert length(packages) == 4 packages |> Enum.zip(packages_to_assert) |> Enum.map(&assert_package/1) end defp assert_package({package, items_to_assert}) do package.items |> Enum.zip(items_to_assert) |> Enum.map(&assert_item/1) end defp assert_item({item, {delta, quantity}}) do assert item.delta == delta assert item.quantity == quantity end def pretty_print_package(package) do %{ items: Enum.map(package.items, fn item -> %{weight: item.variant.weight, quantity: item.quantity, delta: item.delta} end) } end defp variants_with_categories(manifest, context) do variants = manifest |> variants_with_manifest(context) |> Enum.zip(context.weights) |> Enum.map(fn {variant, weight} -> %{variant | weight: Decimal.new(weight)} end) {_, vs} = Repo.insert_all(Product, variants, returning: true) vs end defp stock_locations(manifest) do locations = stock_locations_with_manifest(manifest) {_, stock_locations} = Repo.insert_all(StockLocation, locations, returning: true) Enum.reduce(stock_locations, %{}, fn sl, acc -> Map.put(acc, sl.name, sl) end) end defp stock_items(%{variants: vs, stock_locations: locations} = context) do stock_items = context |> Map.get(:stock_item_manifest, @si_manifest) |> stock_items_with_manifest(vs, locations) {_, stock_items} = Repo.insert_all(StockItem, stock_items, returning: true) [stock_items: stock_items] end end
28.972477
90
0.468123
03b58f657ac898c2d3e2349e98cf81ef209d2ac6
2,964
ex
Elixir
lib/ets_metrics.ex
adobe/bot_army
68369a846d13e4ff973fdbc5decd418cc6e80f43
[ "MIT" ]
9
2020-04-30T20:35:49.000Z
2022-03-05T08:30:57.000Z
lib/ets_metrics.ex
adobe/bot_army
68369a846d13e4ff973fdbc5decd418cc6e80f43
[ "MIT" ]
null
null
null
lib/ets_metrics.ex
adobe/bot_army
68369a846d13e4ff973fdbc5decd418cc6e80f43
[ "MIT" ]
1
2020-09-27T11:44:06.000Z
2020-09-27T11:44:06.000Z
# Copyright 2020 Adobe # All Rights Reserved. # NOTICE: Adobe permits you to use, modify, and distribute this file in # accordance with the terms of the Adobe license agreement accompanying # it. If you have received this file from a source other than Adobe, # then your use, modification, or distribution of it requires the prior # written permission of Adobe. defmodule BotArmy.EtsMetrics do @moduledoc """ Stores information during the but run for metrics gathering. """ use GenServer require Logger defstruct n: nil, start_time: nil, actions: %{} def start_link(_) do GenServer.start_link(__MODULE__, %__MODULE__{}, name: __MODULE__) end def run(count) when is_integer(count) do GenServer.cast(__MODULE__, {:run, count}) end # ---- def init(state) do :metrics = :ets.new(:metrics, [:set, :protected, :named_table, read_concurrency: true]) {:ok, state} end def handle_cast({:run, count}, state) do run_state = %__MODULE__{ n: count, start_time: Timex.now(), actions: %{} } true = :ets.insert(:metrics, {"metrics", run_state}) {:noreply, state} end def handle_info({:action, module, action, duration, outcome}, state) when is_atom(module) and is_atom(action) and is_integer(duration) and duration >= 0 do success = if outcome == :succeed, do: 1, else: 0 error = if outcome == :error, do: 1, else: 0 try do case :ets.lookup(:metrics, "metrics") do [{"metrics", metrics}] -> new_actions = Map.update( metrics.actions, "#{module |> Module.split() |> List.last()}.#{action}", %{runs: 1, avg_duration: duration, success_count: success, error_count: error}, fn %{ runs: runs, avg_duration: avg_duration, success_count: success_count, error_count: error_count } -> %{ runs: runs + 1, avg_duration: running_avg(avg_duration, duration, runs + 1), success_count: success_count + success, error_count: error_count + error } end ) new_metrics = Map.put(metrics, :actions, new_actions) true = :ets.insert(:metrics, {"metrics", new_metrics}) _ -> nil end rescue e in ArgumentError -> Logger.error("ArgumentError processing metrics: #{inspect(e)}") e -> Logger.error("Error processing metrics: #{inspect(e)}") end {:noreply, state} end def handle_info(m, state) do IO.puts("Ignoring unknown message #{inspect(m)}") {:noreply, state} end # ------- # make sure to call with the new count, in other words, `prev_count + 1` defp running_avg(prev_avg, current_val, new_count) do prev_avg + (current_val - prev_avg) / new_count end end
27.962264
93
0.596491
03b5b4c63bdf0a24c0a1581e1d179b9966bebdfd
1,773
exs
Elixir
test/difflist_test.exs
sotojuan/dlist
cefd24f4860d9a55ff7c42d5723ea246ea9b85f3
[ "MIT" ]
1
2017-03-08T13:56:58.000Z
2017-03-08T13:56:58.000Z
test/difflist_test.exs
sotojuan/dlist
cefd24f4860d9a55ff7c42d5723ea246ea9b85f3
[ "MIT" ]
null
null
null
test/difflist_test.exs
sotojuan/dlist
cefd24f4860d9a55ff7c42d5723ea246ea9b85f3
[ "MIT" ]
null
null
null
defmodule DiffListTest do use ExUnit.Case, async: false use ExCheck doctest DiffList property :list_conversion do for_all xs in list(int()) do difflist = DiffList.from_list(xs) DiffList.to_list(difflist) == xs end end property :singleton do for_all x in int() do difflist = DiffList.singleton(x) DiffList.to_list(difflist) == [x] end end property :append do for_all {xs, ys} in {list(int()), list(int())} do difflist_a = DiffList.from_list(xs) difflist_b = DiffList.from_list(ys) difflist_c = DiffList.append(difflist_a, difflist_b) DiffList.to_list(difflist_c) == xs ++ ys end end property :cons do for_all {xs, x} in {list(int()), int()} do difflist_a = DiffList.from_list(xs) difflist_b = DiffList.cons(difflist_a, x) DiffList.to_list(difflist_b) == [x] ++ xs end end property :snoc do for_all {xs, x} in {list(int()), int()} do difflist_a = DiffList.from_list(xs) difflist_b = DiffList.snoc(difflist_a, x) DiffList.to_list(difflist_b) == xs ++ [x] end end property :head do for_all xs in such_that(ys in list(int()) when length(ys) > 0) do difflist = DiffList.from_list(xs) DiffList.head(difflist) == hd(xs) end end property :tail do for_all xs in such_that(ys in list(int()) when length(ys) > 0) do difflist = DiffList.from_list(xs) tail = difflist |> DiffList.tail |> DiffList.to_list tail == tl(xs) end end property :concat do for_all {xs, ys} in {list(int()), list(int())} do lists = [DiffList.from_list(xs), DiffList.from_list(ys)] result = DiffList.concat(lists) DiffList.to_list(result) == xs ++ ys end end end
23.025974
69
0.63057
03b5c14fe935962e378b9b37151e88db0b54ace4
2,611
ex
Elixir
clients/cloud_build/lib/google_api/cloud_build/v1/model/notification.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/cloud_build/lib/google_api/cloud_build/v1/model/notification.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/cloud_build/lib/google_api/cloud_build/v1/model/notification.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.CloudBuild.V1.Model.Notification do @moduledoc """ Notification is the container which holds the data that is relevant to this particular notification. ## Attributes * `filter` (*type:* `String.t`, *default:* `nil`) - The filter string to use for notification filtering. Currently, this is assumed to be a CEL program. See https://opensource.google/projects/cel for more. * `httpDelivery` (*type:* `GoogleApi.CloudBuild.V1.Model.HTTPDelivery.t`, *default:* `nil`) - Configuration for HTTP delivery. * `slackDelivery` (*type:* `GoogleApi.CloudBuild.V1.Model.SlackDelivery.t`, *default:* `nil`) - Configuration for Slack delivery. * `smtpDelivery` (*type:* `GoogleApi.CloudBuild.V1.Model.SMTPDelivery.t`, *default:* `nil`) - Configuration for SMTP (email) delivery. * `structDelivery` (*type:* `map()`, *default:* `nil`) - Escape hatch for users to supply custom delivery configs. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :filter => String.t(), :httpDelivery => GoogleApi.CloudBuild.V1.Model.HTTPDelivery.t(), :slackDelivery => GoogleApi.CloudBuild.V1.Model.SlackDelivery.t(), :smtpDelivery => GoogleApi.CloudBuild.V1.Model.SMTPDelivery.t(), :structDelivery => map() } field(:filter) field(:httpDelivery, as: GoogleApi.CloudBuild.V1.Model.HTTPDelivery) field(:slackDelivery, as: GoogleApi.CloudBuild.V1.Model.SlackDelivery) field(:smtpDelivery, as: GoogleApi.CloudBuild.V1.Model.SMTPDelivery) field(:structDelivery, type: :map) end defimpl Poison.Decoder, for: GoogleApi.CloudBuild.V1.Model.Notification do def decode(value, options) do GoogleApi.CloudBuild.V1.Model.Notification.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudBuild.V1.Model.Notification do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
44.254237
209
0.729989
03b5d04c84cc2537eeb65565af21bce54cb6cae9
2,788
ex
Elixir
lib/mix/lib/mix/cli.ex
Tica2/elixir
6cf1dcbfe4572fc75619f05e40c10fd0844083ef
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/cli.ex
Tica2/elixir
6cf1dcbfe4572fc75619f05e40c10fd0844083ef
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/cli.ex
Tica2/elixir
6cf1dcbfe4572fc75619f05e40c10fd0844083ef
[ "Apache-2.0" ]
null
null
null
defmodule Mix.CLI do @moduledoc false @doc """ Runs Mix according to the command line arguments. """ def main(args \\ System.argv) do Mix.Local.append_archives Mix.Local.append_paths case check_for_shortcuts(args) do :help -> proceed(["help"]) :version -> display_version() nil -> proceed(args) end end defp proceed(args) do load_dot_config() load_mixfile() {task, args} = get_task(args) ensure_hex(task) change_env(task) run_task(task, args) end defp load_mixfile() do file = System.get_env("MIX_EXS") || "mix.exs" _ = if File.regular?(file) do Code.load_file(file) end end defp get_task(["-" <> _|_]) do Mix.shell.error "** (Mix) Cannot implicitly pass flags to default mix task, " <> "please invoke instead: mix #{Mix.Project.config[:default_task]}" exit({:shutdown, 1}) end defp get_task([h|t]) do {h, t} end defp get_task([]) do {Mix.Project.config[:default_task], []} end defp run_task(name, args) do try do Mix.Task.run "loadconfig" Mix.Task.run name, args rescue # We only rescue exceptions in the mix namespace, all # others pass through and will explode on the users face exception -> stacktrace = System.stacktrace if Map.get(exception, :mix) do mod = exception.__struct__ |> Module.split() |> Enum.at(0, "Mix") Mix.shell.error "** (#{mod}) #{Exception.message(exception)}" exit({:shutdown, 1}) else reraise exception, stacktrace end end end defp ensure_hex("local.hex"), do: :ok defp ensure_hex(_task), do: Mix.Hex.ensure_updated?() defp change_env(task) do if is_nil(System.get_env("MIX_ENV")) && (env = preferred_cli_env(task)) do Mix.env(env) if project = Mix.Project.pop do %{name: name, file: file} = project Mix.Project.push name, file end end end defp preferred_cli_env(task) do task = String.to_atom(task) Mix.Project.config[:preferred_cli_env][task] || default_cli_env(task) end defp default_cli_env(:test), do: :test defp default_cli_env(_), do: nil defp load_dot_config do path = Path.join(Mix.Utils.mix_home, "config.exs") if File.regular?(path) do Mix.Task.run "loadconfig", [path] end end defp display_version() do IO.puts "Mix #{System.version}" end # Check for --help or --version in the args defp check_for_shortcuts([first_arg|_]) when first_arg in ["--help", "-h", "-help"], do: :help defp check_for_shortcuts([first_arg|_]) when first_arg in ["--version", "-v"], do: :version defp check_for_shortcuts(_), do: nil end
24.243478
85
0.615854
03b5ed5122223c5c21d9af7dec8726864768ff61
541
exs
Elixir
test/etl/type/list_test.exs
bbalser/etl
24791047ca0ce8066ec73c4196e54e954b1a1471
[ "Apache-2.0" ]
1
2020-06-15T22:41:37.000Z
2020-06-15T22:41:37.000Z
test/etl/type/list_test.exs
inhindsight/etl
24791047ca0ce8066ec73c4196e54e954b1a1471
[ "Apache-2.0" ]
1
2020-09-11T12:24:12.000Z
2020-09-12T11:14:27.000Z
test/etl/type/list_test.exs
bbalser/etl
24791047ca0ce8066ec73c4196e54e954b1a1471
[ "Apache-2.0" ]
null
null
null
defmodule Etl.Type.ListTest do use ExUnit.Case test "normalizes data in list accord type item_type" do type = %Etl.Type.List{ item_type: %Etl.Type.Integer{} } data = [1, "2", 3] assert {:ok, [1, 2, 3]} == Etl.Type.normalize(type, data) end test "an error normalizing any item causes the whole list to error" do type = %Etl.Type.List{ item_type: %Etl.Type.Integer{} } data = [1, "two", 3] assert {:error, {:invalid_list, :invalid_integer}} == Etl.Type.normalize(type, data) end end
22.541667
88
0.624769
03b5f364746ad7b4feb53a70417071b690034928
8,575
exs
Elixir
test/lib/bamboo/adapters/mailgun_adapter_test.exs
vitorioS/bamboo
f05cce842c961b84eea89948d9c3125810904253
[ "MIT" ]
null
null
null
test/lib/bamboo/adapters/mailgun_adapter_test.exs
vitorioS/bamboo
f05cce842c961b84eea89948d9c3125810904253
[ "MIT" ]
null
null
null
test/lib/bamboo/adapters/mailgun_adapter_test.exs
vitorioS/bamboo
f05cce842c961b84eea89948d9c3125810904253
[ "MIT" ]
1
2021-04-20T02:45:55.000Z
2021-04-20T02:45:55.000Z
defmodule Bamboo.MailgunAdapterTest do use ExUnit.Case alias Bamboo.Email alias Bamboo.MailgunAdapter @config %{adapter: MailgunAdapter, api_key: "dummyapikey", domain: "test.tt"} @config_with_env_var_key %{ adapter: MailgunAdapter, api_key: {:system, "MAILGUN_API_KEY"}, domain: {:system, "MAILGUN_DOMAIN"} } defmodule FakeMailgun do use Plug.Router plug( Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Jason ) plug(:match) plug(:dispatch) def start_server(parent) do Agent.start_link(fn -> Map.new() end, name: __MODULE__) Agent.update(__MODULE__, &Map.put(&1, :parent, parent)) port = get_free_port() Application.put_env(:bamboo, :mailgun_base_uri, "http://localhost:#{port}") Plug.Adapters.Cowboy.http(__MODULE__, [], port: port, ref: __MODULE__) end defp get_free_port do {:ok, socket} = :ranch_tcp.listen(port: 0) {:ok, port} = :inet.port(socket) :erlang.port_close(socket) port end def shutdown do Plug.Adapters.Cowboy.shutdown(__MODULE__) end post "/test.tt/messages" do case Map.get(conn.params, "from") do "INVALID_EMAIL" -> send_resp(conn, 500, "Error!!") _ -> send_resp(conn, 200, "SENT") end |> send_to_parent end defp send_to_parent(conn) do parent = Agent.get(__MODULE__, fn set -> Map.get(set, :parent) end) send(parent, {:fake_mailgun, conn}) conn end end setup do FakeMailgun.start_server(self()) on_exit(fn -> FakeMailgun.shutdown() end) :ok end test "can read the settings from an ENV var" do System.put_env("MAILGUN_API_KEY", "env_api_key") System.put_env("MAILGUN_DOMAIN", "env_domain") config = MailgunAdapter.handle_config(@config_with_env_var_key) assert config[:api_key] == "env_api_key" assert config[:domain] == "env_domain" System.delete_env("MAILGUN_API_KEY") System.delete_env("MAILGUN_DOMAIN") end test "raises if the api key is nil" do assert_raise ArgumentError, ~r/no api_key set/, fn -> MailgunAdapter.handle_config(%{domain: "test.tt"}) end end test "raises if the domain is nil" do assert_raise ArgumentError, ~r/no domain set/, fn -> MailgunAdapter.handle_config(%{api_key: "dummyapikey"}) end end test "raises if an invalid ENV var is used for the api_key" do System.put_env("MAILGUN_DOMAIN", "env_domain") assert_raise ArgumentError, ~r/no api_key set/, fn -> new_email(from: "foo@bar.com") |> MailgunAdapter.deliver(@config_with_env_var_key) end assert_raise ArgumentError, ~r/no api_key set/, fn -> MailgunAdapter.handle_config(@config_with_env_var_key) end System.delete_env("MAILGUN_DOMAIN") end test "raises if an invalid ENV var is used for the domain" do System.put_env("MAILGUN_API_KEY", "env_api_key") assert_raise ArgumentError, ~r/no domain set/, fn -> new_email(from: "foo@bar.com") |> MailgunAdapter.deliver(@config_with_env_var_key) end assert_raise ArgumentError, ~r/no domain set/, fn -> MailgunAdapter.handle_config(@config_with_env_var_key) end System.delete_env("MAILGUN_API_KEY") end test "see if default base_uri is set" do Application.delete_env(:bamboo, :mailgun_base_uri) assert MailgunAdapter.handle_config(%{ api_key: "dummyapikey", domain: "test.tt" }).base_uri == "https://api.mailgun.net/v3" end test "see if given base_uri is set" do assert MailgunAdapter.handle_config(%{ api_key: "dummyapikey", domain: "test.tt", base_uri: "https://api.eu.mailgun.net/v3" }).base_uri == "https://api.eu.mailgun.net/v3" end test "adapter-level base_uri overrules application env config" do Application.put_env(:bamboo, :mailgun_base_uri, "https://application") assert MailgunAdapter.handle_config(%{ api_key: "dummyapikey", domain: "test.tt", base_uri: "https://adapter" }).base_uri == "https://adapter" end test "deliver/2 sends the to the right url" do new_email() |> MailgunAdapter.deliver(@config) assert_receive {:fake_mailgun, %{request_path: request_path}} assert request_path == "/test.tt/messages" end test "deliver/2 sends from, subject, text body, html body, headers and custom vars" do email = new_email( from: "from@foo.com", subject: "My Subject", text_body: "TEXT BODY", html_body: "HTML BODY" ) |> Email.put_header("X-My-Header", "my_header_value") |> Email.put_header("Reply-To", "random@foo.com") |> Email.put_private(:mailgun_custom_vars, %{my_custom_var: 42, other_custom_var: 43}) MailgunAdapter.deliver(email, @config) assert_receive {:fake_mailgun, %{params: params, req_headers: headers}} assert params["from"] == elem(email.from, 1) assert params["subject"] == email.subject assert params["text"] == email.text_body assert params["html"] == email.html_body assert params["h:X-My-Header"] == "my_header_value" assert params["v:my_custom_var"] == "42" assert params["v:other_custom_var"] == "43" assert params["h:Reply-To"] == "random@foo.com" hashed_token = Base.encode64("api:" <> @config.api_key) assert {"authorization", "Basic #{hashed_token}"} in headers end # We keep two separate tests, with and without attachment, because the output produced by the adapter changes a lot. (MIME multipart body instead of URL-encoded form) test "deliver/2 sends from, subject, text body, html body, headers, custom vars and attachment" do attachment_source_path = Path.join(__DIR__, "../../../support/attachment.txt") email = new_email( from: "from@foo.com", subject: "My Subject", text_body: "TEXT BODY", html_body: "HTML BODY" ) |> Email.put_header("Reply-To", "random@foo.com") |> Email.put_header("X-My-Header", "my_header_value") |> Email.put_private(:mailgun_custom_vars, %{my_custom_var: 42, other_custom_var: 43}) |> Email.put_attachment(attachment_source_path) MailgunAdapter.deliver(email, @config) assert_receive {:fake_mailgun, %{params: params, req_headers: headers}} assert MailgunAdapter.supports_attachments?() assert params["from"] == elem(email.from, 1) assert params["subject"] == email.subject assert params["text"] == email.text_body assert params["html"] == email.html_body assert params["h:X-My-Header"] == "my_header_value" assert params["v:my_custom_var"] == "42" assert params["v:other_custom_var"] == "43" assert params["h:Reply-To"] == "random@foo.com" assert %Plug.Upload{content_type: content_type, filename: filename, path: download_path} = params["attachment"] assert content_type == "application/octet-stream" assert filename == "attachment.txt" assert File.read!(download_path) == File.read!(attachment_source_path) hashed_token = Base.encode64("api:" <> @config.api_key) assert {"authorization", "Basic #{hashed_token}"} in headers end test "deliver/2 correctly formats recipients" do email = new_email( to: [{"To", "to@bar.com"}, {nil, "noname@bar.com"}], cc: [{"CC", "cc@bar.com"}], bcc: [{"BCC", "bcc@bar.com"}] ) email |> MailgunAdapter.deliver(@config) assert_receive {:fake_mailgun, %{params: params}} assert params["to"] == "To <to@bar.com>,noname@bar.com" assert params["cc"] == "CC <cc@bar.com>" assert params["bcc"] == "BCC <bcc@bar.com>" end test "deliver/2 correctly formats reply-to" do email = new_email( from: "from@foo.com", subject: "My Subject", text_body: "TEXT BODY", html_body: "HTML BODY" ) |> Email.put_header("reply-to", "random@foo.com") MailgunAdapter.deliver(email, @config) assert_receive {:fake_mailgun, %{params: params}} assert params["h:Reply-To"] == "random@foo.com" end test "raises if the response is not a success" do email = new_email(from: "INVALID_EMAIL") assert_raise Bamboo.ApiError, fn -> email |> MailgunAdapter.deliver(@config) end end defp new_email(attrs \\ []) do attrs = Keyword.merge([from: "foo@bar.com", to: []], attrs) Email.new_email(attrs) |> Bamboo.Mailer.normalize_addresses() end end
31.29562
168
0.651429
03b5f4bf95bc36691cba4b803a8aeaf5623a536c
2,127
exs
Elixir
test/integration/telemetry_test.exs
khedaywi/oban
0b79c53a3c41648f438e112dda435ad79c86f811
[ "Apache-2.0" ]
1
2019-07-24T19:06:57.000Z
2019-07-24T19:06:57.000Z
test/integration/telemetry_test.exs
khedaywi/oban
0b79c53a3c41648f438e112dda435ad79c86f811
[ "Apache-2.0" ]
null
null
null
test/integration/telemetry_test.exs
khedaywi/oban
0b79c53a3c41648f438e112dda435ad79c86f811
[ "Apache-2.0" ]
null
null
null
defmodule Oban.Integration.TelemetryTest do use Oban.Case @moduletag :integration @oban_opts repo: Repo, queues: [zeta: 3] defmodule Handler do def handle([:oban, event], %{duration: duration}, meta, pid) do send(pid, {:executed, event, duration, meta}) end end test "telemetry events are emitted for executed jobs" do events = [[:oban, :success], [:oban, :failure]] :telemetry.attach_many("job-handler", events, &Handler.handle/4, self()) {:ok, _} = start_supervised({Oban, @oban_opts}) %Job{id: success_id} = insert_job!(%{ref: 1, action: "OK"}) %Job{id: exception_id} = insert_job!(%{ref: 2, action: "FAIL"}) %Job{id: error_id} = insert_job!(%{ref: 2, action: "ERROR"}) assert_receive {:executed, :success, success_duration, success_meta} assert_receive {:executed, :failure, exception_duration, %{kind: :exception} = exception_meta} assert_receive {:executed, :failure, error_duration, %{kind: :error} = error_meta} assert success_duration > 0 assert exception_duration > 0 assert error_duration > 0 assert %{ id: ^success_id, args: %{}, queue: "zeta", worker: "Oban.Integration.Worker", attempt: 1, max_attempts: 20 } = success_meta assert %{ id: ^exception_id, args: %{}, queue: "zeta", worker: "Oban.Integration.Worker", attempt: 1, max_attempts: 20, kind: :exception, error: _, stack: [_ | _] } = exception_meta assert %{ id: ^error_id, args: %{}, queue: "zeta", worker: "Oban.Integration.Worker", attempt: 1, max_attempts: 20, kind: :error, error: "ERROR", stack: [_ | _] } = error_meta :ok = stop_supervised(Oban) end defp insert_job!(args) do args |> Map.put(:bin_pid, Worker.pid_to_bin()) |> Worker.new(queue: "zeta") |> Repo.insert!() end end
27.986842
98
0.551951
03b5fad2b8987baf6710bb3d07c5b3960bef7871
15,154
ex
Elixir
lib/typed_struct.ex
bobkocisko/typed_struct
97bffcf13e8c29a9bc74fc34354e2efa86073a8b
[ "MIT" ]
null
null
null
lib/typed_struct.ex
bobkocisko/typed_struct
97bffcf13e8c29a9bc74fc34354e2efa86073a8b
[ "MIT" ]
null
null
null
lib/typed_struct.ex
bobkocisko/typed_struct
97bffcf13e8c29a9bc74fc34354e2efa86073a8b
[ "MIT" ]
null
null
null
defmodule TypedStruct do @moduledoc """ TypedStruct is a library for defining structs with a type without writing boilerplate code. ## Rationale To define a struct in Elixir, you probably want to define three things: * the struct itself, with default values, * the list of enforced keys, * its associated type. It ends up in something like this: defmodule Person do @moduledoc \"\"\" A struct representing a person. \"\"\" @enforce_keys [:name] defstruct name: nil, age: nil, happy?: true, phone: nil @typedoc "A person" @type t() :: %__MODULE__{ name: String.t(), age: non_neg_integer() | nil, happy?: boolean(), phone: String.t() | nil } end In the example above you can notice several points: * the keys are present in both the `defstruct` and type definition, * enforced keys must also be written in `@enforce_keys`, * if a key has no default value and is not enforced, its type should be nullable. If you want to add a field in the struct, you must therefore: * add the key with its default value in the `defstruct` list, * add the key with its type in the type definition. If the field is not optional, you should even add it to `@enforce_keys`. This is way too much work for lazy people like me, and moreover it can be error-prone. It would be way better if we could write something like this: defmodule Person do @moduledoc \"\"\" A struct representing a person. \"\"\" use TypedStruct typedstruct do @typedoc "A person" field :name, String.t(), enforce: true field :age, non_neg_integer() field :happy?, boolean(), default: true field :phone, String.t() end end Thanks to TypedStruct, this is now possible :) ## Usage ### Setup To use TypedStruct in your project, add this to your Mix dependencies: {:typed_struct, "~> #{Mix.Project.config()[:version]}"} If you do not plan to compile modules using TypedStruct at runtime, you can add `runtime: false` to the dependency tuple as TypedStruct is only used at build time. If you want to avoid `mix format` putting parentheses on field definitions, you can add to your `.formatter.exs`: [ ..., import_deps: [:typed_struct] ] ### General usage To define a typed struct, use `TypedStruct`, then define your struct within a `typedstruct` block: defmodule MyStruct do # Use TypedStruct to import the typedstruct macro. use TypedStruct # Define your struct. typedstruct do # Define each field with the field macro. field :a_string, String.t() # You can set a default value. field :string_with_default, String.t(), default: "default" # You can enforce a field. field :enforced_field, integer(), enforce: true end end Each field is defined through the `field/2` macro. ### Options If you want to enforce all the keys by default, you can do: defmodule MyStruct do use TypedStruct # Enforce keys by default. typedstruct enforce: true do # This key is enforced. field :enforced_by_default, term() # You can override the default behaviour. field :not_enforced, term(), enforce: false # A key with a default value is not enforced. field :not_enforced_either, integer(), default: 1 end end You can also generate an opaque type for the struct: defmodule MyOpaqueStruct do use TypedStruct # Generate an opaque type for the struct. typedstruct opaque: true do field :name, String.t() end end If you often define submodules containing only a struct, you can avoid boilerplate code: defmodule MyModule do use TypedStruct # You now have %MyModule.Struct{}. typedstruct module: Struct do field :field, term() end end ### Documentation To add a `@typedoc` to the struct type, just add the attribute in the `typedstruct` block: typedstruct do @typedoc "A typed struct" field :a_string, String.t() field :an_int, integer() end You can also document submodules this way: typedstruct module: MyStruct do @moduledoc "A submodule with a typed struct." @typedoc "A typed struct in a submodule" field :a_string, String.t() field :an_int, integer() end ### Plugins It is possible to extend the scope of TypedStruct by using its plugin interface, as described in `TypedStruct.Plugin`. For instance, to automatically generate lenses with the [Lens](https://github.com/obrok/lens) library, you can use [`TypedStructLens`](https://github.com/ejpcmac/typed_struct_lens) and do: defmodule MyStruct do use TypedStruct typedstruct do plugin TypedStructLens field :a_field, String.t() field :other_field, atom() end @spec change(t()) :: t() def change(data) do # a_field/0 is generated by TypedStructLens. lens = a_field() put_in(data, [lens], "Changed") end end ## What do I get? When defining an empty `typedstruct` block: defmodule Example do use TypedStruct typedstruct do end end you get an empty struct with its module type `t()`: defmodule Example do @enforce_keys [] defstruct [] @type t() :: %__MODULE__{} end Each `field` call adds information to the struct, `@enforce_keys` and the type `t()`. A field with no options adds the name to the `defstruct` list, with `nil` as default. The type itself is made nullable: defmodule Example do use TypedStruct typedstruct do field :name, String.t() end end becomes: defmodule Example do @enforce_keys [] defstruct name: nil @type t() :: %__MODULE__{ name: String.t() | nil } end The `default` option adds the default value to the `defstruct`: field :name, String.t(), default: "John Smith" # Becomes defstruct name: "John Smith" When set to `true`, the `enforce` option enforces the key by adding it to the `@enforce_keys` attribute. field :name, String.t(), enforce: true # Becomes @enforce_keys [:name] defstruct name: nil In both cases, the type has no reason to be nullable anymore by default. In one case the field is filled with its default value and not `nil`, and in the other case it is enforced. Both options would generate the following type: @type t() :: %__MODULE__{ name: String.t() # Not nullable } Passing `opaque: true` replaces `@type` with `@opaque` in the struct type specification: typedstruct opaque: true do field :name, String.t() end generates the following type: @opaque t() :: %__MODULE__{ name: String.t() } When passing `module: ModuleName`, the whole `typedstruct` block is wrapped in a module definition. This way, the following definition: defmodule MyModule do use TypedStruct typedstruct module: Struct do field :field, term() end end becomes: defmodule MyModule do defmodule Struct do @enforce_keys [] defstruct field: nil @type t() :: %__MODULE__{ field: term() | nil } end end """ @doc false defmacro __using__(_) do quote do import TypedStruct, only: [typedstruct: 1, typedstruct: 2] end end @doc """ Defines a typed struct. Inside a `typedstruct` block, each field is defined through the `field/2` macro. ## Options * `enforce` - if set to true, sets `enforce: true` to all fields by default. This can be overridden by setting `enforce: false` or a default value on individual fields. * `opaque` - if set to true, creates an opaque type for the struct. * `module` - if set, creates the struct in a submodule named `module`. ## Examples defmodule MyStruct do use TypedStruct typedstruct do field :field_one, String.t() field :field_two, integer(), enforce: true field :field_three, boolean(), enforce: true field :field_four, atom(), default: :hey end end The following is an equivalent using the *enforce by default* behaviour: defmodule MyStruct do use TypedStruct typedstruct enforce: true do field :field_one, String.t(), enforce: false field :field_two, integer() field :field_three, boolean() field :field_four, atom(), default: :hey end end You can create the struct in a submodule instead: defmodule MyModule do use TypedStruct typedstruct, module: Struct do field :field_one, String.t() field :field_two, integer(), enforce: true field :field_three, boolean(), enforce: true field :field_four, atom(), default: :hey end end """ defmacro typedstruct(opts \\ [], do: block) do if is_nil(opts[:module]) do quote do Module.eval_quoted( __ENV__, TypedStruct.__typedstruct__( unquote(Macro.escape(block)), unquote(opts) ) ) end else quote do defmodule unquote(opts[:module]) do Module.eval_quoted( __ENV__, TypedStruct.__typedstruct__( unquote(Macro.escape(block)), unquote(opts) ) ) end end end end @doc false def __typedstruct__(block, opts) do quote do Module.register_attribute(__MODULE__, :ts_plugins, accumulate: true) Module.register_attribute(__MODULE__, :ts_fields, accumulate: true) Module.register_attribute(__MODULE__, :ts_types, accumulate: true) Module.register_attribute(__MODULE__, :ts_enforce_keys, accumulate: true) Module.put_attribute(__MODULE__, :ts_enforce?, unquote(!!opts[:enforce])) Module.put_attribute(__MODULE__, :ts_type?, unquote(!opts[:no_type])) # Create a scope to avoid leaks. (fn -> import TypedStruct unquote(block) end).() @enforce_keys @ts_enforce_keys defstruct @ts_fields if unquote(!opts[:no_type]) do TypedStruct.__type__(@ts_types, unquote(opts)) end Enum.each(@ts_plugins, fn {plugin, plugin_opts} -> if {:after_definition, 1} in plugin.__info__(:functions) do Module.eval_quoted(__MODULE__, plugin.after_definition(plugin_opts)) end end) Module.delete_attribute(__MODULE__, :ts_type?) Module.delete_attribute(__MODULE__, :ts_enforce?) Module.delete_attribute(__MODULE__, :ts_enforce_keys) Module.delete_attribute(__MODULE__, :ts_types) Module.delete_attribute(__MODULE__, :ts_fields) Module.delete_attribute(__MODULE__, :ts_plugins) end end @doc false defmacro __type__(types, opts) do if Keyword.get(opts, :opaque, false) do quote bind_quoted: [types: types] do @opaque t() :: %__MODULE__{unquote_splicing(types)} end else quote bind_quoted: [types: types] do @type t() :: %__MODULE__{unquote_splicing(types)} end end end @doc """ Registers a plugin for the currently defined struct. ## Example typedstruct do plugin MyPlugin field :a_field, String.t() end For more information on how to define your own plugins, please see `TypedStruct.Plugin`. To use a third-party plugin, please refer directly to its documentation. """ defmacro plugin(plugin, opts \\ []) do quote do Module.put_attribute( __MODULE__, :ts_plugins, {unquote(plugin), unquote(opts)} ) require unquote(plugin) unquote(plugin).init(unquote(opts)) end end @no_type nil @doc """ Defines a field in a typed struct. ## Example # A field named :example of type String.t() field :example, String.t() # Or, if no_type: true is set field :example ## Options * `default` - sets the default value for the field * `enforce` - if set to true, enforces the field and makes its type non-nullable """ defmacro field(name), do: field_h(name, @no_type, []) defmacro field(name, [{_,_} | _] = opts), do: field_h(name, @no_type, opts) defmacro field(name, type), do: field_h(name, type, []) defmacro field(name, type, opts), do: field_h(name, type, opts) defp field_h(name, type, opts) do quote do TypedStruct.__field__( __MODULE__, unquote(name), unquote(Macro.escape(type)), unquote(opts) ) Enum.each(@ts_plugins, fn {plugin, plugin_opts} -> if {:field, 3} in plugin.__info__(:functions) do Module.eval_quoted( __MODULE__, plugin.field( unquote(name), unquote(Macro.escape(type)), unquote(opts) ++ plugin_opts ) ) end end) end end @doc false def __field__(mod, name, type, opts) when is_atom(name) do if mod |> Module.get_attribute(:ts_fields) |> Keyword.has_key?(name) do raise ArgumentError, "the field #{inspect(name)} is already set" end if Module.get_attribute(mod, :ts_type?) do if type == @no_type, do: raise ArgumentError, "the field #{inspect(name)} is missing a type specifier, " <> "or else you must specify no_type: true" else if type != @no_type, do: raise ArgumentError, "the field #{inspect(name)} has a type specifier, " <> "but no_type: true has been set" end has_default? = Keyword.has_key?(opts, :default) enforce_by_default? = Module.get_attribute(mod, :ts_enforce?) enforce? = if is_nil(opts[:enforce]), do: enforce_by_default? && !has_default?, else: !!opts[:enforce] nullable? = !has_default? && !enforce? Module.put_attribute(mod, :ts_fields, {name, opts[:default]}) Module.put_attribute(mod, :ts_types, {name, type_for(type, nullable?)}) if enforce?, do: Module.put_attribute(mod, :ts_enforce_keys, name) end def __field__(_mod, name, _type, _opts) do raise ArgumentError, "a field name must be an atom, got #{inspect(name)}" end # Makes the type nullable if the key is not enforced. defp type_for(type, false), do: type defp type_for(type, _), do: quote(do: unquote(type) | nil) end
26.773852
80
0.613105
03b620df5a011ce1252228dccf23e3a3d9c0a2bd
1,755
ex
Elixir
lib/teiserver/telemetry/tasks/export_events_task.ex
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
6
2021-02-08T10:42:53.000Z
2021-04-25T12:12:03.000Z
lib/teiserver/telemetry/tasks/export_events_task.ex
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
14
2021-08-01T02:36:14.000Z
2022-01-30T21:15:03.000Z
lib/teiserver/telemetry/tasks/export_events_task.ex
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
7
2021-05-13T12:55:28.000Z
2022-01-14T06:39:06.000Z
defmodule Teiserver.Telemetry.ExportEventsTask do alias Teiserver.Telemetry alias Central.Helpers.{TimexHelper, DatePresets} def perform(params) do do_query(params) |> do_output(params) end defp do_query(%{"event_type" => event_type, "timeframe" => timeframe, "auth" => auth}) do {start_date, end_date} = DatePresets.parse(timeframe, "", "") start_date = Timex.to_datetime(start_date) end_date = Timex.to_datetime(end_date) case auth do "auth" -> query_auth(event_type, start_date, end_date) "unauth" -> query_unauth(event_type, start_date, end_date) "combined" -> query_auth(event_type, start_date, end_date) ++ query_unauth(event_type, start_date, end_date) end end defp query_auth(event_type, start_date, end_date) do Telemetry.list_client_events( preload: [:event_type, :user], search: [ between: {start_date, end_date}, event_type_id: event_type ], limit: :infinity ) end defp query_unauth(event_type, start_date, end_date) do Telemetry.list_unauth_events( preload: [:event_type], search: [ between: {start_date, end_date}, event_type_id: event_type ], limit: :infinity ) end defp do_output(data, _params) do data |> Stream.map(fn event -> {username, hash} = if Map.has_key?(event, :user) do {event.user.name, nil} else {nil, event.hash} end %{ user: username, hash: hash, event_type: event.event_type.name, timestamp: TimexHelper.date_to_str(event.timestamp, format: :ymd_hms), value: event.value } end) |> Enum.to_list |> Jason.encode! end end
25.434783
102
0.633048
03b634b7b2ee52c757632c447efccfa4ff7e9c03
6,278
ex
Elixir
lib/changelog_web/views/news/news_item_view.ex
boneskull/changelog.com
2fa2e356bb0e8fcf038c46a4a947fef98822e37d
[ "MIT" ]
null
null
null
lib/changelog_web/views/news/news_item_view.ex
boneskull/changelog.com
2fa2e356bb0e8fcf038c46a4a947fef98822e37d
[ "MIT" ]
null
null
null
lib/changelog_web/views/news/news_item_view.ex
boneskull/changelog.com
2fa2e356bb0e8fcf038c46a4a947fef98822e37d
[ "MIT" ]
null
null
null
defmodule ChangelogWeb.NewsItemView do use ChangelogWeb, :public_view alias Changelog.{Episode, Files, Hashid, NewsAd, NewsItem, Podcast, Regexp, UrlKit} alias ChangelogWeb.{Endpoint, NewsAdView, NewsSourceView, EpisodeView, PersonView, TopicView, PodcastView} def admin_edit_link(conn, user, item) do if user && user.admin do content_tag(:span, class: "news_item-toolbar-meta-item") do [ link("[Edit]", to: admin_news_item_path(conn, :edit, item, next: current_path(conn)), data: [turbolinks: false]), content_tag(:span, " (#{item.click_count}/#{item.impression_count})") ] end end end def image_link(item, version \\ :large) do if item.image do content_tag :div, class: "news_item-image" do link to: item.url do tag(:img, src: image_url(item, version), alt: item.headline) end end end end def image_mime_type(item) do Files.Image.mime_type(item.image) end def image_path(item, version) do {item.image, item} |> Files.Image.url(version) |> String.replace_leading("/priv", "") end def image_url(item, version) do static_url(Endpoint, image_path(item, version)) end def items_with_ads(items, []), do: items def items_with_ads(items, ads) do items |> List.insert_at(3, Enum.at(ads, 0)) |> List.insert_at(9, Enum.at(ads, 1)) |> Enum.reject(&is_nil/1) end def object_path(%{object_id: nil}), do: nil def object_path(%{object_id: object_id}), do: "/" <> String.replace(object_id, ":", "/") def permalink_path(conn, item) do if item.object_id, do: dev_relative(item.url), else: news_item_path(conn, :show, slug(item)) end def permalink_data(item) do if item.object_id, do: [news: true], else: [] end def render_item_summary_or_ad(item = %NewsItem{}, assigns), do: render("_summary.html", Map.merge(assigns, %{item: item, style: "relativeShort"})) def render_item_summary_or_ad(ad = %NewsAd{}, assigns), do: render(NewsAdView, "_summary.html", Map.merge(assigns, %{ad: ad, sponsor: ad.sponsor})) def render_meta_people(conn, item = %{type: :audio, object: episode}) when is_map(episode) do render("meta/_featuring.html", conn: conn, item: item, episode: episode) end def render_meta_people(conn, item) do render("meta/_logged_by.html", conn: conn, item: item) end def render_source_image(conn, item = %{type: :audio, object: episode}) when is_map(episode) do render("source/_image_episode.html", conn: conn, item: item, episode: episode) end def render_source_image(conn, item) do cond do item.author -> render("source/_image_author.html", conn: conn, item: item, author: item.author) item.source && item.source.icon -> render("source/_image_source.html", conn: conn, item: item, source: item.source) topic = Enum.find(item.topics, &(&1.icon)) -> render("source/_image_topic.html", conn: conn, item: item, topic: topic) true -> render("source/_image_fallback.html", conn: conn, item: item) end end # same as `render_source_image` except the cascade is re-ordered def render_source_name(conn, item = %{type: :audio, object: episode}) when is_map(episode) do render("source/_name_episode.html", conn: conn, item: item, episode: episode) end def render_source_name(conn, item) do cond do item.source && item.source.icon -> render("source/_name_source.html", conn: conn, item: item, source: item.source) item.author -> render("source/_name_author.html", conn: conn, item: item, author: item.author) true -> render("source/_name_fallback.html", conn: conn, item: item) end end def render_title(conn, item) do if item.object_id do render("title/_internal.html", conn: conn, item: item) else render("title/_external.html", conn: conn, item: item) end end def render_toolbar_button(conn, item = %{type: :audio, object: episode}) when is_map(episode) do render("toolbar/_button_episode.html", conn: conn, item: item, episode: episode) end def render_toolbar_button(conn, item = %{type: :video}) do if id = UrlKit.get_youtube_id(item.url) do render("toolbar/_button_video.html", conn: conn, item: item, id: id) end end def render_toolbar_button(conn, item = %{image: image}) when not is_nil(image) do render("toolbar/_button_image.html", conn: conn, item: item) end def render_toolbar_button(_conn, _item), do: nil def render_youtube_embed(nil), do: nil def render_youtube_embed(id), do: render("_youtube_embed.html", id: id) def slug(item) do item.headline |> String.downcase |> String.replace(~r/[^a-z0-9\s]/, "") |> String.trim |> String.replace(~r/\s+/, "-") |> Kernel.<>("-#{hashid(item)}") end def hashid(item) do Hashid.encode(item.id) end def teaser(item, max_words \\ 20) do item.story |> md_to_html |> prepare_html |> String.split |> truncate(word_count(item.story), max_words) |> Enum.join(" ") end def topic_list(item) do item.topics |> Enum.map(&("##{&1.slug}")) |> Enum.join(" ") end def topic_link(conn, topic) do link("##{topic.slug}", to: topic_path(conn, :show, topic.slug), title: "View #{topic.name}") end def video_embed(item = %{type: :video}) do item.url |> UrlKit.get_youtube_id() |> render_youtube_embed() end def video_embed(_), do: nil defp prepare_html(html) do html |> String.replace("\n", " ") # treat news lines as spaces |> String.replace(Regexp.tag("p"), "") # remove p tags |> String.replace(~r/(<\w+>)\s+(\S)/, "\\1\\2" ) # attach open tags to next word |> String.replace(~r/(\S)\s+(<\/\w+>)/, "\\1\\2" ) # attach close tags to prev word |> String.replace(Regexp.tag("blockquote"), "\\1i\\2") # treat as italics end defp truncate(html_list, total_words, max_words) when total_words <= max_words, do: html_list defp truncate(html_list, _total_words, max_words) do sliced = Enum.slice(html_list, 0..(max_words - 1)) tags = Regex.scan(Regexp.tag, Enum.join(sliced, " "), capture: ["tag"]) |> List.flatten sliced ++ case Integer.mod(length(tags), 2) do 0 -> ["..."] 1 -> ["</#{List.last(tags)}>", "..."] end end end
35.670455
149
0.657534
03b63c841166ddc375f25184d2138877a67a2de3
7,453
ex
Elixir
braccino/lib/braccino/braccio.ex
darcros/braccino
33f4d945daf8eac36e4e88ef412dd53cb1389376
[ "MIT" ]
null
null
null
braccino/lib/braccino/braccio.ex
darcros/braccino
33f4d945daf8eac36e4e88ef412dd53cb1389376
[ "MIT" ]
null
null
null
braccino/lib/braccino/braccio.ex
darcros/braccino
33f4d945daf8eac36e4e88ef412dd53cb1389376
[ "MIT" ]
null
null
null
defmodule Braccino.Braccio do @moduledoc """ This module represents the braccio controlled by the arduino. """ alias Braccino.Braccio.Angles require Logger use GenServer @type reason :: term @type impl_state :: term @type braccio_status :: :disconnected | :uploading_firmware | :connecting | :connected | :error @doc """ Initialize the state of the braccio based on the options in the config. This function should return the initial state or an error. """ @callback init(opts :: Keyword.t()) :: {:ok, impl_state()} | :error @doc """ Upload the Arduino firmware. This function will be called only when the serial port is not open. This function should return `:ok` or an error and the new state. """ @callback upload_firmware(state :: impl_state()) :: {:ok, impl_state()} | {{:error, reason()}, impl_state()} @doc """ Open the serial port with braccio. This function should block until the braccio is ready to accept commands. This function will be called only when the serial port is not open. This function should return `:ok` or an error and the new state. """ @callback connect(state :: impl_state()) :: {:ok, impl_state()} | {{:error, reason()}, impl_state()} @doc """ Close the serial port with the braccio. This function will be called only when the serial port is open. This function should return `:ok` or an error and the new state. """ @callback disconnect(state :: impl_state()) :: {:ok, impl_state()} | {{:error, reason()}, impl_state()} @doc """ Set the angles of the braccio. This function will be called only when the serial port is open. This function should return `:ok` or an error and the new state. """ @callback set_angles(angles :: Angles.t(), state :: impl_state()) :: {:ok, impl_state()} | {{:error, reason()}, impl_state()} # client API def start_link(args) do env_args = Application.get_env(:braccino, __MODULE__) GenServer.start_link(__MODULE__, args ++ env_args, name: __MODULE__) end @doc """ Returns the current status of the braccio. """ @spec current_status() :: braccio_status() def current_status() do GenServer.call(__MODULE__, :current_status) end @doc """ Registers the calling prcocess as the current user of the braccio. Only on process can use the braccio at a time. Calling this function when another process is using it will return `{:error, :busy}`. """ @spec acquire_control() :: :ok | {:error, reason()} def acquire_control() do GenServer.call(__MODULE__, :acquire_control) end @doc """ Set the angles of the braccio. Will return an error if called when the braccio is not connected. """ @spec set_angles(Angles.t()) :: :ok | {:error, reason()} def set_angles(angles = %Angles{}) do GenServer.call(__MODULE__, {:set_angles, angles}) end # callbacks @impl true def init(args) do impl = Keyword.fetch!(args, :implementation) {:ok, impl_state} = impl.init(args) state = %{ impl: impl, impl_state: impl_state, status: :disconnected, task: nil, user_pid: nil, user_ref: nil } {:ok, state, {:continue, :upload_firmware}} end # start a task to upload the firmware @impl true def handle_continue(:upload_firmware, %{status: :disconnected, task: nil} = state) do task = Task.Supervisor.async_nolink(Braccino.TaskSupervisor, fn -> state.impl.upload_firmware(state.impl_state) end) notify_status_change(state.user_pid, :uploading_firmware) {:noreply, %{state | status: :uploading_firmware, task: task}} end # start a task to connect to the braccio @impl true def handle_continue(:connect, %{status: :disconnected, task: nil} = state) do task = Task.Supervisor.async_nolink(Braccino.TaskSupervisor, fn -> state.impl.connect(state.impl_state) end) notify_status_change(state.user_pid, :connecting) {:noreply, %{state | status: :connecting, task: task}} end # handle the result of the task that uploads the firmware # if the task is successful, connect to the braccio @impl true def handle_info({ref, result}, %{status: :uploading_firmware} = state) do # The task succeed so we can cancel the monitoring and discard the DOWN message Process.demonitor(ref, [:flush]) case result do {:ok, impl_state} -> notify_status_change(state.user_pid, :disconnected) state = %{state | impl_state: impl_state, status: :disconnected, task: nil} {:noreply, state, {:continue, :connect}} {{:error, reason}, impl_state} -> Logger.error("Failed to upload arduino firmware: #{inspect(reason)}") notify_status_change(state.user_pid, :error) state = %{state | impl_state: impl_state, status: :error, task: nil} {:noreply, state} end end # handle the result of the task that connects to the braccio @impl true def handle_info({ref, result}, %{status: :connecting} = state) do # The task succeed so we can cancel the monitoring and discard the DOWN message Process.demonitor(ref, [:flush]) case result do {:ok, impl_state} -> notify_status_change(state.user_pid, :connected) state = %{state | impl_state: impl_state, status: :connected, task: nil} {:noreply, state} {{:error, reason}, impl_state} -> Logger.error("Failed to connecte to braccio: #{inspect(reason)}") notify_status_change(state.user_pid, :error) state = %{state | impl_state: impl_state, status: :error, task: nil} {:noreply, state} end end # handle task crashing @impl true def handle_info({:DOWN, ref, :process, _pid, reason}, state) when ref == state.task.ref do case state.status do :uploading_firmware -> Logger.error("Task crashed while uploading firmware: #{inspect(reason)}") :connecting -> Logger.error("Task crashed while connecting: #{inspect(reason)}") end notify_status_change(state.user_pid, :error) state = %{state | status: :error, task: nil} {:noreply, state} end # handle user process crashing @impl true def handle_info({:DOWN, ref, :process, _pid, _reason}, state) when ref == state.user_ref do state = %{state | user_pid: nil, user_ref: nil} {:noreply, state} end @impl true def handle_call(:current_status, _from, state) do {:reply, state.status, state} end @impl true def handle_call(:acquire_control, {pid, _tag}, state) do case state do %{user_pid: nil, user_ref: nil} -> ref = Process.monitor(pid) state = %{state | user_pid: pid, user_ref: ref} {:reply, :ok, state} %{} -> {:reply, {:error, :busy}, state} end end @impl true def handle_call({:set_angles, angles}, {pid, _tag}, state) do case state do %{user_pid: ^pid, status: :connected} -> {reply, impl_state} = state.impl.set_angles(angles, state.impl_state) state = %{state | impl_state: impl_state} {:reply, reply, state} %{user_pid: ^pid} -> {:reply, {:error, :not_connected}, state} %{} -> {:reply, {:error, :unauthorized}, state} end end defp notify_status_change(pid, status) do case pid do nil -> :ok _pid -> send(pid, {:braccio_status, status}) end end end
30.174089
97
0.649537
03b63d200d80ac7f2a856db799fc593d6f091af7
2,155
exs
Elixir
mix.exs
membraneframework/membrane_rtp_vp9_plugin
7dac9476a76a3eea1ed3b90b65aad5660663a98b
[ "Apache-2.0" ]
null
null
null
mix.exs
membraneframework/membrane_rtp_vp9_plugin
7dac9476a76a3eea1ed3b90b65aad5660663a98b
[ "Apache-2.0" ]
3
2020-12-14T10:28:19.000Z
2021-01-05T08:35:15.000Z
mix.exs
membraneframework/membrane_rtp_vp9_plugin
7dac9476a76a3eea1ed3b90b65aad5660663a98b
[ "Apache-2.0" ]
null
null
null
defmodule Membrane.RTP.VP9.MixProject do use Mix.Project @version "0.1.0" @github_url "https://github.com/membraneframework/membrane_rtp_vp9_plugin" def project do [ app: :membrane_rtp_vp9_plugin, version: @version, elixir: "~> 1.10", elixirc_paths: elixirc_paths(Mix.env()), start_permanent: Mix.env() == :prod, deps: deps(), # hex description: "Membrane Multimedia Framework (RTP VP9)", package: package(), # docs name: "Membrane: RTP VP9", source_url: @github_url, homepage_url: "https://membraneframework.org", docs: docs() ] end def application do [ extra_applications: [], mod: {Membrane.RTP.VP9.Plugin.App, []} ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_env), do: ["lib"] defp deps do [ {:membrane_core, "~> 0.6.1", override: true}, {:ex_doc, "~> 0.22", only: :dev, runtime: false}, {:dialyxir, "~> 1.0.0", only: :dev, runtime: false}, {:ex_libsrtp, "~> 0.1.0"}, {:credo, "~> 1.4", only: :dev, runtime: false}, {:membrane_rtp_format, "~> 0.3.0"}, {:membrane_rtp_plugin, github: "membraneframework/membrane_rtp_plugin"}, {:membrane_vp9_format, github: "membraneframework/membrane_vp9_format"}, {:membrane_element_pcap, github: "membraneframework/membrane-element-pcap", only: :test}, {:membrane_element_ivf, github: "membraneframework/membrane-element-ivf", branch: :"generalized-ivf-element", only: :test}, {:membrane_file_plugin, "~> 0.5.0", only: :test}, {:membrane_remote_stream_format, "~> 0.1.0"}, {:membrane_caps_rtp, "~> 0.1.0"} ] end defp package do [ maintainers: ["Membrane Team"], licenses: ["Apache 2.0"], links: %{ "GitHub" => @github_url, "Membrane Framework Homepage" => "https://membraneframework.org" } ] end defp docs do [ main: "readme", extras: ["README.md", "LICENSE"], source_ref: "v#{@version}", nest_modules_by_prefix: [Membrane.RTP.VP9] ] end end
27.278481
95
0.595824
03b66451c84ccc2b88a52801a180a5942cac67b3
183
exs
Elixir
test/controllers/page_controller_test.exs
markhu53/visualixir
80ce8b75fe33476fe7d17110ffc0271f71bc1f91
[ "MIT" ]
1,311
2015-11-08T02:21:41.000Z
2022-03-25T17:32:57.000Z
test/controllers/page_controller_test.exs
hoangpq/visualixir
a8efdee3faea00cf59ae74f4bf8bcfa36e7b6d79
[ "MIT" ]
30
2015-11-09T17:07:50.000Z
2022-02-10T17:13:50.000Z
test/controllers/page_controller_test.exs
hoangpq/visualixir
a8efdee3faea00cf59ae74f4bf8bcfa36e7b6d79
[ "MIT" ]
58
2015-11-08T16:50:00.000Z
2022-03-30T13:03:18.000Z
defmodule VisualixirWeb.PageControllerTest do use VisualixirWeb.ConnCase test "GET /" do conn = get conn(), "/" assert html_response(conn, 200) =~ "Visualixir" end end
20.333333
51
0.699454
03b68a316644f9574e23808cfcbae1402e02289a
232
exs
Elixir
priv/repo/migrations/20200513225257_add_banking_details_table.exs
Hermanlangner/events_dashboard
30d5d3666ac8057bfd91dd33131d8132c97cfec9
[ "MIT" ]
null
null
null
priv/repo/migrations/20200513225257_add_banking_details_table.exs
Hermanlangner/events_dashboard
30d5d3666ac8057bfd91dd33131d8132c97cfec9
[ "MIT" ]
null
null
null
priv/repo/migrations/20200513225257_add_banking_details_table.exs
Hermanlangner/events_dashboard
30d5d3666ac8057bfd91dd33131d8132c97cfec9
[ "MIT" ]
null
null
null
defmodule EventsDashboard.Repo.Migrations.AddBankingDetailsTable do use Ecto.Migration def change do create table("banking_details") do add :customer_id, :integer add :account_number, :integer end end end
21.090909
67
0.737069
03b69e34d9c6d8cc4670aad30c8d0cf1a754ef3b
1,257
exs
Elixir
mix.exs
dmitriid/exqlite
d9ce46b7e3c8e6c907b6d24b14823c783ce666e5
[ "MIT" ]
null
null
null
mix.exs
dmitriid/exqlite
d9ce46b7e3c8e6c907b6d24b14823c783ce666e5
[ "MIT" ]
null
null
null
mix.exs
dmitriid/exqlite
d9ce46b7e3c8e6c907b6d24b14823c783ce666e5
[ "MIT" ]
null
null
null
defmodule Exqlite.MixProject do use Mix.Project def project do [ app: :exqlite, version: "0.1.1", elixir: "~> 1.11", compilers: [:elixir_make] ++ Mix.compilers(), make_targets: ["all"], make_clean: ["clean"], start_permanent: Mix.env() == :prod, source_url: "https://github.com/warmwaffles/exqlite", homepage_url: "https://github.com/warmwaffles/exqlite", deps: deps(), package: package(), description: description() ] 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 [ {:db_connection, "~> 2.1"}, {:decimal, "~> 2.0"}, {:ecto_sql, "~> 3.5.4"}, {:elixir_make, "~> 0.6", runtime: false}, {:ex_doc, "~> 0.23.0", only: [:dev], runtime: false}, {:temp, "~> 0.4", only: [:test]} ] end defp description do "An Sqlite3 Elixir library." end defp package do [ name: "exqlite", licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/warmwaffles/exqlite", "docs" => "https://hexdocs.pm/exqlite" } ] end end
22.854545
61
0.552108
03b6b33b38ad27c99881c608e63905a2cc7a89d5
4,553
ex
Elixir
lib/weddell/client/subscriber/stream.ex
W-Games/weddell
618221495ca3c65f18b463970bd6c40f36ffae71
[ "MIT" ]
1
2018-05-18T15:47:34.000Z
2018-05-18T15:47:34.000Z
lib/weddell/client/subscriber/stream.ex
timuryan/weddell
98d31c183a03d786b804af4b8698e7956c653685
[ "MIT" ]
1
2020-06-24T18:52:41.000Z
2020-06-24T18:52:41.000Z
lib/weddell/client/subscriber/stream.ex
W-Games/weddell
618221495ca3c65f18b463970bd6c40f36ffae71
[ "MIT" ]
1
2018-05-18T15:46:51.000Z
2018-05-18T15:46:51.000Z
defmodule Weddell.Client.Subscriber.Stream do @moduledoc """ A streaming connection to a subscription. """ alias GRPC.Client.Stream, as: GRPCStream alias GRPC.Stub, as: GRPCStub alias Google.Pubsub.V1.{Subscriber.Stub, StreamingPullRequest} alias Weddell.{Message, Client, Client.Util} @typedoc "A Pub/Sub subscriber stream" @opaque t :: %__MODULE__{client: Client.t, subscription: String.t, grpc_stream: GRPCStream.t} defstruct [:client, :subscription, :grpc_stream] @default_ack_deadline 10 @doc """ Open a new stream on a subscription. Streams can be used to pull new messages from a subscription and also respond with acknowledgements or delays. ## Example {:ok, client} = Weddell.Client.connect("weddell-project") Weddell.Client.Subscriber.Stream.open(client, "foo-subscription") #=> %Weddell.Client.Subscriber.Stream{} """ @spec open(Client.t, subscription :: String.t) :: t def open(client, subscription) do stream = %__MODULE__{client: client, subscription: subscription, grpc_stream: Stub.streaming_pull(client.channel, Client.request_opts())} request = StreamingPullRequest.new(subscription: Util.full_subscription(client.project, subscription), stream_ack_deadline_seconds: @default_ack_deadline) stream.grpc_stream |> GRPCStub.stream_send(request) stream end @doc """ Close an open stream. ## Example {:ok, client} = Weddell.Client.connect("weddell-project") stream = Weddell.Client.Subscriber.Stream.open(client, "foo-subscription") Weddell.Client.Subscriber.Stream.close(stream) #=> :ok """ @spec close(t) :: :ok def close(stream) do request = StreamingPullRequest.new( subscription: Util.full_subscription(stream.client.project, stream.subscription)) GRPCStub.stream_send(stream.grpc_stream, request, end_stream: true) end @typedoc "A message and a new deadline in seconds" @type message_delay :: {Message.t, seconds :: pos_integer} @typedoc "Option values used when writing to a stream" @type send_opt :: {:ack, [Message.t]} | {:delay, [message_delay]} | {:stream_deadline, seconds :: pos_integer} @typedoc "Options used when writing to a stream" @type send_opts :: [send_opt] @doc """ Send a response to a stream. ## Example {:ok, client} = Weddell.Client.connect("weddell-project") stream = Weddell.Client.Subscriber.Stream.open(client, "foo-subscription") Weddell.Client.Subscriber.Stream.send(stream, ack: [%Message{}], delay: [{%Message{}, 60}], stream_deadline: 120) #=> :ok ## Options * `ack` - Messages to be acknowledged. _(default: [])_ * `delay` - Messages to be delayed and the period for which to delay. _(default: [])_ * `stream_deadline` - The time period to wait before resending a message on this stream. _(default: 10)_ """ @spec send(stream :: t, send_opts) :: :ok def send(stream, opts \\ []) do ack_ids = opts |> Keyword.get(:ack, []) |> Enum.map(&(&1.ack_id)) {deadline_ack_ids, deadline_seconds} = opts |> Keyword.get(:delay, []) |> Enum.reduce({[], []}, fn ({message, seconds}, {ids, deadlines}) -> {[message.ack_id | ids], [seconds | deadlines]} end) stream_deadline = opts |> Keyword.get(:stream_deadline, @default_ack_deadline) request = StreamingPullRequest.new( ack_ids: ack_ids, modify_deadline_ack_ids: deadline_ack_ids, modify_deadline_seconds: deadline_seconds, stream_ack_deadline_seconds: stream_deadline) GRPCStub.stream_send(stream.grpc_stream, request) end @doc """ Receive messages from a stream. ## Example {:ok, client} = Weddell.Client.connect("weddell-project") client |> Weddell.Client.Subscriber.Stream.open("foo-subscription") |> Weddell.Client.Subscriber.Stream.recv() |> Enum.take(1) #=> [%Message{...}] """ @spec recv(stream :: t) :: Enumerable.t def recv(stream) do GRPCStub.recv(stream.grpc_stream) |> Stream.map(fn response -> response.received_messages |> Enum.map(&Message.new/1) end) end end
32.06338
98
0.62069
03b72d84dfdb55392fbe28c1040a3282e53e965e
2,159
ex
Elixir
clients/iam/lib/google_api/iam/v1/model/oidc.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/iam/lib/google_api/iam/v1/model/oidc.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/iam/lib/google_api/iam/v1/model/oidc.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.IAM.V1.Model.Oidc do @moduledoc """ Represents an OpenId Connect 1.0 identity provider. ## Attributes * `allowedAudiences` (*type:* `list(String.t)`, *default:* `nil`) - Acceptable values for the `aud` field (audience) in the OIDC token. Token exchange requests are rejected if the token audience does not match one of the configured values. Each audience may be at most 256 characters. A maximum of 10 audiences may be configured. If this list is empty, the OIDC token audience must be equal to the full canonical resource name of the WorkloadIdentityPoolProvider, with or without the HTTPS prefix. For example: ``` //iam.googleapis.com/projects//locations//workloadIdentityPools//providers/ https://iam.googleapis.com/projects//locations//workloadIdentityPools//providers/ ``` * `issuerUri` (*type:* `String.t`, *default:* `nil`) - Required. The OIDC issuer URL. Must be an HTTPS endpoint. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :allowedAudiences => list(String.t()) | nil, :issuerUri => String.t() | nil } field(:allowedAudiences, type: :list) field(:issuerUri) end defimpl Poison.Decoder, for: GoogleApi.IAM.V1.Model.Oidc do def decode(value, options) do GoogleApi.IAM.V1.Model.Oidc.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.IAM.V1.Model.Oidc do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
43.18
680
0.736452
03b7ed5ad0824d918213f3c9213af4f422a15d86
1,318
exs
Elixir
config/dev.exs
bitriot/phoenix_base
15ec83a9acf46202102f2b006d577972f5564b2f
[ "MIT" ]
null
null
null
config/dev.exs
bitriot/phoenix_base
15ec83a9acf46202102f2b006d577972f5564b2f
[ "MIT" ]
null
null
null
config/dev.exs
bitriot/phoenix_base
15ec83a9acf46202102f2b006d577972f5564b2f
[ "MIT" ]
null
null
null
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with brunch.io to recompile .js and .css sources. config :phoenix_base, PhoenixBase.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [node: ["node_modules/webpack/bin/webpack.js", "--watch-stdin", "--color", "--progress"]] # Watch static and templates for browser reloading. config :phoenix_base, PhoenixBase.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/gettext/.*(po)$}, ~r{web/views/.*(ex)$}, ~r{web/templates/.*(eex)$} ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Configure your database config :phoenix_base, PhoenixBase.Repo, adapter: Ecto.Adapters.Postgres, username: "postgres", password: "postgres", database: "phoenix_base_dev", hostname: "localhost", pool_size: 10
29.288889
68
0.707132
03b813a802007cd5a50a0cee97143a6bfb458dc9
535
ex
Elixir
elixir/guessing-game/lib/guessing_game.ex
maitesin/exercism
17481409b3a120e3a02bc3df24a0333d0d8e05be
[ "BSD-2-Clause" ]
null
null
null
elixir/guessing-game/lib/guessing_game.ex
maitesin/exercism
17481409b3a120e3a02bc3df24a0333d0d8e05be
[ "BSD-2-Clause" ]
null
null
null
elixir/guessing-game/lib/guessing_game.ex
maitesin/exercism
17481409b3a120e3a02bc3df24a0333d0d8e05be
[ "BSD-2-Clause" ]
null
null
null
defmodule GuessingGame do def compare(_, guess \\ :no_guess) def compare(_, guess) when guess == :no_guess do "Make a guess" end def compare(secret_number, guess) when secret_number == guess do "Correct" end def compare(secret_number, guess) when secret_number + 1 == guess or secret_number == guess + 1 do "So close" end def compare(secret_number, guess) when secret_number > guess do "Too low" end def compare(secret_number, guess) when secret_number < guess do "Too high" end end
22.291667
70
0.685981
03b8170a2e9a14b20e1730c910297ceced96aede
497
exs
Elixir
test/budget_app/operations/income/delete_test.exs
djordje/budget_app.backend
3febe64892e700f3174b8eddbc4b96260c444308
[ "MIT" ]
null
null
null
test/budget_app/operations/income/delete_test.exs
djordje/budget_app.backend
3febe64892e700f3174b8eddbc4b96260c444308
[ "MIT" ]
null
null
null
test/budget_app/operations/income/delete_test.exs
djordje/budget_app.backend
3febe64892e700f3174b8eddbc4b96260c444308
[ "MIT" ]
null
null
null
defmodule BudgetApp.Operations.Income.DeleteTest do use BudgetAppWeb.ConnCase, async: true alias BudgetApp.Operations.Income.Delete alias BudgetApp.Income alias BudgetApp.Repo test "removes record from the DB" do expense = insert(:income) assert Repo.aggregate(Income, :count, :id) == 1 Delete.exec(expense.id) assert Repo.aggregate(Income, :count, :id) == 0 end test "raises exception when income ID not found" do assert {:error, _} = Delete.exec(1) end end
27.611111
53
0.71831
03b88580c7b56295c5d1a46d609a00257e780740
2,403
ex
Elixir
lib/usir/transport/http/server/websocket.ex
usir/usir_ex
059cc1679dcdc9defcad17a4aac3492a33e529e5
[ "MIT" ]
null
null
null
lib/usir/transport/http/server/websocket.ex
usir/usir_ex
059cc1679dcdc9defcad17a4aac3492a33e529e5
[ "MIT" ]
null
null
null
lib/usir/transport/http/server/websocket.ex
usir/usir_ex
059cc1679dcdc9defcad17a4aac3492a33e529e5
[ "MIT" ]
null
null
null
defmodule Usir.Transport.HTTP.Server.Websocket do alias Usir.Protocol.Stateful, as: Protocol alias :cowboy_req, as: Request require Logger def init(req, {acceptor, protocol_opts}) do accepts = Request.parse_header("sec-websocket-protocol", req) |> format_protocols([]) info = request_info(req) {format, conn} = Usir.Acceptor.init(acceptor, accepts, info) state = Protocol.init(conn, protocol_opts) req = set_websocket_protocol(req, "usir|#{format}") {:cowboy_websocket, req, state, protocol_opts[:conn_timeout] || 60_000} rescue error in Usir.Acceptor.Error.Unacceptable -> # TODO is this the best way to tell the client? supported = Map.keys(error.provides) |> Enum.map(&"usir|#{&1}") |> Enum.join(", ") req = set_websocket_protocol(req, supported) req = Request.reply(400, req) {:ok, req, nil} end def websocket_handle({type, msg}, state) when type in [:text, :binary] do state |> Protocol.handle_packet(msg) |> reply() end def websocket_handle(_other, state) do {:ok, state} end def websocket_info(msg, state) do state |> Protocol.handle_info(msg) |> reply() end def terminate(_, _, nil) do :ok end def terminate(reason, _req, state) do state |> Protocol.terminate(reason) :ok end defp reply({:reply, message, state}) do {:reply, message, state} end defp reply({:ok, state}) do {:ok, state} end defp request_info(req) do peer = {remote_ip, _} = Request.peer(req) %Usir.Protocol{ headers: Request.headers(req), host: Request.host(req), owner: self(), path: Request.path(req), params: Request.parse_qs(req) |> :maps.from_list(), peer: peer, port: Request.port(req), protocol: Protocol, remote_ip: remote_ip, scheme: Request.scheme(req) |> format_scheme() } end defp format_scheme("https"), do: :wss defp format_scheme(_), do: :ws defp set_websocket_protocol(req, protocol) do Request.set_resp_header("sec-websocket-protocol", protocol, req) end defp format_protocols([], acc) do :lists.reverse(acc) end defp format_protocols(["usir|" <> format | rest], acc) do format_protocols(rest, [format | acc]) end defp format_protocols([_ | rest], acc) do format_protocols(rest, acc) end defp format_protocols(_, _) do [] end end
26.119565
89
0.650853
03b88c28200db6f543ce02a48f9e84dc0e4b8b09
885
ex
Elixir
lib/exwebapp/application.ex
norrland/exwebapp
862cdc8ee54b92ebcf7577c98160f1284776bdb1
[ "MIT" ]
null
null
null
lib/exwebapp/application.ex
norrland/exwebapp
862cdc8ee54b92ebcf7577c98160f1284776bdb1
[ "MIT" ]
null
null
null
lib/exwebapp/application.ex
norrland/exwebapp
862cdc8ee54b92ebcf7577c98160f1284776bdb1
[ "MIT" ]
null
null
null
defmodule Exwebapp.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false @app :exwebapp use Application require Logger def start(_type, _args) do # fetch which scheme to use ( see config/config.exs ) scheme = Application.get_env(@app, :scheme) # fetch options for plug_cowboy options = Application.get_env(@app, :plug_cowboy) children = [ Plug.Cowboy.child_spec( scheme: scheme, plug: Exwebapp.Endpoint, # point to where Plug.Router is used options: options[scheme] ) ] Logger.info("App started, using #{scheme}.") # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Exwebapp.Supervisor] Supervisor.start_link(children, opts) end end
26.818182
69
0.687006
03b8b237937a38617690b74adea15552791efc28
1,924
ex
Elixir
rustler_tests/lib/rustler_test.ex
BurntCaramel/rustler
9ece1e1da22f1a99383c04302549d6a5cd6abe34
[ "Apache-2.0", "MIT" ]
null
null
null
rustler_tests/lib/rustler_test.ex
BurntCaramel/rustler
9ece1e1da22f1a99383c04302549d6a5cd6abe34
[ "Apache-2.0", "MIT" ]
null
null
null
rustler_tests/lib/rustler_test.ex
BurntCaramel/rustler
9ece1e1da22f1a99383c04302549d6a5cd6abe34
[ "Apache-2.0", "MIT" ]
null
null
null
defmodule NifNotLoadedError do defexception message: "nif not loaded" end defmodule RustlerTest do use Rustler, otp_app: :rustler_test, crate: :rustler_test defp err do throw(NifNotLoadedError) end def add_u32(_, _), do: err() def add_i32(_, _), do: err() def echo_u8(_), do: err() def option_inc(_), do: err() def result_to_int(_), do: err() def sum_list(_), do: err() def make_list(), do: err() def term_debug(_), do: err() def term_eq(_, _), do: err() def term_cmp(_, _), do: err() def sum_map_values(_), do: err() def map_entries_sorted(_), do: err() def map_from_arrays(_keys, _values), do: err() def resource_make(), do: err() def resource_set_integer_field(_, _), do: err() def resource_get_integer_field(_), do: err() def resource_make_immutable(_), do: err() def resource_immutable_count(), do: err() def make_shorter_subbinary(_), do: err() def parse_integer(_), do: err() def binary_new(), do: err() def unowned_to_owned(_), do: err() def realloc_shrink(), do: err() def realloc_grow(), do: err() def encode_string(), do: err() def decode_iolist(_), do: err() def atom_to_string(_), do: err() def atom_equals_ok(_), do: err() def binary_to_atom(_), do: err() def binary_to_existing_atom(_), do: err() def threaded_fac(_), do: err() def threaded_sleep(_), do: err() def send_all(_, _), do: err() def sublists(_), do: err() def tuple_echo(_), do: err() def record_echo(_), do: err() def map_echo(_), do: err() def struct_echo(_), do: err() def unit_enum_echo(_), do: err() def untagged_enum_echo(_), do: err() def untagged_enum_with_truthy(_), do: err() def newtype_echo(_), do: err() def tuplestruct_echo(_), do: err() def newtype_record_echo(_), do: err() def tuplestruct_record_echo(_), do: err() def dirty_io(), do: err() def dirty_cpu(), do: err() def sum_range(_), do: err() end
26
49
0.657484
03b8bb85bd89cef16fa918e15eb118db028df0fb
1,964
ex
Elixir
assets/node_modules/phoenix/lib/mix/phoenix/context.ex
xiongxin/web_chat
4123887993083058a358358595c06970a5ac873f
[ "MIT" ]
null
null
null
assets/node_modules/phoenix/lib/mix/phoenix/context.ex
xiongxin/web_chat
4123887993083058a358358595c06970a5ac873f
[ "MIT" ]
null
null
null
assets/node_modules/phoenix/lib/mix/phoenix/context.ex
xiongxin/web_chat
4123887993083058a358358595c06970a5ac873f
[ "MIT" ]
null
null
null
defmodule Mix.Phoenix.Context do @moduledoc false alias Mix.Phoenix.{Context, Schema} defstruct name: nil, module: nil, schema: nil, alias: nil, base_module: nil, web_module: nil, basename: nil, file: nil, test_file: nil, dir: nil, generate?: true, context_app: nil, opts: [] def valid?(context) do context =~ ~r/^[A-Z]\w*(\.[A-Z]\w*)*$/ end def new(context_name, %Schema{} = schema, opts) do ctx_app = opts[:context_app] || Mix.Phoenix.context_app() base = Module.concat([Mix.Phoenix.context_base(ctx_app)]) module = Module.concat(base, context_name) alias = module |> Module.split() |> tl() |> Module.concat() basedir = Phoenix.Naming.underscore(context_name) basename = Path.basename(basedir) dir = Mix.Phoenix.context_lib_path(ctx_app, basedir) test_dir = Mix.Phoenix.context_test_path(ctx_app, basedir) file = Path.join([dir, basename <> ".ex"]) test_file = Path.join([test_dir, basename <> "_test.exs"]) generate? = Keyword.get(opts, :context, true) %Context{ name: context_name, module: module, schema: schema, alias: alias, base_module: base, web_module: web_module(), basename: basename, file: file, test_file: test_file, dir: dir, generate?: generate?, context_app: ctx_app, opts: opts} end def pre_existing?(%Context{file: file}), do: File.exists?(file) def pre_existing_tests?(%Context{test_file: file}), do: File.exists?(file) defp web_module do base = Mix.Phoenix.base() cond do Mix.Phoenix.context_app() != Mix.Phoenix.otp_app() -> Module.concat([base]) String.ends_with?(base, "Web") -> Module.concat([base]) true -> Module.concat(["#{base}Web"]) end end end
27.661972
76
0.582994
03b8f30580e51cf6b94e4d861c2a21c623fc5bf1
8,358
exs
Elixir
test/uinta/plug_test.exs
epinault/uinta
e1189e2267fd6cd49f87d5ca3be1fe7ced5f5969
[ "MIT" ]
null
null
null
test/uinta/plug_test.exs
epinault/uinta
e1189e2267fd6cd49f87d5ca3be1fe7ced5f5969
[ "MIT" ]
null
null
null
test/uinta/plug_test.exs
epinault/uinta
e1189e2267fd6cd49f87d5ca3be1fe7ced5f5969
[ "MIT" ]
null
null
null
defmodule Uinta.PlugTest do use ExUnit.Case use Plug.Test import ExUnit.CaptureLog require Logger defmodule MyPlug do use Plug.Builder plug(Uinta.Plug) plug(:passthrough) defp passthrough(conn, _) do Plug.Conn.send_resp(conn, 200, "Passthrough") end end defmodule JsonPlug do use Plug.Builder plug(Uinta.Plug, json: true) plug(:passthrough) defp passthrough(conn, _) do Plug.Conn.send_resp(conn, 200, "Passthrough") end end defmodule IgnoredPathsPlug do use Plug.Builder plug(Uinta.Plug, ignored_paths: ["/ignore"]) plug(:passthrough) defp passthrough(conn, _) do Plug.Conn.send_resp(conn, 200, "Passthrough") end end defmodule IgnoredPathsErrorPlug do use Plug.Builder plug(Uinta.Plug, ignored_paths: ["/ignore"]) plug(:passthrough) defp passthrough(conn, _) do Plug.Conn.send_resp(conn, 500, "Passthrough") end end defmodule IncludeVariablesPlug do use Plug.Builder plug(Uinta.Plug, include_variables: true, filter_variables: ~w(password)) plug(:passthrough) defp passthrough(conn, _) do Plug.Conn.send_resp(conn, 200, "Passthrough") end end defmodule IncludeUnnamedQueriesPlug do use Plug.Builder plug(Uinta.Plug, include_unnamed_queries: true) plug(:passthrough) defp passthrough(conn, _) do Plug.Conn.send_resp(conn, 200, "Passthrough") end end defmodule MyChunkedPlug do use Plug.Builder plug(Uinta.Plug) plug(:passthrough) defp passthrough(conn, _) do Plug.Conn.send_chunked(conn, 200) end end defmodule MyHaltingPlug do use Plug.Builder, log_on_halt: :debug plug(:halter) defp halter(conn, _), do: halt(conn) end defmodule MyDebugLevelPlug do use Plug.Builder plug(Uinta.Plug, log: :debug) plug(:passthrough) defp passthrough(conn, _) do Plug.Conn.send_resp(conn, 200, "Passthrough") end end test "logs proper message to console" do message = capture_log(fn -> MyPlug.call(conn(:get, "/"), []) end) assert message =~ ~r"\[info\] GET / - Sent 200 in [0-9]+[µm]s"u message = capture_log(fn -> MyPlug.call(conn(:get, "/hello/world"), []) end) assert message =~ ~r"\[info\] GET /hello/world - Sent 200 in [0-9]+[µm]s"u end test "logs proper graphql message to console" do variables = %{"user_uid" => "b1641ddf-b7b0-445e-bcbb-96ef359eae81"} params = %{"operationName" => "getUser", "query" => "query getUser", "variables" => variables} message = capture_log(fn -> MyPlug.call(conn(:post, "/graphql", params), []) end) assert message =~ ~r"\[info\] QUERY getUser - Sent 200 in [0-9]+[µm]s"u end test "logs proper json to console" do message = capture_log(fn -> JsonPlug.call(conn(:get, "/"), []) end) assert message =~ ~r"{\"method\":\"GET\",\"path\":\"/\",\"status\":\"200\",\"timing\":\"[0-9]+[µm]s\"}"u end test "logs graphql json to console" do variables = %{"user_uid" => "b1641ddf-b7b0-445e-bcbb-96ef359eae81"} params = %{"operationName" => "getUser", "query" => "query getUser", "variables" => variables} message = capture_log(fn -> JsonPlug.call(conn(:post, "/graphql", params), []) end) assert message =~ ~r"{\"method\":\"QUERY\",\"path\":\"getUser\",\"status\":\"200\",\"timing\":\"[0-9]+[µm]s\"}"u end test "logs paths with double slashes and trailing slash" do message = capture_log(fn -> MyPlug.call(conn(:get, "/hello//world/"), []) end) assert message =~ ~r"/hello//world/"u end test "logs chunked if chunked reply" do message = capture_log(fn -> MyChunkedPlug.call(conn(:get, "/hello/world"), []) end) assert message =~ ~r"Chunked 200 in [0-9]+[µm]s"u end test "logs proper log level to console" do message = capture_log(fn -> MyDebugLevelPlug.call(conn(:get, "/"), []) end) assert message =~ ~r"\[debug\] GET / - Sent 200 in [0-9]+[µm]s"u end test "ignores ignored_paths when a 200-level status is returned" do message = capture_log(fn -> IgnoredPathsPlug.call(conn(:post, "/ignore", []), []) end) refute message =~ "Sent 200" end test "logs ignored_paths when an error status is returned" do message = capture_log(fn -> IgnoredPathsErrorPlug.call(conn(:post, "/ignore", []), []) end) assert message =~ "[info] POST /ignore - Sent 500" end test "includes variables when applicable" do variables = %{"user_uid" => "b1641ddf-b7b0-445e-bcbb-96ef359eae81"} params = %{"operationName" => "getUser", "query" => "query getUser", "variables" => variables} message = capture_log(fn -> IncludeVariablesPlug.call(conn(:post, "/graphql", params), []) end) assert message =~ "with {\"user_uid\":\"b1641ddf-b7b0-445e-bcbb-96ef359eae81\"}" end test "doesn't try to include variables on non-graphql requests" do message = capture_log(fn -> IncludeVariablesPlug.call(conn(:post, "/", %{}), []) end) refute message =~ "with" end test "doesn't try to include variables when none were given" do params = %{"operationName" => "getUser", "query" => "query getUser"} message = capture_log(fn -> IncludeVariablesPlug.call(conn(:post, "/graphql", params), []) end) refute message =~ "with" end test "filters variables when applicable" do variables = %{ "user_uid" => "b1641ddf-b7b0-445e-bcbb-96ef359eae81", "password" => "password123" } params = %{"operationName" => "getUser", "query" => "query getUser", "variables" => variables} message = capture_log(fn -> IncludeVariablesPlug.call(conn(:post, "/graphql", params), []) end) assert message =~ "with {\"password\":\"[FILTERED]\",\"user_uid\":\"b1641ddf-b7b0-445e-bcbb-96ef359eae81\"}" end test "gets the GraphQL operation name from the query when it isn't in a separate param" do query = """ mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) { createReview(episode: $ep, review: $review) { stars commentary } } """ variables = %{ "ep" => "JEDI", "review" => %{"stars" => 5, "commentary" => "This is a great movie!"} } params = %{"query" => query, "variables" => variables} message = capture_log(fn -> MyPlug.call(conn(:post, "/graphql", params), []) end) assert message =~ "MUTATION CreateReviewForEpisode" end test "gets the GraphQL operation name from the query when there is an array parameter" do query = """ mutation track($userId: String!, $event: String!, $properties: [String]) { track(userId: $userId, event: $event, properties: $properties) { status } } """ variables = %{ "userId" => "55203f63-0b79-426c-840e-ea68bdac765c", "event" => "WEBSITE_WIDGET_PROMPT_SHOW", "properties" => ["green", "firefox"] } params = %{"query" => query, "variables" => variables} message = capture_log(fn -> MyPlug.call(conn(:post, "/graphql", params), []) end) assert message =~ "MUTATION track" end test "gets the GraphQL operation name from the query when it uses no commas and has whitespace in the parameters" do query = """ mutation CreateReviewForEpisode( $ep: Episode! $review: ReviewInput! ) { createReview(episode: $ep, review: $review) { stars commentary } } """ variables = %{ "ep" => "JEDI", "review" => %{"stars" => 5, "commentary" => "This is a great movie!"} } params = %{"query" => query, "variables" => variables} message = capture_log(fn -> MyPlug.call(conn(:post, "/graphql", params), []) end) assert message =~ "MUTATION CreateReviewForEpisode" end test "includes the query when it isn't named" do query = """ { hero { name } } """ params = %{"query" => query} message = capture_log(fn -> IncludeUnnamedQueriesPlug.call(conn(:post, "/graphql", params), []) end) assert message =~ "QUERY unnamed" assert message =~ "hero {" end end
25.796296
118
0.607442
03b90de9148c40cb9f5e912114f51c0c796db11b
1,726
ex
Elixir
lib/bow/download.ex
kianmeng/bow
d0b2ad564b0ccd06eb7d4582b94177877559d4af
[ "MIT" ]
25
2017-10-06T14:22:13.000Z
2022-01-14T20:59:59.000Z
lib/bow/download.ex
kianmeng/bow
d0b2ad564b0ccd06eb7d4582b94177877559d4af
[ "MIT" ]
9
2017-10-30T06:02:22.000Z
2022-01-03T13:57:57.000Z
lib/bow/download.ex
kianmeng/bow
d0b2ad564b0ccd06eb7d4582b94177877559d4af
[ "MIT" ]
4
2018-03-29T12:59:10.000Z
2021-09-19T09:10:01.000Z
defmodule Bow.Download do use Tesla, only: [:get] plug(Tesla.Middleware.FollowRedirects) @doc """ Download file from given URL """ @spec download(client :: Tesla.Client.t(), url :: String.t()) :: {:ok, Bow.t()} | {:error, any} def download(client \\ %Tesla.Client{}, url) do case get!(client, encode(url)) do %{status: 200, url: url, body: body} = env -> base = url |> URI.parse() |> Map.get(:path) |> Path.basename() name = case Tesla.get_header(env, "content-type") do nil -> base content_type -> case MIME.extensions(content_type) do [ext | _] -> rootname(base) <> "." <> ext _ -> base end end path = Plug.Upload.random_file!("bow-download") case File.write(path, body) do :ok -> {:ok, Bow.new(name: name, path: path)} {:error, reason} -> {:error, reason} end env -> {:error, env} end rescue ex in Tesla.Error -> {:error, ex} end # If path name is malformed, for example looks like this: ".some-data", # we won't be able to extract it and we will treat the name # as file extension instead. # # To handle all kind of problems we simply fallback to auto-generated # name if we cannot read it properly. defp rootname(base) do case Path.rootname(base) do "" -> Ecto.UUID.generate() name -> name end end defp encode(url), do: url |> URI.encode() |> String.replace(~r/%25([0-9a-f]{2})/i, "%\\g{1}") # based on: https://stackoverflow.com/questions/31825687/how-to-avoid-double-encoding-uri end
26.553846
95
0.546929