code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
defmodule KvStore.Bucket do @moduledoc """ Module which is responsible for holding bucket state. Identifiable both by a name and PID. """ @doc """ Starts a new named bucket. """ def start_link(name) when is_atom(name) do Agent.start_link(fn() -> %{} end, name: name) end @doc """ Gets a stream of values from the `bucket` by `key` by PID. """ def get_stream(bucket, key) when is_pid(bucket) do create_stream_from_value(Agent.get(bucket, &Map.get(&1, key))) end @doc """ Gets a value from the `bucket` by `key` by PID. """ def get(bucket, key) when is_pid(bucket) do Agent.get(bucket, &Map.get(&1, key)) end @doc """ Gets a value from the `bucket` by `key` by name. """ def get(bucket, key) when is_atom(bucket) and bucket != nil do get(Process.whereis(bucket), key) end @doc """ Puts the `value` for the given `key` in the `bucket` by PID. """ def put(bucket, key, value) when is_pid(bucket) do Agent.update(bucket, &Map.put(&1, key, value)) end @doc """ Puts the value for the given `key` in the `bucket` by name. """ def put(bucket, key, value) when is_atom(bucket) and bucket != nil do put(Process.whereis(bucket), key, value) end @doc """ Delete the given `key` in the `bucket` by PID. """ def del(bucket, key) when is_pid(bucket) do Agent.update(bucket, &Map.delete(&1, key)) end @doc """ Delete the given `key` in the `bucket` by name. """ def del(bucket, key) when is_atom(bucket) and bucket != nil do del(Process.whereis(bucket), key) end @doc """ Get all keys in the `bucket` by PID. """ def keys(bucket) when is_pid(bucket) do bucket |> Agent.get(&Map.to_list(&1)) |> Enum.map(fn({key, _value}) -> key end) |> Enum.sort(&string_comparison/2) end @doc """ Get all keys in the `bucket` by name. """ def keys(bucket) when is_atom(bucket) and bucket != nil do keys(Process.whereis(bucket)) end # Private functions. defp create_stream_from_value(value) do Stream.resource(fn () -> prepare_all_lines(value) end, &prepare_line/1, &noop/1) end defp convert(string) when is_binary(string), do: string defp convert(other), do: inspect(other) defp prepare_all_lines(long_string) do String.split(convert(long_string), "\n") end defp prepare_line(lines) do case Enum.count(lines) > 0 do true -> line = Enum.take(lines, 1) rest = Enum.slice(lines, 1, Enum.count(lines)) {line, rest}; false -> {:halt, ""} end end defp noop(_empty_word_list) do nil end defp string_comparison(a, b) do Process.sleep(100) a < b end end
lib/kv_store/bucket.ex
0.76973
0.44734
bucket.ex
starcoder
defmodule BitPay.KeyUtils do require Integer @doc """ generates a pem file """ def generate_pem do keys |> entity_from_keys |> der_encode_entity |> pem_encode_der end @doc """ creates a base58 encoded SIN from a pem file """ def get_sin_from_pem pem do compressed_public_key(pem) |> set_version_type |> (&(&1 <> write_checksum &1)).() |> encode_base58 end @doc """ retrieves the compressed public key from a pem file """ def compressed_public_key pem do entity_from_pem(pem) |> extract_coordinates |> compress_key end @doc """ retrieves the private key as a base16 string from the pem file """ def private_key pem do entity_from_pem(pem) |> elem(2) |> :binary.list_to_bin |> Base.encode16 end @doc """ signs the input with the key retrieved from the pem file """ def sign payload, pem do entity = :public_key.pem_decode(pem) |> List.first |> :public_key.pem_entry_decode :public_key.sign(payload, :sha256, entity) |> Base.encode16 end defp keys, do: :crypto.generate_key(:ecdh, :secp256k1) defp entity_from_keys({public, private}) do {:ECPrivateKey, 1, :binary.bin_to_list(private), {:namedCurve, {1, 3, 132, 0, 10}}, {0, public}} end defp der_encode_entity(ec_entity), do: :public_key.der_encode(:ECPrivateKey, ec_entity) defp pem_encode_der(der_encoded), do: :public_key.pem_encode([{:ECPrivateKey, der_encoded, :not_encrypted}]) defp entity_from_pem pem do [{_, dncoded, _}] = :public_key.pem_decode(pem) :public_key.der_decode(:ECPrivateKey, dncoded) end defp extract_coordinates(ec_entity) do elem(ec_entity, 4) |> elem(1) |> Base.encode16 |> split_x_y end defp split_x_y(uncompressed), do: {String.slice(uncompressed, 2..65), String.slice(uncompressed, 66..-1)} defp compress_key({x, y}) do convert_y_to_int({x, y}) |> return_compressed_key end defp convert_y_to_int({x, y}), do: ({x, String.to_integer(y, 16)}) defp return_compressed_key({x, y}) when Integer.is_even(y), do: "02#{x}" defp return_compressed_key({x, y}) when Integer.is_odd(y), do: "03#{x}" defp set_version_type public_key do digest(public_key, :sha256) |> digest(:ripemd160) |> (&("0F02" <> &1)).() end defp write_checksum version do digest(version, :sha256) |> digest(:sha256) |> String.slice(0..7) end defp digest hex_val, encoding do Base.decode16(hex_val) |> elem(1) |> (&(:crypto.hash(encoding, &1))).() |> Base.encode16 end defp encode_base58 string do String.to_integer(string, 16) |> (&(encode("", &1, digit_list))).() end defp encode(output_string, number, _list) when number == 0, do: output_string defp encode(output_string, number, list) do elem(list, rem(number,58)) <> output_string |> encode(div(number, 58), list) end defp digit_list do "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" |> String.split("") |> List.to_tuple end end
lib/bitpay/key-utils.ex
0.789842
0.412501
key-utils.ex
starcoder
defmodule Mix.Tasks.Iana.Specials do use Mix.Task alias Mix @moduledoc """ Download and convert IANA's IPv4/6 Special-Purpose Address Registries Usage: ``` mix iana.specials [force] [dryrun] ``` The `force` will force the download, even though the xml files are already present in the `priv` subdir. The `dryrun` will read and convert the downloaded xml files, convert them to a map and show the map without writing to disk. After download, the xml files are: - parsed into a list [{Pfx.t, %{property: value}] per registry - list are then combined a map %{ip4: [..], ip6: [..]} - that map is then saved as `priv/specials` in erlang external term format Pfx uses that file as an external resource for a module attribute that allows looking up IANA attributes for a given prefix via `Pfx.iana_special/2`. """ @shortdoc "Takes a snapshot of IANA's IPv4/6 Special-Purpose Address Registries" import SweetXml @user_agent {'User-agent', 'Elixir Pfx'} @iana_url "http://www.iana.org/assignments" @ip4_iana_spar "#{@iana_url}/iana-ipv4-special-registry/iana-ipv4-special-registry.xml" @ip4_priv_spar "priv/iana-ipv4-special-registry.xml" @ip6_iana_spar "#{@iana_url}/iana-ipv6-special-registry/iana-ipv6-special-registry.xml" @ip6_priv_spar "priv/iana-ipv6-special-registry.xml" @pfx_priv_spar "priv/specials" @impl Mix.Task def run(args) do force = "force" in args dryrun = "dryrun" in args if force or not File.exists?(@ip4_priv_spar), do: fetch(@ip4_iana_spar, @ip4_priv_spar), else: IO.puts("#{@ip4_priv_spar} exists, skipping download") if force or not File.exists?(@ip6_priv_spar), do: fetch(@ip6_iana_spar, @ip6_priv_spar), else: IO.puts("#{@ip6_priv_spar} exists, skipping download") map = %{ ip4: xml2list(@ip4_priv_spar), ip6: xml2list(@ip6_priv_spar) } if dryrun do Mix.shell().info("IANA IPv4 Special-Purpose Address Registry") IO.inspect(map.ip4) Mix.shell().info("\nIANA IPv6 Special-Purpose Address Registry") IO.inspect(map.ip6) else map |> :erlang.term_to_binary() |> save_term(@pfx_priv_spar) end Mix.shell().info("Done.") end defp fetch(url, priv) do with {:ok, {{_http_ver, 200, 'OK'}, _headers, body}} <- :httpc.request(:get, {url, [@user_agent]}, [], []) do # filter out a line, since xmerl chokes on it. body = List.to_string(body) |> String.split("\n") |> Enum.map(&String.trim/1) |> Enum.filter(fn line -> not String.starts_with?(line, "<?xml-model href") end) |> Enum.join("\n") File.write!(priv, body) IO.puts("donwloaded #{url} -> #{priv} (#{String.length(body)} bytes)") else metadata -> IO.puts("Error: #{url}") IO.puts("#{inspect(metadata)}") end end defp save_term(term, path), do: File.write!(path, term) defp xml2list(file) do # note: sort list on prefix: more to less specific {:ok, xml} = File.read(file) records = xml |> xpath( ~x"//record"l, prefix: ~x"./address/text()"s, name: ~x"./name/text()"s, source: ~x"./source/text()"s, destination: ~x"./destination/text()"s, forward: ~x"./forwardable/text()"s, global: ~x"./global/text()"s, reserved: ~x"./reserved/text()"s, allocation: ~x"./allocation/text()"s, spec: ~x"./spec/xref/@data"l ) |> Enum.map(fn elm -> normalize(elm) end) |> List.flatten() |> Enum.sort(fn x, y -> bit_size(elem(x, 0).bits) >= bit_size(elem(y, 0).bits) end) IO.puts("extract: #{file} -> #{length(records)} records") records end defp normalize(elm) do pfxs = Map.get(elm, :prefix) |> to_prefixp() elm = Map.delete(elm, :prefix) elm = Map.put(elm, :name, to_stringp(elm.name)) elm = Map.put(elm, :source, to_booleanp(elm.source)) elm = Map.put(elm, :destination, to_booleanp(elm.destination)) elm = Map.put(elm, :forward, to_booleanp(elm.forward)) elm = Map.put(elm, :global, to_booleanp(elm.global)) elm = Map.put(elm, :reserved, to_booleanp(elm.reserved)) elm = Map.put(elm, :allocation, to_stringp(elm.allocation)) elm = Map.put(elm, :spec, Enum.map(elm.spec, fn x -> to_stringp(x) end)) for pfx <- pfxs, do: {Pfx.new(pfx), Map.put(elm, :prefix, pfx)} end defp to_stringp(str) do keep = Enum.to_list(?a..?z) ++ Enum.to_list(?0..?9) ++ [?\s, ?-, ?/] str |> to_string() |> String.downcase() |> String.to_charlist() |> Enum.filter(fn c -> c in keep end) |> List.to_string() |> String.replace(~r/\s+/, "-") end defp to_prefixp(str) do str |> String.split(",") |> Enum.map(&String.trim/1) end defp to_booleanp(str) do str = String.downcase(str) cond do String.contains?(str, "false") -> false String.contains?(str, "true") -> true true -> :na end end end
dev/mix/tasks/iana.specials.ex
0.752649
0.754395
iana.specials.ex
starcoder
defmodule Timber.Utils.HTTPEvents do @moduledoc false alias Timber.Config @multi_header_delimiter "," @header_keys_to_sanitize ["authorization", "x-amz-security-token"] @header_value_byte_limit 256 @sanitized_value "[sanitized]" def format_time_ms(time_ms) when is_integer(time_ms), do: [Integer.to_string(time_ms), "ms"] def format_time_ms(time_ms) when is_float(time_ms) and time_ms >= 1, do: [:erlang.float_to_binary(time_ms, decimals: 2), "ms"] def format_time_ms(time_ms) when is_float(time_ms) and time_ms < 1, do: [:erlang.float_to_binary(time_ms * 1000, decimals: 0), "µs"] @doc false # Constructs a full path from the given parts def full_path(path, query_string) do %URI{path: path, query: query_string} |> URI.to_string() end @doc false # Constructs a full path from the given parts def full_url(scheme, host, path, port, query_string) do %URI{scheme: scheme, host: host, path: path, port: port, query: query_string} |> URI.to_string() end @doc false # Attemps to grab the request ID from the headers def get_request_id_from_headers(%{"x-request-id" => request_id}), do: request_id def get_request_id_from_headers(%{"request-id" => request_id}), do: request_id # Amazon uses their own *special* header def get_request_id_from_headers(%{"x-amzn-requestid" => request_id}), do: request_id def get_request_id_from_headers(_headers), do: nil # Move `:headers` (Map.t) into `:headers_json` (String.t) so that all headers are no indexed # within Timber by default. @spec move_headers_to_headers_json(Keyword.t()) :: Keyword.t() def move_headers_to_headers_json(opts) do if opts[:headers] do headers_json = Jason.encode!(opts[:headers]) opts |> Keyword.put(:headers_json, headers_json) |> Keyword.delete(:headers) else opts end end @doc false # Normalizes the body into a truncated string @spec normalize_body(any) :: String.t() def normalize_body(nil = body), do: body def normalize_body("" = body), do: body def normalize_body(body) when is_map(body) do case Jason.encode_to_iodata(body) do {:ok, json} -> normalize_body(to_string(json)) _ -> nil end end def normalize_body(body) when is_list(body) do normalize_body(to_string(body)) end def normalize_body(body) when is_binary(body) do limit = Config.http_body_size_limit() body |> Timber.Utils.Logger.truncate_bytes(limit) |> to_string() end @doc false # Normalizes HTTP headers into a structure expected by the Timber API. @spec normalize_headers(Keyword.t() | map) :: map def normalize_headers(headers) when is_list(headers) do headers |> List.flatten() |> Enum.into(%{}) |> normalize_headers() end def normalize_headers(headers) when is_map(headers) do Enum.into(headers, %{}, fn header -> header |> normalize_header() |> sanitize_header() end) end def normalize_headers(headers), do: headers @doc false # Normalizes an individual header @spec normalize_header({String.t(), String.t()}) :: {String.t(), String.t()} # Normalizes headers with multiple values in a comma delimited string as defined by the # HTTP spec RFC 2616 defp normalize_header({name, value}) when is_list(value) do normalize_header({String.downcase(name), Enum.join(value, @multi_header_delimiter)}) end defp normalize_header({name, value}) do value = value |> Timber.Utils.Logger.truncate_bytes(@header_value_byte_limit) |> to_string() {String.downcase(name), value} end # Sanitizes sensitive headers defp sanitize_header({key, _value}) when key in @header_keys_to_sanitize do {key, @sanitized_value} end defp sanitize_header({key, _value} = header) do if Enum.member?(Config.header_keys_to_sanitize(), key) do {key, @sanitized_value} else header end end @doc false # Normalizes HTTP methods into a value expected by the Timber API. def normalize_method(method) when is_atom(method) do method |> Atom.to_string() |> normalize_method() end def normalize_method(method) when is_binary(method), do: String.upcase(method) def normalize_method(method), do: method @doc false # Normalizes a URL into a Keyword.t that maps to our HTTP event fields. def normalize_url(url) when is_binary(url) do uri = URI.parse(url) [ host: uri.authority, path: uri.path, port: uri.port, query_string: uri.query, scheme: uri.scheme ] end def normalize_url(_url), do: [] @doc false # Convenience method that checks if the value is an atom and also converts it to a string. def try_atom_to_string(nil), do: nil def try_atom_to_string(val) when is_atom(val), do: Atom.to_string(val) def try_atom_to_string(val), do: val end
lib/timber/utils/http_events.ex
0.842928
0.458894
http_events.ex
starcoder
defmodule VintageNetQMI.ASUCalculator do @moduledoc """ Convert raw ASU values to friendlier units See https://en.wikipedia.org/wiki/Mobile_phone_signal#ASU for more information. The following conversions are done: * dBm * Number of "bars" out of 4 bars """ @typedoc """ Number of bars out of 4 to show in a UI """ @type bars :: 0..4 @typedoc """ dBm """ @type dbm :: neg_integer() @typedoc """ GSM ASU values ASU values map to RSSI. 99 means unknown """ @type gsm_asu :: 0..31 | 99 @typedoc """ UMTS ASU values ASU values map to RSCP """ @type umts_asu :: 0..90 | 255 @typedoc """ LTE ASU values ASU values map to RSRP https://arimas.com/78-rsrp-and-rsrq-measurement-in-lte/ """ @type lte_asu :: 0..97 @doc """ Compute signal level numbers from a GSM ASU The `AT+CSQ` command should report ASU values in this format. """ @spec from_gsm_asu(gsm_asu()) :: %{asu: gsm_asu(), dbm: dbm(), bars: bars()} def from_gsm_asu(asu) do clamped_asu = clamp_gsm_asu(asu) %{asu: asu, dbm: gsm_asu_to_dbm(clamped_asu), bars: gsm_asu_to_bars(clamped_asu)} end @spec from_lte_rssi(dbm()) :: %{asu: non_neg_integer(), dbm: dbm(), bars: bars()} def from_lte_rssi(rssi) do %{asu: dbm_to_gsm_asu(rssi), dbm: rssi, bars: lte_rssi_to_bars(rssi)} end defp gsm_asu_to_dbm(asu) when asu == 99, do: -113 defp gsm_asu_to_dbm(asu) do asu * 2 - 113 end defp dbm_to_gsm_asu(dbm) when dbm <= -113, do: 99 defp dbm_to_gsm_asu(dbm) do div(dbm + 113, 2) end defp gsm_asu_to_bars(asu) when asu == 99, do: 0 defp gsm_asu_to_bars(asu) when asu <= 9, do: 1 defp gsm_asu_to_bars(asu) when asu <= 14, do: 2 defp gsm_asu_to_bars(asu) when asu <= 19, do: 3 defp gsm_asu_to_bars(asu) when asu <= 30, do: 4 defp lte_rssi_to_bars(rssi) when rssi > -65, do: 4 defp lte_rssi_to_bars(rssi) when rssi > -75, do: 3 defp lte_rssi_to_bars(rssi) when rssi > -85, do: 2 defp lte_rssi_to_bars(rssi) when rssi > -113, do: 1 defp lte_rssi_to_bars(_rssi), do: 0 # Clamp ASU to the allowed values defp clamp_gsm_asu(asu) when asu < 0, do: 0 defp clamp_gsm_asu(asu) when asu == 99, do: 99 defp clamp_gsm_asu(asu) when asu > 30, do: 30 defp clamp_gsm_asu(asu), do: asu end
lib/vintage_net_qmi/asu_calculator.ex
0.852583
0.554893
asu_calculator.ex
starcoder
defmodule NervesTimeZones do @moduledoc """ Local time support for Nerves devices The `nerves_time_zones` application provides support for local time on Nerves devices. It does this by bundling a time zone database that's compatible with the `zoneinfo` library and providing logic to set the local time zone with the C runtime (and hence Erlang and Elixir). To use, call `NervesTimeZones.set_time_zone/1` with the any IANA time zone name (e.g., `"America/New_York"`). The time zone will be persisted so you won't need to set it again. It is safe to always set it on boot if your project will always be located in one time zone. After this, calls to `NaiveDateTime.local_now/1` will return the local time. If you would prefer `DateTime` struct, call `DateTime.now(NervesTimeZones.get_time_zone())`. If running a non-BEAM program that is time zone aware, you may need to set environment variables for it to work right. See `NervesTimeZones.tz_environment/0` for the proper settings. """ @doc """ Set the local time zone Only known time zone names can be set. Others will return an error. `"Etc/UTC"` should always be available. This time zone will be persisted and restored after a reboot. """ @spec set_time_zone(String.t()) :: :ok | {:error, any} defdelegate set_time_zone(time_zone), to: NervesTimeZones.Server @doc """ Return the current local time zone """ @spec get_time_zone() :: String.t() defdelegate get_time_zone(), to: NervesTimeZones.Server @doc """ Reset the time zone to the default This cleans up any saved time zone information and reapplies the defaults. The default time zone is "Etc/UTC", but this can be changed by adding something like the following to your `config.exs`: ``` config :nerves_time_zones, default_time_zone: "Asia/Tokyo" ``` """ @spec reset_time_zone() :: :ok defdelegate reset_time_zone(), to: NervesTimeZones.Server @doc """ Return environment variables for running OS processes If you're using `System.cmd/3` to start an OS process that is time zone aware, call this to set the environment appropriately. For example, `System.cmd("my_program", [], env: NervesTimeZones.tz_environment())` """ @spec tz_environment() :: %{String.t() => String.t()} defdelegate tz_environment, to: NervesTimeZones.Server @doc """ Return all known time zones This function scans the time zone database each time it's called. It's not slow, but if you just need to verify whether a time zone exists, call `valid_time_zone?/1` instead. """ @spec time_zones() :: [String.t()] defdelegate time_zones(), to: Zoneinfo @doc """ Return whether a time zone is valid """ @spec valid_time_zone?(String.t()) :: boolean defdelegate valid_time_zone?(time_zone), to: Zoneinfo end
lib/nerves_time_zones.ex
0.865991
0.622689
nerves_time_zones.ex
starcoder
defmodule SiteParser do defstruct [:module, :method] @type t :: %SiteParser{ module: module, method: atom } @type host :: %{ host: String.t } | %{ host: String.t, path: String.t } @doc """ iex> parse_host("http://google.com/") {:ok, "google.com"} iex> parse_host("https://www.google.com/") {:ok, "www.google.com"} iex> parse_host("http://192.168.1.2:8080/") {:ok, "192.168.1.2"} iex> parse_host(~s(http://google.com/path?query=yes#hash/a/b/c)) {:ok, "google.com"} iex> parse_host("google.com") {:ok, "google.com"} iex> parse_host("") :error """ @spec parse_host(String.t) :: {:ok, host} | :error def parse_host(url) when is_binary(url) do case URI.parse(url) do %{host: host} when is_binary(host) -> {:ok, host} %{host: host, path: path } when is_nil(host) and is_binary(path) -> {:ok, path} _ -> :error end end @doc """ iex> get_parser("http://www.kmeiju.net/archives/4998.html") {:ok, %SiteParser{module: SiteParser.BuiltIn, method: :parse_keiju}} iex> get_parser("www.kmeiju.net") {:ok, %SiteParser{module: SiteParser.BuiltIn, method: :parse_keiju}} iex> get_parser("http://site_not_exists") :error iex> get_parser(%Show{name: "Legion", url: "http://www.kmeiju.net/archives/4998.html"}) {:ok, %SiteParser{module: SiteParser.BuiltIn, method: :parse_keiju}} """ @spec get_parser(Show.t | String.t) :: {:ok, t} | :error def get_parser(show_or_url_or_host) @spec get_parser(Show.t) :: {:ok, t} | :error def get_parser(%{url: url}) do get_parser(url) end @spec get_parser(String.t) :: {:ok, t} | :error def get_parser(url) when is_binary(url) do with {:ok, host} <- parse_host(url), {:ok, info} <- Map.fetch(site_parsers(), host), do: {:ok, build_struct(info)} end @spec site_parsers() :: map defp site_parsers do Application.get_env(:harvester, :site_parsers) end @spec build_struct({ module, atom }) :: t defp build_struct({ module, method }) do %SiteParser{module: module, method: method} end @spec parse(PageData.t) :: list(Episode.t) def parse(page_data) do with {:ok, parser} <- get_parser(page_data.show), do: invoke_parser(parser, page_data) end @spec invoke_parser(t, PageData.t) :: list(Episode.t) defp invoke_parser(parser, page_data) do apply(parser.module, parser.method, [page_data]) end end
apps/harvester/lib/site_parser.ex
0.656108
0.404537
site_parser.ex
starcoder
defmodule GraphQL do @moduledoc ~S""" An Elixir implementation of Facebook's GraphQL. This is the core GraphQL query parsing and execution engine whose goal is to be transport, server and datastore agnostic. In order to setup an HTTP server (ie Phoenix) to handle GraphQL queries you will need: * [GraphQL Plug](https://github.com/graphql-elixir/plug_graphql) Examples for Phoenix can be found: * [Phoenix Examples](https://github.com/graphql-elixir/hello_graphql_phoenix) Here you'll find some examples which can be used as a starting point for writing your own schemas. Other ways of handling queries will be added in due course. ## Execute a Query on the Schema First setup your schema iex> defmodule TestSchema do ...> def schema do ...> %GraphQL.Schema{ ...> query: %GraphQL.Type.ObjectType{ ...> name: "RootQueryType", ...> fields: %{ ...> greeting: %{ ...> type: %GraphQL.Type.String{}, ...> resolve: &TestSchema.greeting/3, ...> description: "Greeting", ...> args: %{ ...> name: %{type: %GraphQL.Type.String{}, description: "The name of who you'd like to greet."}, ...> } ...> } ...> } ...> } ...> } ...> end ...> def greeting(_, %{name: name}, _), do: "Hello, #{name}!" ...> def greeting(_, _, _), do: "Hello, world!" ...> end ...> ...> GraphQL.execute(TestSchema.schema, "{ greeting }") {:ok, %{data: %{"greeting" => "Hello, world!"}}} ...> ...> GraphQL.execute(TestSchema.schema, ~S[{ greeting(name: "Josh") }]) {:ok, %{data: %{"greeting" => "Hello, Josh!"}}} """ alias GraphQL.Validation.Validator alias GraphQL.Execution.Executor @doc """ Execute a query against a schema (with validation) # iex> GraphQL.execute_with_opts(schema, "{ hello }") # {:ok, %{hello: world}} This is the preferred function signature for `execute` and will replace `execute/5`. """ def execute_with_opts(schema, query, opts \\ []) do execute_with_optional_validation(schema, query, opts) end @doc """ Execute a query against a schema (with validation) # iex> GraphQL.execute(schema, "{ hello }") # {:ok, %{hello: world}} *Deprecation warning*: This will be replaced in a future version with the function signature for `execute_with_opts/3`. """ def execute(schema, query, root_value \\ %{}, variable_values \\ %{}, operation_name \\ nil) do execute_with_optional_validation( schema, query, root_value: root_value, variable_values: variable_values, operation_name: operation_name, validate: true ) end @doc """ Execute a query against a schema (without validation) # iex> GraphQL.execute(schema, "{ hello }") # {:ok, %{hello: world}} """ def execute_without_validation(schema, query, opts) do execute_with_optional_validation(schema, query, Keyword.put(opts, :validate, false)) end defp execute_with_optional_validation(schema, query, opts) do case GraphQL.Lang.Parser.parse(query) do {:ok, document} -> case optionally_validate(Keyword.get(opts, :validate, true), schema, document) do :ok -> case Executor.execute(schema, document, opts) do {:ok, data, []} -> {:ok, %{data: data}} {:ok, data, errors} -> {:ok, %{data: data, errors: errors}} {:error, errors} -> {:error, errors} end {:error, errors} -> {:error, errors} end {:error, errors} -> {:error, errors} end end defp optionally_validate(false, _schema, _document), do: :ok defp optionally_validate(true, schema, document), do: Validator.validate(schema, document) end
lib/graphql.ex
0.867962
0.59249
graphql.ex
starcoder
defmodule AWS.Organizations do @moduledoc """ AWS Organizations """ @doc """ Sends a response to the originator of a handshake agreeing to the action proposed by the handshake request. This operation can be called only by the following principals when they also have the relevant IAM permissions: <ul> <li> **Invitation to join** or **Approve all features request** handshakes: only a principal from the member account. The user who calls the API for an invitation to join must have the `organizations:AcceptHandshake` permission. If you enabled all features in the organization, the user must also have the `iam:CreateServiceLinkedRole` permission so that AWS Organizations can create the required service-linked role named `AWSServiceRoleForOrganizations`. For more information, see [AWS Organizations and Service-Linked Roles](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_integration_services.html#orgs_integration_service-linked-roles) in the *AWS Organizations User Guide*. </li> <li> **Enable all features final confirmation** handshake: only a principal from the management account. For more information about invitations, see [Inviting an AWS Account to Join Your Organization](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_invites.html) in the *AWS Organizations User Guide.* For more information about requests to enable all features in the organization, see [Enabling All Features in Your Organization](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html) in the *AWS Organizations User Guide.* </li> </ul> After you accept a handshake, it continues to appear in the results of relevant APIs for only 30 days. After that, it's deleted. """ def accept_handshake(client, input, options \\ []) do request(client, "AcceptHandshake", input, options) end @doc """ Attaches a policy to a root, an organizational unit (OU), or an individual account. How the policy affects accounts depends on the type of policy. Refer to the *AWS Organizations User Guide* for information about each policy type: <ul> <li> [AISERVICES_OPT_OUT_POLICY](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html) </li> <li> [BACKUP_POLICY](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_backup.html) </li> <li> [SERVICE_CONTROL_POLICY](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scp.html) </li> <li> [TAG_POLICY](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) </li> </ul> This operation can be called only from the organization's management account. """ def attach_policy(client, input, options \\ []) do request(client, "AttachPolicy", input, options) end @doc """ Cancels a handshake. Canceling a handshake sets the handshake state to `CANCELED`. This operation can be called only from the account that originated the handshake. The recipient of the handshake can't cancel it, but can use `DeclineHandshake` instead. After a handshake is canceled, the recipient can no longer respond to that handshake. After you cancel a handshake, it continues to appear in the results of relevant APIs for only 30 days. After that, it's deleted. """ def cancel_handshake(client, input, options \\ []) do request(client, "CancelHandshake", input, options) end @doc """ Creates an AWS account that is automatically a member of the organization whose credentials made the request. This is an asynchronous request that AWS performs in the background. Because `CreateAccount` operates asynchronously, it can return a successful completion message even though account initialization might still be in progress. You might need to wait a few minutes before you can successfully access the account. To check the status of the request, do one of the following: <ul> <li> Use the `Id` member of the `CreateAccountStatus` response element from this operation to provide as a parameter to the `DescribeCreateAccountStatus` operation. </li> <li> Check the AWS CloudTrail log for the `CreateAccountResult` event. For information on using AWS CloudTrail with AWS Organizations, see [Monitoring the Activity in Your Organization](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_monitoring.html) in the *AWS Organizations User Guide.* </li> </ul> The user who calls the API to create an account must have the `organizations:CreateAccount` permission. If you enabled all features in the organization, AWS Organizations creates the required service-linked role named `AWSServiceRoleForOrganizations`. For more information, see [AWS Organizations and Service-Linked Roles](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrate_services.html#orgs_integrate_services-using_slrs) in the *AWS Organizations User Guide*. If the request includes tags, then the requester must have the `organizations:TagResource` permission. AWS Organizations preconfigures the new member account with a role (named `OrganizationAccountAccessRole` by default) that grants users in the management account administrator permissions in the new member account. Principals in the management account can assume the role. AWS Organizations clones the company name and address information for the new account from the organization's management account. This operation can be called only from the organization's management account. For more information about creating accounts, see [Creating an AWS Account in Your Organization](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_create.html) in the *AWS Organizations User Guide.* <important> <ul> <li> When you create an account in an organization using the AWS Organizations console, API, or CLI commands, the information required for the account to operate as a standalone account, such as a payment method and signing the end user license agreement (EULA) is *not* automatically collected. If you must remove an account from your organization later, you can do so only after you provide the missing information. Follow the steps at [ To leave an organization as a member account](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) in the *AWS Organizations User Guide*. </li> <li> If you get an exception that indicates that you exceeded your account limits for the organization, contact [AWS Support](https://console.aws.amazon.com/support/home#/). </li> <li> If you get an exception that indicates that the operation failed because your organization is still initializing, wait one hour and then try again. If the error persists, contact [AWS Support](https://console.aws.amazon.com/support/home#/). </li> <li> Using `CreateAccount` to create multiple temporary accounts isn't recommended. You can only close an account from the Billing and Cost Management Console, and you must be signed in as the root user. For information on the requirements and process for closing an account, see [Closing an AWS Account](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_close.html) in the *AWS Organizations User Guide*. </li> </ul> </important> <note> When you create a member account with this operation, you can choose whether to create the account with the **IAM User and Role Access to Billing Information** switch enabled. If you enable it, IAM users and roles that have appropriate permissions can view billing information for the account. If you disable it, only the account root user can access billing information. For information about how to disable this switch for an account, see [Granting Access to Your Billing Information and Tools](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/grantaccess.html). </note> """ def create_account(client, input, options \\ []) do request(client, "CreateAccount", input, options) end @doc """ This action is available if all of the following are true: <ul> <li> You're authorized to create accounts in the AWS GovCloud (US) Region. For more information on the AWS GovCloud (US) Region, see the [ *AWS GovCloud User Guide*.](http://docs.aws.amazon.com/govcloud-us/latest/UserGuide/welcome.html) </li> <li> You already have an account in the AWS GovCloud (US) Region that is paired with a management account of an organization in the commercial Region. </li> <li> You call this action from the management account of your organization in the commercial Region. </li> <li> You have the `organizations:CreateGovCloudAccount` permission. </li> </ul> AWS Organizations automatically creates the required service-linked role named `AWSServiceRoleForOrganizations`. For more information, see [AWS Organizations and Service-Linked Roles](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrate_services.html#orgs_integrate_services-using_slrs) in the *AWS Organizations User Guide.* AWS automatically enables AWS CloudTrail for AWS GovCloud (US) accounts, but you should also do the following: <ul> <li> Verify that AWS CloudTrail is enabled to store logs. </li> <li> Create an S3 bucket for AWS CloudTrail log storage. For more information, see [Verifying AWS CloudTrail Is Enabled](http://docs.aws.amazon.com/govcloud-us/latest/UserGuide/verifying-cloudtrail.html) in the *AWS GovCloud User Guide*. </li> </ul> If the request includes tags, then the requester must have the `organizations:TagResource` permission. The tags are attached to the commercial account associated with the GovCloud account, rather than the GovCloud account itself. To add tags to the GovCloud account, call the `TagResource` operation in the GovCloud Region after the new GovCloud account exists. You call this action from the management account of your organization in the commercial Region to create a standalone AWS account in the AWS GovCloud (US) Region. After the account is created, the management account of an organization in the AWS GovCloud (US) Region can invite it to that organization. For more information on inviting standalone accounts in the AWS GovCloud (US) to join an organization, see [AWS Organizations](http://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-organizations.html) in the *AWS GovCloud User Guide.* Calling `CreateGovCloudAccount` is an asynchronous request that AWS performs in the background. Because `CreateGovCloudAccount` operates asynchronously, it can return a successful completion message even though account initialization might still be in progress. You might need to wait a few minutes before you can successfully access the account. To check the status of the request, do one of the following: <ul> <li> Use the `OperationId` response element from this operation to provide as a parameter to the `DescribeCreateAccountStatus` operation. </li> <li> Check the AWS CloudTrail log for the `CreateAccountResult` event. For information on using AWS CloudTrail with Organizations, see [Monitoring the Activity in Your Organization](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_monitoring.html) in the *AWS Organizations User Guide.* </li> </ul> <p/> When you call the `CreateGovCloudAccount` action, you create two accounts: a standalone account in the AWS GovCloud (US) Region and an associated account in the commercial Region for billing and support purposes. The account in the commercial Region is automatically a member of the organization whose credentials made the request. Both accounts are associated with the same email address. A role is created in the new account in the commercial Region that allows the management account in the organization in the commercial Region to assume it. An AWS GovCloud (US) account is then created and associated with the commercial account that you just created. A role is also created in the new AWS GovCloud (US) account that can be assumed by the AWS GovCloud (US) account that is associated with the management account of the commercial organization. For more information and to view a diagram that explains how account access works, see [AWS Organizations](http://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-organizations.html) in the *AWS GovCloud User Guide.* For more information about creating accounts, see [Creating an AWS Account in Your Organization](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_create.html) in the *AWS Organizations User Guide.* <important> <ul> <li> When you create an account in an organization using the AWS Organizations console, API, or CLI commands, the information required for the account to operate as a standalone account is *not* automatically collected. This includes a payment method and signing the end user license agreement (EULA). If you must remove an account from your organization later, you can do so only after you provide the missing information. Follow the steps at [ To leave an organization as a member account](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) in the *AWS Organizations User Guide.* </li> <li> If you get an exception that indicates that you exceeded your account limits for the organization, contact [AWS Support](https://console.aws.amazon.com/support/home#/). </li> <li> If you get an exception that indicates that the operation failed because your organization is still initializing, wait one hour and then try again. If the error persists, contact [AWS Support](https://console.aws.amazon.com/support/home#/). </li> <li> Using `CreateGovCloudAccount` to create multiple temporary accounts isn't recommended. You can only close an account from the AWS Billing and Cost Management console, and you must be signed in as the root user. For information on the requirements and process for closing an account, see [Closing an AWS Account](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_close.html) in the *AWS Organizations User Guide*. </li> </ul> </important> <note> When you create a member account with this operation, you can choose whether to create the account with the **IAM User and Role Access to Billing Information** switch enabled. If you enable it, IAM users and roles that have appropriate permissions can view billing information for the account. If you disable it, only the account root user can access billing information. For information about how to disable this switch for an account, see [Granting Access to Your Billing Information and Tools](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/grantaccess.html). </note> """ def create_gov_cloud_account(client, input, options \\ []) do request(client, "CreateGovCloudAccount", input, options) end @doc """ Creates an AWS organization. The account whose user is calling the `CreateOrganization` operation automatically becomes the [management account](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html#account) of the new organization. This operation must be called using credentials from the account that is to become the new organization's management account. The principal must also have the relevant IAM permissions. By default (or if you set the `FeatureSet` parameter to `ALL`), the new organization is created with all features enabled and service control policies automatically enabled in the root. If you instead choose to create the organization supporting only the consolidated billing features by setting the `FeatureSet` parameter to `CONSOLIDATED_BILLING"`, no policy types are enabled by default, and you can't use organization policies """ def create_organization(client, input, options \\ []) do request(client, "CreateOrganization", input, options) end @doc """ Creates an organizational unit (OU) within a root or parent OU. An OU is a container for accounts that enables you to organize your accounts to apply policies according to your business requirements. The number of levels deep that you can nest OUs is dependent upon the policy types enabled for that root. For service control policies, the limit is five. For more information about OUs, see [Managing Organizational Units](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_ous.html) in the *AWS Organizations User Guide.* If the request includes tags, then the requester must have the `organizations:TagResource` permission. This operation can be called only from the organization's management account. """ def create_organizational_unit(client, input, options \\ []) do request(client, "CreateOrganizationalUnit", input, options) end @doc """ Creates a policy of a specified type that you can attach to a root, an organizational unit (OU), or an individual AWS account. For more information about policies and their use, see [Managing Organization Policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html). If the request includes tags, then the requester must have the `organizations:TagResource` permission. This operation can be called only from the organization's management account. """ def create_policy(client, input, options \\ []) do request(client, "CreatePolicy", input, options) end @doc """ Declines a handshake request. This sets the handshake state to `DECLINED` and effectively deactivates the request. This operation can be called only from the account that received the handshake. The originator of the handshake can use `CancelHandshake` instead. The originator can't reactivate a declined request, but can reinitiate the process with a new handshake request. After you decline a handshake, it continues to appear in the results of relevant APIs for only 30 days. After that, it's deleted. """ def decline_handshake(client, input, options \\ []) do request(client, "DeclineHandshake", input, options) end @doc """ Deletes the organization. You can delete an organization only by using credentials from the management account. The organization must be empty of member accounts. """ def delete_organization(client, input, options \\ []) do request(client, "DeleteOrganization", input, options) end @doc """ Deletes an organizational unit (OU) from a root or another OU. You must first remove all accounts and child OUs from the OU that you want to delete. This operation can be called only from the organization's management account. """ def delete_organizational_unit(client, input, options \\ []) do request(client, "DeleteOrganizationalUnit", input, options) end @doc """ Deletes the specified policy from your organization. Before you perform this operation, you must first detach the policy from all organizational units (OUs), roots, and accounts. This operation can be called only from the organization's management account. """ def delete_policy(client, input, options \\ []) do request(client, "DeletePolicy", input, options) end @doc """ Removes the specified member AWS account as a delegated administrator for the specified AWS service. <important> Deregistering a delegated administrator can have unintended impacts on the functionality of the enabled AWS service. See the documentation for the enabled service before you deregister a delegated administrator so that you understand any potential impacts. </important> You can run this action only for AWS services that support this feature. For a current list of services that support it, see the column *Supports Delegated Administrator* in the table at [AWS Services that you can use with AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrated-services-list.html) in the *AWS Organizations User Guide.* This operation can be called only from the organization's management account. """ def deregister_delegated_administrator(client, input, options \\ []) do request(client, "DeregisterDelegatedAdministrator", input, options) end @doc """ Retrieves AWS Organizations-related information about the specified account. This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def describe_account(client, input, options \\ []) do request(client, "DescribeAccount", input, options) end @doc """ Retrieves the current status of an asynchronous request to create an account. This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def describe_create_account_status(client, input, options \\ []) do request(client, "DescribeCreateAccountStatus", input, options) end @doc """ Returns the contents of the effective policy for specified policy type and account. The effective policy is the aggregation of any policies of the specified type that the account inherits, plus any policy of that type that is directly attached to the account. This operation applies only to policy types *other* than service control policies (SCPs). For more information about policy inheritance, see [How Policy Inheritance Works](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies-inheritance.html) in the *AWS Organizations User Guide*. This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def describe_effective_policy(client, input, options \\ []) do request(client, "DescribeEffectivePolicy", input, options) end @doc """ Retrieves information about a previously requested handshake. The handshake ID comes from the response to the original `InviteAccountToOrganization` operation that generated the handshake. You can access handshakes that are `ACCEPTED`, `DECLINED`, or `CANCELED` for only 30 days after they change to that state. They're then deleted and no longer accessible. This operation can be called from any account in the organization. """ def describe_handshake(client, input, options \\ []) do request(client, "DescribeHandshake", input, options) end @doc """ Retrieves information about the organization that the user's account belongs to. This operation can be called from any account in the organization. <note> Even if a policy type is shown as available in the organization, you can disable it separately at the root level with `DisablePolicyType`. Use `ListRoots` to see the status of policy types for a specified root. </note> """ def describe_organization(client, input, options \\ []) do request(client, "DescribeOrganization", input, options) end @doc """ Retrieves information about an organizational unit (OU). This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def describe_organizational_unit(client, input, options \\ []) do request(client, "DescribeOrganizationalUnit", input, options) end @doc """ Retrieves information about a policy. This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def describe_policy(client, input, options \\ []) do request(client, "DescribePolicy", input, options) end @doc """ Detaches a policy from a target root, organizational unit (OU), or account. <important> If the policy being detached is a service control policy (SCP), the changes to permissions for AWS Identity and Access Management (IAM) users and roles in affected accounts are immediate. </important> Every root, OU, and account must have at least one SCP attached. If you want to replace the default `FullAWSAccess` policy with an SCP that limits the permissions that can be delegated, you must attach the replacement SCP before you can remove the default SCP. This is the authorization strategy of an "[allow list](https://docs.aws.amazon.com/organizations/latest/userguide/SCP_strategies.html#orgs_policies_allowlist)". If you instead attach a second SCP and leave the `FullAWSAccess` SCP still attached, and specify `"Effect": "Deny"` in the second SCP to override the `"Effect": "Allow"` in the `FullAWSAccess` policy (or any other attached SCP), you're using the authorization strategy of a "[deny list](https://docs.aws.amazon.com/organizations/latest/userguide/SCP_strategies.html#orgs_policies_denylist)". This operation can be called only from the organization's management account. """ def detach_policy(client, input, options \\ []) do request(client, "DetachPolicy", input, options) end @doc """ Disables the integration of an AWS service (the service that is specified by `ServicePrincipal`) with AWS Organizations. When you disable integration, the specified service no longer can create a [service-linked role](http://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html) in *new* accounts in your organization. This means the service can't perform operations on your behalf on any new accounts in your organization. The service can still perform operations in older accounts until the service completes its clean-up from AWS Organizations. <p/> <important> We recommend that you disable integration between AWS Organizations and the specified AWS service by using the console or commands that are provided by the specified service. Doing so ensures that the other service is aware that it can clean up any resources that are required only for the integration. How the service cleans up its resources in the organization's accounts depends on that service. For more information, see the documentation for the other AWS service. </important> After you perform the `DisableAWSServiceAccess` operation, the specified service can no longer perform operations in your organization's accounts unless the operations are explicitly permitted by the IAM policies that are attached to your roles. For more information about integrating other services with AWS Organizations, including the list of services that work with Organizations, see [Integrating AWS Organizations with Other AWS Services](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrate_services.html) in the *AWS Organizations User Guide.* This operation can be called only from the organization's management account. """ def disable_a_w_s_service_access(client, input, options \\ []) do request(client, "DisableAWSServiceAccess", input, options) end @doc """ Disables an organizational policy type in a root. A policy of a certain type can be attached to entities in a root only if that type is enabled in the root. After you perform this operation, you no longer can attach policies of the specified type to that root or to any organizational unit (OU) or account in that root. You can undo this by using the `EnablePolicyType` operation. This is an asynchronous request that AWS performs in the background. If you disable a policy type for a root, it still appears enabled for the organization if [all features](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html) are enabled for the organization. AWS recommends that you first use `ListRoots` to see the status of policy types for a specified root, and then use this operation. This operation can be called only from the organization's management account. To view the status of available policy types in the organization, use `DescribeOrganization`. """ def disable_policy_type(client, input, options \\ []) do request(client, "DisablePolicyType", input, options) end @doc """ Enables the integration of an AWS service (the service that is specified by `ServicePrincipal`) with AWS Organizations. When you enable integration, you allow the specified service to create a [service-linked role](http://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html) in all the accounts in your organization. This allows the service to perform operations on your behalf in your organization and its accounts. <important> We recommend that you enable integration between AWS Organizations and the specified AWS service by using the console or commands that are provided by the specified service. Doing so ensures that the service is aware that it can create the resources that are required for the integration. How the service creates those resources in the organization's accounts depends on that service. For more information, see the documentation for the other AWS service. </important> For more information about enabling services to integrate with AWS Organizations, see [Integrating AWS Organizations with Other AWS Services](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrate_services.html) in the *AWS Organizations User Guide.* This operation can be called only from the organization's management account and only if the organization has [enabled all features](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html). """ def enable_a_w_s_service_access(client, input, options \\ []) do request(client, "EnableAWSServiceAccess", input, options) end @doc """ Enables all features in an organization. This enables the use of organization policies that can restrict the services and actions that can be called in each account. Until you enable all features, you have access only to consolidated billing, and you can't use any of the advanced account administration features that AWS Organizations supports. For more information, see [Enabling All Features in Your Organization](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html) in the *AWS Organizations User Guide.* <important> This operation is required only for organizations that were created explicitly with only the consolidated billing features enabled. Calling this operation sends a handshake to every invited account in the organization. The feature set change can be finalized and the additional features enabled only after all administrators in the invited accounts approve the change by accepting the handshake. </important> After you enable all features, you can separately enable or disable individual policy types in a root using `EnablePolicyType` and `DisablePolicyType`. To see the status of policy types in a root, use `ListRoots`. After all invited member accounts accept the handshake, you finalize the feature set change by accepting the handshake that contains `"Action": "ENABLE_ALL_FEATURES"`. This completes the change. After you enable all features in your organization, the management account in the organization can apply policies on all member accounts. These policies can restrict what users and even administrators in those accounts can do. The management account can apply policies that prevent accounts from leaving the organization. Ensure that your account administrators are aware of this. This operation can be called only from the organization's management account. """ def enable_all_features(client, input, options \\ []) do request(client, "EnableAllFeatures", input, options) end @doc """ Enables a policy type in a root. After you enable a policy type in a root, you can attach policies of that type to the root, any organizational unit (OU), or account in that root. You can undo this by using the `DisablePolicyType` operation. This is an asynchronous request that AWS performs in the background. AWS recommends that you first use `ListRoots` to see the status of policy types for a specified root, and then use this operation. This operation can be called only from the organization's management account. You can enable a policy type in a root only if that policy type is available in the organization. To view the status of available policy types in the organization, use `DescribeOrganization`. """ def enable_policy_type(client, input, options \\ []) do request(client, "EnablePolicyType", input, options) end @doc """ Sends an invitation to another account to join your organization as a member account. AWS Organizations sends email on your behalf to the email address that is associated with the other account's owner. The invitation is implemented as a `Handshake` whose details are in the response. <important> <ul> <li> You can invite AWS accounts only from the same seller as the management account. For example, if your organization's management account was created by Amazon Internet Services Pvt. Ltd (AISPL), an AWS seller in India, you can invite only other AISPL accounts to your organization. You can't combine accounts from AISPL and AWS or from any other AWS seller. For more information, see [Consolidated Billing in India](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/useconsolidatedbilliing-India.html). </li> <li> If you receive an exception that indicates that you exceeded your account limits for the organization or that the operation failed because your organization is still initializing, wait one hour and then try again. If the error persists after an hour, contact [AWS Support](https://console.aws.amazon.com/support/home#/). </li> </ul> </important> If the request includes tags, then the requester must have the `organizations:TagResource` permission. This operation can be called only from the organization's management account. """ def invite_account_to_organization(client, input, options \\ []) do request(client, "InviteAccountToOrganization", input, options) end @doc """ Removes a member account from its parent organization. This version of the operation is performed by the account that wants to leave. To remove a member account as a user in the management account, use `RemoveAccountFromOrganization` instead. This operation can be called only from a member account in the organization. <important> <ul> <li> The management account in an organization with all features enabled can set service control policies (SCPs) that can restrict what administrators of member accounts can do. This includes preventing them from successfully calling `LeaveOrganization` and leaving the organization. </li> <li> You can leave an organization as a member account only if the account is configured with the information required to operate as a standalone account. When you create an account in an organization using the AWS Organizations console, API, or CLI commands, the information required of standalone accounts is *not* automatically collected. For each account that you want to make standalone, you must perform the following steps. If any of the steps are already completed for this account, that step doesn't appear. <ul> <li> Choose a support plan </li> <li> Provide and verify the required contact information </li> <li> Provide a current payment method </li> </ul> AWS uses the payment method to charge for any billable (not free tier) AWS activity that occurs while the account isn't attached to an organization. Follow the steps at [ To leave an organization when all required account information has not yet been provided](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) in the *AWS Organizations User Guide.* </li> <li> You can leave an organization only after you enable IAM user access to billing in your account. For more information, see [Activating Access to the Billing and Cost Management Console](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/grantaccess.html#ControllingAccessWebsite-Activate) in the *AWS Billing and Cost Management User Guide.* </li> <li> After the account leaves the organization, all tags that were attached to the account object in the organization are deleted. AWS accounts outside of an organization do not support tags. </li> </ul> </important> """ def leave_organization(client, input, options \\ []) do request(client, "LeaveOrganization", input, options) end @doc """ Returns a list of the AWS services that you enabled to integrate with your organization. After a service on this list creates the resources that it requires for the integration, it can perform operations on your organization and its accounts. For more information about integrating other services with AWS Organizations, including the list of services that currently work with Organizations, see [Integrating AWS Organizations with Other AWS Services](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrate_services.html) in the *AWS Organizations User Guide.* This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_a_w_s_service_access_for_organization(client, input, options \\ []) do request(client, "ListAWSServiceAccessForOrganization", input, options) end @doc """ Lists all the accounts in the organization. To request only the accounts in a specified root or organizational unit (OU), use the `ListAccountsForParent` operation instead. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_accounts(client, input, options \\ []) do request(client, "ListAccounts", input, options) end @doc """ Lists the accounts in an organization that are contained by the specified target root or organizational unit (OU). If you specify the root, you get a list of all the accounts that aren't in any OU. If you specify an OU, you get a list of all the accounts in only that OU and not in any child OUs. To get a list of all accounts in the organization, use the `ListAccounts` operation. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_accounts_for_parent(client, input, options \\ []) do request(client, "ListAccountsForParent", input, options) end @doc """ Lists all of the organizational units (OUs) or accounts that are contained in the specified parent OU or root. This operation, along with `ListParents` enables you to traverse the tree structure that makes up this root. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_children(client, input, options \\ []) do request(client, "ListChildren", input, options) end @doc """ Lists the account creation requests that match the specified status that is currently being tracked for the organization. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_create_account_status(client, input, options \\ []) do request(client, "ListCreateAccountStatus", input, options) end @doc """ Lists the AWS accounts that are designated as delegated administrators in this organization. This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_delegated_administrators(client, input, options \\ []) do request(client, "ListDelegatedAdministrators", input, options) end @doc """ List the AWS services for which the specified account is a delegated administrator. This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_delegated_services_for_account(client, input, options \\ []) do request(client, "ListDelegatedServicesForAccount", input, options) end @doc """ Lists the current handshakes that are associated with the account of the requesting user. Handshakes that are `ACCEPTED`, `DECLINED`, or `CANCELED` appear in the results of this API for only 30 days after changing to that state. After that, they're deleted and no longer accessible. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called from any account in the organization. """ def list_handshakes_for_account(client, input, options \\ []) do request(client, "ListHandshakesForAccount", input, options) end @doc """ Lists the handshakes that are associated with the organization that the requesting user is part of. The `ListHandshakesForOrganization` operation returns a list of handshake structures. Each structure contains details and status about a handshake. Handshakes that are `ACCEPTED`, `DECLINED`, or `CANCELED` appear in the results of this API for only 30 days after changing to that state. After that, they're deleted and no longer accessible. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_handshakes_for_organization(client, input, options \\ []) do request(client, "ListHandshakesForOrganization", input, options) end @doc """ Lists the organizational units (OUs) in a parent organizational unit or root. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_organizational_units_for_parent(client, input, options \\ []) do request(client, "ListOrganizationalUnitsForParent", input, options) end @doc """ Lists the root or organizational units (OUs) that serve as the immediate parent of the specified child OU or account. This operation, along with `ListChildren` enables you to traverse the tree structure that makes up this root. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. <note> In the current release, a child can have only a single parent. </note> """ def list_parents(client, input, options \\ []) do request(client, "ListParents", input, options) end @doc """ Retrieves the list of all policies in an organization of a specified type. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_policies(client, input, options \\ []) do request(client, "ListPolicies", input, options) end @doc """ Lists the policies that are directly attached to the specified target root, organizational unit (OU), or account. You must specify the policy type that you want included in the returned list. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_policies_for_target(client, input, options \\ []) do request(client, "ListPoliciesForTarget", input, options) end @doc """ Lists the roots that are defined in the current organization. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. <note> Policy types can be enabled and disabled in roots. This is distinct from whether they're available in the organization. When you enable all features, you make policy types available for use in that organization. Individual policy types can then be enabled and disabled in a root. To see the availability of a policy type in an organization, use `DescribeOrganization`. </note> """ def list_roots(client, input, options \\ []) do request(client, "ListRoots", input, options) end @doc """ Lists tags that are attached to the specified resource. You can attach tags to the following resources in AWS Organizations. <ul> <li> AWS account </li> <li> Organization root </li> <li> Organizational unit (OU) </li> <li> Policy (any type) </li> </ul> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_tags_for_resource(client, input, options \\ []) do request(client, "ListTagsForResource", input, options) end @doc """ Lists all the roots, organizational units (OUs), and accounts that the specified policy is attached to. <note> Always check the `NextToken` response parameter for a `null` value when calling a `List*` operation. These operations can occasionally return an empty set of results even when there are more results available. The `NextToken` response parameter value is `null` *only* when there are no more results to display. </note> This operation can be called only from the organization's management account or by a member account that is a delegated administrator for an AWS service. """ def list_targets_for_policy(client, input, options \\ []) do request(client, "ListTargetsForPolicy", input, options) end @doc """ Moves an account from its current source parent root or organizational unit (OU) to the specified destination parent root or OU. This operation can be called only from the organization's management account. """ def move_account(client, input, options \\ []) do request(client, "MoveAccount", input, options) end @doc """ Enables the specified member account to administer the Organizations features of the specified AWS service. It grants read-only access to AWS Organizations service data. The account still requires IAM permissions to access and administer the AWS service. You can run this action only for AWS services that support this feature. For a current list of services that support it, see the column *Supports Delegated Administrator* in the table at [AWS Services that you can use with AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrated-services-list.html) in the *AWS Organizations User Guide.* This operation can be called only from the organization's management account. """ def register_delegated_administrator(client, input, options \\ []) do request(client, "RegisterDelegatedAdministrator", input, options) end @doc """ Removes the specified account from the organization. The removed account becomes a standalone account that isn't a member of any organization. It's no longer subject to any policies and is responsible for its own bill payments. The organization's management account is no longer charged for any expenses accrued by the member account after it's removed from the organization. This operation can be called only from the organization's management account. Member accounts can remove themselves with `LeaveOrganization` instead. <important> <ul> <li> You can remove an account from your organization only if the account is configured with the information required to operate as a standalone account. When you create an account in an organization using the AWS Organizations console, API, or CLI commands, the information required of standalone accounts is *not* automatically collected. For an account that you want to make standalone, you must choose a support plan, provide and verify the required contact information, and provide a current payment method. AWS uses the payment method to charge for any billable (not free tier) AWS activity that occurs while the account isn't attached to an organization. To remove an account that doesn't yet have this information, you must sign in as the member account and follow the steps at [ To leave an organization when all required account information has not yet been provided](http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) in the *AWS Organizations User Guide.* </li> <li> After the account leaves the organization, all tags that were attached to the account object in the organization are deleted. AWS accounts outside of an organization do not support tags. </li> </ul> </important> """ def remove_account_from_organization(client, input, options \\ []) do request(client, "RemoveAccountFromOrganization", input, options) end @doc """ Adds one or more tags to the specified resource. Currently, you can attach tags to the following resources in AWS Organizations. <ul> <li> AWS account </li> <li> Organization root </li> <li> Organizational unit (OU) </li> <li> Policy (any type) </li> </ul> This operation can be called only from the organization's management account. """ def tag_resource(client, input, options \\ []) do request(client, "TagResource", input, options) end @doc """ Removes any tags with the specified keys from the specified resource. You can attach tags to the following resources in AWS Organizations. <ul> <li> AWS account </li> <li> Organization root </li> <li> Organizational unit (OU) </li> <li> Policy (any type) </li> </ul> This operation can be called only from the organization's management account. """ def untag_resource(client, input, options \\ []) do request(client, "UntagResource", input, options) end @doc """ Renames the specified organizational unit (OU). The ID and ARN don't change. The child OUs and accounts remain in place, and any attached policies of the OU remain attached. This operation can be called only from the organization's management account. """ def update_organizational_unit(client, input, options \\ []) do request(client, "UpdateOrganizationalUnit", input, options) end @doc """ Updates an existing policy with a new name, description, or content. If you don't supply any parameter, that value remains unchanged. You can't change a policy's type. This operation can be called only from the organization's management account. """ def update_policy(client, input, options \\ []) do request(client, "UpdatePolicy", input, options) end @spec request(AWS.Client.t(), binary(), map(), list()) :: {:ok, map() | nil, map()} | {:error, term()} defp request(client, action, input, options) do client = %{client | service: "organizations", region: "us-east-1"} host = build_host("organizations", client) url = build_url(host, client) headers = [ {"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}, {"X-Amz-Target", "AWSOrganizationsV20161128.#{action}"} ] payload = encode!(client, input) headers = AWS.Request.sign_v4(client, "POST", url, headers, payload) post(client, url, payload, headers, options) end defp post(client, url, payload, headers, options) do case AWS.Client.request(client, :post, url, payload, headers, options) do {:ok, %{status_code: 200, body: body} = response} -> body = if body != "", do: decode!(client, body) {:ok, body, response} {:ok, response} -> {:error, {:unexpected_response, response}} error = {:error, _reason} -> error end end defp build_host(_endpoint_prefix, %{region: "local", endpoint: endpoint}) do endpoint end defp build_host(_endpoint_prefix, %{region: "local"}) do "localhost" end defp build_host(endpoint_prefix, %{endpoint: endpoint}) do "#{endpoint_prefix}.#{endpoint}" end defp build_url(host, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}/" end defp encode!(client, payload) do AWS.Client.encode!(client, payload, :json) end defp decode!(client, payload) do AWS.Client.decode!(client, payload, :json) end end
lib/aws/generated/organizations.ex
0.784154
0.487795
organizations.ex
starcoder
defmodule Sled.Tree do @moduledoc "Perform operations on sled trees." @derive {Inspect, except: [:ref]} @enforce_keys [:ref, :db, :name] defstruct ref: nil, db: nil, name: nil @typedoc """ A reference to a sled tenant tree. """ @opaque t :: %__MODULE__{ref: reference(), db: Sled.t(), name: String.t()} @typedoc """ A reference to a sled tree. Passing a `t:Sled.t/0` refers to the default tree for the db, while a `t:t/0` references a "tenant" tree. """ @type tree_ref :: t | Sled.t() @doc """ Retrieve the CRC32 of all keys and values in `tree`. This is O(N) and locks the underlying tree for the duration of the entire scan. """ @spec checksum(tree_ref) :: integer | no_return def checksum(tree) do Sled.Native.sled_checksum(tree) end @doc """ Synchronously flushes all dirty IO buffers for `tree` and calls fsync. If this succeeds, it is guaranteed that all previous writes will be recovered if the system crashes. Returns the number of bytes flushed during this call. Flushing can take quite a lot of time, and you should measure the performance impact of using it on realistic sustained workloads running on realistic hardware. """ @spec flush(tree_ref) :: integer | no_return def flush(tree) do Sled.Native.sled_flush(tree) end @doc """ Insert `value` into `tree` for `key`. Returns `nil` if there was no previous value associated with the key. """ @spec insert(tree_ref, binary, binary) :: binary | nil | no_return def insert(tree, key, value) do Sled.Native.sled_insert(tree, key, value) end @doc """ Retrieve the value for `key` from `tree`. Returns `nil` if there is no value associated with the key. """ @spec get(tree_ref, binary) :: binary | nil | no_return def get(tree, key) do Sled.Native.sled_get(tree, key) end @doc """ Delete the value for `key` from `tree`. Returns `nil` if there is no value associated with the key. """ @spec remove(tree_ref, binary) :: binary | nil | no_return def remove(tree, key) do Sled.Native.sled_remove(tree, key) end @doc """ Compare and swap `old` and `new` values for `key` in `tree`. If `old` is `nil`, the value for `key` will be set if it isn't set yet. If `new` is `nil`, the value for `key` will be deleted if `old` matches the current value. If both `old` and `new` are not `nil`, the value of `key` will be set to `new` if `old` matches the current value. Upon success, returns `{:ok, {}}`. If the operation fails, `{:error, {current, proposed}}` will be returned instead, where `current` is the current value for `key` which caused the CAS to fail, and `proposed` is the value that was proposed unsuccessfully. """ @spec compare_and_swap(tree_ref, binary, binary | nil, binary | nil) :: {:ok, {}} | {:error, {current :: binary, proposed :: binary}} | no_return def compare_and_swap(tree, key, old, new) do Sled.Native.sled_compare_and_swap(tree, key, old, new) end end
lib/sled/tree.ex
0.910177
0.557845
tree.ex
starcoder
defmodule CSP.Channel do @moduledoc """ Module used to create and manage channels. ## Options There are some options that may be used to change a channel behavior, but the channel's options can only be set during it's creation. The available options are: * `name` - Registers the channel proccess with a name. Note that the naming constraints are the same applied to a `GenServer`. * `buffer` - A struct that implements the `CSP.Buffer` protocol. This library ships with three implementations: `CSP.Buffer.Blocking`, `CSP.Buffer.Dropping` and `CSP.Buffer.Sliding`. Check out their documentation for more information on how each one works. ## Using as a collection The `CSP.Channel` struct has underpinnings for working alongside the `Stream` and `Enum` modules. You can use a channel directly as a Collectable: channel = Channel.new() Enum.into([:some, :data], channel) channel = Channel.new() for x <- 1..4, into: channel do x * x end And you can also use the channel as an Enumerable: channel = Channel.new() Enum.take(channel, 2) channel = channel.new() for x <- channel do x * x end Just be mindful that just like the `put` and `get` operations can be blocking, so do these. One trick is to spin up a process to take care of feeding and reading the channel: channel = Channel.new() spawn_link(fn -> Enum.into([:some, :data], channel) end) Enum.take(channel, 2) # => [:some, :data] In the next section we will discuss some of the gotchas of using channels as Collectables/Enumerables. #### As a Collectable Every element that is fed into the channel causes a `put`operation, so be sure that there will be someone reading from your channel or that your channel has a buffer big enough to accommodate the incoming events. #### As an Enumerable Every element that is read from the channel causes a `get` operation. so be sure that there will be someone adding values to your channel. A thing to keep in mind while using channels as Enumerables is that they act like infinite streams, so eager functions that consume the whole stream (like `Enum.map/2` or `Enum.each/2`) will only return when the channel is closed (see `CSP.Channel.close/1`). Unless that is exactly what you want, use functions from the `Stream` module to build your processing pipeline and finish them with something like `Enum.take/2` or `Enum.take_while/2`. Another caveat of using channels as Enumerables is that filtering with `Stream.filter/2` or `Enum.filter/2` does not simply filter what you are going to read from the channel. It reads the values and then discards the rejected ones. If you just want to direct the filtered results elsewhere or partition the events between multiple consumers, use `CSP.Channel.partition/2` and `CSP.Channel.partition/3` respectively. The almost same thing would happen with `Enum.count/1` and `Enum.member?/2`, as the values would be read from the channel to get the result and be discarded afterwards. As an operation like this should not be done on a channel, an error is raised if those functions (and others similar to them) are called with a channel. Using the the Collectable/Enumerable implementation you can get some nice results, like this parallel map over a channel implementation: defmodule ChannelExtensions do alias CSP.Channel # Receive a channel, the number of workers # and a function to be called on each value. # Returns a channel with the results. def pmap(source, workers, fun) do # Create the results channel and a temporary channel just for cleanup. results = Channel.new() done = Channel.new() # Spin up the number of workers passed as argument. # Each worker stream values from on channel # to the other passing each to the function. # After the source is depleted, each worker puts # a message in the done channel. for _ <- 1..workers do Task.start_link(fn -> for value <- source, into: results, do: fun.(value) Channel.put(done, true) end) end # Spin up a cleanup process that blocks until all # the workers put a message in the done channel, # then closes both the done and the results channels. Task.start_link(fn -> Enum.take(done, workers) Channel.close(done) Channel.close(results) end) results end end ## OTP Compatibility Since channels are just GenServers, you can use a channel in a supervision tree: alias CSP.{ Buffer, Channel } children = [ {Channel, name: MyApp.Channel, buffer: Buffer.Blocking.new(10)} ] {:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one) You can use all the functions with the registered name instead of the channel struct: Channel.put(MyApp.Channel, :data) Channel.put(MyApp.Channel, :other) Channel.get(MyApp.Channel) #=> :data Channel.get(MyApp.Channel) #=> :other If you want to use it as a channel struct just call `CSP.Channel.wrap/1`: channel = Channel.wrap(MyApp.Channel) Enum.into(1..4, channel) """ alias CSP.Buffer defstruct [:ref] @server_module CSP.Channel.Server @type options :: [option] @type option :: {:buffer, CSP.Buffer.t()} | {:buffer_size, non_neg_integer()} | {:buffer_type, buffer_type()} | {:name, GenServer.name()} @type buffer_type :: :blocking | :sliding | :dropping @type channel_ref :: term | t @type t :: %__MODULE__{ref: term()} @doc false def child_spec(options) do {buffer, name} = parse_options(options) %{ id: name || __MODULE__, type: :worker, start: {__MODULE__, :start_link, [[buffer: buffer, name: name]]} } end @doc """ Function responsible for the starting of the channel. Ideal for using a CSP in a supervision tree. """ @spec start_link(options) :: GenServer.on_start() def start_link(options \\ []) do {buffer, name} = parse_options(options) GenServer.start_link(@server_module, buffer, name: name) end @doc """ Non-linking version of `CSP.Channel.start_link/1` """ @spec start(options) :: GenServer.on_start() def start(options \\ []) do {buffer, name} = parse_options(options) GenServer.start(@server_module, buffer, name: name) end @doc """ Function responsible for creating a new channel. Useful for using channels outside of a supervision tree. ## Example iex> channel = Channel.new() iex> spawn_link(fn -> Channel.put(channel, :data) end) iex> Channel.get(channel) :data """ @spec new(options) :: t def new(options \\ []) do {:ok, pid} = start_link(options) wrap(pid) end @doc """ Wraps the PID or registered name in a Channel struct. If the passed in value is already a Channel struct, return it unchanged. ## Example iex> {:ok, pid} = Channel.start_link(buffer: CSP.Buffer.Blocking.new(5)) iex> channel = Channel.wrap(pid) iex> Enum.into(1..5, channel) iex> Channel.close(channel) iex> Enum.to_list(channel) [1, 2, 3, 4, 5] iex> channel = Channel.new() iex> channel == Channel.wrap(channel) true """ @spec wrap(channel_ref) :: t def wrap(%__MODULE__{} = channel), do: channel def wrap(channel), do: %__MODULE__{ref: channel} @doc """ Function responsible for fetching a value of the channel. It will block until a value is inserted in the channel or it is closed. Always returns `nil` when the channel is closed. ## Example iex> channel = Channel.new() iex> spawn_link(fn -> Channel.put(channel, :data) end) iex> Channel.get(channel) :data iex> Channel.close(channel) iex> Channel.get(channel) nil """ @spec get(channel_ref) :: term def get(%__MODULE__{} = channel), do: get(channel.ref) def get(channel) do try do GenServer.call(channel, :get, :infinity) catch :exit, {_, {GenServer, :call, [_, :get, _]}} -> nil end end @doc """ Function responsible for putting a value in the channel. It may block until a value is fetched deppending on the buffer type of the channel. Raises if trying to put `nil` or if trying to put anything in a closed channel. ## Example iex> channel = Channel.new(buffer: CSP.Buffer.Blocking.new(5)) iex> Channel.put(channel, :data) iex> Channel.put(channel, :other) iex> Enum.take(channel, 2) [:data, :other] """ @spec put(channel_ref, term) :: :ok def put(%__MODULE__{} = channel, item), do: put(channel.ref, item) def put(_channel, nil), do: raise(ArgumentError, "Can't put nil on a channel.") def put(channel, item) do try do GenServer.call(channel, {:put, item}, :infinity) catch :exit, {_, {GenServer, :call, [_, {:put, _}, _]}} -> {:error, :closed} end end @doc """ Function responsible for closing a channel. ## Example iex> channel = Channel.new() iex> Channel.closed?(channel) false iex> Channel.close(channel) iex> Channel.closed?(channel) true """ @spec close(channel_ref) :: :ok def close(%__MODULE__{} = channel), do: close(channel.ref) def close(channel) do try do GenServer.call(channel, :close) catch :exit, {_, {GenServer, :call, [_, :close, _]}} -> :ok end end @doc """ Returns `true` if the channel is closed or `false` otherwise. """ @spec closed?(channel_ref) :: boolean def closed?(%__MODULE__{} = channel), do: closed?(channel.ref) def closed?(channel) do try do GenServer.call(channel, :closed?) catch :exit, {_, {GenServer, :call, [_, :closed?, _]}} -> true end end @doc """ Creates a channel based on the given enumerables. The created channel is closed when the provided enumerables are depleted. ## Example iex> channel = Channel.from_enumerables([1..4, 5..8]) iex> Enum.to_list(channel) [1, 2, 3, 4, 5, 6, 7, 8] """ @spec from_enumerables([Enum.t()]) :: t def from_enumerables(enums) do result = new() Task.start_link(fn -> enums |> Stream.concat() |> Enum.into(result) close(result) end) result end @doc """ Creates a channel based on the given enumerable. The created channel is closed when the enumerable is depleted. ## Example iex> channel = Channel.from_enumerable(1..4) iex> Enum.to_list(channel) [1, 2, 3, 4] """ @spec from_enumerable(Enum.t()) :: t def from_enumerable(enum) do from_enumerables([enum]) end @doc """ Creates a channel that buffers events from a source channel. The created channel is closed when the source channel is closed. ## Example iex> unbuffered = Channel.new() iex> buffered = Channel.with_buffer(unbuffered, 5) iex> Enum.into(1..5, unbuffered) iex> Enum.take(buffered, 5) [1, 2, 3, 4, 5] """ @spec with_buffer(t, non_neg_integer) :: t def with_buffer(source, size) do result = new(buffer: Buffer.Blocking.new(size)) Task.start_link(fn -> Enum.into(source, result) close(result) end) result end @doc """ Partitions a channel in two, according to the provided function. The created channels are closed when the source channel is closed. ### Important This function expects that you are going to simultaneously read from both channels, as an event that is stuck in one of them will block the other. If you just want to discard values from a channel, use `Stream.filter/2` or `Stream.reject/2`. ## Example iex> require Integer iex> channel = Channel.from_enumerable(1..4) iex> {even, odd} = Channel.partition(channel, &Integer.is_even/1) iex> Channel.get(odd) 1 iex> Channel.get(even) 2 iex> Channel.get(odd) 3 iex> Channel.get(even) 4 """ @spec partition(t, (term -> boolean)) :: {t, t} def partition(source, fun) do %{true => left, false => right} = partition(source, [true, false], fun) {left, right} end @doc """ Partitions events from one channel to an arbitrary number of other channels, according to the partitions definition and the hashing function. Returns a map with the partition as the name and the partition channel as the value. All the created channels are closed when the source channel is closed. ### Important This function expects that you are going to simultaneously read from all channels, as an event that is stuck in one of them will block the others. ## Example iex> channel = Channel.from_enumerable(1..10) iex> partitions = Channel.partition(channel, 0..3, &rem(&1, 4)) iex> partitions ...> |> Enum.map(fn {key, channel} -> {key, Channel.with_buffer(channel, 5)} end) ...> |> Enum.map(fn {key, channel} -> {key, Enum.to_list(channel)} end) [{0, [4, 8]}, {1, [1, 5, 9]}, {2, [2, 6, 10]}, {3, [3, 7]}] """ @spec partition(t, Enum.t(), (term -> term)) :: %{term => t} def partition(source, partitions, hashing_fun) do partitions = Map.new(partitions, &{&1, new()}) Task.start_link(fn -> for value <- source do partition = hashing_fun.(value) case Map.fetch(partitions, partition) do {:ok, channel} -> put(channel, value) :error -> valid_partitions = Map.keys(partitions) raise """ The partition #{inspect(partition)} returned by the hashing function is invalid. The valid partitions are: #{inspect(valid_partitions)}. """ end end partitions |> Map.values() |> Enum.each(&close/1) end) partitions end defp parse_options(options) do buffer = case Keyword.fetch(options, :buffer) do {:ok, value} -> value :error -> parse_legacy_buffer(options) end {buffer, options[:name]} end defp parse_legacy_buffer(options) do size = Keyword.get(options, :buffer_size, 0) case Keyword.fetch(options, :buffer_type) do {:ok, :blocking} -> Buffer.Blocking.new(size) {:ok, :dropping} -> Buffer.Dropping.new(size) {:ok, :sliding} -> Buffer.Sliding.new(size) :error -> Buffer.Blocking.new(size) end end defimpl Enumerable do require Logger def reduce(_channel, {:halt, acc}, _fun) do {:halted, acc} end def reduce(channel, {:suspend, acc}, fun) do {:suspended, acc, &reduce(channel, &1, fun)} end def reduce(channel, {:cont, acc}, fun) do case CSP.Channel.get(channel) do nil -> {:done, acc} value -> reduce(channel, fun.(value, acc), fun) end end def member?(_channel, _value) do error() end def count(_channel) do error() end def slice(_channel) do error() end defp error do raise """ Don't use a `CSP.Channel` in functions like `Enum.count/1`, `Enum.at/2` and `Enum.member?/2`, as they will fetch and discard events from the channel to get their results. When using the channel as an Enumerable, use only collection processing functions, preferably from the `Stream` module. """ end end defimpl Collectable do def into(channel) do {channel, fn channel, {:cont, x} -> :ok = CSP.Channel.put(channel, x) channel channel, :done -> channel _, :halt -> :ok end} end end defimpl Inspect do import Inspect.Algebra def inspect(channel, opts) do state = if CSP.Channel.closed?(channel) do "closed" else "open" end concat(["#Channel<ref=", to_doc(channel.ref, opts), ", state=", state, ">"]) end end end
lib/csp/channel.ex
0.908187
0.66651
channel.ex
starcoder
defmodule Xgit.FileMode do @moduledoc ~S""" Describes the file type as represented on disk. """ import Xgit.Util.ForceCoverage @typedoc ~S""" An integer describing the file type as represented on disk. Git uses a variation on the Unix file permissions flags to denote a file's intended type on disk. The following values are recognized: * `0o100644` - normal file * `0o100755` - executable file * `0o120000` - symbolic link * `0o040000` - tree (subdirectory) * `0o160000` - submodule (aka gitlink) This module is intended to be `use`d. Doing so will create an `alias` to the module so as to make `FileMode.t` available for typespecs and will `import` the `is_file_mode/1` guard. """ @type t :: 0o100644 | 0o100755 | 0o120000 | 0o040000 | 0o160000 @doc "Mode indicating an entry is a tree (aka directory)." @spec tree :: t def tree, do: cover(0o040000) @doc "Mode indicating an entry is a symbolic link." @spec symlink :: t def symlink, do: cover(0o120000) @doc "Mode indicating an entry is a non-executable file." @spec regular_file :: t def regular_file, do: cover(0o100644) @doc "Mode indicating an entry is an executable file." @spec executable_file :: t def executable_file, do: cover(0o100755) @doc "Mode indicating an entry is a submodule commit in another repository." @spec gitlink :: t def gitlink, do: cover(0o160000) @doc "Return `true` if the file mode represents a tree." @spec tree?(file_mode :: term) :: boolean def tree?(file_mode) def tree?(0o040000), do: cover(true) def tree?(_), do: cover(false) @doc "Return `true` if the file mode a symbolic link." @spec symlink?(file_mode :: term) :: boolean def symlink?(file_mode) def symlink?(0o120000), do: cover(true) def symlink?(_), do: cover(false) @doc "Return `true` if the file mode represents a regular file." @spec regular_file?(file_mode :: term) :: boolean def regular_file?(file_mode) def regular_file?(0o100644), do: cover(true) def regular_file?(_), do: cover(false) @doc "Return `true` if the file mode represents an executable file." @spec executable_file?(file_mode :: term) :: boolean def executable_file?(file_mode) def executable_file?(0o100755), do: cover(true) def executable_file?(_), do: cover(false) @doc "Return `true` if the file mode represents a submodule commit in another repository." @spec gitlink?(file_mode :: term) :: boolean def gitlink?(file_mode) def gitlink?(0o160000), do: cover(true) def gitlink?(_), do: cover(false) @doc ~S""" Return `true` if the value is one of the known file mode values. """ @spec valid?(term) :: boolean def valid?(0o040000), do: cover(true) def valid?(0o120000), do: cover(true) def valid?(0o100644), do: cover(true) def valid?(0o100755), do: cover(true) def valid?(0o160000), do: cover(true) def valid?(_), do: cover(false) @valid_file_modes [0o100644, 0o100755, 0o120000, 0o040000, 0o160000] @doc ~S""" Return a rendered version of this file mode as an octal charlist. No leading zeros are included. Optimized for the known file modes. Errors out for any other mode. """ @spec to_short_octal(file_mode :: t) :: charlist def to_short_octal(file_mode) def to_short_octal(0o040000), do: cover('40000') def to_short_octal(0o120000), do: cover('120000') def to_short_octal(0o100644), do: cover('100644') def to_short_octal(0o100755), do: cover('100755') def to_short_octal(0o160000), do: cover('160000') @doc ~S""" This guard requires the value to be one of the known git file mode values. """ defguard is_file_mode(t) when t in @valid_file_modes defmacro __using__(opts) do quote location: :keep, bind_quoted: [opts: opts] do alias Xgit.FileMode import Xgit.FileMode, only: [is_file_mode: 1] end end end
lib/xgit/file_mode.ex
0.85081
0.407805
file_mode.ex
starcoder
defmodule AoC.Intcode.PaintingRobot do @moduledoc false use Task def initialize(initial_state \\ %{}) do %{ state: :ready, cpu: nil, position: {0, 0}, heading: :up, known_panels: %{}, default_color: :black, pending_color: nil, pending_direction: nil, trace: false } |> Map.merge(initial_state) |> run() end defp run(%{state: :ready} = state) do receive do :start -> run(%{state | state: :running}) :term -> {:halt, %{state | state: :term}} end end defp run(%{state: :running, pending_color: nil} = state) do state = read_camera(state) receive do :term -> {:halt, %{state | state: :term}} color -> run(%{state | pending_color: color}) end end defp run(%{state: :running, pending_direction: nil} = state) do receive do :term -> {:halt, %{state | state: :term}} direction -> run(%{state | pending_direction: direction}) end end defp run(%{state: :running, pending_color: color, pending_direction: direction} = state) do new_state = execute_instructions(state, {color, direction}) run(%{new_state | pending_color: nil, pending_direction: nil}) end defp execute_instructions( %{known_panels: panels, position: position, heading: :up} = state, {0, 0} ), do: %{ state | known_panels: paint_panel(panels, position, :black, state.trace), heading: :left, position: update_position(position, :left, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :up} = state, {1, 0} ), do: %{ state | known_panels: paint_panel(panels, position, :white, state.trace), heading: :left, position: update_position(position, :left, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :left} = state, {0, 0} ), do: %{ state | known_panels: paint_panel(panels, position, :black, state.trace), heading: :down, position: update_position(position, :down, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :left} = state, {1, 0} ), do: %{ state | known_panels: paint_panel(panels, position, :white, state.trace), heading: :down, position: update_position(position, :down, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :down} = state, {0, 0} ), do: %{ state | known_panels: paint_panel(panels, position, :black, state.trace), heading: :right, position: update_position(position, :right, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :down} = state, {1, 0} ), do: %{ state | known_panels: paint_panel(panels, position, :white, state.trace), heading: :right, position: update_position(position, :right, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :right} = state, {0, 0} ), do: %{ state | known_panels: paint_panel(panels, position, :black, state.trace), heading: :up, position: update_position(position, :up, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :right} = state, {1, 0} ), do: %{ state | known_panels: paint_panel(panels, position, :white, state.trace), heading: :up, position: update_position(position, :up, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :up} = state, {0, 1} ), do: %{ state | known_panels: paint_panel(panels, position, :black, state.trace), heading: :right, position: update_position(position, :right, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :up} = state, {1, 1} ), do: %{ state | known_panels: paint_panel(panels, position, :white, state.trace), heading: :right, position: update_position(position, :right, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :left} = state, {0, 1} ), do: %{ state | known_panels: paint_panel(panels, position, :black, state.trace), heading: :up, position: update_position(position, :up, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :left} = state, {1, 1} ), do: %{ state | known_panels: paint_panel(panels, position, :white, state.trace), heading: :up, position: update_position(position, :up, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :down} = state, {0, 1} ), do: %{ state | known_panels: paint_panel(panels, position, :black, state.trace), heading: :left, position: update_position(position, :left, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :down} = state, {1, 1} ), do: %{ state | known_panels: paint_panel(panels, position, :white, state.trace), heading: :left, position: update_position(position, :left, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :right} = state, {0, 1} ), do: %{ state | known_panels: paint_panel(panels, position, :black, state.trace), heading: :down, position: update_position(position, :down, state.trace) } defp execute_instructions( %{known_panels: panels, position: position, heading: :right} = state, {1, 1} ), do: %{ state | known_panels: paint_panel(panels, position, :white, state.trace), heading: :down, position: update_position(position, :down, state.trace) } defp paint_panel(panels, position, color, true) do if Map.has_key?(panels, position) do IO.puts("repainting #{inspect(position)} #{inspect(color)}") else IO.puts("painting #{inspect(position)} #{inspect(color)}") end paint_panel(panels, position, color, false) end defp paint_panel(panels, position, color, _), do: Map.put(panels, position, color) defp read_camera(%{position: position, known_panels: panels, cpu: cpu} = state) do color_number = panels |> Map.get(position, state.default_color) |> convert_color_to_number() send(cpu.pid, color_number) state end defp convert_color_to_number(:black), do: 0 defp convert_color_to_number(:white), do: 1 defp update_position(position, :up, true) do IO.puts("facing up and moving forward") update_position(position, :up, false) end defp update_position(position, :left, true) do IO.puts("facing left and moving forward") update_position(position, :left, false) end defp update_position(position, :down, true) do IO.puts("facing down and moving forward") update_position(position, :down, false) end defp update_position(position, :right, true) do IO.puts("facing right and moving forward") update_position(position, :right, false) end defp update_position({x, y}, :up, _), do: {x, y - 1} defp update_position({x, y}, :left, _), do: {x - 1, y} defp update_position({x, y}, :down, _), do: {x, y + 1} defp update_position({x, y}, :right, _), do: {x + 1, y} end
lib/aoc/intcode/painting_robot.ex
0.792986
0.546315
painting_robot.ex
starcoder
defmodule Sentix.Bridge do @moduledoc """ This module provides the bridge between Sentix and `fswatch`, via an Erlang port. This is where any translation will be done in order to handle the types of communication between the port and the program. """ # add internal aliases alias __MODULE__.Command alias __MODULE__.Options alias Sentix.Cache @doc """ Opens a bridged port to `fswatch`, using the provided paths and options. We listen on `stdout` from `fswatch` so that we may forward the output to any subscribers. In addition, we monitor the port to ensure that any host server will crash if the port does, allowing Supervision trees to restart the ports. The options available are described in `Sentix.start_link/3`, so please view documentation there for further information. """ @spec open(paths :: [ binary ], options :: Keyword.t) :: { :ok, pid, process :: number } | { :error, reason :: atom } | { :error, reason :: binary } def open(paths, options \\ []) when is_list(paths) and is_list(options) do with { :ok, exe } <- Cache.find_binary('fswatch'), { :ok, opts } <- Options.parse(options), { :ok, cmd } <- Command.generate(exe, opts, paths), do: :exec.run(cmd, [ :stdout, :stderr, :monitor ]) end @doc """ Converts an event name between the Sentix representation and the `fswatch` representation. The conversion technique used is determined by the type of the passed in event, as atoms are converted to `fswatch` style, and binaries are converted to Sentix style. """ @spec convert_name(event :: atom | binary) :: event :: binary | atom def convert_name(event) when is_binary(event) do event |> Macro.underscore |> String.to_atom end def convert_name(event) when is_atom(event) do event |> Kernel.to_string |> Macro.camelize end @doc """ Similar to `convert_name/1` but with the ability to enforce a type. This means that we can safely no-op if we already have the style of name we want. """ @spec convert_name(event :: atom | binary, style :: binary) :: event :: binary | atom def convert_name(event, "atom") when is_atom(event), do: event def convert_name(event, "binary") when is_binary(event), do: event def convert_name(event, _style), do: convert_name(event) @doc """ Returns the separator for use when splitting fswatch events. """ @spec divider :: binary def divider do "__stx__" end @doc """ Locates the port driver for the current toolchain. This is done via a wildcard search, as the name of the port is not deterministic due to the upstream naming incorrectly. We simply fetch a wildcard of ports and find the first one which contains the current osname in the directory name. """ @spec locate_port :: path :: binary | nil def locate_port do { _family, osname } = :os.type() priv = :code.priv_dir(:erlexec) '*/exec-port' |> :filelib.wildcard(priv) |> filter_port(osname) |> join_port(priv) end # Filters a list of ports by using a very basic fuzzy match to determine which # of the discovered ports might be the correct one for this system. If there's # only one, it's practically guaranteed to be found correctly. defp filter_port(ports, osname) do str_name = to_string(osname) Enum.find(ports, fn(port) -> port |> Kernel.to_string |> String.contains?(str_name) end) end # Joins a port with the priv directory to make sure that we use an absolute # path when referring to it to avoid any issues with relative lookups. defp join_port(port, priv) do priv |> Path.join(port) |> :binary.bin_to_list end end
lib/sentix/bridge.ex
0.860677
0.609146
bridge.ex
starcoder
defmodule Booklist.Reports do @moduledoc """ The Reports context. """ import Ecto.Query, warn: false alias Booklist.Repo alias Booklist.Admin.Rating @doc """ Gets lowest rating for the year, or nil if none exists """ def get_lowest_rating(year) do from(r in Rating, join: book in assoc(r, :book), preload: [book: book], where: fragment("EXTRACT(year FROM ?)", r.date_scored) == ^year, order_by: [asc: r.score, desc: r.id], limit: 1) |> Repo.one end @doc """ Gets the top ratings for the given year up to the limit """ def get_top_ratings(year, limit) do from(r in Rating, join: book in assoc(r, :book), preload: [book: book], where: fragment("EXTRACT(year FROM ?)", r.date_scored) == ^year, order_by: [desc: r.score, desc: r.id], limit: ^limit) |> Repo.all end def get_rating_statistics(year) do from(r in Rating, where: fragment("EXTRACT(year FROM ?)", r.date_scored) == ^year, select: %{count: count(r.id), average: coalesce(avg(r.score), 0)}) |> Repo.one end @doc """ Gets the week number and number of ratings (books read) in that week for the given year How to group by using alias based on: https://angelika.me/2016/09/10/how-to-order-by-the-result-of-select-count-in-ecto/ """ def get_ratings_count_by_week_base_query(year) do #need to create rating subquery or weeks with 0 ratings won't be returned rating_subquery = from( r in Rating, where: fragment("EXTRACT(year FROM ?)", r.date_scored) == ^year, select: %{ id: r.id, date_scored: r.date_scored, } ) from( r in subquery(rating_subquery), right_join: week_number in fragment("SELECT generate_series(1,53) AS week_number"), on: fragment("week_number = extract(week FROM ?)", r.date_scored), group_by: [fragment("week_number")], select: %{ week_number: fragment("week_number"), count: count(r.id) }, order_by: [fragment("week_number")] ) end def get_ratings_count_by_week_query(year, should_limit) do case should_limit do #limit results only to weeks in current year true -> get_ratings_count_by_week_base_query(year) |> limit(fragment("SELECT EXTRACT(WEEK FROM current_timestamp)")) false -> get_ratings_count_by_week_base_query(year) end end @doc """ Gets the week number and number of ratings (books read) in that week for the given year """ def get_ratings_count_by_week(year, should_limit) when is_boolean(should_limit) do get_ratings_count_by_week_query(year, should_limit) |> Repo.all end end
lib/booklist/admin/reports.ex
0.529993
0.507385
reports.ex
starcoder
defmodule Core.Utils.Converter do @moduledoc """ Pure elixir trytes/trits/integer converter. """ alias Core.Utils.Struct.Transaction @trytesAlphabet "9ABCDEFGHIJKLMNOPQRSTUVWXYZ" # All possible tryte values # map of all trits representations @trytesTrits [ [ 0, 0, 0], [ 1, 0, 0], [-1, 1, 0], [ 0, 1, 0], [ 1, 1, 0], [-1, -1, 1], [ 0, -1, 1], [ 1, -1, 1], [-1, 0, 1], [ 0, 0, 1], [ 1, 0, 1], [-1, 1, 1], [ 0, 1, 1], [ 1, 1, 1], [-1, -1, -1], [ 0, -1, -1], [ 1, -1, -1], [-1, 0, -1], [ 0, 0, -1], [ 1, 0, -1], [-1, 1, -1], [ 0, 1, -1], [ 1, 1, -1], [-1, -1, 0], [ 0, -1, 0], [ 1, -1, 0], [-1, 0, 0] ] for <<tryte::1-bytes <- @trytesAlphabet>> do {index, _} = :binary.match(@trytesAlphabet, tryte) trits = Enum.at(@trytesTrits, index) def trits?(unquote(tryte)) do unquote(trits) end end # convert trytes to integer @spec trytes_to_integer(binary) :: integer def trytes_to_integer(trytes) when is_binary(trytes) do trits_to_integer(trytes_to_trits(trytes)) end # convert trits to integer @spec trits_to_integer(list) :: integer def trits_to_integer(trits) do trits_to_integer(trits, 0) end @spec trits_to_integer(list, integer) :: integer defp trits_to_integer([], returnvalue) do returnvalue end @spec trits_to_integer(list, integer) :: integer defp trits_to_integer([trit | trits], returnvalue) do returnvalue = returnvalue*3 + trit trits_to_integer(trits, returnvalue) end # convert trytes to trits @spec trytes_to_trits(binary) :: list def trytes_to_trits(trytes) when is_binary(trytes) do trytes_to_trits(trytes, []) end @spec trytes_to_trits(binary,list) :: list defp trytes_to_trits(<<tryte::1-bytes, trytes::binary>>, acc) do acc = revrese_acc(trits?(tryte), acc) trytes_to_trits(trytes, acc) end @spec trytes_to_trits(binary,list) :: list defp trytes_to_trits(<<>>, acc) do acc end @spec revrese_acc(list,list) :: list defp revrese_acc([h | t], acc) do revrese_acc(t, [h | acc]) end @spec revrese_acc(list,list) :: list defp revrese_acc([], acc) do acc end @doc """ convert dmp file line to tx_object. """ @spec line_to_tx_object(binary) :: Transaction.t def line_to_tx_object(line) do # pattern matching <<hash::81-bytes,_,signature::2187-bytes,address::81-bytes,value::27-bytes, obsolete_tag::27-bytes,timestamp::9-bytes,current_index::9-bytes, last_index::9-bytes,bundle_hash::81-bytes, trunk::81-bytes, branch::81-bytes,tag::27-bytes, atime::9-bytes, alower::9-bytes, aupper::9-bytes, nonce::27-bytes,_,snapshot_index::binary>> = line # - First we convert some columns to varinteger form. last_index = trytes_to_integer(last_index) current_index = trytes_to_integer(current_index) value = trytes_to_integer(value) timestamp = trytes_to_integer(timestamp) atime = trytes_to_integer(atime) alower = trytes_to_integer(alower) aupper = trytes_to_integer(aupper) snapshot_index = String.to_integer(String.trim(snapshot_index, "\n")) # - Put transaction line in map. Transaction.create(signature, address,value, obsolete_tag,timestamp, current_index,last_index,bundle_hash,trunk,branch,tag,atime, alower,aupper,nonce,hash,snapshot_index) end @doc """ convert dmp file line to tx_object. """ @spec line_81_to_tx_object(binary,binary) :: Transaction.t def line_81_to_tx_object(line,snapshot_index) do # pattern matching <<hash::81-bytes,_,signature::2187-bytes,address::81-bytes,value::27-bytes, obsolete_tag::27-bytes,timestamp::9-bytes,current_index::9-bytes, last_index::9-bytes,bundle_hash::81-bytes, trunk::81-bytes, branch::81-bytes, nonce::81-bytes,_>> = line # - First we convert some columns to varinteger form. last_index = trytes_to_integer(last_index) current_index = trytes_to_integer(current_index) value = trytes_to_integer(value) timestamp = trytes_to_integer(timestamp) # - Put transaction line in map. Transaction.create(signature, address,value, obsolete_tag,timestamp, current_index,last_index,bundle_hash,trunk,branch,nil,nil, nil,nil,nonce,hash,snapshot_index) end @doc """ convert dmp file line to tx_object. """ @spec line_81_to_tx_object(binary) :: Transaction.t def line_81_to_tx_object(line) do # pattern matching <<hash::81-bytes,_,signature::2187-bytes,address::81-bytes,value::27-bytes, obsolete_tag::27-bytes,timestamp::9-bytes,current_index::9-bytes, last_index::9-bytes,bundle_hash::81-bytes, trunk::81-bytes, branch::81-bytes, nonce::81-bytes,_,snapshot_index::binary>> = line # - First we convert some columns to varinteger form. last_index = trytes_to_integer(last_index) current_index = trytes_to_integer(current_index) value = trytes_to_integer(value) timestamp = trytes_to_integer(timestamp) snapshot_index = String.to_integer(String.trim(snapshot_index, "\n")) # - Put transaction line in map. Transaction.create(signature, address,value, obsolete_tag,timestamp, current_index,last_index,bundle_hash,trunk,branch,nil,nil, nil,nil,nonce,hash,snapshot_index) end @doc """ Convert trytes to tx-object """ @spec trytes_to_tx_object(binary, binary, integer) :: Transaction.t def trytes_to_tx_object(hash, trytes, snapshot_index) do <<signature::2187-bytes,address::81-bytes,value::27-bytes, obsolete_tag::27-bytes,timestamp::9-bytes,current_index::9-bytes, last_index::9-bytes,bundle_hash::81-bytes, trunk::81-bytes, branch::81-bytes,tag::27-bytes, atime::9-bytes, alower::9-bytes, aupper::9-bytes, nonce::27-bytes>> = trytes # - First we convert some columns to varinteger form. last_index = trytes_to_integer(last_index) current_index = trytes_to_integer(current_index) value = trytes_to_integer(value) timestamp = trytes_to_integer(timestamp) atime = trytes_to_integer(atime) alower = trytes_to_integer(alower) aupper = trytes_to_integer(aupper) # - Put transaction line in map. Transaction.create(signature, address,value, obsolete_tag,timestamp, current_index,last_index,bundle_hash,trunk,branch,tag,atime, alower,aupper,nonce,hash,snapshot_index,trytes) end end
apps/core/lib/utils/converter/converter.ex
0.551815
0.459986
converter.ex
starcoder
defmodule Alfred.ResultList do @moduledoc """ Represents a list of `Alfred.Result` items. Since a result list can contain other information such as variables, it is useful sometimes to create an explicit list for results. """ alias Alfred.Result @type t :: %__MODULE__{ items: [Result.t()], variables: %{optional(String.t()) => String.t()}, rerun: float | nil } defstruct items: [], rerun: nil, variables: %{} @doc """ Creates a new result list. ## Options * `:rerun` &mdash; Instructs Alfred to rerun the script every given number of seconds, must be between 1.0 and 5.0 inclusive * `:variables` &mdash; A `Map` of variables to return with the result list ## Examples Creating a list of items: iex> result = Alfred.Result.new("title", "subtitle") iex> Alfred.ResultList.new([result, result, result]) %Alfred.ResultList{items: [%Alfred.Result{subtitle: "subtitle", title: "title"}, %Alfred.Result{subtitle: "subtitle", title: "title"}, %Alfred.Result{subtitle: "subtitle", title: "title"}]} Creating a list of items and including variables: iex> result = Alfred.Result.new("title", "subtitle") iex> Alfred.ResultList.new([result, result, result], variables: %{foo: "bar"}) %Alfred.ResultList{items: [%Alfred.Result{subtitle: "subtitle", title: "title"}, %Alfred.Result{subtitle: "subtitle", title: "title"}, %Alfred.Result{subtitle: "subtitle", title: "title"}], variables: %{foo: "bar"}} Creating a list of items with variables and a rerun value: iex> result = Alfred.Result.new("title", "subtitle") iex> Alfred.ResultList.new([result, result, result], variables: %{foo: "bar"}, rerun: 3.0) %Alfred.ResultList{items: [%Alfred.Result{subtitle: "subtitle", title: "title"}, %Alfred.Result{subtitle: "subtitle", title: "title"}, %Alfred.Result{subtitle: "subtitle", title: "title"}], rerun: 3.0, variables: %{foo: "bar"}} """ @spec new([Result.t()], Keyword.t()) :: t def new(items \\ [], options \\ []) def new(items, options) when is_list(items) do variables = variables_option(options) rerun = rerun_option(options) %__MODULE__{items: items, variables: variables, rerun: rerun} end def new(map, options) when is_map(map), do: new([map], options) def new(value, _), do: raise( ArgumentError, "items must be an `Alfred.Result` or a list, you gave #{inspect(value)} instead" ) @doc """ Converts the given list to the expected output format. See the Alfred documentation on [the JSON output format.][json-output] [json-output]: https://www.alfredapp.com/help/workflows/inputs/script-filter/json/ """ @spec to_json(t) :: String.t() def to_json(list) do list |> convert_result_list |> Poison.encode() end defp convert_items(items) do Enum.map(items, fn item -> convert_item(item) end) end defp convert_result_list(list) do %{} |> insert_items(list) |> insert_variables(list) |> insert_rerun(list) end defp convert_item(struct) do Enum.reduce(Map.keys(struct), %{}, fn key, map -> case Map.get(struct, key) do nil -> map value -> Map.put(map, key, value) end end) end defp insert_items(map, %{items: items}) do Map.put(map, :items, convert_items(items)) end defp insert_rerun(map, %{rerun: rerun}) do case rerun do nil -> map _ -> Map.put(map, :rerun, rerun) end end defp insert_variables(map, %{variables: variables}) do case Enum.count(variables) do 0 -> map _ -> Map.put(map, :variables, variables) end end defp rerun_option(options) do options |> Keyword.get(:rerun) |> validate_rerun_option end defp validate_rerun_option(nil), do: nil defp validate_rerun_option(rerun) when not is_number(rerun) do raise ArgumentError, ":rerun must be a number or nil" end defp validate_rerun_option(rerun) when rerun < 1.0 or rerun > 5.0 do raise ArgumentError, ":rerun must be between 1.0 and 5.0 inclusive" end defp validate_rerun_option(rerun), do: rerun defp variables_option(options), do: Keyword.get(options, :variables, %{}) end
lib/alfred/result_list.ex
0.883742
0.466785
result_list.ex
starcoder
defmodule Squitter.StatsTracker do use GenServer require Logger @rate_buffer_size 500 def start_link(clock) do GenServer.start_link(__MODULE__, [clock], name: __MODULE__) end def init([clock]) do Logger.debug("Starting up #{__MODULE__}") counts = :array.new(@rate_buffer_size, default: 0) times = :array.new(@rate_buffer_size, default: System.monotonic_time(:millisecond)) schedule_tick(clock) {:ok, %{rate: 0.0, clock: clock, position: 0, totals: %{}, counts: counts, times: times}} end def handle_cast({:dispatched, counts}, state) do {time, %{received: received} = totals} = counts new_totals = calculate_totals(totals, state.totals) counts = :array.set(state.position, received, state.counts) times = :array.set(state.position, time, state.times) next_position = if state.position + 1 >= @rate_buffer_size, do: 0, else: state.position + 1 {:noreply, %{state | totals: new_totals, counts: counts, times: times, position: next_position}} end def handle_cast({:count, {type, count}}, state) do new_totals = Map.update(state.totals, type, count, fn current -> count + current end) {:noreply, %{state | totals: new_totals}} end def handle_info(:tick, state) do times = :array.to_list(state.times) counts = :array.to_list(state.counts) rate = calculate_rate(times, counts) Logger.debug(fn -> "[stats] #{format_stats({rate, state.totals})}" end) schedule_tick(state.clock) {:noreply, %{state | rate: rate}} end defp calculate_rate(times, counts) do count = Enum.sum(counts) {oldest, newest} = Enum.min_max(times) time_diff = (newest - oldest) / 1000 if time_diff > 0, do: Float.round(count / time_diff, 1), else: 0.0 end defp calculate_totals(totals, acc) do Map.merge(totals, acc, fn _k, ct, ca -> ct + ca end) end defp format_stats({rate, totals}) do [ "rate=#{rate}/sec" | Enum.map(totals, fn {k, v} -> key = format_total_key(k) "#{key}=#{v}" end) ] |> Enum.join("\n") end defp format_total_key(key) when is_tuple(key) do format_total_key(Tuple.to_list(key)) end defp format_total_key(key) when is_atom(key) do to_string(key) end defp format_total_key(key) when is_list(key) do Enum.join(key, ".") end defp schedule_tick(time) do Process.send_after(self(), :tick, time) end ## Client API @spec dispatched({number(), map}) :: :ok def dispatched({_time, _counts} = event) do GenServer.cast(__MODULE__, {:dispatched, event}) end def count(type, count \\ 1) do GenServer.cast(__MODULE__, {:count, {type, count}}) end end
squitter/lib/squitter/stats_tracker.ex
0.525612
0.484685
stats_tracker.ex
starcoder
defmodule MangoPay.PreAuthorization do @moduledoc """ Functions for MangoPay [pre authorization](https://docs.mangopay.com/endpoints/v2.01/preauthorizations#e183_the-preauthorization-object). """ use MangoPay.Query.Base set_path "preauthorizations" @doc """ Get a preauthorization. ## Examples {:ok, preauthorization} = MangoPay.PreAuthorization.get(id) """ def get id do _get id end @doc """ Get a preauthorization. ## Examples preauthorization = MangoPay.PreAuthorization.get!(id) """ def get! id do _get! id end @doc """ Create a preauthorization. ## Examples params = %{ "Tag": "custom meta", "AuthorId": "8494514", "DebitedFunds": %{ "Currency": "EUR", "Amount": 12 }, "Billing": %{ "Address": %{ "AddressLine1": "1 Mangopay Street", "AddressLine2": "The Loop", "City": "Paris", "Region": "Ile de France", "PostalCode": "75001", "Country": "FR" } }, "SecureMode": "DEFAULT", "CardId": "14213157", "SecureModeReturnURL": "http://www.my-site.com/returnURL" } {:ok, preauthorization} = MangoPay.PreAuthorization.create(params) """ def create params do _create params, "/card/direct" end @doc """ Create a preauthorization. ## Examples params = %{ "Tag": "custom meta", "AuthorId": "8494514", "DebitedFunds": %{ "Currency": "EUR", "Amount": 12 }, "Billing": %{ "Address": %{ "AddressLine1": "1 Mangopay Street", "AddressLine2": "The Loop", "City": "Paris", "Region": "Ile de France", "PostalCode": "75001", "Country": "FR" } }, "SecureMode": "DEFAULT", "CardId": "14213157", "SecureModeReturnURL": "http://www.my-site.com/returnURL" } preauthorization = MangoPay.PreAuthorization.create!(params) """ def create! params do _create! params, "/card/direct" end @doc """ Cancel a preauthorization. ## Examples params = %{ "Tag": "custom meta", "PaymentStatus": "CANCELED" } {:ok, preauthorization} = MangoPay.PreAuthorization.cancel("preauthorization_id", params) """ def cancel id, params do _update params, id end @doc """ Cancel a preauthorization. ## Examples params = %{ "Tag": "custom meta", "PaymentStatus": "CANCELED" } preauthorization = MangoPay.PreAuthorization.cancel!("preauthorization_id", params) """ def cancel! id, params do _update! params, id end @doc """ List all preauthorizations for a credit card. ## Examples {:ok, preauthorizations} = MangoPay.PreAuthorization.all_by_card("card_id") """ def all_by_card id, query \\ %{} do _all [MangoPay.Card.path(id), resource()], query end @doc """ List all preauthorizations for a credit card. ## Examples preauthorizations = MangoPay.PreAuthorization.all_by_card!("card_id") """ def all_by_card! id, query \\ %{} do _all! [MangoPay.Card.path(id), resource()], query end @doc """ List all preauthorizations for a user. ## Examples user_id = Id of a user object query = %{ "Page": 1, "Per_Page": 25, "Sort": "CreationDate:DESC", "ResultCode": "000000,009199", "Status": "CREATED", "PaymentStatus": "WAITING" } {:ok, preauthorizations} = MangoPay.PreAuthorization.all_by_user(user_id, query) """ def all_by_user id, query \\ %{} do _all [MangoPay.User.path(id), resource()], query end @doc """ List all preauthorizations for a user. ## Examples user_id = Id of a user query = %{ "Page": 1, "Per_Page": 25, "Sort": "CreationDate:DESC", "ResultCode": "000000,009199", "Status": "CREATED", "PaymentStatus": "WAITING" } preauthorizations = MangoPay.PreAuthorization.all_by_user!(user_id, query) """ def all_by_user! id, query \\ %{} do _all! [MangoPay.User.path(id), resource()], query end end
lib/mango_pay/preauthorization.ex
0.778144
0.459137
preauthorization.ex
starcoder
defmodule Membrane.AAC do @moduledoc """ Capabilities for [Advanced Audio Codec](https://wiki.multimedia.cx/index.php/Understanding_AAC). """ @type profile_t :: :main | :LC | :SSR | :LTP | :HE | :HEv2 @type mpeg_version_t :: 2 | 4 @type samples_per_frame_t :: 1024 | 960 @typedoc """ Indicates whether stream contains AAC frames only or are they encapsulated in [ADTS](https://wiki.multimedia.cx/index.php/ADTS) """ @type encapsulation_t :: :none | :ADTS @typedoc """ Identifiers of [MPEG Audio Object Types](https://wiki.multimedia.cx/index.php/MPEG-4_Audio#Audio_Object_Types) """ @type audio_object_type_id_t :: 1..5 | 29 @typedoc """ Identifiers of [MPEG Audio sampling frequencies](https://wiki.multimedia.cx/index.php/MPEG-4_Audio#Sampling_Frequencies) """ @type sampling_frequency_id_t :: 0..12 | 15 @typedoc """ Identifiers of [MPEG Audio channel configurations](https://wiki.multimedia.cx/index.php/MPEG-4_Audio#Channel_Configurations) """ @type channel_config_id_t :: 0..7 @typedoc """ AAC frame length identifiers. `0` indicates 1024 samples/frame and `1` - 960 samples/frame. """ @type frame_length_id_t :: 0 | 1 @type t :: %__MODULE__{ profile: profile_t, mpeg_version: mpeg_version_t, sample_rate: pos_integer, channels: pos_integer, samples_per_frame: 1024 | 960, frames_per_buffer: pos_integer, encapsulation: encapsulation_t } @enforce_keys [ :profile, :sample_rate, :channels ] defstruct @enforce_keys ++ [ mpeg_version: 2, samples_per_frame: 1024, frames_per_buffer: 1, encapsulation: :none ] @audio_object_type BiMap.new(%{ 1 => :main, 2 => :LC, 3 => :SSR, 4 => :LTP, 5 => :HE, 29 => :HEv2 }) @sampling_frequency BiMap.new(%{ 0 => 96000, 1 => 88200, 2 => 64000, 3 => 48000, 4 => 44100, 5 => 32000, 6 => 24000, 7 => 22050, 8 => 16000, 9 => 12000, 10 => 11025, 11 => 8000, 12 => 7350, 15 => :explicit }) @channel_config BiMap.new(%{ 0 => :AOT_specific, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 8 }) @frame_length BiMap.new(%{ 0 => 1024, 1 => 960 }) @spec aot_id_to_profile(audio_object_type_id_t) :: profile_t def aot_id_to_profile(audio_object_type_id), do: BiMap.fetch!(@audio_object_type, audio_object_type_id) @spec profile_to_aot_id(profile_t) :: audio_object_type_id_t def profile_to_aot_id(profile), do: BiMap.fetch_key!(@audio_object_type, profile) @spec sampling_frequency_id_to_sample_rate(sampling_frequency_id_t) :: pos_integer def sampling_frequency_id_to_sample_rate(sampling_frequency_id), do: BiMap.fetch!(@sampling_frequency, sampling_frequency_id) @spec sample_rate_to_sampling_frequency_id(sample_rate :: pos_integer | :explicit) :: sampling_frequency_id_t def sample_rate_to_sampling_frequency_id(sample_rate), do: BiMap.fetch_key!(@sampling_frequency, sample_rate) @spec channel_config_id_to_channels(channel_config_id_t) :: pos_integer | :AOT_specific def channel_config_id_to_channels(channel_config_id), do: BiMap.fetch!(@channel_config, channel_config_id) @spec channels_to_channel_config_id(channels :: pos_integer | :AOT_specific) :: channel_config_id_t def channels_to_channel_config_id(channels), do: BiMap.fetch_key!(@channel_config, channels) @spec frame_length_id_to_samples_per_frame(frame_length_id_t) :: samples_per_frame_t def frame_length_id_to_samples_per_frame(frame_length_id), do: BiMap.fetch!(@frame_length, frame_length_id) @spec samples_per_frame_to_frame_length_id(samples_per_frame_t) :: pos_integer def samples_per_frame_to_frame_length_id(samples_per_frame), do: BiMap.fetch_key!(@frame_length, samples_per_frame) end
lib/membrane_aac_format/aac.ex
0.865977
0.562417
aac.ex
starcoder
defmodule AWS.SNS do @moduledoc """ Amazon Simple Notification Service Amazon Simple Notification Service (Amazon SNS) is a web service that enables you to build distributed web-enabled applications. Applications can use Amazon SNS to easily push real-time notification messages to interested subscribers over multiple delivery protocols. For more information about this product see the [Amazon SNS product page](http://aws.amazon.com/sns/). For detailed information about Amazon SNS features and their associated API calls, see the [Amazon SNS Developer Guide](https://docs.aws.amazon.com/sns/latest/dg/). For information on the permissions you need to use this API, see [Identity and access management in Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/sns-authentication-and-access-control.html) in the *Amazon SNS Developer Guide.* We also provide SDKs that enable you to access Amazon SNS from your preferred programming language. The SDKs contain functionality that automatically takes care of tasks such as: cryptographically signing your service requests, retrying requests, and handling error responses. For a list of available SDKs, go to [Tools for Amazon Web Services](http://aws.amazon.com/tools/). """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: "Amazon SNS", api_version: "2010-03-31", content_type: "application/x-www-form-urlencoded", credential_scope: nil, endpoint_prefix: "sns", global?: false, protocol: "query", service_id: "SNS", signature_version: "v4", signing_name: "sns", target_prefix: nil } end @doc """ Adds a statement to a topic's access control policy, granting access for the specified Amazon Web Services accounts to the specified actions. """ def add_permission(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "AddPermission", input, options) end @doc """ Accepts a phone number and indicates whether the phone holder has opted out of receiving SMS messages from your Amazon Web Services account. You cannot send SMS messages to a number that is opted out. To resume sending messages, you can opt in the number by using the `OptInPhoneNumber` action. """ def check_if_phone_number_is_opted_out(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CheckIfPhoneNumberIsOptedOut", input, options) end @doc """ Verifies an endpoint owner's intent to receive messages by validating the token sent to the endpoint by an earlier `Subscribe` action. If the token is valid, the action creates a new subscription and returns its Amazon Resource Name (ARN). This call requires an AWS signature only when the `AuthenticateOnUnsubscribe` flag is set to "true". """ def confirm_subscription(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ConfirmSubscription", input, options) end @doc """ Creates a platform application object for one of the supported push notification services, such as APNS and GCM (Firebase Cloud Messaging), to which devices and mobile apps may register. You must specify `PlatformPrincipal` and `PlatformCredential` attributes when using the `CreatePlatformApplication` action. `PlatformPrincipal` and `PlatformCredential` are received from the notification service. * For `ADM`, `PlatformPrincipal` is `client id` and `PlatformCredential` is `client secret`. * For `Baidu`, `PlatformPrincipal` is `API key` and `PlatformCredential` is `secret key`. * For `APNS` and `APNS_SANDBOX` using certificate credentials, `PlatformPrincipal` is `SSL certificate` and `PlatformCredential` is `private key`. * For `APNS` and `APNS_SANDBOX` using token credentials, `PlatformPrincipal` is `signing key ID` and `PlatformCredential` is `signing key`. * For `GCM` (Firebase Cloud Messaging), there is no `PlatformPrincipal` and the `PlatformCredential` is `API key`. * For `MPNS`, `PlatformPrincipal` is `TLS certificate` and `PlatformCredential` is `private key`. * For `WNS`, `PlatformPrincipal` is `Package Security Identifier` and `PlatformCredential` is `secret key`. You can use the returned `PlatformApplicationArn` as an attribute for the `CreatePlatformEndpoint` action. """ def create_platform_application(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreatePlatformApplication", input, options) end @doc """ Creates an endpoint for a device and mobile app on one of the supported push notification services, such as GCM (Firebase Cloud Messaging) and APNS. `CreatePlatformEndpoint` requires the `PlatformApplicationArn` that is returned from `CreatePlatformApplication`. You can use the returned `EndpointArn` to send a message to a mobile app or by the `Subscribe` action for subscription to a topic. The `CreatePlatformEndpoint` action is idempotent, so if the requester already owns an endpoint with the same device token and attributes, that endpoint's ARN is returned without creating a new endpoint. For more information, see [Using Amazon SNS Mobile Push Notifications](https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). When using `CreatePlatformEndpoint` with Baidu, two attributes must be provided: ChannelId and UserId. The token field must also contain the ChannelId. For more information, see [Creating an Amazon SNS Endpoint for Baidu](https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePushBaiduEndpoint.html). """ def create_platform_endpoint(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreatePlatformEndpoint", input, options) end @doc """ Adds a destination phone number to an Amazon Web Services account in the SMS sandbox and sends a one-time password (OTP) to that phone number. When you start using Amazon SNS to send SMS messages, your Amazon Web Services account is in the *SMS sandbox*. The SMS sandbox provides a safe environment for you to try Amazon SNS features without risking your reputation as an SMS sender. While your Amazon Web Services account is in the SMS sandbox, you can use all of the features of Amazon SNS. However, you can send SMS messages only to verified destination phone numbers. For more information, including how to move out of the sandbox to send messages without restrictions, see [SMS sandbox](https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html) in the *Amazon SNS Developer Guide*. """ def create_sms_sandbox_phone_number(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateSMSSandboxPhoneNumber", input, options) end @doc """ Creates a topic to which notifications can be published. Users can create at most 100,000 standard topics (at most 1,000 FIFO topics). For more information, see [Creating an Amazon SNS topic](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html) in the *Amazon SNS Developer Guide*. This action is idempotent, so if the requester already owns a topic with the specified name, that topic's ARN is returned without creating a new topic. """ def create_topic(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateTopic", input, options) end @doc """ Deletes the endpoint for a device and mobile app from Amazon SNS. This action is idempotent. For more information, see [Using Amazon SNS Mobile Push Notifications](https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). When you delete an endpoint that is also subscribed to a topic, then you must also unsubscribe the endpoint from the topic. """ def delete_endpoint(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteEndpoint", input, options) end @doc """ Deletes a platform application object for one of the supported push notification services, such as APNS and GCM (Firebase Cloud Messaging). For more information, see [Using Amazon SNS Mobile Push Notifications](https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). """ def delete_platform_application(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeletePlatformApplication", input, options) end @doc """ Deletes an Amazon Web Services account's verified or pending phone number from the SMS sandbox. When you start using Amazon SNS to send SMS messages, your Amazon Web Services account is in the *SMS sandbox*. The SMS sandbox provides a safe environment for you to try Amazon SNS features without risking your reputation as an SMS sender. While your Amazon Web Services account is in the SMS sandbox, you can use all of the features of Amazon SNS. However, you can send SMS messages only to verified destination phone numbers. For more information, including how to move out of the sandbox to send messages without restrictions, see [SMS sandbox](https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html) in the *Amazon SNS Developer Guide*. """ def delete_sms_sandbox_phone_number(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteSMSSandboxPhoneNumber", input, options) end @doc """ Deletes a topic and all its subscriptions. Deleting a topic might prevent some messages previously sent to the topic from being delivered to subscribers. This action is idempotent, so deleting a topic that does not exist does not result in an error. """ def delete_topic(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteTopic", input, options) end @doc """ Retrieves the endpoint attributes for a device on one of the supported push notification services, such as GCM (Firebase Cloud Messaging) and APNS. For more information, see [Using Amazon SNS Mobile Push Notifications](https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). """ def get_endpoint_attributes(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "GetEndpointAttributes", input, options) end @doc """ Retrieves the attributes of the platform application object for the supported push notification services, such as APNS and GCM (Firebase Cloud Messaging). For more information, see [Using Amazon SNS Mobile Push Notifications](https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). """ def get_platform_application_attributes(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "GetPlatformApplicationAttributes", input, options) end @doc """ Returns the settings for sending SMS messages from your Amazon Web Services account. These settings are set with the `SetSMSAttributes` action. """ def get_sms_attributes(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "GetSMSAttributes", input, options) end @doc """ Retrieves the SMS sandbox status for the calling Amazon Web Services account in the target Amazon Web Services Region. When you start using Amazon SNS to send SMS messages, your Amazon Web Services account is in the *SMS sandbox*. The SMS sandbox provides a safe environment for you to try Amazon SNS features without risking your reputation as an SMS sender. While your Amazon Web Services account is in the SMS sandbox, you can use all of the features of Amazon SNS. However, you can send SMS messages only to verified destination phone numbers. For more information, including how to move out of the sandbox to send messages without restrictions, see [SMS sandbox](https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html) in the *Amazon SNS Developer Guide*. """ def get_sms_sandbox_account_status(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "GetSMSSandboxAccountStatus", input, options) end @doc """ Returns all of the properties of a subscription. """ def get_subscription_attributes(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "GetSubscriptionAttributes", input, options) end @doc """ Returns all of the properties of a topic. Topic properties returned might differ based on the authorization of the user. """ def get_topic_attributes(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "GetTopicAttributes", input, options) end @doc """ Lists the endpoints and endpoint attributes for devices in a supported push notification service, such as GCM (Firebase Cloud Messaging) and APNS. The results for `ListEndpointsByPlatformApplication` are paginated and return a limited list of endpoints, up to 100. If additional records are available after the first page results, then a NextToken string will be returned. To receive the next page, you call `ListEndpointsByPlatformApplication` again using the NextToken string received from the previous call. When there are no more records to return, NextToken will be null. For more information, see [Using Amazon SNS Mobile Push Notifications](https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). This action is throttled at 30 transactions per second (TPS). """ def list_endpoints_by_platform_application(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListEndpointsByPlatformApplication", input, options) end @doc """ Lists the calling Amazon Web Services account's dedicated origination numbers and their metadata. For more information about origination numbers, see [Origination numbers](https://docs.aws.amazon.com/sns/latest/dg/channels-sms-originating-identities-origination-numbers.html) in the *Amazon SNS Developer Guide*. """ def list_origination_numbers(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListOriginationNumbers", input, options) end @doc """ Returns a list of phone numbers that are opted out, meaning you cannot send SMS messages to them. The results for `ListPhoneNumbersOptedOut` are paginated, and each page returns up to 100 phone numbers. If additional phone numbers are available after the first page of results, then a `NextToken` string will be returned. To receive the next page, you call `ListPhoneNumbersOptedOut` again using the `NextToken` string received from the previous call. When there are no more records to return, `NextToken` will be null. """ def list_phone_numbers_opted_out(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListPhoneNumbersOptedOut", input, options) end @doc """ Lists the platform application objects for the supported push notification services, such as APNS and GCM (Firebase Cloud Messaging). The results for `ListPlatformApplications` are paginated and return a limited list of applications, up to 100. If additional records are available after the first page results, then a NextToken string will be returned. To receive the next page, you call `ListPlatformApplications` using the NextToken string received from the previous call. When there are no more records to return, `NextToken` will be null. For more information, see [Using Amazon SNS Mobile Push Notifications](https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). This action is throttled at 15 transactions per second (TPS). """ def list_platform_applications(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListPlatformApplications", input, options) end @doc """ Lists the calling Amazon Web Services account's current verified and pending destination phone numbers in the SMS sandbox. When you start using Amazon SNS to send SMS messages, your Amazon Web Services account is in the *SMS sandbox*. The SMS sandbox provides a safe environment for you to try Amazon SNS features without risking your reputation as an SMS sender. While your Amazon Web Services account is in the SMS sandbox, you can use all of the features of Amazon SNS. However, you can send SMS messages only to verified destination phone numbers. For more information, including how to move out of the sandbox to send messages without restrictions, see [SMS sandbox](https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html) in the *Amazon SNS Developer Guide*. """ def list_sms_sandbox_phone_numbers(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListSMSSandboxPhoneNumbers", input, options) end @doc """ Returns a list of the requester's subscriptions. Each call returns a limited list of subscriptions, up to 100. If there are more subscriptions, a `NextToken` is also returned. Use the `NextToken` parameter in a new `ListSubscriptions` call to get further results. This action is throttled at 30 transactions per second (TPS). """ def list_subscriptions(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListSubscriptions", input, options) end @doc """ Returns a list of the subscriptions to a specific topic. Each call returns a limited list of subscriptions, up to 100. If there are more subscriptions, a `NextToken` is also returned. Use the `NextToken` parameter in a new `ListSubscriptionsByTopic` call to get further results. This action is throttled at 30 transactions per second (TPS). """ def list_subscriptions_by_topic(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListSubscriptionsByTopic", input, options) end @doc """ List all tags added to the specified Amazon SNS topic. For an overview, see [Amazon SNS Tags](https://docs.aws.amazon.com/sns/latest/dg/sns-tags.html) in the *Amazon Simple Notification Service Developer Guide*. """ def list_tags_for_resource(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListTagsForResource", input, options) end @doc """ Returns a list of the requester's topics. Each call returns a limited list of topics, up to 100. If there are more topics, a `NextToken` is also returned. Use the `NextToken` parameter in a new `ListTopics` call to get further results. This action is throttled at 30 transactions per second (TPS). """ def list_topics(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListTopics", input, options) end @doc """ Use this request to opt in a phone number that is opted out, which enables you to resume sending SMS messages to the number. You can opt in a phone number only once every 30 days. """ def opt_in_phone_number(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "OptInPhoneNumber", input, options) end @doc """ Sends a message to an Amazon SNS topic, a text message (SMS message) directly to a phone number, or a message to a mobile platform endpoint (when you specify the `TargetArn`). If you send a message to a topic, Amazon SNS delivers the message to each endpoint that is subscribed to the topic. The format of the message depends on the notification protocol for each subscribed endpoint. When a `messageId` is returned, the message is saved and Amazon SNS immediately deliverers it to subscribers. To use the `Publish` action for publishing a message to a mobile endpoint, such as an app on a Kindle device or mobile phone, you must specify the EndpointArn for the TargetArn parameter. The EndpointArn is returned when making a call with the `CreatePlatformEndpoint` action. For more information about formatting messages, see [Send Custom Platform-Specific Payloads in Messages to Mobile Devices](https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-custommessage.html). You can publish messages only to topics and endpoints in the same Amazon Web Services Region. """ def publish(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "Publish", input, options) end @doc """ Publishes up to ten messages to the specified topic. This is a batch version of `Publish`. For FIFO topics, multiple messages within a single batch are published in the order they are sent, and messages are deduplicated within the batch and across batches for 5 minutes. The result of publishing each message is reported individually in the response. Because the batch request can result in a combination of successful and unsuccessful actions, you should check for batch errors even when the call returns an HTTP status code of `200`. The maximum allowed individual message size and the maximum total payload size (the sum of the individual lengths of all of the batched messages) are both 256 KB (262,144 bytes). Some actions take lists of parameters. These lists are specified using the `param.n` notation. Values of `n` are integers starting from 1. For example, a parameter list with two elements looks like this: &AttributeName.1=first &AttributeName.2=second If you send a batch message to a topic, Amazon SNS publishes the batch message to each endpoint that is subscribed to the topic. The format of the batch message depends on the notification protocol for each subscribed endpoint. When a `messageId` is returned, the batch message is saved and Amazon SNS immediately delivers the message to subscribers. """ def publish_batch(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "PublishBatch", input, options) end @doc """ Removes a statement from a topic's access control policy. """ def remove_permission(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "RemovePermission", input, options) end @doc """ Sets the attributes for an endpoint for a device on one of the supported push notification services, such as GCM (Firebase Cloud Messaging) and APNS. For more information, see [Using Amazon SNS Mobile Push Notifications](https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). """ def set_endpoint_attributes(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "SetEndpointAttributes", input, options) end @doc """ Sets the attributes of the platform application object for the supported push notification services, such as APNS and GCM (Firebase Cloud Messaging). For more information, see [Using Amazon SNS Mobile Push Notifications](https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). For information on configuring attributes for message delivery status, see [Using Amazon SNS Application Attributes for Message Delivery Status](https://docs.aws.amazon.com/sns/latest/dg/sns-msg-status.html). """ def set_platform_application_attributes(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "SetPlatformApplicationAttributes", input, options) end @doc """ Use this request to set the default settings for sending SMS messages and receiving daily SMS usage reports. You can override some of these settings for a single message when you use the `Publish` action with the `MessageAttributes.entry.N` parameter. For more information, see [Publishing to a mobile phone](https://docs.aws.amazon.com/sns/latest/dg/sms_publish-to-phone.html) in the *Amazon SNS Developer Guide*. To use this operation, you must grant the Amazon SNS service principal (`sns.amazonaws.com`) permission to perform the `s3:ListBucket` action. """ def set_sms_attributes(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "SetSMSAttributes", input, options) end @doc """ Allows a subscription owner to set an attribute of the subscription to a new value. """ def set_subscription_attributes(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "SetSubscriptionAttributes", input, options) end @doc """ Allows a topic owner to set an attribute of the topic to a new value. """ def set_topic_attributes(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "SetTopicAttributes", input, options) end @doc """ Subscribes an endpoint to an Amazon SNS topic. If the endpoint type is HTTP/S or email, or if the endpoint and the topic are not in the same Amazon Web Services account, the endpoint owner must run the `ConfirmSubscription` action to confirm the subscription. You call the `ConfirmSubscription` action with the token from the subscription response. Confirmation tokens are valid for three days. This action is throttled at 100 transactions per second (TPS). """ def subscribe(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "Subscribe", input, options) end @doc """ Add tags to the specified Amazon SNS topic. For an overview, see [Amazon SNS Tags](https://docs.aws.amazon.com/sns/latest/dg/sns-tags.html) in the *Amazon SNS Developer Guide*. When you use topic tags, keep the following guidelines in mind: * Adding more than 50 tags to a topic isn't recommended. * Tags don't have any semantic meaning. Amazon SNS interprets tags as character strings. * Tags are case-sensitive. * A new tag with a key identical to that of an existing tag overwrites the existing tag. * Tagging actions are limited to 10 TPS per Amazon Web Services account, per Amazon Web Services Region. If your application requires a higher throughput, file a [technical support request](https://console.aws.amazon.com/support/home#/case/create?issueType=technical). """ def tag_resource(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "TagResource", input, options) end @doc """ Deletes a subscription. If the subscription requires authentication for deletion, only the owner of the subscription or the topic's owner can unsubscribe, and an Amazon Web Services signature is required. If the `Unsubscribe` call does not require authentication and the requester is not the subscription owner, a final cancellation message is delivered to the endpoint, so that the endpoint owner can easily resubscribe to the topic if the `Unsubscribe` request was unintended. This action is throttled at 100 transactions per second (TPS). """ def unsubscribe(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "Unsubscribe", input, options) end @doc """ Remove tags from the specified Amazon SNS topic. For an overview, see [Amazon SNS Tags](https://docs.aws.amazon.com/sns/latest/dg/sns-tags.html) in the *Amazon SNS Developer Guide*. """ def untag_resource(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "UntagResource", input, options) end @doc """ Verifies a destination phone number with a one-time password (OTP) for the calling Amazon Web Services account. When you start using Amazon SNS to send SMS messages, your Amazon Web Services account is in the *SMS sandbox*. The SMS sandbox provides a safe environment for you to try Amazon SNS features without risking your reputation as an SMS sender. While your Amazon Web Services account is in the SMS sandbox, you can use all of the features of Amazon SNS. However, you can send SMS messages only to verified destination phone numbers. For more information, including how to move out of the sandbox to send messages without restrictions, see [SMS sandbox](https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html) in the *Amazon SNS Developer Guide*. """ def verify_sms_sandbox_phone_number(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "VerifySMSSandboxPhoneNumber", input, options) end end
lib/aws/generated/sns.ex
0.851922
0.493042
sns.ex
starcoder
defmodule Commando do alias Commando.State alias Commando.Help @moduledoc """ Command line parser with default values, useful help messages, and other features. Uses OptionParser for parsing, and extends it with: - Simple and informative help messages - Default values for switches - Ability to specify required switches - Descriptive error messages """ @type switch_type :: :boolean | :count | :integer | :float | :string @type conf :: {:required, boolean()} | {:alias, atom()} | {:default, any()} @type conf_list :: [conf] @type parse_result :: [{atom(), any()}] @doc ~S""" Creates a new Commando instance. ## Examples iex> Commando.create("app").app_name "app" iex> Commando.create("app", "Doc test app").app_description "Doc test app" iex> Commando.create("app", "Doc test app", "mix run").example "mix run" """ @spec create(String.t, String.t, String.t) :: State.t def create(name, description \\ "", example \\ "") do %State{app_name: name, app_description: description, example: example} end @doc """ Add a standardized help-message switch (--help, -h) to the Commando instance. ## Usage The application should check the result of `Commando.parse/2` to verify if this switch is true. If so, it should show the `Commando.help_message/1` and exit. """ @spec with_help(State.t) :: State.t def with_help(commando) do commando |> with_switch(:help, :boolean, "Print help message", alias: :h) end @doc """ Add a switch to a Commando instance. Returns a new Commando instance containing the switch. ## Description The description will be shown for the switch in the help message generated by `Commando.help_message/1`. ## Switch Types The available switch types are `:boolean`, `:count`, `:integer`, `:float`, `:string`. The following switches types take no arguments: * `:boolean` - sets the value to `true` when given (see also the "Negation switches" section below) * `:count` - counts the number of times the switch is given The following switches take one argument: * `:integer` - parses the value as an integer * `:float` - parses the value as a float * `:string` - parses the value as a string For more information on available switch types, see https://hexdocs.pm/elixir/OptionParser.html#parse/2 ## Configuration `conf` is a list of configuration keywords. The following condfigurations are available: * `default: any` - If switch is not specified, it will recieve this default value. * `alias: atom` - An alias for this switch. e.g. for `:data` you might pass `alias: :d`, you can then on the command line use `--data` or `-d`. * `required: boolean` - If true, `Commando.parse/2` will return an error if this switch is not present in `args`. ## Examples iex> Commando.create("test_app", "Test app", "mix run") |> ...> Commando.with_switch(:path, :string, "Path", required: true, alias: :p, default: "path/") %Commando.State{aliases: [p: :path], app_description: "Test app", app_name: "test_app", defaults: [path: "path/"], descriptions: [path: "Path"], example: "mix run", required: [:path], switches: [path: :string]} """ @spec with_switch(State.t, atom(), State.switch_type, String.t, conf_list) :: State.t def with_switch(commando, switch, type, description, conf \\ []) do commando |> State.add_switch(switch, type) |> State.add_description(switch, description) |> add_configurations(switch, conf) end @doc ~S""" Parse command line arguments. Returns one of: * `{:help, message}` - If you added the help swith using `Commando.with_help/1` and `--help` or `-h` switches were present. `message` contains the formatted help message to show. * `{:ok, result}` - If command line args were parsed successfully and all required arguments were present. `result` is a keyword list mapping switches to their parsed values. * `{:error, reason}` - If invalid flags were supplied, or a required argument was missing. ## Examples iex> Commando.create("app") |> Commando.with_switch(:path, :string, "Path") |> Commando.parse(["--path", "abc"]) {:ok, [path: "abc"]} iex> import Commando iex> create("app") |> with_switch(:path, :string, "Path", alias: :p) |> parse(["-p", "abc"]) {:ok, [path: "abc"]} iex> import Commando iex> create("app") |> parse(["--path", "abc"]) {:error, "Unknown options: --path"} iex> import Commando iex> create("app") |> with_switch(:foo, :boolean, "") |> parse(["--foo"]) {:ok, [foo: true]} iex> import Commando iex> create("app") |> with_switch(:foo, :count, "", alias: :f) |> parse(["--foo", "-f", "-f"]) {:ok, [foo: 3]} iex> import Commando iex> create("app") |> with_switch(:foo, :integer, "") |> parse(["--foo", "12"]) {:ok, [foo: 12]} iex> import Commando iex> create("app") |> with_switch(:foo, :integer, "") |> parse(["--foo", "bar"]) {:error, "Unknown options: --foo"} """ @spec parse(State.t, [String.t]) :: {:ok, parse_result} | :help | {:error, String.t} def parse(commando, args) do opts = [strict: commando.switches, aliases: commando.aliases] case args |> OptionParser.parse(opts) |> missing_switches(commando) |> check_help_flag() do :help -> {:help, help_message(commando)} {result, [], []} -> {:ok, result |> result_add_defaults(commando)} {_, [], missing} -> {:error, Help.build_missing_options(missing)} {_, invalid, _} -> {:error, Help.build_invalid_options(invalid)} end end @doc ~S""" Returns a help message for the Commando instance, to be displayed with e.g. `IO.puts`. Below is an example help message: ``` demo - Short demo app Arguments: --path, -p : (Required) Some path (Default: "path") --help : Print help message Example: mix run ``` ## Examples iex> Commando.create("demo", "Short demo app", "mix run") |> ...> Commando.with_help() |> ...> Commando.with_switch(:path, :string, "Some path", required: true, alias: :p, default: "path") |> ...> Commando.help_message() "demo - Short demo app\n\nArguments:\n --path, -p : (Required) Some path (Default: \"path\")\n --help, -h : Print help message\n\nExample: mix run" """ @spec help_message(State.t) :: String.t def help_message(commando) do Help.build_help(commando) end defp missing_switches({result, _args, invalid}, state) do missing = state.required |> Enum.filter(fn r -> !(Keyword.has_key?(result, r)) end) {result, invalid, missing} end defp check_help_flag({result, args, invalid}) do if Keyword.get(result, :help) == true do :help else {result, args, invalid} end end @spec result_add_defaults(parse_result, State.t) :: parse_result defp result_add_defaults(result, commando) do defaults = commando.defaults defaults |> Enum.reduce(result, fn ({switch, default}, result) -> result |> Keyword.put_new(switch, default) end) end @spec add_configurations(State.t, atom(), conf_list) :: State.t defp add_configurations(commando, switch, [{:default, default} | tail]) do commando |> State.add_default(switch, default) |> add_configurations(switch, tail) end defp add_configurations(commando, switch, [{:alias, al} | tail]) do commando |> State.add_alias(switch, al) |> add_configurations(switch, tail) end defp add_configurations(commando, switch, [{:required, true} | tail]) do commando |> State.add_required(switch) |> add_configurations(switch, tail) end defp add_configurations(commando, switch, [{:required, _} | tail]) do commando |> add_configurations(switch, tail) end defp add_configurations(commando, _switch, []) do commando end end
lib/commando.ex
0.888172
0.608216
commando.ex
starcoder
defmodule ExZipper.Zipper.Navigation do @moduledoc """ Utility module for functions that concern navigating through zippers """ alias ExZipper.Zipper @doc """ Moves to the leftmost child of the current focus, or returns an error if the current focus is a leaf or an empty branch. ## Example iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]]) iex> zipper |> Zipper.down |> Zipper.node 1 iex> zipper |> Zipper.down |> Zipper.down {:error, :down_from_leaf} iex> zipper |> Zipper.down |> Zipper.right |> Zipper.down {:error, :down_from_empty_branch} """ @spec down(Zipper.t) :: Zipper.maybe_zipper def down(zipper = %Zipper{}) do case Zipper.branch?(zipper) do false -> {:error, :down_from_leaf} true -> case Zipper.children(zipper) do [] -> {:error, :down_from_empty_branch} [new_focus | new_right] -> %Zipper{ focus: new_focus, crumbs: %{ left: [], right: new_right, pnodes: zipper.crumbs, ppath: case zipper.crumbs do nil -> [zipper.focus] crumbs -> [zipper.focus | crumbs.ppath] end }, functions: zipper.functions } end end end @doc """ Moves up to the parent of the current focus, or returns an error if already at the root of the zipper ## Example iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]]) iex> Zipper.up(zipper) {:error, :up_from_root} iex> zipper |> Zipper.down |> Zipper.right |> Zipper.up |> Zipper.node [1,[],[2,3,[4,5]]] """ @spec up(Zipper.t) :: Zipper.maybe_zipper def up(%Zipper{crumbs: nil}), do: {:error, :up_from_root} def up(zipper = %Zipper{}) do new_children = Enum.reverse(zipper.crumbs.left) ++ [zipper.focus | zipper.crumbs.right] [new_focus | _] = zipper.crumbs.ppath new_focus = Zipper.make_node(zipper, new_focus, new_children) %{zipper | focus: new_focus, crumbs: zipper.crumbs.pnodes} end @doc """ Moves to the next sibling to the right of the current focus. Returns an error if at the root or already at the rightmost sibling at its depth in the tree. ## Examples iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]]) iex> Zipper.right(zipper) {:error, :right_from_root} iex> zipper |> Zipper.down |> Zipper.right |> Zipper.node [] iex> zipper |> Zipper.down |> Zipper.right |> Zipper.right |> Zipper.right {:error, :right_from_rightmost} """ @spec right(Zipper.t) :: Zipper.maybe_zipper def right(%Zipper{crumbs: nil}), do: {:error, :right_from_root} def right(%Zipper{crumbs: %{right: []}}) do {:error, :right_from_rightmost} end def right(zipper = %Zipper{}) do [new_focus | new_right] = zipper.crumbs.right new_left = [zipper.focus | zipper.crumbs.left] %{zipper | focus: new_focus, crumbs: %{zipper.crumbs | left: new_left, right: new_right } } end @doc """ Moves to the next sibling to the left of the current focus. Returns an error if at the root or already at the leftmost sibling at its depth in the tree. ## Examples iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]]) iex> Zipper.left(zipper) {:error, :left_from_root} iex> zipper |> Zipper.down |> Zipper.left {:error, :left_from_leftmost} iex> zipper |> Zipper.down |> Zipper.right |> Zipper.right |> Zipper.left |> Zipper.node [] """ @spec left(Zipper.t) :: Zipper.maybe_zipper def left(%Zipper{crumbs: nil}), do: {:error, :left_from_root} def left(%Zipper{crumbs: %{left: []}}), do: {:error, :left_from_leftmost} def left(zipper = %Zipper{}) do [new_focus | new_left] = zipper.crumbs.left new_right = [zipper.focus | zipper.crumbs.right] %{zipper | focus: new_focus, crumbs: %{zipper.crumbs | left: new_left, right: new_right } } end @doc """ Moves to the leftmost sibling at the same depth as the current focus. Remains in place if already focused on the leftmost sibling. Returns an error if called on the root. ## Examples iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]]) iex> Zipper.rightmost(zipper) {:error, :rightmost_from_root} iex> zipper |> Zipper.down |> Zipper.rightmost|> Zipper.node [2,3,[4,5]] iex> zipper |> Zipper.down |> Zipper.rightmost |> Zipper.rightmost |> Zipper.node [2,3,[4,5]] """ @spec rightmost(Zipper.t) :: Zipper.maybe_zipper def rightmost(%Zipper{crumbs: nil}), do: {:error, :rightmost_from_root} def rightmost(zipper = %Zipper{crumbs: %{right: []}}), do: zipper def rightmost(zipper = %Zipper{}) do {new_focus, old_right} = List.pop_at(zipper.crumbs.right, -1) new_left = Enum.reverse(old_right) ++ [zipper.focus | zipper.crumbs.left] %{zipper | focus: new_focus, crumbs: %{zipper.crumbs | left: new_left, right: []} } end @doc """ Moves to the leftmost sibling at the same depth as the current focus. Remains in place if already focused on the leftmost sibling. Returns an error if called on the root. ## Examples iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]]) iex> Zipper.leftmost(zipper) {:error, :leftmost_from_root} iex> zipper |> Zipper.down |> Zipper.leftmost |> Zipper.node 1 iex> zipper |> Zipper.down |> Zipper.right |> Zipper.right |> Zipper.leftmost |> Zipper.node 1 """ @spec leftmost(Zipper.t) :: Zipper.maybe_zipper def leftmost(%Zipper{crumbs: nil}), do: {:error, :leftmost_from_root} def leftmost(zipper = %Zipper{crumbs: %{left: []}}), do: zipper def leftmost(zipper = %Zipper{}) do {new_focus, old_left} = List.pop_at(zipper.crumbs.left, -1) new_right = Enum.reverse(old_left) ++ [zipper.focus | zipper.crumbs.right] %{zipper | focus: new_focus, crumbs: %{zipper.crumbs | right: new_right, left: []} } end @doc """ Moves to the next focus in a depth-first walk through the zipper. If it reaches the end, subsequent calls to `next` return the same focus ## Examples iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]]) iex> zipper |> Zipper.next |> Zipper.node 1 iex> zipper |> Zipper.next |> Zipper.next |> Zipper.node [] iex> zipper |> Zipper.next |> Zipper.next ...> |> Zipper.next |> Zipper.next |> Zipper.node 2 iex> zipper = zipper |> Zipper.down |> Zipper.rightmost ...> |> Zipper.down |> Zipper.rightmost ...> |> Zipper.down |> Zipper.rightmost iex> zipper |> Zipper.next |> Zipper.node [1,[],[2,3,[4,5]]] iex> zipper |> Zipper.next |> Zipper.next |> Zipper.node [1,[],[2,3,[4,5]]] """ @spec next(Zipper.t) :: Zipper.t def next(zipper = %Zipper{}) do case Zipper.end?(zipper) do true -> zipper false -> case {down(zipper), right(zipper)} do {{:error, _}, {:error, _}} -> recur_next(zipper) {{:error, _}, right_zipper} -> right_zipper {down_zipper, _} -> down_zipper end end end @doc """ Moves to the previous focus in a depth-first walk through the zipper. Returns an error if called on the end of the walk. Returns the root if called on the root. ## Examples iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]]) iex> zipper |> Zipper.prev |> Zipper.node [1,[],[2,3,[4,5]]] iex> zipper |> Zipper.down |> Zipper.rightmost |> Zipper.prev |> Zipper.node [] iex> zipper |> Zipper.down |> Zipper.rightmost |> Zipper.down |> Zipper.rightmost ...> |> Zipper.down |> Zipper.rightmost |> Zipper.next |> Zipper.prev {:error, :prev_of_end} """ @spec prev(Zipper.t) :: Zipper.maybe_zipper def prev(%Zipper{crumbs: :end}), do: {:error, :prev_of_end} def prev(zipper = %Zipper{crumbs: nil}), do: zipper def prev(zipper = %Zipper{}) do case left(zipper) do {:error, _} -> up(zipper) left_zipper -> recur_prev(left_zipper) end end defp recur_prev(zipper = %Zipper{}) do case down(zipper) do {:error, _} -> zipper child -> child |> rightmost |> recur_prev end end defp recur_next(zipper = %Zipper{}) do case up(zipper) do {:error, _} -> %{zipper | crumbs: :end} next_zipper -> case right(next_zipper) do {:error, _} -> recur_next(next_zipper) new_zipper -> new_zipper end end end end
lib/ex_zipper/zipper/navigation.ex
0.869521
0.465509
navigation.ex
starcoder
defmodule Data.Json.Decode do @type value :: any @type error :: {:field, String.t(), error} | {:index, integer, error} | {:one_of, list(error)} | {:failure, String.t(), value} @type decoder(a) :: :boolean | :integer | :float | :string | {:null, a} | :value | {:list, decoder(a)} | {:field, String.t(), decoder(a)} | {:index, integer, decoder(a)} | {:map, (any -> any), list(decoder(a))} | {:and_map, decoder((any -> any)), decoder(a)} | {:and_then, (any -> decoder(any)), decoder(a)} | {:one_of, list(decoder(a))} | {:fail, String.t()} | {:succeed, a} @spec boolean() :: decoder(boolean) def boolean(), do: :boolean @spec integer() :: decoder(integer) def integer(), do: :integer @spec float() :: decoder(float) def float(), do: :float @spec string() :: decoder(String.t()) def string(), do: :string @spec null(a) :: decoder(a) when a: var def null(default), do: {:null, default} @spec value() :: decoder(value) def value(), do: :value @spec list(decoder(a)) :: decoder(list(a)) when a: var def list(decoder), do: {:list, decoder} @spec field(String.t(), decoder(a)) :: decoder(a) when a: var def field(path, decoder), do: {:field, path, decoder} @spec index(integer, decoder(a)) :: decoder(a) when a: var def index(i, decoder), do: {:index, i, decoder} @spec map(decoder(a), (a -> b)) :: decoder(b) when a: var, b: var def map(d, f), do: {:map, f, d} @spec and_map(decoder((a -> b)), decoder(a)) :: decoder(b) when a: var, b: var def and_map(fd, d), do: {:and_map, fd, d} @spec and_then(decoder(a), (a -> decoder(b))) :: decoder(b) when a: var, b: var def and_then(d, f), do: {:and_then, f, d} @spec one_of(list(decoder(a))) :: decoder(a) when a: var def one_of(ds), do: {:one_of, ds} @spec fail(String.t()) :: decoder(any) def fail(message), do: {:fail, message} @spec succeed(a) :: decoder(a) when a: var def succeed(a), do: {:succeed, a} @spec decode_string(String.t(), decoder(a)) :: {:ok, a} | {:error, error} when a: var def decode_string(input, decoder) do case Poison.decode(input) do {:ok, stuff} -> run_help(decoder, stuff) {:error, :invalid, _} -> {:error, {:failure, "This is not valid JSON!", input}} {:error, {:invalid, message, _}} -> {:error, {:failure, "This is not valid JSON! #{message}", input}} end end @spec decode_value(value, decoder(a)) :: {:ok, a} | {:error, error} when a: var def decode_value(value, decoder) do run_help(decoder, value) end defp run_help(decoder, value) do case {decoder, value} do {:boolean, v} when is_boolean(v) -> {:ok, v} {:boolean, v} -> {:error, {:failure, "Expecting a Boolean", v}} {:integer, v} when is_integer(v) -> {:ok, v} {:integer, v} -> {:error, {:failure, "Expecting an Integer", v}} {:float, v} when is_float(v) -> {:ok, v} {:float, v} -> {:error, {:failure, "Expecing a Float", v}} {:string, v} when is_binary(v) -> {:ok, v} {:string, v} -> {:error, {:failure, "Expecting a String", v}} {{:null, default}, v} when is_nil(v) -> {:ok, default} {{:null, _}, v} -> {:error, {:failure, "Expecting null", v}} {:value, v} -> {:ok, v} {{:list, inner}, v} when is_list(v) -> case run_array_decoder(inner, v) do {:ok, list} -> {:ok, Enum.reverse(list)} {:error, reason} -> {:error, reason} end {{:list, _}, v} -> {:error, {:failure, "Expecting a list", v}} {{:field, field, inner}, v} -> if not is_map(v) || not Map.has_key?(v, field) do {:error, {:failure, "Expecting an Object with a field named `#{field}`", v}} else case run_help(inner, Map.get(v, field)) do {:ok, output} -> {:ok, output} {:error, reason} -> {:error, {:field, field, reason}} end end {{:index, index, inner}, v} -> cond do not is_list(v) -> {:error, {:failure, "Expecting an Array", v}} index >= Enum.count(v) -> {:error, {:failure, "Expecting a longer Array. Need index #{index} but only see #{Enum.count(v)} entries", v}} true -> case run_help(inner, Enum.at(v, index)) do {:ok, output} -> {:ok, output} {:error, reason} -> {:error, {:index, index, reason}} end end {{:map, f, d}, v} -> case run_help(d, v) do {:ok, out} -> {:ok, f.(out)} {:error, reason} -> {:error, reason} end {{:and_map, fd, d}, v} -> case {run_help(fd, v), run_help(d, v)} do {{:ok, f}, {:ok, out}} -> {:ok, f.(out)} {{:error, reason}, _} -> {:error, reason} {_, {:error, reason}} -> {:error, reason} end {{:and_then, callback, inner}, v} -> case run_help(inner, v) do {:error, reason} -> {:error, reason} {:ok, a} -> run_help(callback.(a), v) end {{:one_of, decoders}, v} -> Enum.reduce_while(decoders, {:error, {:one_of, []}}, fn inner, {:error, {:one_of, errors}} -> case run_help(inner, v) do {:ok, out} -> {:halt, {:ok, out}} {:error, reason} -> {:cont, {:error, {:one_of, [reason | errors]}}} end end) {{:fail, message}, v} -> {:error, {:failure, message, v}} {{:succeed, a}, _} -> {:ok, a} end end defp run_array_decoder(decoder, value) do value |> Enum.reduce_while({:ok, []}, fn item, memo -> case memo do {:ok, stuff} -> case run_help(decoder, item) do {:ok, thing} -> {:cont, {:ok, [thing | stuff]}} {:error, reason} -> {:halt, {:error, reason}} end {:error, reason} -> {:halt, {:error, reason}} end end) end end
lib/data/json/decode.ex
0.872
0.562958
decode.ex
starcoder
defmodule BlueJet.CRM.Customer do @behaviour BlueJet.Data use BlueJet, :data import BlueJet.Utils, only: [put_parameterized: 2, downcase: 1, remove_space: 1, digit_only: 1] alias __MODULE__.Proxy alias BlueJet.CRM.PointAccount schema "customers" do field :account_id, UUID field :account, :map, virtual: true field :status, :string, default: "guest" field :code, :string field :name, :string field :label, :string field :first_name, :string field :last_name, :string field :email, :string field :phone_number, :string field :caption, :string field :description, :string field :custom_data, :map, default: %{} field :translations, :map, default: %{} field :stripe_customer_id, :string field :user_id, UUID field :user, :map, virtual: true field :username, :string, virtual: true field :password, :string, virtual: true field :file_collections, {:array, :map}, virtual: true, default: [] timestamps() has_one :point_account, PointAccount belongs_to :enroller, __MODULE__ belongs_to :sponsor, __MODULE__ end @type t :: Ecto.Schema.t() @system_fields [ :id, :account_id, :inserted_at, :updated_at ] def writable_fields do (__MODULE__.__schema__(:fields) -- @system_fields) ++ [:username, :password] end def translatable_fields do [ :caption, :description, :custom_data ] end @spec changeset(__MODULE__.t(), atom, map) :: Changeset.t() def changeset(customer, :insert, params) do customer |> cast(params, writable_fields()) |> Map.put(:action, :insert) |> put_name() |> put_parameterized(:email) |> validate() end @spec changeset(__MODULE__.t(), atom, map, String.t()) :: Changeset.t() def changeset(customer, :update, params, locale \\ nil) do customer = Proxy.put_account(customer) default_locale = customer.account.default_locale locale = locale || default_locale customer |> cast(params, writable_fields()) |> Map.put(:action, :update) |> put_name() |> put_parameterized(:email) |> validate() |> Translation.put_change(translatable_fields(), locale, default_locale) end @spec changeset(__MODULE__.t(), atom) :: Changeset.t() def changeset(customer, :delete) do change(customer) |> Map.put(:action, :delete) end defp put_name(changeset = %{changes: %{name: _}}), do: changeset defp put_name(changeset) do first_name = get_field(changeset, :first_name) last_name = get_field(changeset, :last_name) if first_name && last_name do put_change(changeset, :name, "#{first_name} #{last_name}") else changeset end end @spec validate(Changeset.t()) :: Changeset.t() def validate(changeset) do changeset |> validate_required(required_fields(changeset)) |> validate_format(:email, Application.get_env(:blue_jet, :email_regex)) |> foreign_key_constraint(:account_id) |> unique_constraint(:email, name: :customers_account_id_status_email_index) end defp required_fields(changeset) do status = get_field(changeset, :status) case status do "guest" -> [:status] "internal" -> [:status] "registered" -> [:status, :name, :email] "suspended" -> [:status] end end @spec match_by(__MODULE__.t() | nil, list) :: __MODULE__.t() | nil def match_by(nil, _), do: nil def match_by(customer, matcher) do matcher = Map.take(matcher, [:name, :phone_number]) do_match_by(customer, matcher) end defp do_match_by(customer, matcher) when map_size(matcher) == 0, do: customer defp do_match_by(customer, matcher) do leftover = Enum.reject(matcher, fn {k, v} -> case k do :name -> remove_space(downcase(v)) == remove_space(downcase(customer.name)) :phone_number -> digit_only(v) == digit_only(customer.phone_number) :email -> downcase(v) == downcase(customer.email) end end) case length(leftover) do 0 -> customer _ -> nil end end end
lib/blue_jet/app/crm/customer.ex
0.639398
0.40642
customer.ex
starcoder
defmodule FusionDsl.Runtime.Executor do @moduledoc """ Functions to control and manage execution cycles of fusion dsl. """ alias FusionDsl.Helpers.FunctionNames alias FusionDsl.Impl alias FusionDsl.Processor.Program alias FusionDsl.Processor.Environment @jump_start_throttle Application.get_env( :fusion_dsl, :jump_start_throttle, 200 ) @jump_throttle_every Application.get_env( :fusion_dsl, :jump_throttle_every, 20 ) @jump_throttle_time_ms Application.get_env( :fusion_dsl, :jump_throttle_time_ms, 50 ) @doc """ Executes the program in given enviornment """ @spec execute(Environment.t(), atom()) :: {:end, Environment.t()} def execute(env, proc \\ :main) do env = Map.put(env, :cur_proc, [proc | env.cur_proc]) execute_procedure(env.prog.procedures[proc], env) end defp execute_procedure([ast | t], env) do case execute_ast(ast, env) do {:ok, _, env} -> execute_procedure(t, env) {:jump, jump_amount, env} -> t = jump(t, jump_amount) execute_procedure(t, env) {:jump_to, {line_number, skip, opt}, env} -> proc = List.first(env.cur_proc) t = jump_to(env.prog.procedures[proc], line_number) t = jump(t, skip) jump_c = env.jump_c + 1 env = Map.put(env, :jump_c, jump_c) if opt and jump_c > @jump_start_throttle and rem(jump_c, @jump_throttle_every) == 0 do :timer.sleep(@jump_throttle_time_ms) end execute_procedure(t, env) {:end, env} -> [_ | t] = env.cur_proc {:end, Map.put(env, :cur_proc, t)} end end defp execute_procedure([], env) do [_ | t] = env.cur_proc env = Map.put(env, :cur_proc, t) {:end, env} end defp jump(t, 0), do: t defp jump([_ | t], r_jmp) do jump(t, r_jmp - 1) end defp jump_to([{_, ctx, _} | t] = p, ln) do cond do ctx[:ln] == ln -> p true -> jump_to(t, ln) end end @doc """ Executes a single FusionDsl AST and returns the result. """ @spec execute_ast(Program.ast(), Environment.t()) :: {:ok, any(), Environment.t()} | {:jump, integer(), Environment.t()} | {:jump_to, any(), Environment.t()} | {:error, String.t()} def execute_ast({{module, func}, ctx, args}, env) do module_func = FunctionNames.normalize!(func) case apply(module, module_func, [{func, ctx, args}, env]) do {:ok, output, env} -> {:ok, output, env} {:jump, amount, env} -> {:jump, amount, env} {:jump_to, data, env} -> {:jump_to, data, env} {:error, message} -> error(env.prog, ctx, message) end end def execute_ast({:return, _, _}, env) do {:end, env} end def execute_ast({:var, _ctx, [var]}, env) do Impl.get_var(env, var) end def execute_ast({:goto, ctx, [proc]}, env) when is_atom(proc) do case env.prog.procedures[proc] do proc_asts when is_list(proc_asts) -> :timer.sleep(50) # Sleep is to prevent high cpu utilization in case of an infinity # recursion env = Map.put(env, :cur_proc, [proc | env.cur_proc]) {:end, env} = execute_procedure(proc_asts, env) {:ok, nil, env} nil -> error(env.prog, ctx, "Procedure #{proc} not found!") end end def execute_ast({:jump, _ctx, [jump_amount]}, env) do {:jump, jump_amount, env} end def execute_ast({:jump_to, _ctx, [line_number, skip, opt]}, env) do {:jump_to, {line_number, skip, opt}, env} end def execute_ast({:noop, _, _}, env), do: {:ok, nil, env} def execute_ast(num, env) when is_number(num) do {:ok, num, env} end def execute_ast(string, env) when is_binary(string) do {:ok, string, env} end def execute_ast(bool, env) when is_boolean(bool) do {:ok, bool, env} end def execute_ast(list, env) when is_list(list) do {:ok, list, env} end def execute_ast(map, env) when is_map(map) do {:ok, map, env} end def execute_ast(v, env) when is_nil(v) do {:ok, nil, env} end def execute_ast(%Regex{} = v, env) do {:ok, v, env} end defp error(_prog, ctx, msg) do # raise("Kernel error\n Line: #{ctx[:ln]}: #{msg}") {:error, "Kernel error\n Line: #{ctx[:ln]}: #{msg}"} end end
lib/fusion_dsl/runtime/executor.ex
0.707203
0.506836
executor.ex
starcoder
defmodule ProcessTreeDictionary do require Logger @moduledoc """ Implements a dictionary that is scoped to a process tree by replacing the group leader with a process that: - Maintains a dictionary of state - Forwards all unrecognized messages to the original group leader so that IO still works Any process can be the root of its own process tree by starting a `ProcessTreeDictionary`. The [Erlang docs](http://erlang.org/doc/man/erlang.html#group_leader-0) provide a summary of what a group leader is: > Every process is a member of some process group and all groups have a > group leader. All I/O from the group is channeled to the group leader. > When a new process is spawned, it gets the same group leader as the > spawning process. Since every new process inherits the group leader from its parent, a process can start a `ProcessTreeDictionary` in place of its existing group leader, and *every* descendant process will inherit it, allowing them to access the state of the same `ProcessTreeDictionary`. Note that _all_ functions provided by this module rely upon side effects. Since referential transparency is a primary value of Elixir, Erlang, and functional programming in general, and _none_ of the functions provided by this module are referentially transparent, we recommend you limit your usage of this module to specialized situations, such as for building test fakes to stand-in for stateful modules. Important caveat: if any processes in your tree start an application with `Application.start`, `Application.ensure_started`, or `Application.ensure_all_started`, the started application processes will _not_ be a part of the process tree, because OTP manages application starts for you. If you need to access the `ProcessTreeDictionary` from the started processes, you'll need to start the supervisor of the application yourself. For more info, see the [Erlang docs](http://erlang.org/doc/apps/kernel/application.html#start-1). """ @type simple_key :: String.t | atom | integer @type key :: simple_key | [simple_key] @doc """ Starts a `ProcessTreeDictionary` if this process does not already have access to one. If a `ProcessTreeDictionary` has already been started in this process or in a parent process (prior to this process being spawned), this will be a no-op. ### Examples iex> ProcessTreeDictionary.ensure_started() :ok """ @spec ensure_started() :: :ok def ensure_started do case get_existing_group_leader() do {:already_a_dict, _} -> :ok :dict_has_exited -> gl_pid = Process.get(:__process_tree_dictionary_original_group_leader) {:ok, new_pid} = GenServer.start_link(__MODULE__.Server, {gl_pid, %{}}) :erlang.group_leader(new_pid, self()) :ok {:not_a_dict, gl_pid} -> {:ok, new_pid} = GenServer.start_link(__MODULE__.Server, {gl_pid, %{}}) Process.put(:__process_tree_dictionary_original_group_leader, gl_pid) :erlang.group_leader(new_pid, self()) :ok end end @doc """ Puts the given `value` into the dictionary under the given `key`. The `key` can be a simple key (such as a string, atom, or integer) or a key path, expressed as a list. Raises an error if a `ProcessTreeDictionary` has not been started. ### Examples iex> ProcessTreeDictionary.ensure_started() iex> ProcessTreeDictionary.put(:language, "Elixir") :ok iex> ProcessTreeDictionary.ensure_started() iex> ProcessTreeDictionary.put([MyApp, :meta, :language], "Elixir") :ok """ @spec put(key :: key, value :: any) :: :ok def put(key, value) do call_server(:put, [key, value]) end @doc """ Gets the value for the given `key` from the dictionary. Returns the `default` value if the `ProcessTreeDictionary` has not been started or if the dictionary does not contain `key`. The `key` can be a simple key (such as a string, atom, or integer) or a key path, expressed as a list. ### Examples iex> ProcessTreeDictionary.ensure_started() iex> ProcessTreeDictionary.put(:language, "Elixir") iex> ProcessTreeDictionary.get(:language) "Elixir" iex> ProcessTreeDictionary.ensure_started() iex> ProcessTreeDictionary.put([MyApp, :meta, :language], "Elixir") iex> ProcessTreeDictionary.get([MyApp, :meta, :language]) "Elixir" """ @spec get(key :: key, default :: any) :: any def get(key, default \\ nil) do call_server(:get, [key, default], fn -> default end) end @doc """ Updates the `key` in the dictionary using the given function. The `key` can be a simple key (such as a string, atom, or integer) or a key path, expressed as a list. If the key does not exist, raises a `KeyError`. ### Examples iex> ProcessTreeDictionary.ensure_started() iex> ProcessTreeDictionary.put(:language, "Elixir") iex> ProcessTreeDictionary.update!(:language, &String.downcase/1) iex> ProcessTreeDictionary.get(:language) "elixir" iex> ProcessTreeDictionary.ensure_started() iex> ProcessTreeDictionary.put([MyApp, :meta, :language], "Elixir") iex> ProcessTreeDictionary.update!([MyApp, :meta, :language], &String.downcase/1) iex> ProcessTreeDictionary.get([MyApp, :meta, :language]) "elixir" """ @spec update!(key :: key, ((any) -> any)) :: any def update!(key, fun) do call_server(:update!, [key, fun]) end defp call_server(message_name, args, fallback \\ fn -> raise __MODULE__.NotRunningError end ) do case get_existing_group_leader() do :dict_has_exited -> Logger.warn "Attempting to use the process tree dictionary process after it " <> "has already exited for message: #{inspect message_name}, #{inspect args}. " <> "The fallback callback will be used." fallback.() {:not_a_dict, _} -> fallback.() {:already_a_dict, gl_pid} -> message = [__MODULE__.Server, message_name | args] |> List.to_tuple case GenServer.call(gl_pid, message) do {__MODULE__.Server, :run_fun, fun} -> fun.() other_response -> other_response end end end defp get_existing_group_leader do group_leader = :erlang.group_leader case Process.info(group_leader, :dictionary) do {:dictionary, dict} -> case Keyword.get(dict, :"$initial_call") do {__MODULE__.Server, _fun, _args} -> {:already_a_dict, group_leader} _otherwise -> {:not_a_dict, group_leader} end nil -> :dict_has_exited end end defmodule Server do use GenServer @moduledoc false def handle_call({__MODULE__, :put, key, value}, _from, {gl, dict}) do updated = put_in(dict, to_key_path(key), value) {:reply, :ok, {gl, updated}} end def handle_call({__MODULE__, :get, key, default}, _from, {gl, dict}) do key_path = to_key_path_with_last_default(key, default) value = get_in(dict, key_path) {:reply, value, {gl, dict}} end def handle_call({__MODULE__, :update!, key, fun}, _from, {gl, dict}) do key_not_found_ref = make_ref() get_path = to_key_path_with_last_default(key, key_not_found_ref) if get_in(dict, get_path) == key_not_found_ref do client_fun = fn -> raise KeyError, key: key end {:reply, {__MODULE__, :run_fun, client_fun}, {gl, dict}} else updated = update_in(dict, to_key_path(key), fun) {:reply, :ok, {gl, updated}} end end def handle_call(unrecognized_message, from, state) do forward_message({:"$gen_call", from, unrecognized_message}, state) end def handle_cast(unrecognized_message, state) do forward_message({:"$gen_cast", unrecognized_message}, state) end def handle_info(message, state) do forward_message(message, state) end defp to_key_path(key, fallback \\ %{}) defp to_key_path(key, fallback) when not is_list(key) do key |> List.wrap |> to_key_path(fallback) end defp to_key_path(list, fallback) do Enum.map(list, &Access.key(&1, fallback)) end defp to_key_path_with_last_default(key, default) do [last_key | rest] = key |> List.wrap |> Enum.reverse [Access.key(last_key, default) | to_key_path(rest)] |> Enum.reverse end defp forward_message(message, {original_group_leader, _} = state) do send(original_group_leader, message) {:noreply, state} end end defmodule NotRunningError do @moduledoc """ Raised when attempting to write to a `ProcessTreeDictionary` before it has been started or after it has exited. """ defexception message: "Must start a ProcessTreeDictionary before writing to it (and must still be up)" end end
lib/process_tree_dictionary.ex
0.886681
0.482429
process_tree_dictionary.ex
starcoder
defmodule NimbleStrftime do @moduledoc """ Simple datetime formatting based on the strftime format found on UNIX-like systems. ## Formatting syntax The formatting syntax for strftime is a sequence of characters in the following format: %<padding><width><format> where: * `%`: indicates the start of a formatted section * `<padding>`: set the padding (see below) * `<width>`: a number indicating the minimum size of the formatted section * `<format>`: the format iself (see below) ### Accepted padding options * `-`: no padding, removes all padding from the format * `_`: pad with spaces * `0`: pad with zeroes ### Accepted formats The accepted formats are: Format | Description | Examples (in ISO) :----- | :-----------------------------------------------------------------------| :------------------------ a | Abbreviated name of day | Mon A | Full name of day | Monday b | Abbreviated month name | Jan B | Full month name | January c | Preferred date+time representation | 2018-10-17 12:34:56 d | Day of the month | 01, 12 f | Microseconds *(does not support width and padding modifiers)* | 000000, 999999, 0123 H | Hour using a 24-hour clock | 00, 23 I | Hour using a 12-hour clock | 01, 12 j | Day of the year | 001, 366 m | Month | 01, 12 M | Minute | 00, 59 p | "AM" or "PM" (noon is "PM", midnight as "AM") | AM, PM P | "am" or "pm" (noon is "pm", midnight as "am") | am, pm q | Quarter | 1, 2, 3, 4 S | Second | 00, 59, 60 u | Day of the week | 1 (Monday), 7 (Sunday) x | Preferred date (without time) representation | 2018-10-17 X | Preferred time (without date) representation | 12:34:56 y | Year as 2-digits | 01, 01, 86, 18 Y | Year | -0001, 0001, 1986 z | +hhmm/-hhmm time zone offset from UTC (empty string if naive) | +0300, -0530 Z | Time zone abbreviation (empty string if naive) | CET, BRST % | Literal "%" character | % Any other character will be interpreted as an invalid format and raise an error """ @doc """ Formats received datetime into a string. The datetime can be any of the Calendar types (`Time`, `Date`, `NaiveDateTime`, and `DateTime`) or any map, as long as they contain all of the relevant fields necessary for formatting. For example, if you use `%Y` to format the year, the datatime must have the `:year` field. Therefore, if you pass a `Time`, or a map without the `:year` field to a format that expects `%Y`, an error will be raised. ## Options * `:preferred_datetime` - a string for the preferred format to show datetimes, it can't contain the `%c` format and defaults to `"%Y-%m-%d %H:%M:%S"` if the option is not received * `:preferred_date` - a string for the preferred format to show dates, it can't contain the `%x` format and defaults to `"%Y-%m-%d"` if the option is not received * `:preferred_time` - a string for the preferred format to show times, it can't contain the `%X` format and defaults to `"%H:%M:%S"` if the option is not received * `:am_pm_names` - a function that receives either `:am` or `:pm` and returns the name of the period of the day, if the option is not received it defaults to a function that returns `"am"` and `"pm"`, respectively * `:month_names` - a function that receives a number and returns the name of the corresponding month, if the option is not received it defaults to a function thet returns the month names in english * `:abbreviated_month_names` - a function that receives a number and returns the abbreviated name of the corresponding month, if the option is not received it defaults to a function thet returns the abbreviated month names in english * `:day_of_week_names` - a function that receives a number and returns the name of the corresponding day of week, if the option is not received it defaults to a function that returns the day of week names in english * `:abbreviated_day_of_week_names` - a function that receives a number and returns the abbreviated name of the corresponding day of week, if the option is not received it defaults to a function that returns the abbreviated day of week names in english ## Examples Without options: iex> NimbleStrftime.format(~U[2019-08-26 13:52:06.0Z], "%y-%m-%d %I:%M:%S %p") "19-08-26 01:52:06 PM" iex> NimbleStrftime.format(~U[2019-08-26 13:52:06.0Z], "%a, %B %d %Y") "Mon, August 26 2019" iex> NimbleStrftime.format(~U[2019-08-26 13:52:06.0Z], "%c") "2019-08-26 13:52:06" With options: iex> NimbleStrftime.format(~U[2019-08-26 13:52:06.0Z], "%c", preferred_datetime: "%H:%M:%S %d-%m-%y") "13:52:06 26-08-19" iex> NimbleStrftime.format( ...> ~U[2019-08-26 13:52:06.0Z], ...> "%A", ...> day_of_week_names: fn day_of_week -> ...> {"segunda-feira", "terça-feira", "quarta-feira", "quinta-feira", ...> "sexta-feira", "sábado", "domingo"} ...> |> elem(day_of_week - 1) ...> end ...>) "segunda-feira" iex> NimbleStrftime.format( ...> ~U[2019-08-26 13:52:06.0Z], ...> "%B", ...> month_names: fn month -> ...> {"январь", "февраль", "март", "апрель", "май", "июнь", ...> "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"} ...> |> elem(month - 1) ...> end ...>) "август" """ @spec format(map(), String.t(), keyword()) :: String.t() def format(date_or_time_or_datetime, string_format, user_options \\ []) do parse( string_format, date_or_time_or_datetime, options(user_options), [] ) |> IO.iodata_to_binary() end defp parse("", _datetime, _format_options, acc), do: Enum.reverse(acc) defp parse("%" <> rest, datetime, format_options, acc), do: parse_modifiers(rest, nil, nil, {datetime, format_options, acc}) defp parse(<<char::binary-1, rest::binary>>, datetime, format_options, acc), do: parse(rest, datetime, format_options, [char | acc]) defp parse_modifiers("-" <> rest, width, nil, parser_data) do parse_modifiers(rest, width, "", parser_data) end defp parse_modifiers("0" <> rest, width, nil, parser_data) do parse_modifiers(rest, width, ?0, parser_data) end defp parse_modifiers("_" <> rest, width, nil, parser_data) do parse_modifiers(rest, width, ?\s, parser_data) end defp parse_modifiers(<<digit, rest::binary>>, width, pad, parser_data) when digit in ?0..?9 do new_width = case pad do ?- -> 0 _ -> (width || 0) * 10 + (digit - ?0) end parse_modifiers(rest, new_width, pad, parser_data) end # set default padding if none was specfied defp parse_modifiers(<<format, _::binary>> = rest, width, nil, parser_data) do parse_modifiers(rest, width, default_pad(format), parser_data) end # set default width if none was specified defp parse_modifiers(<<format, _::binary>> = rest, nil, pad, parser_data) do parse_modifiers(rest, default_width(format), pad, parser_data) end defp parse_modifiers(rest, width, pad, {datetime, format_options, acc}) do format_modifiers(rest, width, pad, datetime, format_options, acc) end defp am_pm(hour, format_options) when hour > 11 do format_options.am_pm_names.(:pm) end defp am_pm(hour, format_options) when hour <= 11 do format_options.am_pm_names.(:am) end defp default_pad(format) when format in 'aAbBpPZ', do: ?\s defp default_pad(_format), do: ?0 defp default_width(format) when format in 'dHImMSy', do: 2 defp default_width(?j), do: 3 defp default_width(format) when format in 'Yz', do: 4 defp default_width(_format), do: 0 # Literally just % defp format_modifiers("%" <> rest, width, pad, datetime, format_options, acc) do parse(rest, datetime, format_options, [pad_leading("%", width, pad) | acc]) end # Abbreviated name of day defp format_modifiers("a" <> rest, width, pad, datetime, format_options, acc) do result = datetime |> Date.day_of_week() |> format_options.abbreviated_day_of_week_names.() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Full name of day defp format_modifiers("A" <> rest, width, pad, datetime, format_options, acc) do result = datetime |> Date.day_of_week() |> format_options.day_of_week_names.() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Abbreviated month name defp format_modifiers("b" <> rest, width, pad, datetime, format_options, acc) do result = datetime.month |> format_options.abbreviated_month_names.() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Full month name defp format_modifiers("B" <> rest, width, pad, datetime, format_options, acc) do result = datetime.month |> format_options.month_names.() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Preferred date+time representation defp format_modifiers( "c" <> _rest, _width, _pad, _datetime, %{preferred_datetime_invoked: true}, _acc ) do raise RuntimeError, "tried to format preferred_datetime within another preferred_datetime format" end defp format_modifiers("c" <> rest, width, pad, datetime, format_options, acc) do result = format_options.preferred_datetime |> parse(datetime, %{format_options | preferred_datetime_invoked: true}, []) |> pad_preferred(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Day of the month defp format_modifiers("d" <> rest, width, pad, datetime, format_options, acc) do result = datetime.day |> Integer.to_string() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Microseconds defp format_modifiers("f" <> rest, _width, _pad, datetime, format_options, acc) do {microsecond, precision} = datetime.microsecond result = microsecond |> Integer.to_string() |> String.pad_leading(6, "0") |> binary_part(0, max(precision, 1)) parse(rest, datetime, format_options, [result | acc]) end # Hour using a 24-hour clock defp format_modifiers("H" <> rest, width, pad, datetime, format_options, acc) do result = datetime.hour |> Integer.to_string() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Hour using a 12-hour clock defp format_modifiers("I" <> rest, width, pad, datetime, format_options, acc) do result = (rem(datetime.hour() + 23, 12) + 1) |> Integer.to_string() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Day of the year defp format_modifiers("j" <> rest, width, pad, datetime, format_options, acc) do result = datetime |> Date.day_of_year() |> Integer.to_string() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Month defp format_modifiers("m" <> rest, width, pad, datetime, format_options, acc) do result = datetime.month |> Integer.to_string() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Minute defp format_modifiers("M" <> rest, width, pad, datetime, format_options, acc) do result = datetime.minute |> Integer.to_string() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # “AM” or “PM” (noon is “PM”, midnight as “AM”) defp format_modifiers("p" <> rest, width, pad, datetime, format_options, acc) do result = datetime.hour |> am_pm(format_options) |> String.upcase() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # “am” or “pm” (noon is “pm”, midnight as “am”) defp format_modifiers("P" <> rest, width, pad, datetime, format_options, acc) do result = datetime.hour |> am_pm(format_options) |> String.downcase() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Quarter defp format_modifiers("q" <> rest, width, pad, datetime, format_options, acc) do result = datetime |> Date.quarter_of_year() |> Integer.to_string() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Second defp format_modifiers("S" <> rest, width, pad, datetime, format_options, acc) do result = datetime.second |> Integer.to_string() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Day of the week defp format_modifiers("u" <> rest, width, pad, datetime, format_options, acc) do result = datetime |> Date.day_of_week() |> Integer.to_string() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Preferred date (without time) representation defp format_modifiers( "x" <> _rest, _width, _pad, _datetime, %{preferred_date_invoked: true}, _acc ) do raise RuntimeError, "tried to format preferred_date within another preferred_date format" end defp format_modifiers("x" <> rest, width, pad, datetime, format_options, acc) do result = format_options.preferred_date |> parse(datetime, %{format_options | preferred_date_invoked: true}, []) |> pad_preferred(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Preferred time (without date) representation defp format_modifiers( "X" <> _rest, _width, _pad, _datetime, %{preferred_time_invoked: true}, _acc ) do raise RuntimeError, "tried to format preferred_time within another preferred_time format" end defp format_modifiers("X" <> rest, width, pad, datetime, format_options, acc) do result = format_options.preferred_time |> parse(datetime, %{format_options | preferred_time_invoked: true}, []) |> pad_preferred(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Year as 2-digits defp format_modifiers("y" <> rest, width, pad, datetime, format_options, acc) do result = datetime.year |> rem(100) |> Integer.to_string() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # Year defp format_modifiers("Y" <> rest, width, pad, datetime, format_options, acc) do result = datetime.year |> Integer.to_string() |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end # +hhmm/-hhmm time zone offset from UTC (empty string if naive) defp format_modifiers( "z" <> rest, width, pad, datetime = %{utc_offset: utc_offset, std_offset: std_offset}, format_options, acc ) do absolute_offset = abs(utc_offset + std_offset) offset_number = Integer.to_string(div(absolute_offset, 3600) * 100 + rem(div(absolute_offset, 60), 60)) sign = if utc_offset + std_offset >= 0, do: "+", else: "-" result = "#{sign}#{pad_leading(offset_number, width, pad)}" parse(rest, datetime, format_options, [result | acc]) end defp format_modifiers("z" <> rest, _width, _pad, datetime, format_options, acc) do parse(rest, datetime, format_options, ["" | acc]) end # Time zone abbreviation (empty string if naive) defp format_modifiers("Z" <> rest, width, pad, datetime, format_options, acc) do result = datetime |> Map.get(:zone_abbr, "") |> pad_leading(width, pad) parse(rest, datetime, format_options, [result | acc]) end defp pad_preferred(result, width, pad) when length(result) < width do pad_preferred([pad | result], width, pad) end defp pad_preferred(result, _width, _pad), do: result defp pad_leading(string, count, padding) do to_pad = count - byte_size(string) if to_pad > 0, do: do_pad_leading(to_pad, padding, string), else: string end defp do_pad_leading(0, _, acc), do: acc defp do_pad_leading(count, padding, acc), do: do_pad_leading(count - 1, padding, [padding | acc]) defp options(user_options) do default_options = %{ preferred_date: "%Y-%m-%d", preferred_time: "%H:%M:%S", preferred_datetime: "%Y-%m-%d %H:%M:%S", am_pm_names: fn :am -> "am" :pm -> "pm" end, month_names: fn month -> {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} |> elem(month - 1) end, day_of_week_names: fn day_of_week -> {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"} |> elem(day_of_week - 1) end, abbreviated_month_names: fn month -> {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} |> elem(month - 1) end, abbreviated_day_of_week_names: fn day_of_week -> {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"} |> elem(day_of_week - 1) end, preferred_datetime_invoked: false, preferred_date_invoked: false, preferred_time_invoked: false } Enum.reduce(user_options, default_options, fn {key, value}, acc -> if Map.has_key?(acc, key) do %{acc | key => value} else acc end end) end end
lib/nimble_strftime.ex
0.896484
0.627152
nimble_strftime.ex
starcoder
alias Graphqexl.Query.{ Operation, ResultSet, Validator, } alias Graphqexl.{ Schema, Tokens, } alias Treex.Tree defmodule Graphqexl.Query do @moduledoc """ GraphQL query, comprised of one or more `t:Graphqexl.Query.Operation.t/0`s. Built by calling `parse/1` with either a `t:Graphqexl.Query.gql/0` string (see `Graphqexl.Schema.Dsl`) or `t:Graphqexl.Query.json/0`. """ @moduledoc since: "0.1.0" @enforce_keys [:operations] defstruct [:operations] @type gql:: String.t @type json:: %{String.t => term} @type resolver_fun:: (Map.t, Map.t, Map.t -> term) @type tokenizing_map:: %{stack: list, current: Operation.t, operations: list(Operation.t)} @type t :: %Graphqexl.Query{operations: list(Operation.t)} @doc """ Execute the given `t:Graphqexl.Query.t/0` Returns: `t:Graphqexl.Query.ResultSet.t/0` """ @doc since: "0.1.0" @spec execute(t, Schema.t) :: ResultSet.t def execute(query, schema) do query |> validate!(schema) |> resolve!(schema) end @doc """ Parse the given `t:Graphqexl.Schema.gql/0` string (see `Graphqexl.Schema.Dsl`) into a `t:Graphqexl.Query.t/0` Returns: `t:Graphqexl.Query.t/0` """ @doc since: "0.1.0" @spec parse(gql):: t def parse(gql) when is_binary(gql) do %Graphqexl.Query{ operations: gql |> preprocess |> Enum.reduce(%{stack: [], current: nil, operations: []}, &tokenize/2) |> Map.get(:operations) } end @doc """ Parse the given `t:Graphqexl.Query.json/0` object into a `t:Graphqexl.Query.t/0` Returns: `t:Graphqexl.Query.t/0` """ @doc since: "0.1.0" @spec parse(json):: t def parse(_json) # TODO: convert bare map to %Query{} @doc false @spec hydrate_arguments(Map.t, Map.t):: Map.t defp hydrate_arguments(arguments, variables) do arguments |> Enum.reduce(%{}, fn ({key, value}, hydrated_args) -> val = if is_atom(value) do variables |> Map.get(value) else value end hydrated_args |> Map.update(key, val, &(&1)) end) end @doc false @spec insert(ResultSet.t, Operation.t, Schema.t, Map.t):: ResultSet.t defp insert(result_set, operation, schema, context) do # TODO: pattern match on the whole {:ok, data} / {:error, errors} idea data_or_errors = operation |> invoke!( schema.resolvers |> Map.get(operation.name), context ) %{ result_set | data: result_set.data |> Map.update(operation.user_defined_name, data_or_errors, &(&1)) } end @doc false @spec invoke!(Operation.t, resolver_fun, Map.t):: Map.t | list(Map.t) defp invoke!(operation, resolver, context) do # TODO: probably want to do the error handling here, and return a {:ok, data} or {:error, errors} type of structure # TODO: parent context (i.e. where in the current query tree is this coming from) # TODO: recursively filter to selected fields resolver |> apply([%{}, operation.arguments |> hydrate_arguments(operation.variables), context]) end @doc false @spec new_operation(String.t):: Operation.t defp new_operation(line) do %{"type" => type, "name" => name, "arguments" => arguments} = %{"type" => "query"} |> Map.merge(:query_operation |> Tokens.patterns |> Regex.named_captures(line)) {args, vars} = if arguments |> String.at(1) == :variable |> Tokens.get do {nil, arguments} else {arguments, nil} end %Operation{ name: "@TO_BE_SET", type: type |> String.to_atom, user_defined_name: name |> String.to_atom, arguments: args |> tokenize_arguments, fields: %{}, variables: vars |> tokenize_variables } end @doc false @spec parse_value(String.t):: boolean | integer | float | String.t defp parse_value("false"), do: false defp parse_value("true"), do: true defp parse_value("null"), do: nil defp parse_value(value) do numeric? = Regex.match?(~r/"(\d+(\.\d+)?)"/, value) string? = Regex.match?(~r/\"(.*)\"/, value) cond do numeric? -> value |> String.replace(:quote |> Tokens.get, "") string? -> value |> String.replace(:quote |> Tokens.get, "") true -> raise "Invalid type: expected a string, number, boolean or null, got #{value}" end end @doc false @spec postprocess_variables(String.t):: String.t defp postprocess_variables(variables) do variables |> String.replace(:argument |> Tokens.get |> Map.get(:close), "") |> String.replace(:argument |> Tokens.get |> Map.get(:open), "") |> String.replace(:variable |> Tokens.get, "") |> preprocess_line end @doc false @spec preprocess(gql):: list(String.t) defp preprocess(gql) do gql |> pre_preprocess |> String.split(:newline |> Tokens.get) |> Enum.map(&String.trim/1) # This only works _after_ the map/trim above (otherwise the # may not be the first char) |> Enum.filter(&(!String.starts_with?(&1, :comment_char |> Tokens.get))) |> Enum.map(&(&1 |> String.replace("#{:newline |> Tokens.get}#{:fields |> Tokens.get |> Map.get(:open)}", :fields |> Tokens.get |> Map.get(:open)))) end @doc false @spec preprocess_line(String.t):: String.t defp preprocess_line(line) do line |> String.replace(:ignored_delimiter |> Tokens.get, "") |> String.replace(:fields |> Tokens.get |> Map.get(:close), "") |> String.replace(:fields |> Tokens.get |> Map.get(:open), "") |> String.trim end @doc false @spec pre_preprocess(gql):: String.t defp pre_preprocess(gql), do: gql |> String.trim @doc false @spec preprocess_variables(String.t):: String.t defp preprocess_variables(variables) do variables |> String.replace( "#{:argument_delimiter |> Tokens.get}#{:space |> Tokens.get}", :argument_delimiter |> Tokens.get ) end @doc false @spec resolve!(t, Schema.t, Map.t):: ResultSet.t defp resolve!(query, schema, context \\ %{}) do query.operations |> Enum.reduce(%ResultSet{}, &(&2 |> insert(&1, schema, context))) |> ResultSet.validate!(schema) |> ResultSet.filter(query.operations |> List.first |> Map.get(:fields)) end @doc false @spec stack_pop(list):: term defp stack_pop(stack), do: stack |> List.pop_at(0) @doc false @spec stack_push(list, term):: list defp stack_push(stack, value), do: stack |> List.insert_at(0, value) @doc false @spec tokenize(String.t, tokenizing_map):: tokenizing_map defp tokenize(line, %{stack: stack, current: current, operations: operations}) do last_char = line |> String.at(-1) cond do last_char == :fields |> Tokens.get |> Map.get(:open) -> case stack |> Enum.count do 0 -> if is_nil(current) do %{stack: stack, current: line |> new_operation, operations: operations} else if line |> String.contains?(:argument_delimiter |> Tokens.get) do %{"name" => name, "arguments" => arguments} = %{"type" => "query"} |> Map.merge( :query_operation |> Tokens.patterns |> Regex.named_captures(line) ) new_current = %{ current | name: name |> String.to_atom, arguments: arguments |> tokenize_arguments } %{stack: stack |> stack_push([]), current: new_current, operations: operations} else %{stack: stack |> stack_push([]), current: current, operations: operations} end end _ -> {top, remaining} = stack |> stack_pop new_top = top |> stack_push({ line |> preprocess_line |> String.to_atom, %{} }) new_stack = remaining |> stack_push(new_top) |> stack_push([]) %{stack: new_stack, current: current, operations: operations} end last_char == :fields |> Tokens.get |> Map.get(:close) -> case stack |> Enum.count do 0 -> %{stack: [], current: nil, operations: operations} 1 -> %{ stack: [], current: current, operations: operations |> stack_push(%{ current | fields: stack |> stack_pop |> elem(0) |> Enum.into(%{}) |> Tree.from_map(current.user_defined_name) }) } _ -> {top, rest} = stack |> stack_pop {new_top, remaining} = rest |> stack_pop {parent, others} = new_top |> stack_pop new_parent = others |> stack_push({parent |> elem(0), top |> Enum.into(%{})}) %{stack: remaining |> stack_push(new_parent), current: current, operations: operations} end true -> {top, remaining} = stack |> stack_pop new_top = top |> stack_push({line |> preprocess_line |> String.to_atom, %{}}) %{stack: remaining |> stack_push(new_top), current: current, operations: operations} end end @doc false @spec tokenize_arguments(String.t | nil):: Map.t defp tokenize_arguments(nil), do: %{} defp tokenize_arguments(arguments) do arguments |> preprocess_variables |> String.split(:space |> Tokens.get) |> Enum.reduce(%{}, fn (arg, vars) -> [name, value] = arg |> String.split(:argument_delimiter |> Tokens.get) vars |> Map.update( name |> postprocess_variables |> String.to_atom, value |> postprocess_variables |> String.to_atom, &(&1) ) end) end @doc false @spec tokenize_variables(String.t | nil):: Map.t defp tokenize_variables(nil), do: %{} defp tokenize_variables(variables) do variables |> preprocess_variables |> String.split(:space |> Tokens.get) |> Enum.reduce(%{}, fn (arg, vars) -> [name, value] = arg |> String.split(:argument_delimiter |> Tokens.get) vars |> Map.update( name |> postprocess_variables |> String.to_atom, value |> postprocess_variables |> parse_value, &(&1) ) end) end @doc false @spec validate!(t, Schema.t):: boolean defp validate!(query, schema) do true = query.operations |> Enum.all?(&(Validator.valid?(&1, schema))) query end end
lib/graphqexl/query.ex
0.730866
0.496704
query.ex
starcoder
defmodule AWS.Codestarnotifications do @moduledoc """ This AWS CodeStar Notifications API Reference provides descriptions and usage examples of the operations and data types for the AWS CodeStar Notifications API. You can use the AWS CodeStar Notifications API to work with the following objects: Notification rules, by calling the following: * `CreateNotificationRule`, which creates a notification rule for a resource in your account. * `DeleteNotificationRule`, which deletes a notification rule. * `DescribeNotificationRule`, which provides information about a notification rule. * `ListNotificationRules`, which lists the notification rules associated with your account. * `UpdateNotificationRule`, which changes the name, events, or targets associated with a notification rule. * `Subscribe`, which subscribes a target to a notification rule. * `Unsubscribe`, which removes a target from a notification rule. Targets, by calling the following: * `DeleteTarget`, which removes a notification rule target (SNS topic) from a notification rule. * `ListTargets`, which lists the targets associated with a notification rule. Events, by calling the following: * `ListEventTypes`, which lists the event types you can include in a notification rule. Tags, by calling the following: * `ListTagsForResource`, which lists the tags already associated with a notification rule in your account. * `TagResource`, which associates a tag you provide with a notification rule in your account. * `UntagResource`, which removes a tag from a notification rule in your account. For information about how to use AWS CodeStar Notifications, see link in the CodeStarNotifications User Guide. """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: nil, api_version: "2019-10-15", content_type: "application/x-amz-json-1.1", credential_scope: nil, endpoint_prefix: "codestar-notifications", global?: false, protocol: "rest-json", service_id: "codestar notifications", signature_version: "v4", signing_name: "codestar-notifications", target_prefix: nil } end @doc """ Creates a notification rule for a resource. The rule specifies the events you want notifications about and the targets (such as SNS topics) where you want to receive them. """ def create_notification_rule(%Client{} = client, input, options \\ []) do url_path = "/createNotificationRule" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Deletes a notification rule for a resource. """ def delete_notification_rule(%Client{} = client, input, options \\ []) do url_path = "/deleteNotificationRule" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Deletes a specified target for notifications. """ def delete_target(%Client{} = client, input, options \\ []) do url_path = "/deleteTarget" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Returns information about a specified notification rule. """ def describe_notification_rule(%Client{} = client, input, options \\ []) do url_path = "/describeNotificationRule" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Returns information about the event types available for configuring notifications. """ def list_event_types(%Client{} = client, input, options \\ []) do url_path = "/listEventTypes" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Returns a list of the notification rules for an AWS account. """ def list_notification_rules(%Client{} = client, input, options \\ []) do url_path = "/listNotificationRules" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Returns a list of the tags associated with a notification rule. """ def list_tags_for_resource(%Client{} = client, input, options \\ []) do url_path = "/listTagsForResource" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Returns a list of the notification rule targets for an AWS account. """ def list_targets(%Client{} = client, input, options \\ []) do url_path = "/listTargets" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Creates an association between a notification rule and an SNS topic so that the associated target can receive notifications when the events described in the rule are triggered. """ def subscribe(%Client{} = client, input, options \\ []) do url_path = "/subscribe" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Associates a set of provided tags with a notification rule. """ def tag_resource(%Client{} = client, input, options \\ []) do url_path = "/tagResource" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Removes an association between a notification rule and an Amazon SNS topic so that subscribers to that topic stop receiving notifications when the events described in the rule are triggered. """ def unsubscribe(%Client{} = client, input, options \\ []) do url_path = "/unsubscribe" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Removes the association between one or more provided tags and a notification rule. """ def untag_resource(%Client{} = client, input, options \\ []) do url_path = "/untagResource" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Updates a notification rule for a resource. You can change the events that trigger the notification rule, the status of the rule, and the targets that receive the notifications. To add or remove tags for a notification rule, you must use `TagResource` and `UntagResource`. """ def update_notification_rule(%Client{} = client, input, options \\ []) do url_path = "/updateNotificationRule" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end end
lib/aws/generated/codestarnotifications.ex
0.838481
0.405979
codestarnotifications.ex
starcoder
defmodule Surface.Components.Context do @moduledoc """ A built-in component that allows users to set and retrieve values from the context. """ use Surface.Component @doc """ Puts a value into the context. ## Usage ``` <Context put={{ scope, values }}> ... </Context> ``` Where: * `scope` - Optional. Is an atom representing the scope where the values will be stored. If no scope is provided, the value is stored at the root of the context map. * `values`- A keyword list containing the key-value pairs that will be stored in the context. ## Examples With scope: ``` <Context put={{ __MODULE__, form: @form }}> ... </Context> ``` Without scope: ``` <Context put={{ key1: @value1, key2: "some other value" }}> ... </Context> ``` """ prop put, :context_put, accumulate: true, default: [] @doc """ Retrieves a set of values from the context binding them to local variables. ## Usage ``` <Context get={{ scope, bindings }}> ... </Context> ``` Where: * `scope` - Optional. Is an atom representing the scope where the values will be stored. If no scope is provided, the value is stored at the root of the context map. * `bindings`- A keyword list of bindings that will be retrieved from the context as local variables. ## Examples ``` <Context get={{ Form, form: form }} get={{ Field, field: my_field }}> <MyTextInput form={{ form }} field={{ my_field }} /> </Context> ``` """ prop get, :context_get, accumulate: true, default: [] @doc "The content of the `<Context>`" slot default, required: true def transform(node) do Module.put_attribute(node.meta.caller.module, :use_context?, true) let = node.props |> Enum.filter(fn %{name: name} -> name == :get end) |> Enum.map(fn %{value: %{value: value}} -> value end) |> Enum.flat_map(fn {scope, values} -> if scope == nil do values else Enum.map(values, fn {key, value} -> {{scope, key}, value} end) end end) update_let_for_template(node, :default, let) end def render(assigns) do ~F""" {case context_map(@__context__, @put, @get) do {ctx, props} -> render_block(@inner_block, {:default, 0, props, ctx}) end} """ end defp context_map(context, puts, gets) do ctx = for {scope, values} <- puts, {key, value} <- values, reduce: context do acc -> {full_key, value} = normalize_set(scope, key, value) Map.put(acc, full_key, value) end props = for {scope, values} <- gets, {key, _value} <- values, into: %{} do key = if scope == nil do key else {scope, key} end {key, Map.get(ctx, key, nil)} end {ctx, props} end defp normalize_set(nil, key, value) do {key, value} end defp normalize_set(scope, key, value) do {{scope, key}, value} end defp update_let_for_template(node, template_name, let) do updated = node.templates |> Map.get(template_name, []) |> Enum.map(fn template -> %{template | let: let} end) templates = Map.put(node.templates, template_name, updated) Map.put(node, :templates, templates) end end
lib/surface/components/context.ex
0.928587
0.918626
context.ex
starcoder
defmodule Comms.Actor do @moduledoc """ A behaviour module for implementing general purpose actors. A `Comms.Actor` is designed to allow easy implementation of the actor model. ## Example defmodule Ping do use Comms.Actor @impl Comms.Actor def handle({:ping, pid}, state) do {[{pid, :pong}], state} end end {:ok, p} = Comms.Actor.start_link(Ping, nil) send(p, {:ping, self()}) flush() # => :pong ## Actor Model > An actor is a computational entity that, in response to a message it receives, can concurrently: > > 1. send a finite number of messages to other actors; > 2. create a finite number of new actors; > 3. designate the behavior to be used for the next message it receives. > > There is no assumed sequence to the above actions and they could be carried out in parallel. The `Comms.Actor` behavior is a replacement for `GenServer` that more closely follows these principles. - There is only one callback to deal with incomming messages, `handle/2`. `Comms.Actor` works with `GenServer.call/2` etc but these are just another type of message - The return value of the `handle/2` callback is always the same shape. A list of outbound messages and a new state. This allows an `Comms.Agent` to send any number of replies rather than 1 or 0 that is the case for GenServers. ## Gen messages Calls and cast from the `GenServer` module etc are just wrappers around the erlang `:gen` module. A proccess implementing `Comms.Actor` can respond to these like normal messages. defmodule PairUp do use Comms.Actor def start_link do Comms.Actor.start_link(__MODULE__, :none) end @impl Comms.Actor def handle({:"$gen_call", from, {:pair, pid}}, :none) do {[], {:waiting, from, pid}} end def handle({:"$gen_call", from2, {:pair, pid2}}, {:waiting, from1, pid1}) do messages = [ {from2, {:other, pid1}}, {from1, {:other, pid2}}, ] {messages, :none} end end """ @typedoc """ Location where an actor can direct messages too. """ @type address :: pid | {pid, reference} | :timeout @typedoc """ The payload of a sent or received message """ @type message :: term @typedoc """ Any value that an actor maintains between receiving messages """ @type state :: term @typedoc """ Response to a """ @type reaction :: {[{address, message}], state} @callback handle(message, state) :: reaction defmacro __using__(_opts) do quote location: :keep do use GenServer @behaviour unquote(__MODULE__) @impl GenServer def handle_call(message, from, state) do handle({:"$gen_call", from, message}, state) |> react_to_action() end @impl GenServer def handle_cast(message, state) do handle({:"$gen_cast", message}, state) |> react_to_action() end @impl GenServer def handle_info(message, state) do handle(message, state) |> react_to_action() end defp react_to_action({outbound, new_state}) do {timeout, outbound} = Keyword.pop(outbound, :timeout, :infinity) outbound |> Enum.each(fn {t, m} -> deliver(t, m) end) case new_state do {:STOP, reason, state} -> {:stop, reason, state} _ -> {:noreply, new_state, timeout} end end defp deliver(target, message) when is_pid(target) do send(target, message) end defp deliver(from = {p, r}, message) when is_pid(p) and is_reference(r) do GenServer.reply(from, message) end end end @doc """ Starts a `Comms.Actor` process without links (outside of a supervision tree). See start_link/3 for more information. """ @spec start(module(), any(), GenServer.options()) :: GenServer.on_start() def start(module, args, options \\ []) do GenServer.start(module, args, options) end @doc """ Starts a `Comms.Actor` process linked to the current process. The arguments for this are identical to `GenServer.start_link/3` and should be used for reference docs. """ @spec start_link(module(), any(), GenServer.options()) :: GenServer.on_start() def start_link(module, args, options \\ []) do GenServer.start_link(module, args, options) end end
lib/comms/actor.ex
0.878783
0.529081
actor.ex
starcoder
defmodule BSV.PubKey do @moduledoc """ A PubKey is a data structure representing a Bitcoin public key. Internally, a public key is the `x` and `y` coordiantes of a point of the `secp256k1` curve. It is derived by performaing elliptic curve multiplication on a corresponding private key. """ alias BSV.PrivKey alias Curvy.{Key, Point} import BSV.Util, only: [decode: 2, encode: 2] defstruct point: nil, compressed: true @typedoc "Public key struct" @type t() :: %__MODULE__{ point: Point.t(), compressed: boolean() } @doc """ Parses the given binary into a `t:BSV.PubKey.t/0`. Returns the result in an `:ok` / `:error` tuple pair. ## Options The accepted options are: * `:encoding` - Optionally decode the binary with either the `:base64` or `:hex` encoding scheme. ## Examples iex> PubKey.from_binary("03f81f8c8b90f5ec06ee4245eab166e8af903fc73a6dd73636687ef027870abe39", encoding: :hex) {:ok, %PubKey{ compressed: true, point: %Curvy.Point{ x: 112229328714845468078961951285525025245993969218674417992740440691709714284089, y: 691772308660403791193362590139379363593914935665750098177712560871566383255 } }} """ @spec from_binary(binary(), keyword()) :: {:ok, t()} | {:error, term()} def from_binary(pubkey, opts \\ []) when is_binary(pubkey) do encoding = Keyword.get(opts, :encoding) with {:ok, pubkey} when byte_size(pubkey) in [33, 65] <- decode(pubkey, encoding) do %Key{point: point, compressed: compressed} = Key.from_pubkey(pubkey) {:ok, struct(__MODULE__, point: point, compressed: compressed)} else {:ok, pubkey} -> {:error, {:invalid_pubkey, byte_size(pubkey)}} error -> error end end @doc """ Parses the given binary into a `t:BSV.PubKey.t/0`. As `from_binary/2` but returns the result or raises an exception. """ @spec from_binary!(binary(), keyword()) :: t() def from_binary!(pubkey, opts \\ []) when is_binary(pubkey) do case from_binary(pubkey, opts) do {:ok, pubkey} -> pubkey {:error, {:invalid_pubkey, _length} = error} -> raise BSV.DecodeError, error {:error, error} -> raise error end end @doc """ Returns a `t:BSV.PubKey.t/0` derived from the given `t:BSV.PrivKey.t/0`. """ @spec from_privkey(PrivKey.t()) :: t() def from_privkey(%PrivKey{d: d, compressed: compressed}) do {pubkey, _privkey} = :crypto.generate_key(:ecdh, :secp256k1, d) %Key{point: point} = Key.from_pubkey(pubkey) struct(__MODULE__, point: point, compressed: compressed) end @doc """ Serialises the given `t:BSV.PrivKey.t/0` into a binary. ## Options The accepted options are: * `:encoding` - Optionally encode the binary with either the `:base64` or `:hex` encoding scheme. ## Examples iex> PubKey.to_binary(@pubkey, encoding: :hex) "03f81f8c8b90f5ec06ee4245eab166e8af903fc73a6dd73636687ef027870abe39" """ @spec to_binary(t(), keyword()) :: binary() def to_binary(%__MODULE__{point: point, compressed: compressed}, opts \\ []) do encoding = Keyword.get(opts, :encoding) %Key{point: point, compressed: compressed} |> Key.to_pubkey() |> encode(encoding) end end
lib/bsv/pub_key.ex
0.936793
0.711757
pub_key.ex
starcoder
defmodule Prometheus.PlugInstrumenter do @moduledoc """ Helps you create a plug that instruments another plug(s). Internally works like and uses Plug.Builder so can instrument many plugs at once. Just use regular plug macro! ### Usage 1. Define your instrumenter: ```elixir defmodule EnsureAuthenticatedInstrumenter do use Prometheus.PlugInstrumenter plug Guardian.Plug.EnsureAuthenticated def label_value(:authenticated, {conn, _}) do conn.status != 401 end end ``` 2. Configuration: ```elixir config :prometheus, EnsureAuthenticatedInstrumenter, counter: :guardian_ensure_authenticated_total, counter_help: "Total number of EnsureAuthenticated plug calls.", histogram: :guardian_ensure_authenticated_duration_microseconds, histogram_help: "Duration of EnsureAuthenticated plug calls.", labels: [:authenticated] ``` 3. Call `EnsureAuthenticatedInstrumenter.setup/0` when application starts (e.g. supervisor setup): ```elixir EnsureAuthenticatedInstrumenter.setup() ``` 4. Add `EnsureAuthenticatedInstrumenter` to your plug pipeline or replace `Guardian.Plug.EnsureAuthenticated` if it already present. ```elixir: plug EnsureAuthenticatedInstrumenter, handler: Guardian.Plug.ErrorHandler ``` As you can see you can transparently pass options to the underlying plug. ### Metrics Currently PlugInstrumenter supports two metrics - counter for total calls count and histogram for calls duration. Metric can be disabled by setting it's name to false: ```elixir counter: false ``` There should be at least one active metric. ### Configuration Plug pipeline instrumenter can be configured via `EnsureAuthenticatedInstrumenter` (you should replace this with the name of your plug) key of prometheus app env. Mandatory keys: - counter or histogram. Optional keys with defaults: - registry - Prometheus registry for metrics (:default); - counter - counter metric name (false); - counter_help - help string for counter metric (""); - histogram - histogram metric name (false); - histogram_help - help string for histogram metric (""); - histogram_buckets - histogram metric buckets (Prometheus.Contrib.HTTP.microseconds_duration_buckets()); - labels - labels for counter and histogram ([]); - duration_units - duration units for the histogram, if histogram name already has known duration unit this can be omitted (:undefined). As noted above at least one metric name should be given. Of course you must tell what plug(s) to instrument. We don't have default labels because they are highly specific to a particular plug(s) hence default is []. Bear in mind that buckets are ***<duration_unit>*** so if you are not using default unit you also have to override buckets. """ require Logger require Prometheus.Contrib.HTTP use Prometheus.Config, counter: false, counter_help: "", histogram: false, histogram_help: "", histogram_buckets: Prometheus.Contrib.HTTP.microseconds_duration_buckets(), labels: [], registry: :default, duration_unit: :undefined use Prometheus.Metric defmacro __using__(_opts) do module_name = __CALLER__.module counter = Config.counter(module_name) counter_help = Config.counter_help(module_name) histogram = Config.histogram(module_name) histogram_help = Config.histogram_help(module_name) histogram_buckets = Config.histogram_buckets(module_name) labels = Config.labels(module_name) nlabels = normalize_labels(labels) registry = Config.registry(module_name) duration_unit = Config.duration_unit(module_name) if !counter and !histogram do raise "No metrics!" end quote location: :keep do @behaviour Plug Module.register_attribute(__MODULE__, :plugs, accumulate: true) use Prometheus.Metric import Prometheus.PlugInstrumenter def setup() do unquote( if counter do quote do Counter.declare( name: unquote(counter), help: unquote(counter_help), labels: unquote(nlabels), registry: unquote(registry) ) end end ) unquote( if histogram do quote do Histogram.declare( name: unquote(histogram), help: unquote(histogram_help), labels: unquote(nlabels), buckets: unquote(histogram_buckets), registry: unquote(registry), duration_unit: unquote(duration_unit) ) end end ) end def init(opts) do opts end def call(conn, state) do unquote( if histogram do quote do start = :erlang.monotonic_time() end end ) conn = call_pipeline(conn) unquote( if histogram do quote do diff = :erlang.monotonic_time() - start end end ) labels = unquote(construct_labels(labels)) unquote( if histogram do quote do Histogram.observe( [name: unquote(histogram), labels: labels, registry: unquote(registry)], diff ) end end ) unquote( if counter do quote do Counter.inc( name: unquote(counter), labels: labels, registry: unquote(registry) ) end end ) conn end @before_compile Prometheus.PlugInstrumenter end end @doc """ Stores a plug to be instrumented. """ defmacro plug(plug, opts \\ []) do quote do @plugs {unquote(plug), unquote(opts), true} end end @doc false defmacro __before_compile__(env) do plugs = Module.get_attribute(env.module, :plugs) {conn, body} = Plug.Builder.compile(env, plugs, []) quote do defp call_pipeline(unquote(conn)), do: unquote(body) end end defp normalize_labels(labels) do for label <- labels do case label do {name, _} -> name name -> name end end end defp construct_labels(labels) do for label <- labels, do: label_value(label) end defp label_value({label, {module, fun}}) do quote do unquote(module).unquote(fun)(unquote(label), {conn, state}) end end defp label_value({label, module}) do quote do unquote(module).label_value(unquote(label), {conn, state}) end end defp label_value(label) do quote do label_value(unquote(label), {conn, state}) end end end
lib/prometheus/plug_instrumenter.ex
0.870418
0.836488
plug_instrumenter.ex
starcoder
defmodule RouteGuide.Client do def main(channel) do print_feature(channel, Routeguide.Point.new(latitude: 409_146_138, longitude: -746_188_906)) print_feature(channel, Routeguide.Point.new(latitude: 0, longitude: 0)) # Looking for features between 40, -75 and 42, -73. print_features( channel, Routeguide.Rectangle.new( lo: Routeguide.Point.new(latitude: 400_000_000, longitude: -750_000_000), hi: Routeguide.Point.new(latitude: 420_000_000, longitude: -730_000_000) ) ) run_record_route(channel) run_route_chat(channel) end def print_feature(channel, point) do IO.puts("Getting feature for point (#{point.latitude}, #{point.longitude})") {:ok, reply} = channel |> Routeguide.RouteGuide.Stub.get_feature(point) IO.inspect(reply) end def print_features(channel, rect) do IO.puts("Looking for features within #{inspect(rect)}") {:ok, stream} = channel |> Routeguide.RouteGuide.Stub.list_features(rect) Enum.each(stream, fn {:ok, feature} -> IO.inspect(feature) end) end def run_record_route(channel) do ts = :os.timestamp() seed = :rand.seed(:exs64, ts) {count, seed} = :rand.uniform_s(seed) count = trunc(count * 100 + 2) {points, _seed} = Enum.reduce(1..count, {[], seed}, fn _, {acc, seed} -> {point, seed} = random_point(seed) {[point | acc], seed} end) IO.puts("Traversing #{length(points)} points.") stream = channel |> Routeguide.RouteGuide.Stub.record_route() Enum.reduce(points, points, fn _, [point | tail] -> opts = if length(tail) == 0, do: [end_stream: true], else: [] GRPC.Stub.send_request(stream, point, opts) tail end) res = GRPC.Stub.recv(stream) IO.puts("Route summary: #{inspect(res)}") end def run_route_chat(channel) do data = [ %{lat: 0, long: 1, msg: "First message"}, %{lat: 0, long: 2, msg: "Second message"}, %{lat: 0, long: 3, msg: "Third message"}, %{lat: 0, long: 1, msg: "Fourth message"}, %{lat: 0, long: 2, msg: "Fifth message"}, %{lat: 0, long: 3, msg: "Sixth message"} ] stream = channel |> Routeguide.RouteGuide.Stub.route_chat() notes = Enum.map(data, fn %{lat: lat, long: long, msg: msg} -> point = Routeguide.Point.new(latitude: lat, longitude: long) Routeguide.RouteNote.new(location: point, message: msg) end) task = Task.async(fn -> Enum.reduce(notes, notes, fn _, [note | tail] -> opts = if length(tail) == 0, do: [end_stream: true], else: [] GRPC.Stub.send_request(stream, note, opts) tail end) end) {:ok, result_enum} = GRPC.Stub.recv(stream) Task.await(task) Enum.each(result_enum, fn {:ok, note} -> IO.puts( "Got message #{note.message} at point(#{note.location.latitude}, #{ note.location.longitude })" ) end) end defp random_point(seed) do {lat, seed} = :rand.uniform_s(seed) {long, seed} = :rand.uniform_s(seed) lat = trunc((trunc(lat * 180) - 90) * 1.0e7) long = trunc((trunc(long * 360) - 180) * 1.0e7) {Routeguide.Point.new(latitude: lat, longitude: long), seed} end end
examples/route_guide/lib/client.ex
0.569015
0.489015
client.ex
starcoder
defmodule Cog.TemplateCase do use ExUnit.CaseTemplate, async: true alias Cog.Template alias Greenbar.Renderers.SlackRenderer alias Greenbar.Renderers.HipChatRenderer using do quote do # Extract the processor name from the module. We can then set the @moduletag # to 'template: <processor>' so we can more easily target processor specific # template tests. processor = Module.split(__MODULE__) |> Enum.map(&String.downcase/1) |> Enum.reduce_while(nil, fn ("hipchat", nil) -> {:halt, :hipchat} ("slack", nil) -> {:halt, :slack} (_, nil) -> {:cont, nil} end) import unquote(__MODULE__) @moduletag templates: processor end end def assert_rendered_template(:hipchat, bundle, template_name, data, expected) when is_binary(expected) do directives = directives_for_template(bundle, template_name, data) rendered = HipChatRenderer.render(directives) assert expected == rendered end def assert_rendered_template(:slack, bundle, template_name, data, expected) when is_binary(expected) do directives = directives_for_template(bundle, template_name, data) {rendered, _} = SlackRenderer.render(directives) assert expected == rendered end def assert_rendered_template(:slack, bundle, template_name, data, {text, attachments}) do directives = directives_for_template(bundle, template_name, data) {message, rendered} = SlackRenderer.render(directives) assert text == message cond do is_binary(attachments) -> assert attachments == Enum.at(rendered, 0) |> Map.get("text") length(attachments) == 0 -> assert attachments == rendered attachments -> attachments |> Enum.with_index |> Enum.each(fn({attachment, index}) -> assert attachment == Enum.at(rendered, index) |> Map.get("text") end) end end def assert_directives({bundle, template_name}, data, expected), do: assert expected == directives_for_template(bundle, template_name, data) def assert_directives(template_name, data, expected), do: assert_directives({:common, template_name}, data, expected) def directives_for_template(bundle, template_name, data) do source = template_source(template_name, bundle) case Cog.Template.Evaluator.do_evaluate(template_name, source, data) do {:error, reason} -> flunk "Greenbar evaluation error: #{reason}" directives -> directives |> stringify end end # This mimics the round-trip through Carrier that real code will # experience. defp stringify(input), do: input |> Poison.encode! |> Poison.decode! def template_source(template_name, bundle) when bundle in [:common, :embedded] do Template.template_dir(bundle) |> Path.join("#{template_name}#{Template.extension}") |> File.read! end end
test/support/template_case.ex
0.698844
0.468122
template_case.ex
starcoder
defmodule Ecto.Changeset do @moduledoc """ Changesets allow filtering, casting and validation of model changes. There is an example of working with changesets in the introductory documentation in the `Ecto` module. ## The Ecto.Changeset struct The fields are: * `valid?` - Stores if the changeset is valid * `repo` - The repository applying the changeset (only set after a Repo function is called) * `model` - The changeset root model * `params` - The parameters as given on changeset creation * `changes` - The `changes` from parameters that were approved in casting * `errors` - All errors from validations * `validations` - All validations performed in the changeset * `required` - All required fields as a list of atoms * `optional` - All optional fields as a list of atoms * `filters` - Filters (as a map `%{field => value}`) to narrow the scope of update/delete queries """ alias __MODULE__ import Ecto.Query, only: [from: 2] defstruct valid?: false, model: nil, params: nil, changes: %{}, repo: nil, errors: [], validations: [], required: [], optional: [], filters: %{} @type error :: {atom, atom | {atom, [term]}} @type t :: %Changeset{valid?: boolean(), repo: atom | nil, model: Ecto.Model.t | nil, params: %{String.t => term} | nil, changes: %{atom => term}, required: [atom], optional: [atom], errors: [error], validations: [{atom, atom | {atom, [term]}}], filters: %{atom => term}} @doc """ Wraps the given model in a changeset or adds changes to a changeset. This function is useful for: * wrapping a model inside a changeset * directly changing the model without performing castings nor validations * directly bulk-adding changes to a changeset Since no validation nor casting is performed, `change/2` expects the keys in `changes` to be atoms. `changes` can be a map as well as a keyword list. When a changeset is passed as the first argument, the changes passed as the second argument are merged over the changes already in the changeset (with precedence to the new changes). If `changes` is not present or is an empty map, this function is a no-op. See `cast/4` if you'd prefer to cast and validate external parameters. ## Examples iex> changeset = change(%Post{}) %Ecto.Changeset{...} iex> changeset.valid? true iex> changeset.changes %{} iex> changeset = change(%Post{}, title: "title") iex> changeset.changes.title "title" iex> changeset = change(changeset, %{title: "new title", body: "body"}) iex> changeset.changes.title "new title" iex> changeset.changes.body "body" """ @spec change(Ecto.Model.t | t, %{atom => term} | [Keyword.t]) :: t def change(model_or_changeset, changes \\ %{}) def change(model_or_changeset, changes) when is_list(changes) do change(model_or_changeset, Enum.into(changes, %{})) end def change(%Changeset{changes: changes} = changeset, new_changes) when is_map(new_changes) do %{changeset | changes: Map.merge(changes, new_changes)} end def change(%{__struct__: _} = model, changes) when is_map(changes) do %Changeset{valid?: true, model: model, changes: changes} end @doc """ Converts the given `params` into a changeset for `model` keeping only the set of `required` and `optional` keys. This functions receives a model and some `params`, and casts the `params` according to the schema information from `model`. `params` is a map with string keys or a map with atom keys containing potentially unsafe data. During casting, all valid parameters will have their key name converted to an atom and stored as a change in the `:changes` field of the changeset. All parameters that are not listed in `required` or `optional` are ignored. If casting of all fields is successful and all required fields are present either in the model or in the given params, the changeset is returned as valid. ## No parameters The `params` argument can also be `nil`. In such cases, the changeset is automatically marked as invalid, with an empty `:changes` map. This is useful to run the changeset through all validation steps for introspection. ## Composing casts `cast/4` also accepts a changeset instead of a model as its first argument. In such cases, all the effects caused by the call to `cast/4` (additional and optional fields, errors and changes) are simply added to the ones already present in the argument changeset. Parameters are merged (**not deep-merged**) and the ones passed to `cast/4` take precedence over the ones already in the changeset. Note that if a field is marked both as *required* as well as *optional* (for example by being in the `:required` field of the argument changeset and also in the `optional` list passed to `cast/4`), then it will be marked as required and not optional). This represents the fact that required fields are "stronger" than optional fields. ## Examples iex> changeset = cast(post, params, ~w(title), ~w()) iex> if changeset.valid? do ...> Repo.update(changeset) ...> end Passing a changeset as the first argument: iex> changeset = cast(post, %{title: "Hello"}, ~w(), ~w(title)) iex> new_changeset = cast(changeset, %{title: "Foo", body: "Bar"}, ~w(title), ~w(body)) iex> new_changeset.params %{title: "Foo", body: "Bar"} iex> new_changeset.required [:title] iex> new_changeset.optional [:body] """ @spec cast(Ecto.Model.t | t, %{binary => term} | %{atom => term} | nil, [String.t | atom], [String.t | atom]) :: t def cast(model_or_changeset, params, required, optional \\ []) def cast(_model, %{__struct__: _} = params, _required, _optional) do raise ArgumentError, "expected params to be a map, got struct `#{inspect params}`" end def cast(%{__struct__: _} = model, nil, required, optional) when is_list(required) and is_list(optional) do to_atom = fn key when is_atom(key) -> key key when is_binary(key) -> String.to_atom(key) end required = Enum.map(required, to_atom) optional = Enum.map(optional, to_atom) %Changeset{params: nil, model: model, valid?: false, errors: [], changes: %{}, required: required, optional: optional} end def cast(%Changeset{} = changeset, %{} = params, required, optional) when is_list(required) and is_list(optional) do new_changeset = cast(changeset.model, params, required, optional) merge(changeset, new_changeset) end def cast(%{__struct__: module} = model, %{} = params, required, optional) when is_list(required) and is_list(optional) do params = convert_params(params) types = module.__changeset__ {optional, {changes, errors}} = Enum.map_reduce(optional, {%{}, []}, &process_optional(&1, params, types, &2)) {required, {changes, errors}} = Enum.map_reduce(required, {changes, errors}, &process_required(&1, params, types, model, &2)) %Changeset{params: params, model: model, valid?: errors == [], errors: errors, changes: changes, required: required, optional: optional} end defp process_required(key, params, types, model, {changes, errors}) do {key, param_key} = cast_key(key) type = type!(types, key) {key, case cast_field(param_key, type, params) do {:ok, value} -> {Map.put(changes, key, value), error_on_nil(key, value, errors)} :missing -> value = Map.get(model, key) {changes, error_on_nil(key, value, errors)} :invalid -> {changes, [{key, :invalid}|errors]} end} end defp process_optional(key, params, types, {changes, errors}) do {key, param_key} = cast_key(key) type = type!(types, key) {key, case cast_field(param_key, type, params) do {:ok, value} -> {Map.put(changes, key, value), errors} :missing -> {changes, errors} :invalid -> {changes, [{key, :invalid}|errors]} end} end defp type!(types, key), do: Map.get(types, key) || raise ArgumentError, "unknown field `#{key}`" defp cast_key(key) when is_binary(key), do: {String.to_atom(key), key} defp cast_key(key) when is_atom(key), do: {key, Atom.to_string(key)} defp cast_field(param_key, type, params) do case Map.fetch(params, param_key) do {:ok, value} -> case Ecto.Type.cast(type, value) do {:ok, value} -> {:ok, value} :error -> :invalid end :error -> :missing end end defp convert_params(params) do Enum.reduce(params, nil, fn {key, _value}, nil when is_binary(key) -> nil {key, _value}, _ when is_binary(key) -> raise ArgumentError, "expected params to be a map with atoms or string keys, " <> "got a map with mixed keys: #{inspect params}" {key, value}, acc when is_atom(key) -> Map.put(acc || %{}, Atom.to_string(key), value) end) || params end defp error_on_nil(key, value, errors) do if is_nil value do [{key, :required}|errors] else errors end end ## Working with changesets @doc """ Merges two changesets. This function merges two changesets provided they have been applied to the same model (their `:model` field is equal); if the models differ, an `ArgumentError` exception is raised. If one of the changesets has a `:repo` field which is not `nil`, then the value of that field is used as the `:repo` field of the resulting changeset; if both changesets have a non-`nil` and different `:repo` field, an `ArgumentError` exception is raised. The other fields are merged with the following criteria: * `params` - params are merged (not deep-merged) giving precedence to the params of `changeset2` in case of a conflict. If either changeset has its `:params` field set to `nil`, the resulting changeset will have its params set to `nil` too. * `changes` - changes are merged giving precedence to the `changeset2` changes. * `errors` and `validations` - they are simply concatenated. * `required` and `optional` - they are merged; all the fields that appear in the optional list of either changesets and also in the required list of the other changeset are moved to the required list of the resulting changeset. ## Examples iex> changeset1 = cast(%{title: "Title"}, %Post{}, ~w(title), ~w(body)) iex> changeset2 = cast(%{title: "New title", body: "Body"}, %Post{}, ~w(title body), ~w()) iex> changeset = merge(changeset1, changeset2) iex> changeset.changes %{body: "Body", title: "New title"} iex> changeset.required [:title, :body] iex> changeset.optional [] iex> changeset1 = cast(%{title: "Title"}, %Post{body: "Body"}, ~w(title), ~w(body)) iex> changeset2 = cast(%{title: "New title"}, %Post{}, ~w(title), ~w()) iex> merge(changeset1, changeset2) ** (ArgumentError) different models when merging changesets """ @spec merge(t, t) :: t def merge(changeset1, changeset2) def merge(%Changeset{model: model, repo: repo1} = cs1, %Changeset{model: model, repo: repo2} = cs2) when is_nil(repo1) or is_nil(repo2) or repo1 == repo2 do new_repo = repo1 || repo2 new_params = cs1.params && cs2.params && Map.merge(cs1.params, cs2.params) new_changes = Map.merge(cs1.changes, cs2.changes) new_validations = cs1.validations ++ cs2.validations new_errors = cs1.errors ++ cs2.errors new_required = Enum.uniq(cs1.required ++ cs2.required) new_optional = Enum.uniq(cs1.optional ++ cs2.optional) -- new_required %Changeset{params: new_params, model: model, valid?: new_errors == [], errors: new_errors, changes: new_changes, repo: new_repo, required: new_required, optional: new_optional, validations: new_validations} end def merge(%Changeset{model: m1}, %Changeset{model: m2}) when m1 != m2 do raise ArgumentError, message: "different models when merging changesets" end def merge(%Changeset{repo: r1}, %Changeset{repo: r2}) when r1 != r2 do raise ArgumentError, message: "different repos when merging changesets" end @doc """ Fetches the given field from changes or from the model. While `fetch_change/2` only looks at the current `changes` to retrieve a value, this function looks at the changes and then falls back on the model, finally returning `:error` if no value is available. ## Examples iex> post = %Post{title: "Foo", body: "Bar baz bong"} iex> changeset = change(post, %{title: "New title"}) iex> fetch_field(changeset, :title) {:changes, "New title"} iex> fetch_field(changeset, :body) {:model, "Bar baz bong"} iex> fetch_field(changeset, :not_a_field) :error """ @spec fetch_field(t, atom) :: {:changes, term} | {:model, term} | :error def fetch_field(%{changes: changes, model: model} = _changeset, key) do case Map.fetch(changes, key) do {:ok, value} -> {:changes, value} :error -> case Map.fetch(model, key) do {:ok, value} -> {:model, value} :error -> :error end end end @doc """ Gets a field from changes or from the model. While `get_change/3` only looks at the current `changes` to retrieve a value, this function looks at the changes and then falls back on the model, finally returning `default` if no value is available. iex> post = %Post{title: "A title", body: "My body is a cage"} iex> changeset = change(post, %{title: "A new title"}) iex> get_field(changeset, :title) "A new title" iex> get_field(changeset, :not_a_field, "Told you, not a field!") "Told you, not a field!" """ @spec get_field(t, atom, term) :: term def get_field(%{changes: changes, model: model} = _changeset, key, default \\ nil) do case Map.fetch(changes, key) do {:ok, value} -> value :error -> case Map.fetch(model, key) do {:ok, value} -> value :error -> default end end end @doc """ Fetches a change from the given changeset. This function only looks at the `:changes` field of the given `changeset` and returns `{:ok, value}` if the change is present or `:error` if it's not. ## Examples iex> changeset = change(%Post{body: "foo"}, %{title: "bar"}) iex> fetch_change(changeset, :title) {:ok, "bar"} iex> fetch_change(changeset, :body) :error """ @spec fetch_change(t, atom) :: {:ok, term} | :error def fetch_change(%{changes: changes} = _changeset, key) when is_atom(key) do Map.fetch(changes, key) end @doc """ Gets a change or returns a default value. ## Examples iex> changeset = change(%Post{body: "foo"}, %{title: "bar"}) iex> get_change(changeset, :title) "bar" iex> get_change(changeset, :body) nil """ @spec get_change(t, atom, term) :: term def get_change(%{changes: changes} = _changeset, key, default \\ nil) when is_atom(key) do Map.get(changes, key, default) end @doc """ Updates a change. The given `function` is invoked with the change value only if there is a change for the given `key`. Note that the value of the change can still be `nil` (unless the field was marked as required on `cast/4`). ## Examples iex> changeset = change(%Post{}, %{impressions: 1}) iex> changeset = update_change(changeset, :impressions, &(&1 + 1)) iex> changeset.changes.impressions 2 """ @spec update_change(t, atom, (term -> term)) :: t def update_change(%{changes: changes} = changeset, key, function) when is_atom(key) do case Map.fetch(changes, key) do {:ok, value} -> changes = Map.put(changes, key, function.(value)) %{changeset | changes: changes} :error -> changeset end end @doc """ Puts a change on the given `key` with `value`. If the change is already present, it is overridden with the new value. ## Examples iex> changeset = change(%Post{}, %{title: "foo"}) iex> changeset = put_change(changeset, :title, "bar") iex> changeset.changes.title "bar" """ @spec put_change(t, atom, term) :: t def put_change(changeset, key, value) do update_in changeset.changes, &Map.put(&1, key, value) end @doc """ Puts a change on the given `key` only if a change with that key doesn't already exist. ## Examples iex> changeset = put_new_change(changeset, :title, "foo") iex> changeset.changes.title "foo" iex> changeset = put_new_change(changeset, :title, "bar") iex> changeset.changes.title "foo" """ @spec put_new_change(t, atom, term) :: t def put_new_change(changeset, key, value) do update_in changeset.changes, &Map.put_new(&1, key, value) end @doc """ Deletes a change with the given key. ## Examples iex> changeset = change(%Post{}, %{title: "foo"}) iex> changeset = delete_change(changeset, :title) iex> get_change(changeset, :title) nil """ @spec delete_change(t, atom) :: t def delete_change(changeset, key) do update_in changeset.changes, &Map.delete(&1, key) end @doc """ Applies the changeset changes to the changeset model. Note this operation is automatically performed on `Ecto.Repo.insert/2` and `Ecto.Repo.update/2`, however this function is provided for debugging and testing purposes. ## Examples apply(changeset) """ @spec apply(t) :: Ecto.Model.t def apply(%{changes: changes, model: model} = _changeset) do struct(model, changes) end ## Validations @doc """ Adds an error to the changeset. ## Examples iex> changeset = change(%Post{}, %{title: ""}) iex> changeset = add_error(changeset, :title, :empty) iex> changeset.errors [title: :empty] iex> changeset.valid? false """ @spec add_error(t, atom, error) :: t def add_error(%{errors: errors} = changeset, key, error) do %{changeset | errors: [{key, error}|errors], valid?: false} end @doc """ Validates the given `field` change. It invokes the `validator` function to perform the validation only if a change for the given `field` exists and the change value is not `nil`. The function must return a list of errors (with an empty list meaning no errors). In case there's at least one error, the list of errors will be appended to the `:errors` field of the changeset and the `:valid?` flag will be set to `false`. ## Examples iex> changeset = change(%Post{}, %{title: "foo"}) iex> changeset = validate_change changeset, :title, fn ...> # Value must not be "foo"! ...> :title, "foo" -> [{:title, :is_foo}] ...> :title, _ -> [] ...> end iex> changeset.errors [{:title, :is_foo}] """ @spec validate_change(t, atom, (atom, term -> [error])) :: t def validate_change(changeset, field, validator) when is_atom(field) do %{changes: changes, errors: errors} = changeset new = if value = Map.get(changes, field), do: validator.(field, value), else: [] case new do [] -> changeset [_|_] -> %{changeset | errors: new ++ errors, valid?: false} end end @doc """ Stores the validation `metadata` and validates the given `field` change. Similar to `validate_change/3` but stores the validation metadata into the changeset validators. The validator metadata is often used as a reflection mechanism, to automatically generate code based on the available validations. ## Examples iex> changeset = change(%Post{}, %{title: "foo"}) iex> changeset = validate_change changeset, :title, :useless_validator, fn ...> _, _ -> [] ...> end iex> changeset.validations [title: :useless_validator] """ @spec validate_change(t, atom, any, (atom, term -> [error])) :: t def validate_change(%{validations: validations} = changeset, field, metadata, validator) do changeset = %{changeset | validations: [{field, metadata}|validations]} validate_change(changeset, field, validator) end @doc """ Validates a change has the given format. The format has to be expressed as a regular expression. ## Examples validate_format(changeset, :email, ~r/@/) """ @spec validate_format(t, atom, Regex.t) :: t def validate_format(changeset, field, format) do validate_change changeset, field, {:format, format}, fn _, value -> if value =~ format, do: [], else: [{field, :format}] end end @doc """ Validates a change is included in the given enumerable. ## Examples validate_inclusion(changeset, :gender, ["male", "female", "who cares?"]) validate_inclusion(changeset, :age, 0..99) """ @spec validate_inclusion(t, atom, Enum.t) :: t def validate_inclusion(changeset, field, data) do validate_change changeset, field, {:inclusion, data}, fn _, value -> if value in data, do: [], else: [{field, :inclusion}] end end @doc """ Validates a change is not included in given the enumerable. ## Examples validate_exclusion(changeset, :name, ~w(admin superadmin)) """ @spec validate_exclusion(t, atom, Enum.t) :: t def validate_exclusion(changeset, field, data) do validate_change changeset, field, {:exclusion, data}, fn _, value -> if value in data, do: [{field, :exclusion}], else: [] end end @doc """ Validates the given `field`'s uniqueness on the given repository. ## Examples validate_unique(changeset, :email, on: Repo) ## Options * `:on` - the repository to perform the query on * `:downcase` - when `true`, downcase values when performing the uniqueness query ## Case sensitivity Unfortunately, different databases provide different guarantees when it comes to case-sensitiveness. For example, in MySQL, comparisons are case-insensitive by default. In Postgres, users can define case insensitive column by using the `:citext` type/extension. These behaviours make it hard for Ecto to guarantee if the unique validation is case insensitive or not and that's why Ecto **does not** provide a `:case_sensitive` option. However `validate_unique/3` does provide a `:downcase` option that guarantees values are downcased when doing the uniqueness check. When this option is set, values are downcased regardless of the database being used. Since the `:downcase` option downcases the database values on the fly, it should be uses with care as it may affect performance. For example, if this option is used, it could be appropriate to create an index with the downcased value. Using `Ecto.Migration` syntax, one could write: create index(:posts, ["lower(title)"]) Many times though, you don't even need to use the downcase option at `validate_unique/3` and instead you can explicitly downcase values before inserting them into the database: Many times, however, it's even simpler to just explicitly downcase values before inserting them into the database (and avoid the `:downcase` option in `validate_unique/3`): cast(params, model, ~w(email), ~w()) |> update_change(:email, &String.downcase/1) |> validate_unique(:email, on: Repo) """ @spec validate_unique(t, atom, [Keyword.t]) :: t def validate_unique(%{model: model} = changeset, field, opts) when is_list(opts) do repo = Keyword.fetch!(opts, :on) validate_change changeset, field, :unique, fn _, value -> struct = model.__struct__ query = from m in struct, select: field(m, ^field), limit: 1 query = if opts[:downcase] do from m in query, where: fragment("lower(?)", field(m, ^field)) == fragment("lower(?)", ^value) else from m in query, where: field(m, ^field) == ^value end if pk_value = Ecto.Model.primary_key(model) do pk_field = struct.__schema__(:primary_key) query = from m in query, where: field(m, ^pk_field) != ^pk_value end case repo.all(query) do [] -> [] [_] -> [{field, :unique}] end end end @doc """ Validates a change is a string of the given length. ## Length The length that the given string should have can be expressed through a range (the string length must be in the range) or with a series of options: * `:is` - the string length must be exactly this value * `:min` - the string length must be greater than or equal to this value * `:max` - the string lenght must be less than or equal to this value ## Examples validate_length(changeset, :title, 3..100) validate_length(changeset, :title, min: 3) validate_length(changeset, :title, max: 100) validate_length(changeset, :code, is: 9) """ @spec validate_length(t, atom, Range.t | [Keyword.t]) :: t def validate_length(changeset, field, min..max) when is_integer(min) and is_integer(max) do validate_length changeset, field, [min: min, max: max] end def validate_length(changeset, field, opts) when is_list(opts) do validate_change changeset, field, {:length, opts}, fn _, value when is_binary(value) -> length = String.length(value) error = ((is = opts[:is]) && wrong_length(length, is)) || ((min = opts[:min]) && too_short(length, min)) || ((max = opts[:max]) && too_long(length, max)) if error, do: [{field, error}], else: [] end end defp wrong_length(value, value), do: nil defp wrong_length(_length, value), do: {:wrong_length, value} defp too_short(length, value) when length >= value, do: nil defp too_short(_length, value), do: {:too_short, value} defp too_long(length, value) when length <= value, do: nil defp too_long(_length, value), do: {:too_long, value} end
lib/ecto/changeset.ex
0.939283
0.531635
changeset.ex
starcoder
defmodule Blinkchain.Config.Matrix do @moduledoc """ Represents a contiguous matrix of pixels, composed of liner strips with a regular spacing and orientation pattern. * `count`: The number of pixels in each axis, expressed as `{x, y}`. (default: `{1, 1}`) * `direction`: The `t:Blinkchain.Config.Strip.direction/0` of the wiring connection along each axis, expressed as `{major, minor}`. (default: `{:right, :down}`) * `origin`: The top-left-most location in the matrix, expressed as `{x, y}`. (default: `{0, 0}`) * `progressive`: Whether the wiring `t:Blinkchain.Config.Strip.direction/0` of each successive strip is reversed on the major axis. (default: `false`) * `spacing`: How far each row and column are spaced on the virtual canvas, expressed as `{x, y}`. (default: `{1, 1}`) """ alias Blinkchain.Config.{ Matrix, Strip } @typedoc @moduledoc @type t :: %__MODULE__{ count: {Blinkchain.uint16(), Blinkchain.uint16()}, direction: {Strip.direction(), Strip.direction()}, origin: {Blinkchain.uint16(), Blinkchain.uint16()}, progressive: boolean(), spacing: {Blinkchain.uint16(), Blinkchain.uint16()} } defstruct count: {1, 1}, direction: {:right, :down}, origin: {0, 0}, progressive: false, spacing: {1, 1} def new(%{type: :matrix} = config) do sanitized_config = Map.take(config, [:origin, :count, :direction, :spacing, :progressive]) %Matrix{} |> Map.merge(sanitized_config) end def to_strip_list(%Matrix{} = matrix) do %Matrix{ origin: {x, y}, count: {width, height}, direction: {major, minor}, spacing: {x_spacing, y_spacing}, progressive: progressive } = matrix head = %Strip{ origin: {x, y}, count: component_for_direction({width, height}, major), direction: major, spacing: component_for_direction({x_spacing, y_spacing}, major) } remaining = component_for_direction({width, height}, minor) - 1 minor_spacing = component_for_direction({x_spacing, y_spacing}, minor) [head | next_strips(remaining, head, minor, minor_spacing, progressive)] end # Private Helpers defp next_strips(0, _, _, _, _), do: [] defp next_strips(remaining, prev_strip, minor, minor_spacing, progressive) do strip = prev_strip |> Map.put(:origin, next_progressive_origin(prev_strip.origin, minor, minor_spacing)) |> flip_if_not_progressive(progressive) [strip | next_strips(remaining - 1, strip, minor, minor_spacing, progressive)] end defp next_progressive_origin({x, y}, :right, spacing), do: {x + spacing, y} defp next_progressive_origin({x, y}, :left, spacing), do: {x - spacing, y} defp next_progressive_origin({x, y}, :down, spacing), do: {x, y + spacing} defp next_progressive_origin({x, y}, :up, spacing), do: {x, y - spacing} defp flip_if_not_progressive(%Strip{} = strip, true), do: strip defp flip_if_not_progressive(%Strip{direction: direction} = strip, false) do %Strip{strip | origin: tail_coordinates(strip), direction: opposite(direction)} end defp tail_coordinates(%Strip{origin: {x, y}, direction: :right, count: count, spacing: spacing}) do {x + (count - 1) * spacing, y} end defp tail_coordinates(%Strip{origin: {x, y}, direction: :left, count: count, spacing: spacing}) do {x - (count - 1) * spacing, y} end defp tail_coordinates(%Strip{origin: {x, y}, direction: :down, count: count, spacing: spacing}) do {x, y + (count - 1) * spacing} end defp tail_coordinates(%Strip{origin: {x, y}, direction: :up, count: count, spacing: spacing}) do {x, y - (count - 1) * spacing} end defp opposite(:right), do: :left defp opposite(:left), do: :right defp opposite(:down), do: :up defp opposite(:up), do: :down defp component_for_direction({x, _y}, :right), do: x defp component_for_direction({x, _y}, :left), do: x defp component_for_direction({_x, y}, :down), do: y defp component_for_direction({_x, y}, :up), do: y end
lib/blinkchain/config/matrix.ex
0.941412
0.825625
matrix.ex
starcoder
defmodule Alambic.CountDown do @moduledoc """ A simple countdown latch implementation useful for simple fan in scenarios. It is initialized with a count and clients can wait on it to be signaled when the count reaches 0, decrement the count or increment the count. It is implemented as a `GenServer`. In the unlikely case you need to start a named `CountDown` you can directly use the `GenServer.start/start_link` functions passing the required initial `count` as argument. """ @vsn 1 use GenServer alias Alambic.CountDown defstruct id: nil @type t :: %__MODULE__{id: pid} @doc ~S""" Create a CountDown object with `count` initial count. `count` must be a positive integer. ## Example iex> c = Alambic.CountDown.create(2) iex> is_nil(c.id) false """ @spec create(integer) :: t def create(count) when is_integer(count) and count >= 0 do {:ok, pid} = GenServer.start(__MODULE__, count) %CountDown{id: pid} end @doc """ Create a CountDown with `count` initial count. It is linked to the current process. ## Example iex> c = Alambic.CountDown.create_link(2) iex> Alambic.CountDown.destroy(c) :ok """ @spec create_link(integer) :: t def create_link(count) when is_integer(count) and count >= 0 do {:ok, pid} = GenServer.start_link(__MODULE__, count) %CountDown{id: pid} end @doc """ Destroy the countdown object, returning `:error` to all waiters. ## Example iex> c = Alambic.CountDown.create(2) iex> Alambic.CountDown.destroy(c) :ok """ @spec destroy(t) :: :ok def destroy(_ = %CountDown{id: pid}) do GenServer.cast(pid, :destroy) end @doc "Wait for the count to reach 0." @spec wait(t) :: :ok | :error def wait(_ = %CountDown{id: pid}) do GenServer.call(pid, :wait, :infinity) end @doc """ Decrease the count by one. Returns true if the count reached 0, false otherwise. ## Example iex> c = Alambic.CountDown.create(1) iex> Alambic.CountDown.signal(c) true """ @spec signal(t) :: true | false def signal(_ = %CountDown{id: pid}) do GenServer.call(pid, :signal) end @doc """ Increase the count by one. ## Example iex> c = Alambic.CountDown.create(0) iex> Alambic.CountDown.increase(c) iex> Alambic.CountDown.signal(c) true """ @spec increase(t) :: :ok | :error def increase(_ = %CountDown{id: pid}) do GenServer.call(pid, :increase) end @doc """ Reset the count to a new value. ## Example iex> c = Alambic.CountDown.create(10) iex> false = Alambic.CountDown.signal(c) iex> Alambic.CountDown.reset(c, 1) iex> Alambic.CountDown.signal(c) true """ @spec reset(t, integer) :: :ok def reset(_ = %CountDown{id: pid}, count) when is_integer(count) and count >= 0 do GenServer.call(pid, {:reset, count}) end @doc """ Return the current count. ## Example iex> c = Alambic.CountDown.create(10) iex> Alambic.CountDown.count(c) 10 """ @spec count(t) :: integer def count(_ = %CountDown{id: pid}) do GenServer.call(pid, :count) end # ----------------- # Waitable protocol defimpl Alambic.Waitable, for: CountDown do @spec wait(CountDown.t) :: :ok | :error def wait(countdown) do CountDown.wait(countdown) end @spec free?(CountDown.t) :: true | false def free?(countdown) do CountDown.count(countdown) == 0 end end # ------------------- # GenServer callbacks def init(count) do {:ok, {[], count}} end def terminate(_, {waiting, _}) do waiting |> Enum.each(&GenServer.reply(&1, :error)) end def handle_cast(:destroy, state) do {:stop, :normal, state} end def handle_call(:wait, _, state = {[], 0}) do {:reply, :ok, state} end def handle_call(:wait, from, {waiting, count}) do {:noreply, {[from | waiting], count}} end def handle_call(:signal, _, state = {[], 0}) do {:reply, :error, state} end def handle_call(:signal, _, {waiting, 1}) do flush_waiting(waiting) {:reply, true, {[], 0}} end def handle_call(:signal, _, {w, count}) do {:reply, false, {w, count - 1}} end def handle_call(:increase, _, {w, count}) do {:reply, :ok, {w, count + 1}} end def handle_call({:reset, 0}, _, {w, _}) do flush_waiting(w) {:reply, :ok, {[], 0}} end def handle_call({:reset, count}, _, {w, _}) do {:reply, :ok, {w, count}} end def handle_call(:count, _, {w, count}) do {:reply, count, {w, count}} end defp flush_waiting(waiting) do waiting |> Enum.each(&GenServer.reply(&1, :ok)) end end
lib/alambic/countdown.ex
0.855655
0.631694
countdown.ex
starcoder
defmodule Game.Format.Quests do @moduledoc """ Format function for quests """ alias Game.Format alias Game.Format.Rooms alias Game.Format.Table alias Game.Quest @doc """ Format a quest name iex> Game.Format.quest_name(%{name: "Into the Dungeon"}) "{quest}Into the Dungeon{/quest}" """ def quest_name(quest) do "{quest}#{quest.name}{/quest}" end @doc """ Format the status of a player's quests """ @spec quest_progress([QuestProgress.t()]) :: String.t() def quest_progress(quests) do rows = quests |> Enum.map(fn %{status: status, quest: quest} -> [to_string(quest.id), quest.name, quest.giver.name, status] end) Table.format("You have #{length(quests)} active quests.", rows, [5, 30, 20, 10]) end @doc """ Format the status of a player's quest """ @spec quest_detail(QuestProgress.t(), Save.t()) :: String.t() def quest_detail(progress, save) do %{quest: quest} = progress steps = quest.quest_steps |> Enum.map(&quest_step(&1, progress, save)) header = "#{quest.name} - #{progress.status}" """ #{header} #{header |> Format.underline()} #{quest.description |> Format.wrap()} #{steps |> Enum.join("\n")} """ |> String.trim() |> Format.resources() end defp quest_step(step, progress, save) do case step.type do "item/collect" -> current_step_progress = Quest.current_step_progress(step, progress, save) " - Collect #{item_name(step.item)} - #{current_step_progress}/#{step.count}" "item/give" -> current_step_progress = Quest.current_step_progress(step, progress, save) " - Give #{item_name(step.item)} to #{npc_name(step.npc)} - #{current_step_progress}/#{ step.count }" "item/have" -> current_step_progress = Quest.current_step_progress(step, progress, save) " - Have #{item_name(step.item)} - #{current_step_progress}/#{step.count}" "npc/kill" -> current_step_progress = Quest.current_step_progress(step, progress, save) " - Kill #{npc_name(step.npc)} - #{current_step_progress}/#{step.count}" "room/explore" -> current_step_progress = Quest.current_step_progress(step, progress, save) " - Explore #{room_name(step.room)} - #{current_step_progress}" end end defp item_name(item), do: Format.item_name(item) defp npc_name(npc), do: Format.npc_name(npc) defp room_name(room), do: Rooms.room_name(room) end
lib/game/format/quests.ex
0.602646
0.434221
quests.ex
starcoder
defmodule Text.Streamer do @moduledoc """ Functions to support streaming text samples in various languages and to execute detection test cases against them. """ @doc """ Returns an Enumerable stream of random strings from a given corpus and language. ## Arguments * `corpus` is any module that implements the `Text.Corpus` behaviour * `language` is a BCP-47 language tag in the set of `corpus.known_languages/0` * `sample_length` is a the length of the string in graphemes to be sampled and tested. For each iteration a new string is randomly selected from the language corpus. ## Returns * A random string from the corpus with a length of `sample_length` """ def corpus_random_stream(corpus, language, sample_length) do content = corpus.language_content(language) length = String.length(content) Stream.resource( fn -> {content, length} end, fn {content, length} -> index = Enum.random(1..(length - sample_length)) string = String.slice(content, index, sample_length) {[string], {content, length}} end, fn {_content, _length} -> nil end ) end @doc """ For a given BCP-47 language, a sample length and options, test language detection over a number of iterations. ## Arguments * `corpus` is any module that implements the `Text.Corpus` behaviour * `language` is a BCP47 language tag in the set of `corpus.known_languages/0` * `sample_length` is a the length of the string in graphemes to be sampled and tested. For each iteration a new string is randomly selected from the language corpus. * `options` is a keyword list of options ## Options * `:max_iterations` is the number of iterations to be exectuted for each sample. The default is `1_000` * `:classifier` is the classifier to be used from the set `Text.Language.known_classifiers/0`. The defautls is `Text.Language.Classifier.NaiveBayesian` * `:vocabulary` is the vocabulary to be used from the set of `corpus.known_vocabularies/0`. The default is `Text.Vocabulary.Udhr.Multigram`. ## Returns * A `{iterations, successful_detection, unsuccessful_detection}` tuple """ def test(corpus, language, sample_length, options \\ []) do max = Keyword.get(options, :max_iterations, 1_000) classifier = Keyword.get(options, :classifier, Text.Language.Classifier.NaiveBayesian) vocabulary = Keyword.get(options, :vocabulary, Text.Vocabulary.Udhr.Multigram) corpus_random_stream(corpus, language, sample_length) |> Enum.reduce_while({0, 0, 0}, fn string, {count, good, bad} -> {count, good, bad} = case Text.Language.classify(string, classifier: classifier, vocabulary: vocabulary) do [{lang, _} | _rest] when lang == language -> {count + 1, good + 1, bad} _other -> {count + 1, good, bad + 1} end if count >= max do {:halt, {count, good, bad}} else {:cont, {count, good, bad}} end end) end @doc """ Executes a language detection test matrix over all known classifiers and vocabularies for a given list of langauges and sample lengths. ## Arguments * `corpus` is any module that implements the `Text.Corpus` behaviour * `languages` is a list of BCP-47 language ids in the set of `corpus.known_languages/0` * `sample_length` is a list of the length of strings in graphemes to be sampled and tested. ## Returns * A list of lists where the inner list contains the test results for one matrix element. The elements are `[language, classifier, vocabulary, sample_length, iterations, correct_count, incorrect_count]` """ def matrix(corpus, languages, lengths) when is_list(languages) and is_list(lengths) do for classifier <- Text.Language.known_classifiers, vocabulary <- corpus.known_vocabularies, language <- languages, sample_length <- lengths do {iterations, correct, incorrect} = test(corpus, language, sample_length, classifier: classifier, vocabulary: vocabulary) [language, classifier, vocabulary, sample_length, iterations, correct, incorrect] |> Enum.join(",") end end @csv_path "analysis/detection_analysis.csv" @headers [ "Language", "Classifier", "Vocabulary", "Sample Length", "Iterations", "Correct", "Incorrect" ] |> Enum.join(",") @doc """ Saves the results of `matrix/2` as a CSV file #{inspect @csv_path}. """ def save_as_csv(rows) do rows = [@headers | rows] content = Enum.join(rows, "\n") File.write!(@csv_path, content) end end
mix/text_streamer.ex
0.910744
0.718841
text_streamer.ex
starcoder
defmodule Excommerce.Query.Zone do use Excommerce.Query, schema: Excommerce.Addresses.Zone import Ecto, only: [assoc: 2] def zoneable!(repo, %Excommerce.Addresses.Zone{type: "Country"} = _schema, zoneable_id) do repo.get!(Excommerce.Addresses.Country, zoneable_id) end def zoneable!(repo, %Excommerce.Addresses.Zone{type: "State"} = _schema, zoneable_id) do repo.get!(Excommerce.Addresses.State, zoneable_id) end def member_with_id(repo, %Excommerce.Addresses.Zone{type: "Country"} = schema, zone_member_id) do repo.one(from m in assoc(schema, :country_zone_members), where: m.id == ^zone_member_id) end def member_with_id(repo, %Excommerce.Addresses.Zone{type: "State"} = schema, zone_member_id) do repo.one(from m in assoc(schema, :state_zone_members), where: m.id == ^zone_member_id) end def zoneable_candidates(repo, %Excommerce.Addresses.Zone{type: "Country"} = schema) do existing_zoneable_ids = existing_zoneable_ids(repo, schema) repo.all(from c in Excommerce.Addresses.Country, where: not c.id in ^existing_zoneable_ids) end def zoneable_candidates(repo, %Excommerce.Addresses.Zone{type: "State"} = schema) do existing_zoneable_ids = existing_zoneable_ids(repo, schema) repo.all(from s in Excommerce.Addresses.State, where: not s.id in ^existing_zoneable_ids) end def member_ids_and_names(%Excommerce.Addresses.Zone{type: "Country"} = schema) do from v in assoc(schema, :country_zone_members), join: c in Excommerce.Addresses.Country, on: c.id == v.zoneable_id, select: {v.id, c.name} end def member_ids_and_names(%Excommerce.Addresses.Zone{type: "State"} = schema) do from v in assoc(schema, :state_zone_members), join: c in Excommerce.Addresses.State, on: c.id == v.zoneable_id, select: {v.id, c.name} end def member_ids_and_names(repo, schema) do repo.all(member_ids_and_names(schema)) end def members(%Excommerce.Addresses.Zone{type: "Country"} = schema) do from v in assoc(schema, :country_zone_members) end def members(%Excommerce.Addresses.Zone{type: "State"} = schema) do from v in assoc(schema, :state_zone_members) end def members(repo, schema) do repo.all(members(schema)) end defp existing_zoneable_ids(%Excommerce.Addresses.Zone{type: "State"} = schema) do from cz in assoc(schema, :state_zone_members), select: cz.zoneable_id end defp existing_zoneable_ids(%Excommerce.Addresses.Zone{type: "Country"} = schema) do from cz in assoc(schema, :country_zone_members), select: cz.zoneable_id end defp existing_zoneable_ids(repo, schema) do repo.all(existing_zoneable_ids(schema)) end end
lib/excommerce/queries/zone.ex
0.533154
0.411525
zone.ex
starcoder
defmodule Pummpcomm.History.BolusNormal do @moduledoc """ A normal bolus, entered by the user. """ alias Pummpcomm.{DateDecoder, Insulin} @typedoc """ The duration of the square wave bolus. `0` when not a normal bolus. """ # TODO determine units and document @type duration :: non_neg_integer @typedoc """ Whether the bolus is delivered `:normal` (all at once) or as a `:square` wave over a `duration`. """ @type type :: :normal | :square # Functions @doc """ A `:normal` or `:square` bolus, entered manually by the user. """ # TODO document difference between programmed and amount # TODO document all fields in type @spec decode(binary, Pummpcomm.PumpModel.pump_options()) :: %{ programmed: Insulin.units(), amount: Insulin.units(), duration: duration, type: type, timestamp: NaiveDateTime.t() } | %{ programmed: Insulin.units(), amount: Insulin.units(), duration: duration, unabsorbed_insulin: Insulin.units(), type: type, timestamp: NaiveDateTime.t() } def decode(body, pump_options) def decode(<<programmed::8, amount::8, raw_duration::8, timestamp::binary-size(5)>>, %{ strokes_per_unit: strokes_per_unit }) do duration = raw_duration * 30 %{ programmed: programmed / strokes_per_unit, amount: amount / strokes_per_unit, duration: duration, type: type_from_duration(duration), timestamp: DateDecoder.decode_history_timestamp(timestamp) } end def decode( <<programmed::16, amount::16, unabsorbed_insulin::16, raw_duration::8, timestamp::binary-size(5)>>, %{strokes_per_unit: strokes_per_unit} ) do duration = raw_duration * 30 %{ programmed: programmed / strokes_per_unit, amount: amount / strokes_per_unit, duration: duration, unabsorbed_insulin: unabsorbed_insulin / strokes_per_unit, type: type_from_duration(duration), timestamp: DateDecoder.decode_history_timestamp(timestamp) } end ## Private Functions defp type_from_duration(0), do: :normal defp type_from_duration(_), do: :square end
lib/pummpcomm/history/bolus_normal.ex
0.587233
0.508422
bolus_normal.ex
starcoder
defmodule Solution.Enum do @moduledoc """ Helper functions to work with ok/error tuples in Enumerables. """ require Solution import Solution @doc """ Changes a list of oks into `{:ok, list_of_values}` If any element of the list is an error, returns this error element. If all elements are oks, takes the first non-tag value from each of them for the list. (in the case of `:ok`, nothing is added to the resulting list.) iex> combine([{:ok, 1}, {:ok, "a", %{meta: "this will be dropped"}}, {:ok, :asdf}]) {:ok, [1, "a", :asdf]} iex> combine([{:ok, 1}, {:ok, 2}, {:error, 3}]) {:error, 3} iex> combine([{:ok, 1}, {:ok, 2}, {:error, 3, 4, 5}]) {:error, 3, 4, 5} """ def combine(enum) do result = Enum.reduce_while(enum, [], fn x, acc when is_ok(x, 2) -> {:cont, [elem(x, 1) | acc]} x, acc when is_ok(x, 0) or is_ok(x, 1) -> {:cont, acc} x, _acc when is_error(x) -> {:halt, x} end) case result do x when is_error(x) -> x x -> {:ok, :lists.reverse(x)} end end @doc """ Returns a list of only all `ok`-type elements in the enumerable. iex> oks([{:ok, 1}, {:error, 2}, {:ok, 3}]) [{:ok, 1}, {:ok, 3}] """ def oks(enum) do enum |> Enum.filter(&is_ok/1) end @doc """ Returns a list of the values of all `ok`-type elements in the enumerable. Note that the 'value' is taken to be the first element: iex> ok_vals([{:ok, 1}, {:ok, 2,3,4,5}]) [1, 2] """ def ok_vals(enum) do enum |> Enum.filter(&is_ok(&1, 2)) |> Enum.map(fn oktuple -> elem(oktuple, 1) end) end @doc """ Returns a list of the tuple-values of all `ok`-type elements in the enumerable. The 'tuple-value' consists of all elements in the `ok`-type element, except for the initial `:ok` tag. iex> ok_valstuples([{:ok, 1}, {:ok, 2,3,4,5}]) [{1}, {2,3,4,5}] """ def ok_valstuples(enum) do enum |> Enum.filter(&is_ok(&1, 2)) |> Enum.map(fn oktuple -> oktuple |> Tuple.delete_at(0) end) end @doc """ Returns a list of only all `error`-type elements in the enumerable. iex> errors([{:ok, 1}, {:error, 2}, {:ok, 3}]) [{:error, 2}] """ def errors(enum) do enum |> Enum.filter(&is_error/1) end @doc """ Returns a list of the values of all `error`-type elements in the enumerable. Note that the 'value' is taken to be the first element: iex> error_vals([{:error, 1}, {:error, 2,3,4,5}]) [1, 2] """ def error_vals(enum) do enum |> Enum.filter(&is_error(&1, 2)) |> Enum.map(fn errortuple -> elem(errortuple, 1) end) end @doc """ Returns a list of the tuple-values of all `error`-type elements in the enumerable. The 'tuple-value' consists of all elements in the `error`-type element, except for the initial `:error` tag. iex> error_valstuples([{:error, 1}, {:error, 2,3,4,5}]) [{1}, {2,3,4,5}] """ def error_valstuples(enum) do enum |> Enum.filter(&is_error(&1, 2)) |> Enum.map(fn errortuple -> errortuple |> Tuple.delete_at(0) end) end end
lib/solution/enum.ex
0.846213
0.674644
enum.ex
starcoder
defmodule PlugBest do @moduledoc """ A library that parses HTTP `Accept-*` headers and returns the best match based on a list of values. ## Examples ```elixir iex> conn = %Plug.Conn{req_headers: [{"accept-language", "fr-CA,fr;q=0.8,en;q=0.6,en-US;q=0.4"}]} iex> conn |> PlugBest.best_language(["en", "fr"]) {"fr-CA", "fr", 1.0} iex> conn = %Plug.Conn{req_headers: [{"accept-language", "es"}]} iex> conn |> PlugBest.best_language(["fr", "ru"]) nil iex> conn = %Plug.Conn{req_headers: [{"accept-language", "es"}]} iex> conn |> PlugBest.best_language_or_first(["ru", "fr"]) {"ru", "ru", 0.0} ``` """ # Aliases alias Plug.Conn # Types @type value :: {String.t(), String.t(), float} @doc """ Returns the best supported langage based on the connection `Accept-Language` HTTP header. Returns `nil` if none is found. """ @spec best_language(%Conn{}, [String.t()]) :: value | nil def best_language(conn = %Conn{}, supported_values), do: best_value(conn, "accept-language", supported_values) @doc """ Returns the best supported langage based on the connection `Accept-Language` HTTP header. Returns the first supported language if none is found. """ @spec best_language_or_first(%Conn{}, [String.t()]) :: value | nil def best_language_or_first(conn = %Conn{}, supported_values), do: best_value_or_first(conn, "accept-language", supported_values) @doc """ Returns the best supported charset based on the connection `Accept-Charset` HTTP header. Returns `nil` if none is found. """ @spec best_charset(%Conn{}, [String.t()]) :: value | nil def best_charset(conn = %Conn{}, supported_values), do: best_value(conn, "accept-charset", supported_values) @doc """ Returns the best supported charset based on the connection `Accept-Charset` HTTP header. Returns the first supported charset if none is found. """ @spec best_charset_or_first(%Conn{}, [String.t()]) :: value | nil def best_charset_or_first(conn = %Conn{}, supported_values), do: best_value_or_first(conn, "accept-charset", supported_values) @doc """ Returns the best supported encoding based on the connection `Accept-Encoding` HTTP header. Returns `nil` if none is found. """ @spec best_encoding(%Conn{}, [String.t()]) :: value | nil def best_encoding(conn = %Conn{}, supported_values), do: best_value(conn, "accept-encoding", supported_values) @doc """ Returns the best supported encoding based on the connection `Accept-Encoding` HTTP header. Returns the first supported encoding if none is found. """ @spec best_encoding_or_first(%Conn{}, [String.t()]) :: value | nil def best_encoding_or_first(conn = %Conn{}, supported_values), do: best_value_or_first(conn, "accept-encoding", supported_values) @doc """ Returns the best supported type based on the connection `Accept` HTTP header. Returns `nil` if none is found. """ @spec best_type(%Conn{}, [String.t()]) :: value | nil def best_type(conn = %Conn{}, supported_values), do: best_value(conn, "accept", supported_values) @doc """ Returns the best supported type based on the connection `Accept` HTTP header. Returns the first supported type if none is found. """ @spec best_type_or_first(%Conn{}, [String.t()]) :: value | nil def best_type_or_first(conn = %Conn{}, supported_values), do: best_value_or_first(conn, "accept", supported_values) @spec best_value(%Conn{}, String.t(), [String.t()]) :: value | nil defp best_value(conn = %Conn{}, header, supported_values) do # Fetch the raw header content conn |> fetch_header_value(header) # Convert it to a list |> String.split(",") |> Enum.map(&parse_header_item/1) # Only keep values that we support |> Enum.filter(&filter_header_value_item(&1, supported_values)) # Sort the parsed header with each score |> Enum.sort(&sort_header_value_items/2) # Return the first (best!) item |> List.first() end @spec best_value_or_first(%Conn{}, String.t(), [String.t()]) :: value defp best_value_or_first(conn = %Conn{}, header, supported_values) do conn |> best_value(header, supported_values) || default_supported_value(supported_values) end @spec default_supported_value([String.t()]) :: value defp default_supported_value(supported_values) do [default_value | _] = supported_values {default_value, default_value, 0.0} end @spec fetch_header_value(%Conn{}, String.t()) :: String.t() defp fetch_header_value(conn, header_name) do header_value = conn |> Conn.get_req_header(header_name) |> List.first() header_value || "" end @spec parse_header_item(String.t()) :: value defp parse_header_item(item) do [value, score] = case String.split(item, ";") do [value] -> [value, 1.0] [value, "q=" <> score] -> [value, parse_score(score)] end # Extract base value by removing its suffix base_value = value |> String.replace(~r/-.+$/, "") {value, base_value, score} end @spec sort_header_value_items(value, value) :: boolean defp sort_header_value_items({_, _, first_score}, {_, _, second_score}) do first_score > second_score end @spec filter_header_value_item(value, [String.t()]) :: boolean defp filter_header_value_item({_, base_value, _}, supported_values) do Enum.member?(supported_values, base_value) end @spec parse_score(String.t()) :: float defp parse_score(score) do case Float.parse(score) do {score, _} -> score :error -> 0.0 end end end
lib/plug_best.ex
0.895043
0.79542
plug_best.ex
starcoder
defmodule Carrot.Backoff do @moduledoc """ Provides functions to facilitate exponential backoff. """ import Bitwise alias Carrot.Backoff @min 1_000 @max 30_000 defstruct min: @min, max: @max, state: nil @type option :: {:max, pos_integer()} | {:min, pos_integer()} @type options :: [option()] @type state :: pos_integer() | nil @type t :: %Backoff{ min: pos_integer(), max: pos_integer(), state: pos_integer() | nil } @doc """ Creates a new `Backoff` struct based on provided options. ## Options * `:min` - The minimum number of milliseconds for starting the backoff process (default: `1000`) * `:max` - The maximum number of milliseconds before restarting the backoff process (default: `30_000`) ## Examples iex> Carrot.Backoff.new() %Carrot.Backoff{min: 1000, max: 30_000, state: nil} iex> Carrot.Backoff.new(min: 100, max: 1000) %Carrot.Backoff{min: 100, max: 1_000, state: nil} """ @spec new(options()) :: Backoff.t() def new(opts \\ []) do min = Keyword.get(opts, :min, @min) max = Keyword.get(opts, :max, @max) %Backoff{min: min, max: max} end @doc """ Returns a new `Backoff` struct with updated state. ## Examples iex> backoff = Carrot.Backoff.new(min: 100, max: 400) %Carrot.Backoff{min: 100, max: 400, state: nil} iex> backoff = Carrot.Backoff.next(backoff) %Carrot.Backoff{min: 100, max: 400, state: 100} iex> backoff = Carrot.Backoff.next(backoff) %Carrot.Backoff{min: 100, max: 400, state: 200} iex> backoff = Carrot.Backoff.next(backoff) %Carrot.Backoff{min: 100, max: 400, state: 400} iex> _backoff = Carrot.Backoff.next(backoff) %Carrot.Backoff{min: 100, max: 400, state: nil} """ @spec next(Backoff.t()) :: Backoff.t() def next(%Backoff{min: min, state: nil} = state) do %Backoff{state | state: min} end def next(%Backoff{max: max, state: max} = state) do %Backoff{state | state: nil} end def next(%Backoff{max: max, state: prev} = state) do %Backoff{state | state: min(prev <<< 1, max)} end @doc """ Resets the backoff state. ## Example iex> backoff = Carrot.Backoff.new() %Carrot.Backoff{min: 1000, max: 30_000, state: nil} iex> backoff = Carrot.Backoff.next(backoff) %Carrot.Backoff{min: 1000, max: 30_000, state: 1000} iex> _backoff = Carrot.Backoff.reset(backoff) %Carrot.Backoff{min: 1000, max: 30_000, state: nil} """ @spec reset(Backoff.t()) :: Backoff.t() def reset(%Backoff{} = state) do %Backoff{state | state: nil} end @doc """ Schedules the next backoff interval. This function will send the given message to the given PID based on the current state of the `Backoff` struct. ## Examples iex> backoff = Carrot.Backoff.new(min: 100, max: 200) %Carrot.Backoff{min: 100, max: 200, state: nil} iex> backoff = Carrot.Backoff.next(backoff) %Carrot.Backoff{min: 100, max: 200, state: 100} iex> _backoff = Carrot.Backoff.schedule(backoff, self(), :connect) %Carrot.Backoff{min: 100, max: 200, state: 100} iex> receive do ...> :connect -> ...> :ok ...> end :ok """ @spec schedule(Backoff.t(), pid(), any()) :: Backoff.t() def schedule(%Backoff{state: state} = backoff, pid, message) do ms = if state, do: state, else: 0 _ = Process.send_after(pid, message, ms) backoff end end
lib/carrot/backoff.ex
0.940449
0.538073
backoff.ex
starcoder
defmodule Day12 do defmodule Triplet do defstruct x: 0, y: 0, z: 0 end defmodule Moon do defstruct pos: %Triplet{}, vel: %Triplet{} end @spec new_moon(String.t()) :: Moon.t() def new_moon(line) do [[x, y, z]] = Regex.scan(~r/<x=([-0-9]*), y=([-0-9]*), z=([-0-9]*)>/, line, capture: :all_but_first) %Moon{ pos: %Triplet{x: String.to_integer(x), y: String.to_integer(y), z: String.to_integer(z)} } end @spec pairs([any()]) :: [{any(), any()}] def pairs(items) do case items do [_] -> [] [one | rest] -> for(two <- rest, do: {one, two}) ++ pairs(rest) end end @spec gravity_delta(integer, integer) :: {integer, integer} def gravity_delta(pos_1, pos_2) do cond do pos_1 == pos_2 -> {0, 0} pos_1 > pos_2 -> {-1, 1} true -> {1, -1} end end @spec gravity(Moon.t(), Moon.t()) :: {Moon.t(), Moon.t()} def gravity(moon_1, moon_2) do {dvx1, dvx2} = gravity_delta(moon_1.pos.x, moon_2.pos.x) {dvy1, dvy2} = gravity_delta(moon_1.pos.y, moon_2.pos.y) {dvz1, dvz2} = gravity_delta(moon_1.pos.z, moon_2.pos.z) {%Moon{ pos: moon_1.pos, vel: %Triplet{x: moon_1.vel.x + dvx1, y: moon_1.vel.y + dvy1, z: moon_1.vel.z + dvz1} }, %Moon{ pos: moon_2.pos, vel: %Triplet{x: moon_2.vel.x + dvx2, y: moon_2.vel.y + dvy2, z: moon_2.vel.z + dvz2} }} end @spec triplet_energy(Triplet.t()) :: integer def triplet_energy(triplet) do abs(triplet.x) + abs(triplet.y) + abs(triplet.z) end @spec total_energy(Moon.t()) :: integer def total_energy(moon) do triplet_energy(moon.pos) * triplet_energy(moon.vel) end @spec step(map()) :: map() def step(moons) do names = Map.keys(moons) delta_v_moons = Enum.reduce(pairs(names), moons, fn {name_1, name_2}, moon_state -> {new_1, new_2} = gravity(moon_state[name_1], moon_state[name_2]) nm = Map.put(moon_state, name_1, new_1) Map.put(nm, name_2, new_2) end) Enum.reduce(names, delta_v_moons, fn name, moon_state -> moon = moon_state[name] Map.put(moon_state, name, %Moon{ pos: %Triplet{ x: moon.pos.x + moon.vel.x, y: moon.pos.y + moon.vel.y, z: moon.pos.z + moon.vel.z }, vel: moon.vel }) end) end @spec steps(map(), integer) :: map() def steps(moons, count) do Enum.reduce(1..count, moons, fn _, state -> step(state) end) end @spec system_energy(map()) :: integer def system_energy(moons) do Enum.sum(Enum.map(Map.values(moons), &total_energy/1)) end def load_map(file_name) do Files.read_lines!(file_name) |> Enum.map(&new_moon/1) |> Enum.reduce({%{}, 0}, fn moon, {moon_map, index} -> {Map.put(moon_map, index, moon), index + 1} end) |> elem(0) end @spec part1(String.t()) :: integer def part1(file_name) do load_map(file_name) |> steps(1000) |> system_energy() end def count_steps(initial_state, moon_state, steps) do if rem(steps, 1_000_000) == 0, do: IO.write(".") if steps > 0 and moon_state == initial_state do steps else count_steps(initial_state, step(moon_state), steps + 1) end end def back_to_the_future(moon_state) do count_steps(moon_state, moon_state, 0) end @spec part2(String.t()) :: integer def part2(file_name) do load_map(file_name) |> back_to_the_future() end end
lib/day12.ex
0.803521
0.596492
day12.ex
starcoder
defmodule EdgeDB.NamedTuple do @moduledoc """ An immutable value representing an EdgeDB named tuple value. `EdgeDB.NamedTuple` implements `Access` behavior to access fields by index or key and `Enumerable` protocol for iterating over tuple values. ```elixir iex(1)> {:ok, pid} = EdgeDB.start_link() iex(2)> nt = EdgeDB.query_required_single!(pid, "SELECT (a := 1, b := 'a', c := [3])") #EdgeDB.NamedTuple<a: 1, b: "a", c: [3]> iex(3)> nt[:b] "a" iex(4)> nt["c"] [3] iex(4)> nt[0] 1 ``` """ @behaviour Access defstruct [ :__fields_ordering__, :__items__ ] @typedoc """ An immutable value representing an EdgeDB named tuple value. """ @opaque t() :: %__MODULE__{} @doc """ Convert a named tuple to a regular erlang tuple. ```elixir iex(1)> {:ok, pid} = EdgeDB.start_link() iex(2)> nt = EdgeDB.query_required_single!(pid, "SELECT (a := 1, b := 'a', c := [3])") iex(3)> EdgeDB.NamedTuple.to_tuple(nt) {1, "a", [3]} ``` """ @spec to_tuple(t()) :: tuple() def to_tuple(%__MODULE__{__items__: items}) do items |> Map.values() |> List.to_tuple() end @doc """ Get named tuple keys ```elixir iex(1)> {:ok, pid} = EdgeDB.start_link() iex(2)> nt = EdgeDB.query_required_single!(pid, "SELECT (a := 1, b := 'a', c := [3])") iex(3)> EdgeDB.NamedTuple.keys(nt) ["a", "b", "c"] ``` """ @spec keys(t()) :: list(String.t()) def keys(%__MODULE__{__items__: items}) do Map.keys(items) end @impl Access def fetch(%__MODULE__{__items__: items, __fields_ordering__: fields_order}, index) when is_integer(index) do with {:ok, name} <- Map.fetch(fields_order, index) do Map.fetch(items, name) end rescue ArgumentError -> :error end @impl Access def fetch(%__MODULE__{} = tuple, key) when is_atom(key) do fetch(tuple, Atom.to_string(key)) end @impl Access def fetch(%__MODULE__{__items__: items}, key) when is_binary(key) do Map.fetch(items, key) end @impl Access def get_and_update(%__MODULE__{}, _key, _function) do raise EdgeDB.Error.interface_error("named tuples can't be mutated") end @impl Access def pop(%__MODULE__{}, _key) do raise EdgeDB.Error.interface_error("named tuples can't be mutated") end end defimpl Enumerable, for: EdgeDB.NamedTuple do @impl Enumerable def count(%EdgeDB.NamedTuple{__items__: items}) do Enumerable.count(items) end @impl Enumerable def member?(%EdgeDB.NamedTuple{__items__: items}, element) do items |> Map.values() |> Enumerable.member?(element) end @impl Enumerable def reduce(%EdgeDB.NamedTuple{__items__: items}, acc, fun) do items |> Map.values() |> Enumerable.reduce(acc, fun) end @impl Enumerable def slice(%EdgeDB.NamedTuple{__items__: items}) do items |> Map.values() |> Enumerable.slice() end end defimpl Inspect, for: EdgeDB.NamedTuple do import Inspect.Algebra @impl Inspect def inspect(%EdgeDB.NamedTuple{__items__: items, __fields_ordering__: fields_order}, _opts) do {max_index, _name} = Enum.max(fields_order, fn -> {nil, nil} end) elements_docs = fields_order |> Enum.map(fn {index, name} -> {index, glue(name, ": ", inspect(items[name]))} end) |> Enum.sort() |> Enum.map(fn {^max_index, doc} -> doc {_index, doc} -> concat(doc, ", ") end) concat(["#EdgeDB.NamedTuple<", concat(elements_docs), ">"]) end end
lib/edgedb/types/named_tuple.ex
0.887558
0.766949
named_tuple.ex
starcoder
defmodule AWS.Codestarnotifications do @moduledoc """ This AWS CodeStar Notifications API Reference provides descriptions and usage examples of the operations and data types for the AWS CodeStar Notifications API. You can use the AWS CodeStar Notifications API to work with the following objects: Notification rules, by calling the following: <ul> <li> `CreateNotificationRule`, which creates a notification rule for a resource in your account. </li> <li> `DeleteNotificationRule`, which deletes a notification rule. </li> <li> `DescribeNotificationRule`, which provides information about a notification rule. </li> <li> `ListNotificationRules`, which lists the notification rules associated with your account. </li> <li> `UpdateNotificationRule`, which changes the name, events, or targets associated with a notification rule. </li> <li> `Subscribe`, which subscribes a target to a notification rule. </li> <li> `Unsubscribe`, which removes a target from a notification rule. </li> </ul> Targets, by calling the following: <ul> <li> `DeleteTarget`, which removes a notification rule target (SNS topic) from a notification rule. </li> <li> `ListTargets`, which lists the targets associated with a notification rule. </li> </ul> Events, by calling the following: <ul> <li> `ListEventTypes`, which lists the event types you can include in a notification rule. </li> </ul> Tags, by calling the following: <ul> <li> `ListTagsForResource`, which lists the tags already associated with a notification rule in your account. </li> <li> `TagResource`, which associates a tag you provide with a notification rule in your account. </li> <li> `UntagResource`, which removes a tag from a notification rule in your account. </li> </ul> For information about how to use AWS CodeStar Notifications, see link in the CodeStarNotifications User Guide. """ @doc """ Creates a notification rule for a resource. The rule specifies the events you want notifications about and the targets (such as SNS topics) where you want to receive them. """ def create_notification_rule(client, input, options \\ []) do path_ = "/createNotificationRule" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Deletes a notification rule for a resource. """ def delete_notification_rule(client, input, options \\ []) do path_ = "/deleteNotificationRule" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Deletes a specified target for notifications. """ def delete_target(client, input, options \\ []) do path_ = "/deleteTarget" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Returns information about a specified notification rule. """ def describe_notification_rule(client, input, options \\ []) do path_ = "/describeNotificationRule" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Returns information about the event types available for configuring notifications. """ def list_event_types(client, input, options \\ []) do path_ = "/listEventTypes" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Returns a list of the notification rules for an AWS account. """ def list_notification_rules(client, input, options \\ []) do path_ = "/listNotificationRules" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Returns a list of the tags associated with a notification rule. """ def list_tags_for_resource(client, input, options \\ []) do path_ = "/listTagsForResource" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Returns a list of the notification rule targets for an AWS account. """ def list_targets(client, input, options \\ []) do path_ = "/listTargets" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates an association between a notification rule and an SNS topic so that the associated target can receive notifications when the events described in the rule are triggered. """ def subscribe(client, input, options \\ []) do path_ = "/subscribe" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Associates a set of provided tags with a notification rule. """ def tag_resource(client, input, options \\ []) do path_ = "/tagResource" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Removes an association between a notification rule and an Amazon SNS topic so that subscribers to that topic stop receiving notifications when the events described in the rule are triggered. """ def unsubscribe(client, input, options \\ []) do path_ = "/unsubscribe" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Removes the association between one or more provided tags and a notification rule. """ def untag_resource(client, input, options \\ []) do path_ = "/untagResource" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Updates a notification rule for a resource. You can change the events that trigger the notification rule, the status of the rule, and the targets that receive the notifications. <note> To add or remove tags for a notification rule, you must use `TagResource` and `UntagResource`. </note> """ def update_notification_rule(client, input, options \\ []) do path_ = "/updateNotificationRule" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @spec request(AWS.Client.t(), binary(), binary(), list(), list(), map(), list(), pos_integer()) :: {:ok, map() | nil, map()} | {:error, term()} defp request(client, method, path, query, headers, input, options, success_status_code) do client = %{client | service: "codestar-notifications"} host = build_host("codestar-notifications", client) url = host |> build_url(path, client) |> add_query(query, client) additional_headers = [{"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}] headers = AWS.Request.add_headers(additional_headers, headers) payload = encode!(client, input) headers = AWS.Request.sign_v4(client, method, url, headers, payload) perform_request(client, method, url, payload, headers, options, success_status_code) end defp perform_request(client, method, url, payload, headers, options, success_status_code) do case AWS.Client.request(client, method, url, payload, headers, options) do {:ok, %{status_code: status_code, body: body} = response} when is_nil(success_status_code) and status_code in [200, 202, 204] when status_code == success_status_code -> body = if(body != "", do: decode!(client, body)) {:ok, body, response} {:ok, response} -> {:error, {:unexpected_response, response}} error = {:error, _reason} -> error end end defp build_host(_endpoint_prefix, %{region: "local", endpoint: endpoint}) do endpoint end defp build_host(_endpoint_prefix, %{region: "local"}) do "localhost" end defp build_host(endpoint_prefix, %{region: region, endpoint: endpoint}) do "#{endpoint_prefix}.#{region}.#{endpoint}" end defp build_url(host, path, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}#{path}" end defp add_query(url, [], _client) do url end defp add_query(url, query, client) do querystring = encode!(client, query, :query) "#{url}?#{querystring}" end defp encode!(client, payload, format \\ :json) do AWS.Client.encode!(client, payload, format) end defp decode!(client, payload) do AWS.Client.decode!(client, payload, :json) end end
lib/aws/generated/codestarnotifications.ex
0.853776
0.469034
codestarnotifications.ex
starcoder
defmodule RayTracer.World do @moduledoc """ This module defines world. World is a bag for elements like objects and light sources. """ alias RayTracer.Light alias RayTracer.Sphere alias RayTracer.Shape alias RayTracer.Material alias RayTracer.Transformations alias RayTracer.RTuple alias RayTracer.Color alias RayTracer.Intersection alias RayTracer.Ray @type t :: %__MODULE__{ objects: list(Shape.t), light: Light.t | nil } defstruct [:objects, :light] @doc """ Builds a world with given objects and light """ @spec new(list(Shape.t), Light.t | nil) :: t def new(objects \\ [], light \\ nil) do %__MODULE__{objects: objects, light: light} end @doc """ Builds a default world containing some objects and light """ @spec default() :: t def default() do material = %Material{Material.new | color: Color.new(0.8, 1.0, 0.6), diffuse: 0.7, specular: 0.2} s1 = %Sphere{Sphere.new | material: material} s2 = Sphere.new |> Shape.set_transform(Transformations.scaling(0.5, 0.5, 0.5)) light = Light.point_light(RTuple.point(-10, 10, -10), Color.white) new([s1, s2], light) end @doc """ Computes shading for a ray hitting a world """ @spec color_at(t, Ray.t, integer) :: Color.t def color_at(world, ray, remaining \\ 5) do xs = world |> Intersection.intersect_world(ray) hit = xs |> Intersection.hit() if hit do comps = Intersection.prepare_computations(hit, ray, xs) world |> shade_hit(comps, remaining) else Color.black end end @doc """ Shades an intersection """ @spec shade_hit(t, Intersection.computation, integer) :: Color.t def shade_hit(world, comps, remaining \\ 5) do material = comps.object.material surface = Light.lighting( material, comps.object, world.light, comps.over_point, comps.eyev, comps.normalv, world |> is_shadowed(comps.over_point) ) reflected = world |> reflected_color(comps, remaining) refracted = world |> refracted_color(comps, remaining) if material.reflective > 0 && material.transparency > 0 do reflectance = Intersection.schlick(comps) surface |> Color.add(reflected |> Color.mul(reflectance)) |> Color.add(refracted |> Color.mul(1 - reflectance)) else surface |> Color.add(reflected) |> Color.add(refracted) end end @doc """ Computes a color when refraction occurs (hit at the border of two materials with different refraction indices - e.g. glass and air) t - angle of incoming ray i - angle of refracted ray """ @spec refracted_color(t, Intersection.computation, integer) :: Color.t def refracted_color(_, _, remaining \\ 5) def refracted_color(_, _, 0), do: Color.black def refracted_color(_, %{object: %{material: %{transparency: transparency }}}, _) when transparency == 0, do: Color.black def refracted_color(world, comps, remaining) do # Find the ratio of first index of refraction to the second. # (Yup, this is inverted from the definition of Snell's Law.) n_ratio = comps.n1 / comps.n2 # cos(theta_i) is the same as the dot product of the two vectors cos_i = RTuple.dot(comps.eyev, comps.normalv) # Find sin(theta_t)^2 via trigonometric identity sin2_t = n_ratio * n_ratio * (1 - cos_i * cos_i) if sin2_t > 1 do # We have a total internal reflection here, light won't escape Color.black else cos_t = :math.sqrt(1 - sin2_t) # Compute the direction of the refracted ray direction = RTuple.sub( comps.normalv |> RTuple.mul(n_ratio * cos_i - cos_t), comps.eyev |> RTuple.mul(n_ratio) ) # Create the refracted ray refract_ray = Ray.new(comps.under_point, direction) # Find the color of the refracted ray, making sure to multiply by # the transparency value to account for any opacity. world |> color_at(refract_ray, remaining - 1) |> Color.mul(comps.object.material.transparency) end end @doc """ Computes a color for reflection """ @spec reflected_color(t, Intersection.computation, integer) :: Color.t def reflected_color(_, _, remaining \\ 5) def reflected_color(_, _, 0), do: Color.black def reflected_color(_, %{object: %{material: %{reflective: r }}}, _) when r == 0, do: Color.black def reflected_color(world, comps, remaining) do reflect_ray = Ray.new(comps.over_point, comps.reflectv) color = world |> color_at(reflect_ray, remaining - 1) color |> Color.mul(comps.object.material.reflective) end @doc """ Informs whether a given point is in shadow """ @spec is_shadowed(t, RTuple.point) :: boolean def is_shadowed(world, point) do point_to_light_vector = RTuple.sub(world.light.position, point) distance = point_to_light_vector |> RTuple.length shadow_ray = Ray.new(point, point_to_light_vector |> RTuple.normalize) shadow_hit = world |> ray_hit(shadow_ray) shadow_hit != nil && shadow_hit.t < distance end # Returns a closest ray hit defp ray_hit(world, ray) do world |> Intersection.intersect_world(ray) |> Intersection.hit end end
lib/world.ex
0.927388
0.565659
world.ex
starcoder
defmodule Toprox do @moduledoc """ A simple proxy for different Logger backends which allows to filter messages based on metadata. ## Usage In `config.exs`: config :logger, backends: [ {Toprox, :graylog}, ] config :logger, :graylog, level: :info, backend: { Logger.Backends.Gelf, [ host: "graylog.example.com", port: 12201, application: "MyApplication", compression: :gzip, metadata: [:request_id, :function, :module, :file, :line] ] } In code: Logger.info "Info", topic: :graylog """ @behaviour :gen_event @doc false def init({__MODULE__, name}) do {:ok, configure(name, [])} end @doc false def handle_call({:configure, opts}, %{name: name} = state) do {:ok, :ok, configure(name, opts, state)} end @doc false def handle_event({level, _gl, {Logger, _msg, _ts, md}} = event, %{module: module} = state) do if level?(level, state.level) and topic?(state.name, md[:topic]) do {:ok, new_backend_state} = module.handle_event(event, state.backend_state) {:ok, %{state | backend_state: new_backend_state}} else {:ok, state} end end @doc false def handle_event(:flush, %{module: module} = state) do {:ok, new_backend_state} = module.handle_event(:flush, state.backend_state) {:ok, %{state | backend_state: new_backend_state}} end @doc false def handle_info(info, %{module: module} = state) do {:ok, new_backend_state} = module.handle_info(info, state.backend_state) {:ok, %{state | backend_state: new_backend_state}} end ## Helpers defp level?(_, nil), do: true defp level?(level, min), do: Logger.compare_levels(level, min) != :lt defp topic?(name, topic) when is_list(topic), do: name in topic defp topic?(name, topic), do: name == topic defp configure(name, opts) do state = %{name: nil, level: nil, module: nil, backend_state: nil} configure(name, opts, state) end defp configure(name, opts, state) do env = Application.get_env(:logger, name, []) opts = Keyword.merge(env, opts) Application.put_env(:logger, name, opts) level = Keyword.get(opts, :level, :debug) {module, backend_opts} = Keyword.get(opts, :backend) backend_opts = Keyword.put(backend_opts, :level, level) Application.put_env(:logger, :"_proxy_#{name}", backend_opts) {:ok, backend_state} = module.init({module, :"_proxy_#{name}"}) %{state | name: name, level: level, module: module, backend_state: backend_state} end end
lib/toprox.ex
0.589716
0.42057
toprox.ex
starcoder
defmodule Phoenix.Router.Route do # This module defines the Route struct that is used # throughout Phoenix's router. This struct is private # as it contains internal routing information. @moduledoc false alias Phoenix.Router.Route @doc """ The `Phoenix.Router.Route` struct. It stores: * :verb - the HTTP verb as an upcased string * :path - the normalized path as string * :host - the request host or host prefix * :controller - the controller module * :action - the action as an atom * :helper - the name of the helper as a string (may be nil) * :private - the private route info * :pipe_through - the pipeline names as a list of atoms """ defstruct [:verb, :path, :host, :controller, :action, :helper, :private, :pipe_through] @type t :: %Route{} @doc """ Receives the verb, path, controller, action and helper and returns a `Phoenix.Router.Route` struct. """ @spec build(String.t, String.t, String.t | nil, atom, atom, atom | nil, atom, %{}) :: t def build(verb, path, host, controller, action, helper, pipe_through, private) when is_binary(verb) and is_binary(path) and (is_binary(host) or is_nil(host)) and is_atom(controller) and is_atom(action) and (is_binary(helper) or is_nil(helper)) and is_list(pipe_through) and is_map(private) do %Route{verb: verb, path: path, host: host, private: private, controller: controller, action: action, helper: helper, pipe_through: pipe_through} end @doc """ Builds the expressions used by the route. """ def exprs(route) do {path, binding} = build_path_and_binding(route.path) %{path: path, host: build_host(route.host), binding: binding, dispatch: build_dispatch(route, binding)} end defp build_path_and_binding(path) do {params, segments} = Plug.Router.Utils.build_path_match(path) binding = Enum.map(params, fn var -> {Atom.to_string(var), Macro.var(var, nil)} end) {segments, binding} end defp build_host(host) do cond do is_nil(host) -> quote do: _ String.last(host) == "." -> quote do: unquote(host) <> _ true -> host end end defp build_dispatch(route, binding) do exprs = [maybe_binding(binding), maybe_merge(:private, route.private), build_pipes(route)] {:__block__, [], Enum.filter(exprs, & &1 != nil)} end defp maybe_merge(key, data) do if map_size(data) > 0 do quote do var!(conn) = update_in var!(conn).unquote(key), &Map.merge(&1, unquote(Macro.escape(data))) end end end defp maybe_binding([]), do: nil defp maybe_binding(binding) do quote do var!(conn) = update_in var!(conn).params, &Map.merge(&1, unquote({:%{}, [], binding})) end end defp build_pipes(route) do initial = quote do var!(conn) |> Plug.Conn.put_private(:phoenix_pipelines, unquote(route.pipe_through)) |> Plug.Conn.put_private(:phoenix_route, fn conn -> opts = unquote(route.controller).init(unquote(route.action)) unquote(route.controller).call(conn, opts) end) end Enum.reduce(route.pipe_through, initial, &{&1, [], [&2, []]}) end end
lib/phoenix/router/route.ex
0.845002
0.473901
route.ex
starcoder
defmodule Ivy.Attribute do import AtomUtils alias Ivy.{Anomaly, Database, Datom, Transaction} @type cardinality :: :one | :many @type unique :: :identity | :value @type type :: :integer | :float | :boolean | :instant | :atom | :ref | :string | :tuple | :uuid | :uri @type attr_pred :: {module, atom, 1} | (Datom.value -> boolean) @enforce_keys [:ident, :cardinality, :value_type] defstruct [:ident, :cardinality, :value_type, :id, :doc, :unique, :attr_preds, is_component: false, no_history: false, index: false] @type t :: %__MODULE__{ ident: Ivy.ident, cardinality: cardinality, value_type: type, doc: String.t | nil, unique: unique | nil, is_component: boolean | nil, id: Datom.ref | nil, no_history: boolean | nil, attr_preds: [attr_pred, ...] | nil, index: boolean | nil } # @spec parse(tx_data, Database.t) :: {:ok, Transaction.t} | {:error, Anomaly.t} # translate updates -> [Datom.t] + tx_datom # idents -> ids # reified tx (via :db/id "ivy.tx") # explicit :db/tx_instant # @spec resolve(Transaction.t, Database.t) :: {:ok, Database.t} | {:error, Anomaly.t} # temp_id resolution # add idents to db.keys & db.ids # add attributes to db.elements # update index, memidx, & memlog # @spec validate(Transaction.t, Database.t) :: :ok | {:error, Anomaly.t} # redundancy elimination (i.e. existing datom that differs only by tx_id) # @spec validate(Datom.t, Transaction.t, Database.t) :: {:ok, :add | :retract | :swap | :noop} | {:error, Anomaly.t} # lookup attribute # redundancy elimination (i.e. existing datom that differs only by tx_id) # virtual datom handling (e.g. :db/ensure) # @spec validate(Attribute.t, Datom.t, Transaction.t, Database.t) :: :ok | {:error, Anomaly.t} # typing # predicates # identity uniqueness # value uniqueness # :db.type/ref -> verify the entity referenced exists in the txn + db # :db/ident id / atom is registered in db (or in tx) @spec validate(t, Datom.t, Transaction.t, Database.t) :: :ok | {:error, Anomaly.t} def validate(_attribute, _datom, _tx, _db) do end @spec typed?(t, Datom.value, boolean) :: :ok | {:error, Anomaly.t} defp typed?(attribute, value, only_scalar? \\ false) defp typed?(%{value_type: :integer}, val, _) when is_integer(val), do: true defp typed?(%{value_type: :float}, val, _) when is_float(val), do: true defp typed?(%{value_type: :boolean}, val, _) when is_boolean(val), do: true defp typed?(%{value_type: :atom}, val, _) when is_atom(val), do: true defp typed?(%{value_type: :string}, val, _) when is_bitstring(val), do: true defp typed?(%{value_type: :uri}, %URI{}, _), do: true defp typed?(%{value_type: :datetime}, %DateTime{}, _), do: true defp typed?(%{value_type: :ref}, val, _), do: Datom.ref?(val) defp typed?(%{value_type: :uuid}, val, _), do: match?({:ok, _}, UUID.info(val)) defp typed?(%{value_type: :tuple} = attr, val, false) when is_tuple(val) and tuple_size(val) in 2..8 do # case attr do # %{tuple_attrs: ta} when not is_nil(ta) -> false # %{tuple_types: ts} when length(ts) == tuple_size(val) -> # Tuple.to_list(val) # |> Enum.zip(ts) # |> Enum.reduce_while() # %{tuple_type: t} -> # Tuple.to_list(val) # |> Enum.all?(&typed?()) # _ -> false # end end defp typed?(_, _, _), do: false # TODO: ... @spec apply_preds([attr_pred] | nil, Datom.value) :: :ok | {:error, Anomaly.t} defp apply_preds(nil, val), do: :ok defp apply_preds([], val), do: :ok defp apply_preds([p | ps], val) do case execute(p, [val]) do true -> apply_preds(ps, val) _ -> {:error, p} end end defp execute(fun, args) do case fun do f when is_function(f, length(args)) -> apply(f, args) {m, f} -> apply(m, f, args) end rescue exception -> {:error, exception} catch :exit, reason -> {:error, reason} thrown -> {:error, thrown} end @attribute_keys [ :"db/ident", :"db/cardinality", :"db/value_type" ] @spec attribute?(term) :: boolean def attribute?(datoms) when is_list(datoms) do Enum.all?() end def attribute?(map) when is_map(map) do Enum.all?(@attribute_keys, &Map.has_key?(map, &1)) end def attribute?(_), do: false @spec from_datoms(Database.t, [Datom.t]) :: t def from_datoms(_db, _datoms) do end end
archive/ivy/attribute.ex
0.548553
0.487917
attribute.ex
starcoder
if Code.ensure_loaded?(Plug) do defmodule Guardian.Plug.SlidingCookie do @moduledoc """ WARNING! Use of this plug MAY allow a session to be maintained indefinitely without primary authentication by issuing new refresh tokens off the back of previous (still valid) tokens. Especially if your `resource_from_claims` implemention does not check resource validity (in a user database or whatever), you SHOULD then at least make such checks in the `sliding_cookie/3` implementation to make sure the resource still exists, is valid and permitted. Looks for a valid token in the request cookies, and replaces it, if: a. A valid unexpired token is found in the request cookies. b. There is a `:sliding_cookie` configuration (or plug option). c. The token age (since issue) exceeds that configuration. d. The implementation module `sliding_cookie/3` returns `{:ok, new_claims}`. Otherwise the plug does nothing. The implementation module MUST implement the `sliding_cookie/3` function if this plug is used. The return value, if an updated cookie is approved of, should be `{:ok, new_claims}`. The `sliding_cookie/3` function should take any security action (such as checking a database to check a user has not been disabled). Anything else returned will be taken as an indication that the cookie should not refreshed. The only case whereby the error handler is employed is if the `sliding_cookie/3` function is not provided, in which case it is called with a type of `:implementation_fault` and reason `:no_sliding_cookie_fn`. This, like all other Guardian plugs, requires a Guardian pipeline to be setup. It requires an implementation module, an error handler and a key. These can be set either: 1. Upstream on the connection with `plug Guardian.Pipeline` 2. Upstream on the connection with `Guardian.Pipeline.{put_module, put_error_handler, put_key}` 3. Inline with an option of `:module`, `:error_handler`, `:key` Nothing is done with the token, refreshed or not, no errors are handled as validity and expiry can be checked by the VerifyCookie and EnsureAuthenticated plugs respectively. Options: * `:key` - The location of the token (default `:default`) * `:sliding_cookie` - The minimum TTL remaining after which a replacement will be issued. Defaults to configured values. * `:halt` - Whether to halt the connection in case of error. Defaults to `true`. The `:sliding_cookie` config (or plug option) should be the same format as `:ttl`, for example `{1, :hour}`, and obviously it should be less than the prevailing `:ttl`. """ import Plug.Conn import Guardian.Plug, only: [find_token_from_cookies: 2, maybe_halt: 2] alias Guardian.Plug.Pipeline import Guardian, only: [ttl_to_seconds: 1, decode_and_verify: 4, timestamp: 0] @behaviour Plug @impl Plug @spec init(opts :: Keyword.t()) :: Keyword.t() def init(opts), do: opts @impl Plug @spec call(conn :: Plug.Conn.t(), opts :: Keyword.t()) :: Plug.Conn.t() def call(%{req_cookies: %Plug.Conn.Unfetched{}} = conn, opts) do conn |> fetch_cookies() |> call(opts) end def call(conn, opts) do with {:ok, token} <- find_token_from_cookies(conn, opts), module <- Pipeline.fetch_module!(conn, opts), {:ok, ttl_softlimit} <- sliding_window(module, opts), {:ok, %{"exp" => exp} = claims} <- decode_and_verify(module, token, %{}, opts), {:ok, resource} <- module.resource_from_claims(claims), true <- timestamp() >= exp - ttl_softlimit, {:ok, new_c} <- module.sliding_cookie(claims, resource, opts) do conn |> Guardian.Plug.remember_me(module, resource, new_c) else {:error, :not_implemented} -> conn |> Pipeline.fetch_error_handler!(opts) |> apply(:auth_error, [conn, {:implementation_fault, :no_sliding_cookie_fn}, opts]) |> maybe_halt(opts) _ -> conn end end defp sliding_window(module, opts) do case Keyword.get(opts, :sliding_cookie, module.config(:sliding_cookie)) do nil -> :no_sliding_window ttl_descr -> {:ok, ttl_to_seconds(ttl_descr)} end end end end
lib/guardian/plug/sliding_cookie.ex
0.773131
0.502502
sliding_cookie.ex
starcoder
defmodule Ockam.TypedCBOR do @moduledoc """ Helpers encode/decode structs to/from CBOR, aimed at compatibility with minicbor rust library. Prefered usage is through TypedStruct macros, see examples on test/plugin_test.exs """ @doc ~S""" iex> to_cbor_term(:integer, 2) 2 iex> from_cbor_term(:integer, to_cbor_term(:integer, 2)) 2 iex> to_cbor_term(:integer, "2") ** (Ockam.TypedCBOR.Exception) type mismatch, expected schema :integer iex> to_cbor_term(:string, "2") "2" iex> from_cbor_term(:string, to_cbor_term(:string, "2")) "2" iex> from_cbor_term(:integer, to_cbor_term(:string, "2")) ** (Ockam.TypedCBOR.Exception) type mismatch, expected schema :integer iex> to_cbor_term(:string, <<255>>) ** (Ockam.TypedCBOR.Exception) invalid string <<255>> iex> from_cbor_term(:string, <<255>>) ** (Ockam.TypedCBOR.Exception) invalid string <<255>> iex> to_cbor_term(:boolean, true) true iex> from_cbor_term(:boolean, to_cbor_term(:boolean, true)) true iex> to_cbor_term(:binary, <<255>>) %CBOR.Tag{tag: :bytes, value: <<255>>} iex> from_cbor_term(:binary, to_cbor_term(:binary, <<255>>)) <<255>> iex> to_cbor_term({:enum, [a: 0, b: 1]}, :a) 0 iex> from_cbor_term({:enum, [a: 0, b: 1]}, to_cbor_term({:enum, [a: 0, b: 1]}, :b)) :b iex> to_cbor_term({:enum, [a: 0, b: 1]}, :c) ** (Ockam.TypedCBOR.Exception) invalid enum val: :c, allowed: [:a, :b] iex> from_cbor_term({:enum, [a: 0, b: 1]}, 3) ** (Ockam.TypedCBOR.Exception) invalid enum encoding: 3, allowed: [a: 0, b: 1] iex> to_cbor_term({:list, :integer}, [0, 1]) [0,1] iex> from_cbor_term({:list, :integer}, to_cbor_term({:list, :integer}, [0, 1])) [0,1] iex> to_cbor_term({:list, {:enum, [a: 0, b: 1]}}, [:b, :c]) ** (Ockam.TypedCBOR.Exception) invalid enum val: :c, allowed: [:a, :b] iex> to_cbor_term({:struct, %{a1: %{key: 1, schema: :string, required: true}, ...> a2: %{key: 2, schema: {:enum, [a: 0, b: 1]}}}}, ...> %{a1: "aa", a2: nil}) %{1 => "aa"} iex> from_cbor_term({:struct, %{a1: %{key: 1, schema: :string, required: true}, ...> a2: %{key: 2, schema: {:enum, [a: 0, b: 1]}}}}, ...> to_cbor_term({:struct, %{a1: %{key: 1, schema: :string, required: true}, ...> a2: %{key: 2, schema: {:enum, [a: 0, b: 1]}}}}, ...> %{a1: "aa", a2: nil})) %{a1: "aa"} iex> to_cbor_term({:struct, %{a1: %{key: 1, schema: :string, required: true}, ...> a2: %{key: 2, schema: {:enum, [a: 0, b: 1]}}}}, ...> %{a1: "aa", a2: :a}) %{1 => "aa", 2 => 0} iex> from_cbor_term({:struct, %{a1: %{key: 1, schema: :string, required: true}, ...> a2: %{key: 2, schema: {:enum, [a: 0, b: 1]}}}}, ...> to_cbor_term({:struct, %{a1: %{key: 1, schema: :string, required: true}, ...> a2: %{key: 2, schema: {:enum, [a: 0, b: 1]}}}}, ...> %{a1: "aa", a2: :a})) %{a1: "aa", a2: :a} iex> to_cbor_term({:struct, %{a1: %{key: 1, schema: :string, required: true}, ...> a2: %{key: 2, schema: {:enum, [a: 0, b: 1]}}, ...> a3: %{key: 3, schema: {:list, :binary}}}}, ...> %{a1: "aa", a2: :a, a3: ["hello", "world"]}) %{1 => "aa", 2 => 0, 3 => [%CBOR.Tag{tag: :bytes, value: "hello"}, %CBOR.Tag{tag: :bytes, value: "world"}]} iex> to_cbor_term({:struct, %{a1: %{key: 1, schema: :string, required: true}, ...> a2: %{key: 2, schema: {:enum, [a: 0, b: 1]}}}}, ...> %{a2: :b}) ** (Ockam.TypedCBOR.Exception) field a1 is required iex> from_cbor_term({:struct, %{tag: %{key: 0, schema: :integer, required: true, constant: 123}, ...> a1: %{key: 1, schema: :string, required: true}, ...> a2: %{key: 2, schema: {:enum, [a: 0, b: 1]}}}}, ...> %{0 => 123, 2 => 0}) ** (Ockam.TypedCBOR.Exception) field a1 (1) is required """ alias Ockam.TypedCBOR.Exception def from_cbor_term(:integer, val) when is_integer(val), do: val def from_cbor_term(:boolean, val) when is_boolean(val), do: val def from_cbor_term(:string, val) when is_binary(val) do if String.valid?(val) do val else raise Exception, message: "invalid string #{inspect(val)}" end end def from_cbor_term(:binary, %CBOR.Tag{tag: :bytes, value: val}), do: val def from_cbor_term({:enum, vals}, n) when is_integer(n) do case List.keyfind(vals, n, 1) do nil -> raise Exception, message: "invalid enum encoding: #{n}, allowed: #{inspect(vals)}" {val, ^n} -> val end end def from_cbor_term({:list, element_schema}, values) when is_list(values), do: Enum.map(values, fn val -> from_cbor_term(element_schema, val) end) def from_cbor_term({:map, key_schema, value_schema}, values) when is_map(values) do values |> Enum.map(fn {k, v} -> {from_cbor_term(key_schema, k), from_cbor_term(value_schema, v)} end) |> Enum.into(%{}) end def from_cbor_term({:struct, fields}, struct) when is_map(struct) do from_cbor_fields(Map.to_list(fields), struct) |> Enum.into(%{}) end def from_cbor_term({:struct, mod, fields}, struct) when is_map(struct) do struct(mod, from_cbor_term({:struct, fields}, struct)) end def from_cbor_term(:term, any), do: any def from_cbor_term(schema, _) do raise(Exception, "type mismatch, expected schema #{inspect(schema)}") end def from_cbor_fields([], _), do: [] def from_cbor_fields([{field_name, field_options} | rest], struct) do key = Map.fetch!(field_options, :key) schema = Map.fetch!(field_options, :schema) required = Map.get(field_options, :required, false) case Map.fetch(struct, key) do :error when required -> raise Exception, message: "field #{field_name} (#{key}) is required" :error -> from_cbor_fields(rest, struct) {:ok, val} -> val = from_cbor_term(schema, val) case Map.fetch(field_options, :constant) do :error -> [{field_name, val} | from_cbor_fields(rest, struct)] {:ok, ^val} -> [{field_name, val} | from_cbor_fields(rest, struct)] {:ok, expected} -> raise Exception, message: "field #{field_name} expected #{inspect(expected)}, got #{inspect(val)}" end end end def to_cbor_term(:integer, val) when is_integer(val), do: val def to_cbor_term(:boolean, val) when is_boolean(val), do: val def to_cbor_term(:string, val) when is_binary(val) do if String.valid?(val) do val else raise Exception, message: "invalid string #{inspect(val)}" end end def to_cbor_term(:binary, val) when is_binary(val), do: %CBOR.Tag{tag: :bytes, value: val} def to_cbor_term({:enum, vals}, val) when is_atom(val) do case vals[val] do nil -> raise Exception, message: "invalid enum val: #{inspect(val)}, allowed: #{inspect(Keyword.keys(vals))}" n when is_integer(n) -> n end end def to_cbor_term({:list, element_schema}, values) when is_list(values), do: Enum.map(values, fn val -> to_cbor_term(element_schema, val) end) def to_cbor_term({:map, key_schema, value_schema}, values) when is_map(values) do values |> Enum.map(fn {k, v} -> {to_cbor_term(key_schema, k), to_cbor_term(value_schema, v)} end) |> Enum.into(%{}) end def to_cbor_term({:struct, fields}, struct) when is_map(struct) do extra_keys = Map.drop(struct, Map.keys(fields)) if not Enum.empty?(extra_keys), do: raise(Exception, message: "Extra fields: #{inspect(Map.keys(extra_keys))}") to_cbor_fields(Map.to_list(fields), struct) |> Enum.into(%{}) end def to_cbor_term({:struct, mod, fields}, struct) when is_map(struct) do if struct.__struct__ != mod, do: raise(Exception, message: "a %#{mod}{} struct must be provided") to_cbor_fields(Map.to_list(fields), struct) |> Enum.into(%{}) end def to_cbor_term(:term, any), do: any def to_cbor_term(schema, _) do raise(Exception, "type mismatch, expected schema #{inspect(schema)}") end def to_cbor_fields([], _), do: [] def to_cbor_fields([{field_name, field_options} | rest], struct) do key = Map.fetch!(field_options, :key) schema = Map.fetch!(field_options, :schema) required = Map.get(field_options, :required, false) case Map.get(struct, field_name) do nil when required -> raise Exception, message: "field #{field_name} is required" nil -> to_cbor_fields(rest, struct) val -> [{key, to_cbor_term(schema, val)} | to_cbor_fields(rest, struct)] end end end
implementations/elixir/ockam/ockam_typed_cbor/lib/typed_cbor.ex
0.606848
0.486941
typed_cbor.ex
starcoder
defmodule Beamchmark.Formatter do @moduledoc """ The module defines a behaviour that will be used to format and output `#{inspect(Beamchmark.Suite)}`. You can adopt this behaviour to implement custom formatters. The module contains helper functions for validating and applying formatters defined in configuration of `#{inspect(Beamchmark.Suite)}`. """ alias Beamchmark.Suite @typedoc """ Represents a module implementing `#{inspect(__MODULE__)}` behaviour. """ @type t :: module() @typedoc """ Options given to formatters (defined by formatters authors). """ @type options_t :: Keyword.t() @doc """ Takes the suite and transforms it into some internal representation, that later on will be passed to `write/2`. """ @callback format(Suite.t(), options_t) :: any() @doc """ Works like `format/2`, but can provide additional information by comparing the latest suite with the previous one (passed as the second argument). """ @callback format(Suite.t(), Suite.t(), options_t) :: any() @doc """ Takes the return value of `format/1` or `format/2` and outputs it in a convenient form (stdout, file, UI...). """ @callback write(any, options_t) :: :ok @doc """ Takes the suite and uses its formatters to output it. If the suite was configured with `compare?` flag enabled, the previous suite will be also provided to the formatters. """ @spec output(Suite.t()) :: :ok def output(%Suite{} = suite) do with true <- suite.configuration.compare?, {:ok, base_suite} <- Suite.try_load_base(suite) do output_compare(suite, base_suite) else false -> output_single(suite) {:error, posix} -> Mix.shell().info(""" Comparison is enabled, but did not found any previous measurements (error: #{inspect(posix)}). Proceeding with single suite... """) output_single(suite) end end defp output_single(%Suite{} = suite) do suite |> get_formatters() |> Enum.each(fn {formatter, options} -> :ok = suite |> formatter.format(options) |> formatter.write(options) end) end defp output_compare(%Suite{} = suite, %Suite{} = base) do suite |> get_formatters() |> Enum.each(fn {formatter, options} -> :ok = suite |> formatter.format(base, options) |> formatter.write(options) end) end defp get_formatters(%Suite{configuration: config}) do config.formatters |> Enum.map(fn formatter -> case formatter do {module, options} -> {module, options} module -> {module, []} end end) |> tap(fn formatters -> Enum.each(formatters, &validate/1) end) end defp validate({formatter, options}) do unless Keyword.keyword?(options) do raise( "Options for #{inspect(formatter)} need to be passed as a keyword list. Got: #{inspect(options)}." ) end implements_formatter? = formatter.module_info(:attributes) |> Keyword.get(:behaviour, []) |> Enum.member?(__MODULE__) unless implements_formatter? do raise "#{inspect(formatter)} does not implement #{inspect(__MODULE__)} behaviour." end end end
lib/beamchmark/formatter.ex
0.894531
0.613323
formatter.ex
starcoder
defmodule AWS.Route53Domains do @moduledoc """ Amazon Route 53 API actions let you register domain names and perform related operations. """ @doc """ Accepts the transfer of a domain from another AWS account to the current AWS account. You initiate a transfer between AWS accounts using [TransferDomainToAnotherAwsAccount](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html). Use either [ListOperations](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html) or [GetOperationDetail](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html) to determine whether the operation succeeded. [GetOperationDetail](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html) provides additional information, for example, `Domain Transfer from Aws Account 111122223333 has been cancelled`. """ def accept_domain_transfer_from_another_aws_account(client, input, options \\ []) do request(client, "AcceptDomainTransferFromAnotherAwsAccount", input, options) end @doc """ Cancels the transfer of a domain from the current AWS account to another AWS account. You initiate a transfer between AWS accounts using [TransferDomainToAnotherAwsAccount](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html). You must cancel the transfer before the other AWS account accepts the transfer using [AcceptDomainTransferFromAnotherAwsAccount](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_AcceptDomainTransferFromAnotherAwsAccount.html). Use either [ListOperations](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html) or [GetOperationDetail](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html) to determine whether the operation succeeded. [GetOperationDetail](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html) provides additional information, for example, `Domain Transfer from Aws Account 111122223333 has been cancelled`. """ def cancel_domain_transfer_to_another_aws_account(client, input, options \\ []) do request(client, "CancelDomainTransferToAnotherAwsAccount", input, options) end @doc """ This operation checks the availability of one domain name. Note that if the availability status of a domain is pending, you must submit another request to determine the availability of the domain name. """ def check_domain_availability(client, input, options \\ []) do request(client, "CheckDomainAvailability", input, options) end @doc """ Checks whether a domain name can be transferred to Amazon Route 53. """ def check_domain_transferability(client, input, options \\ []) do request(client, "CheckDomainTransferability", input, options) end @doc """ This operation deletes the specified tags for a domain. All tag operations are eventually consistent; subsequent operations might not immediately represent all issued operations. """ def delete_tags_for_domain(client, input, options \\ []) do request(client, "DeleteTagsForDomain", input, options) end @doc """ This operation disables automatic renewal of domain registration for the specified domain. """ def disable_domain_auto_renew(client, input, options \\ []) do request(client, "DisableDomainAutoRenew", input, options) end @doc """ This operation removes the transfer lock on the domain (specifically the `clientTransferProhibited` status) to allow domain transfers. We recommend you refrain from performing this action unless you intend to transfer the domain to a different registrar. Successful submission returns an operation ID that you can use to track the progress and completion of the action. If the request is not completed successfully, the domain registrant will be notified by email. """ def disable_domain_transfer_lock(client, input, options \\ []) do request(client, "DisableDomainTransferLock", input, options) end @doc """ This operation configures Amazon Route 53 to automatically renew the specified domain before the domain registration expires. The cost of renewing your domain registration is billed to your AWS account. The period during which you can renew a domain name varies by TLD. For a list of TLDs and their renewal policies, see [Domains That You Can Register with Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/registrar-tld-list.html) in the *Amazon Route 53 Developer Guide*. Route 53 requires that you renew before the end of the renewal period so we can complete processing before the deadline. """ def enable_domain_auto_renew(client, input, options \\ []) do request(client, "EnableDomainAutoRenew", input, options) end @doc """ This operation sets the transfer lock on the domain (specifically the `clientTransferProhibited` status) to prevent domain transfers. Successful submission returns an operation ID that you can use to track the progress and completion of the action. If the request is not completed successfully, the domain registrant will be notified by email. """ def enable_domain_transfer_lock(client, input, options \\ []) do request(client, "EnableDomainTransferLock", input, options) end @doc """ For operations that require confirmation that the email address for the registrant contact is valid, such as registering a new domain, this operation returns information about whether the registrant contact has responded. If you want us to resend the email, use the `ResendContactReachabilityEmail` operation. """ def get_contact_reachability_status(client, input, options \\ []) do request(client, "GetContactReachabilityStatus", input, options) end @doc """ This operation returns detailed information about a specified domain that is associated with the current AWS account. Contact information for the domain is also returned as part of the output. """ def get_domain_detail(client, input, options \\ []) do request(client, "GetDomainDetail", input, options) end @doc """ The GetDomainSuggestions operation returns a list of suggested domain names. """ def get_domain_suggestions(client, input, options \\ []) do request(client, "GetDomainSuggestions", input, options) end @doc """ This operation returns the current status of an operation that is not completed. """ def get_operation_detail(client, input, options \\ []) do request(client, "GetOperationDetail", input, options) end @doc """ This operation returns all the domain names registered with Amazon Route 53 for the current AWS account. """ def list_domains(client, input, options \\ []) do request(client, "ListDomains", input, options) end @doc """ Returns information about all of the operations that return an operation ID and that have ever been performed on domains that were registered by the current account. """ def list_operations(client, input, options \\ []) do request(client, "ListOperations", input, options) end @doc """ This operation returns all of the tags that are associated with the specified domain. All tag operations are eventually consistent; subsequent operations might not immediately represent all issued operations. """ def list_tags_for_domain(client, input, options \\ []) do request(client, "ListTagsForDomain", input, options) end @doc """ This operation registers a domain. Domains are registered either by Amazon Registrar (for .com, .net, and .org domains) or by our registrar associate, Gandi (for all other domains). For some top-level domains (TLDs), this operation requires extra parameters. When you register a domain, Amazon Route 53 does the following: * Creates a Route 53 hosted zone that has the same name as the domain. Route 53 assigns four name servers to your hosted zone and automatically updates your domain registration with the names of these name servers. * Enables autorenew, so your domain registration will renew automatically each year. We'll notify you in advance of the renewal date so you can choose whether to renew the registration. * Optionally enables privacy protection, so WHOIS queries return contact information either for Amazon Registrar (for .com, .net, and .org domains) or for our registrar associate, Gandi (for all other TLDs). If you don't enable privacy protection, WHOIS queries return the information that you entered for the registrant, admin, and tech contacts. * If registration is successful, returns an operation ID that you can use to track the progress and completion of the action. If the request is not completed successfully, the domain registrant is notified by email. * Charges your AWS account an amount based on the top-level domain. For more information, see [Amazon Route 53 Pricing](http://aws.amazon.com/route53/pricing/). """ def register_domain(client, input, options \\ []) do request(client, "RegisterDomain", input, options) end @doc """ Rejects the transfer of a domain from another AWS account to the current AWS account. You initiate a transfer between AWS accounts using [TransferDomainToAnotherAwsAccount](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html). Use either [ListOperations](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html) or [GetOperationDetail](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html) to determine whether the operation succeeded. [GetOperationDetail](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html) provides additional information, for example, `Domain Transfer from Aws Account 111122223333 has been cancelled`. """ def reject_domain_transfer_from_another_aws_account(client, input, options \\ []) do request(client, "RejectDomainTransferFromAnotherAwsAccount", input, options) end @doc """ This operation renews a domain for the specified number of years. The cost of renewing your domain is billed to your AWS account. We recommend that you renew your domain several weeks before the expiration date. Some TLD registries delete domains before the expiration date if you haven't renewed far enough in advance. For more information about renewing domain registration, see [Renewing Registration for a Domain](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-renew.html) in the *Amazon Route 53 Developer Guide*. """ def renew_domain(client, input, options \\ []) do request(client, "RenewDomain", input, options) end @doc """ For operations that require confirmation that the email address for the registrant contact is valid, such as registering a new domain, this operation resends the confirmation email to the current email address for the registrant contact. """ def resend_contact_reachability_email(client, input, options \\ []) do request(client, "ResendContactReachabilityEmail", input, options) end @doc """ This operation returns the AuthCode for the domain. To transfer a domain to another registrar, you provide this value to the new registrar. """ def retrieve_domain_auth_code(client, input, options \\ []) do request(client, "RetrieveDomainAuthCode", input, options) end @doc """ Transfers a domain from another registrar to Amazon Route 53. When the transfer is complete, the domain is registered either with Amazon Registrar (for .com, .net, and .org domains) or with our registrar associate, Gandi (for all other TLDs). For more information about transferring domains, see the following topics: * For transfer requirements, a detailed procedure, and information about viewing the status of a domain that you're transferring to Route 53, see [Transferring Registration for a Domain to Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-to-route-53.html) in the *Amazon Route 53 Developer Guide*. * For information about how to transfer a domain from one AWS account to another, see [TransferDomainToAnotherAwsAccount](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html). * For information about how to transfer a domain to another domain registrar, see [Transferring a Domain from Amazon Route 53 to Another Registrar](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-from-route-53.html) in the *Amazon Route 53 Developer Guide*. If the registrar for your domain is also the DNS service provider for the domain, we highly recommend that you transfer your DNS service to Route 53 or to another DNS service provider before you transfer your registration. Some registrars provide free DNS service when you purchase a domain registration. When you transfer the registration, the previous registrar will not renew your domain registration and could end your DNS service at any time. If the registrar for your domain is also the DNS service provider for the domain and you don't transfer DNS service to another provider, your website, email, and the web applications associated with the domain might become unavailable. If the transfer is successful, this method returns an operation ID that you can use to track the progress and completion of the action. If the transfer doesn't complete successfully, the domain registrant will be notified by email. """ def transfer_domain(client, input, options \\ []) do request(client, "TransferDomain", input, options) end @doc """ Transfers a domain from the current AWS account to another AWS account. Note the following: * The AWS account that you're transferring the domain to must accept the transfer. If the other account doesn't accept the transfer within 3 days, we cancel the transfer. See [AcceptDomainTransferFromAnotherAwsAccount](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_AcceptDomainTransferFromAnotherAwsAccount.html). * You can cancel the transfer before the other account accepts it. See [CancelDomainTransferToAnotherAwsAccount](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_CancelDomainTransferToAnotherAwsAccount.html). * The other account can reject the transfer. See [RejectDomainTransferFromAnotherAwsAccount](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_RejectDomainTransferFromAnotherAwsAccount.html). When you transfer a domain from one AWS account to another, Route 53 doesn't transfer the hosted zone that is associated with the domain. DNS resolution isn't affected if the domain and the hosted zone are owned by separate accounts, so transferring the hosted zone is optional. For information about transferring the hosted zone to another AWS account, see [Migrating a Hosted Zone to a Different AWS Account](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-migrating.html) in the *Amazon Route 53 Developer Guide*. Use either [ListOperations](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html) or [GetOperationDetail](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html) to determine whether the operation succeeded. [GetOperationDetail](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html) provides additional information, for example, `Domain Transfer from Aws Account 111122223333 has been cancelled`. """ def transfer_domain_to_another_aws_account(client, input, options \\ []) do request(client, "TransferDomainToAnotherAwsAccount", input, options) end @doc """ This operation updates the contact information for a particular domain. You must specify information for at least one contact: registrant, administrator, or technical. If the update is successful, this method returns an operation ID that you can use to track the progress and completion of the action. If the request is not completed successfully, the domain registrant will be notified by email. """ def update_domain_contact(client, input, options \\ []) do request(client, "UpdateDomainContact", input, options) end @doc """ This operation updates the specified domain contact's privacy setting. When privacy protection is enabled, contact information such as email address is replaced either with contact information for Amazon Registrar (for .com, .net, and .org domains) or with contact information for our registrar associate, Gandi. This operation affects only the contact information for the specified contact type (registrant, administrator, or tech). If the request succeeds, Amazon Route 53 returns an operation ID that you can use with [GetOperationDetail](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html) to track the progress and completion of the action. If the request doesn't complete successfully, the domain registrant will be notified by email. By disabling the privacy service via API, you consent to the publication of the contact information provided for this domain via the public WHOIS database. You certify that you are the registrant of this domain name and have the authority to make this decision. You may withdraw your consent at any time by enabling privacy protection using either `UpdateDomainContactPrivacy` or the Route 53 console. Enabling privacy protection removes the contact information provided for this domain from the WHOIS database. For more information on our privacy practices, see [https://aws.amazon.com/privacy/](https://aws.amazon.com/privacy/). """ def update_domain_contact_privacy(client, input, options \\ []) do request(client, "UpdateDomainContactPrivacy", input, options) end @doc """ This operation replaces the current set of name servers for the domain with the specified set of name servers. If you use Amazon Route 53 as your DNS service, specify the four name servers in the delegation set for the hosted zone for the domain. If successful, this operation returns an operation ID that you can use to track the progress and completion of the action. If the request is not completed successfully, the domain registrant will be notified by email. """ def update_domain_nameservers(client, input, options \\ []) do request(client, "UpdateDomainNameservers", input, options) end @doc """ This operation adds or updates tags for a specified domain. All tag operations are eventually consistent; subsequent operations might not immediately represent all issued operations. """ def update_tags_for_domain(client, input, options \\ []) do request(client, "UpdateTagsForDomain", input, options) end @doc """ Returns all the domain-related billing records for the current AWS account for a specified period """ def view_billing(client, input, options \\ []) do request(client, "ViewBilling", input, options) end @spec request(AWS.Client.t(), binary(), map(), list()) :: {:ok, map() | nil, map()} | {:error, term()} defp request(client, action, input, options) do client = %{client | service: "route53domains"} host = build_host("route53domains", client) url = build_url(host, client) headers = [ {"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}, {"X-Amz-Target", "Route53Domains_v20140515.#{action}"} ] payload = encode!(client, input) headers = AWS.Request.sign_v4(client, "POST", url, headers, payload) post(client, url, payload, headers, options) end defp post(client, url, payload, headers, options) do case AWS.Client.request(client, :post, url, payload, headers, options) do {:ok, %{status_code: 200, body: body} = response} -> body = if body != "", do: decode!(client, body) {:ok, body, response} {:ok, response} -> {:error, {:unexpected_response, response}} error = {:error, _reason} -> error end end defp build_host(_endpoint_prefix, %{region: "local", endpoint: endpoint}) do endpoint end defp build_host(_endpoint_prefix, %{region: "local"}) do "localhost" end defp build_host(endpoint_prefix, %{region: region, endpoint: endpoint}) do "#{endpoint_prefix}.#{region}.#{endpoint}" end defp build_url(host, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}/" end defp encode!(client, payload) do AWS.Client.encode!(client, payload, :json) end defp decode!(client, payload) do AWS.Client.decode!(client, payload, :json) end end
lib/aws/generated/route53_domains.ex
0.896126
0.459743
route53_domains.ex
starcoder
defmodule Mix.UAInspector.Verify.Cleanup do @moduledoc """ Cleans up testcases. """ alias UAInspector.ShortCodeMap.DeviceBrands @empty_to_quotes [ [:bot, :category], [:bot, :producer, :name], [:bot, :producer, :url], [:bot, :url] ] @empty_to_unknown [ [:client], [:client, :engine], [:client, :engine_version], [:client, :version], [:device, :brand], [:device, :model], [:device, :type], [:os, :platform], [:os, :version] ] @number_to_string [ [:client, :engine_version], [:client, :version], [:device, :brand], [:device, :model], [:os, :version] ] @unknown_to_atom [ [:browser_family], [:os_family] ] @doc """ Cleans up a test case. """ @spec cleanup(testcase :: map) :: map def cleanup(testcase) do testcase |> convert_empty(@empty_to_quotes, "") |> convert_empty(@empty_to_unknown, :unknown) |> convert_numbers(@number_to_string) |> convert_unknown(@unknown_to_atom) |> cleanup_client_engine() |> cleanup_client_engine_version() |> cleanup_os_entry() |> remove_client_short_name() |> remove_os_short_name() |> remove_unknown_device() |> unshorten_device_brand() end defp convert_empty(testcase, [], _), do: testcase defp convert_empty(testcase, [path | paths], replacement) do testcase |> get_in(path) |> case do :null -> put_in(testcase, path, replacement) "" -> put_in(testcase, path, replacement) _ -> testcase end |> convert_empty(paths, replacement) rescue FunctionClauseError -> convert_empty(testcase, paths, replacement) end defp convert_numbers(testcase, []), do: testcase defp convert_numbers(testcase, [path | paths]) do testcase |> get_in(path) |> case do v when is_number(v) -> put_in(testcase, path, to_string(v)) _ -> testcase end |> convert_numbers(paths) rescue FunctionClauseError -> convert_numbers(testcase, paths) end defp convert_unknown(testcase, []), do: testcase defp convert_unknown(testcase, [path | paths]) do testcase |> get_in(path) |> case do "Unknown" -> put_in(testcase, path, :unknown) _ -> testcase end |> convert_unknown(paths) end defp cleanup_client_engine(%{client: client} = testcase) when is_map(client) do client = if Map.has_key?(client, :engine) do client else Map.put(client, :engine, :unknown) end %{testcase | client: client} end defp cleanup_client_engine(testcase), do: testcase defp cleanup_client_engine_version(%{client: client} = testcase) when is_map(client) do client = if Map.has_key?(client, :engine_version) do client else Map.put(client, :engine_version, :unknown) end %{testcase | client: client} end defp cleanup_client_engine_version(testcase), do: testcase defp cleanup_os_entry(%{os: os} = testcase) do os = case Map.keys(os) do [] -> :unknown _ -> os end %{testcase | os: os} end defp cleanup_os_entry(testcase), do: testcase defp remove_client_short_name(%{client: :unknown} = testcase), do: testcase defp remove_client_short_name(%{client: _} = testcase) do %{testcase | client: Map.delete(testcase.client, :short_name)} end defp remove_client_short_name(testcase), do: testcase defp remove_os_short_name(%{os: :unknown} = testcase), do: testcase defp remove_os_short_name(%{os: _} = testcase) do %{testcase | os: Map.delete(testcase.os, :short_name)} end defp remove_os_short_name(testcase), do: testcase defp remove_unknown_device( %{device: %{type: :unknown, brand: :unknown, model: :unknown}} = result ) do %{result | device: :unknown} end defp remove_unknown_device(result), do: result def unshorten_device_brand(%{device: %{brand: brand}} = testcase) do put_in(testcase, [:device, :brand], DeviceBrands.to_long(brand)) end def unshorten_device_brand(testcase), do: testcase end
verify/lib/mix/ua_inspector/verify/cleanup.ex
0.602179
0.553324
cleanup.ex
starcoder
defmodule Plymio.Fontais.Result do @moduledoc ~S""" Functions for Result Patterns: `{:ok, value}` or `{:error, error}`. See `Plymio.Fontais` for overview and documentation terms. """ require Plymio.Fontais.Guard @type opts :: Plymio.Fontais.opts() @type error :: Plymio.Fontais.error() @type result :: Plymio.Fontais.result() @type results :: Plymio.Fontais.results() import Plymio.Fontais.Error, only: [ new_error_result: 1, new_runtime_error_result: 1, new_argument_error_result: 1 ] import Plymio.Fontais.Guard, only: [ is_value_unset_or_nil: 1 ] @doc ~S""" `normalise0_result/1` takes an argument an enforces *pattern 0*. If the argument is `{:ok, value}` or `{:error, error}`, it is passed through unchanged. If the argument is anything else, it is converted into `{:error, error}`. ## Examples iex> {:ok, 42} |> normalise0_result {:ok, 42} iex> {:error, error} = {:error, %ArgumentError{message: "value is 42"}} |> normalise0_result ...> error |> Exception.message "value is 42" iex> {:error, error} = 42 |> normalise0_result ...> error |> Exception.message "pattern0 result invalid, got: 42" """ @since "0.1.0" @spec normalise0_result(any) :: {:ok, any} | {:error, error} def normalise0_result(result) def normalise0_result({:ok, _} = result) do result end def normalise0_result({:error, %{__struct__: _}} = result) do result end def normalise0_result(x) do new_argument_error_result(m: "pattern0 result invalid", v: x) end @doc ~S""" `normalise1_result/1` takes an argument an enforces *pattern 1*. If the argument is `{:ok, value}` or `{:error, error}`, it is passed through unchanged. An other `value` is converted into `{:ok, value}`. ## Examples iex> {:ok, 42} |> normalise1_result {:ok, 42} iex> {:error, error} = {:error, %ArgumentError{message: "value is 42"}} |> normalise1_result ...> error |> Exception.message "value is 42" iex> 42 |> normalise1_result {:ok, 42} """ @since "0.1.0" @spec normalise1_result(any) :: {:ok, any} | {:error, error} def normalise1_result(result) def normalise1_result({:ok, _} = result) do result end def normalise1_result({:error, %{__struct__: _}} = result) do result end def normalise1_result(value) do {:ok, value} end @doc ~S""" `normalise2_result/1` takes an argument an applies *pattern 2*. Its works like `normalise1_result/1` **except** if the `value` is `nil` or *the unset value* (see `Plymio.Fontais.Guard.the_unset_value/0`), it is passed through unchanged. ## Examples iex> {:ok, 42} |> normalise2_result {:ok, 42} iex> {:error, error} = {:error, %ArgumentError{message: "value is 42"}} |> normalise2_result ...> error |> Exception.message "value is 42" iex> 42 |> normalise2_result {:ok, 42} iex> nil |> normalise2_result nil iex> value1 = Plymio.Fontais.Guard.the_unset_value ...> value2 = value1 ...> value3 = value1 |> normalise2_result ...> value3 == value2 true """ @since "0.1.0" @spec normalise2_result(any) :: atom | {:ok, any} | {:error, error} def normalise2_result(result) def normalise2_result({:ok, _} = result) do result end def normalise2_result({:error, %{__struct__: _}} = result) do result end def normalise2_result(value) when is_value_unset_or_nil(value) do value end def normalise2_result(value) do {:ok, value} end @doc ~S""" `normalise0_results/1` takes an *enum* and applies *pattern 0* to each element, returning `{:ok, enum}` where `enum` will be a `Stream`. ## Examples iex> {:ok, enum} = [ ...> {:ok, 42}, ...> {:error, %BadMapError{term: :not_a_map}}, ...> "HelloWorld" ...> ] |> normalise0_results ...> enum |> Enum.to_list [{:ok, 42}, {:error, %BadMapError{term: :not_a_map}}, {:error, %ArgumentError{message: "pattern0 result invalid, got: HelloWorld"}}] """ @since "0.1.0" @spec normalise0_results(any) :: {:ok, results} | {:error, error} def normalise0_results(results) def normalise0_results(results) when is_list(results) do {:ok, results |> Stream.map(&normalise0_result/1)} end def normalise0_results(results) do new_error_result(m: "results invalid", v: results) end @doc ~S""" `normalise1_results/1` takes an *enum* and applies *pattern 1* to each element, returning `{:ok, enum}` where `enum` will be a `Stream`. ## Examples iex> {:ok, enum} = [ ...> {:ok, 42}, ...> {:error, %BadMapError{term: :not_a_map}}, ...> "HelloWorld" ...> ] |> normalise1_results ...> enum |> Enum.to_list [{:ok, 42}, {:error, %BadMapError{term: :not_a_map}}, {:ok, "HelloWorld"}] """ @since "0.1.0" @spec normalise1_results(any) :: {:ok, results} | {:error, error} def normalise1_results(results) def normalise1_results(results) when is_list(results) do {:ok, results |> Stream.map(&normalise1_result/1)} end def normalise1_results(results) do new_error_result(m: "results invalid", v: results) end @doc ~S""" `normalise2_results/1` takes an *enum* and applies *pattern 2* to each element, returning `{:ok, enum}` where `enum` will be a `Stream`. ## Examples iex> unset_value = Plymio.Fontais.Guard.the_unset_value() ...> {:ok, enum} = [ ...> nil, ...> {:ok, 42}, ...> {:error, %BadMapError{term: :not_a_map}}, ...> unset_value, ...> "HelloWorld" ...> ] |> normalise2_results ...> results = enum |> Enum.to_list ...> nil = results |> Enum.at(0) ...> {:error, %BadMapError{term: :not_a_map}} = results |> Enum.at(2) ...> ^unset_value = results |> Enum.at(3) ...> results |> Enum.at(3) |> Plymio.Fontais.Guard.is_value_unset true """ @since "0.1.0" @spec normalise2_results(any) :: {:ok, results} | {:error, error} def normalise2_results(results) def normalise2_results(results) when is_list(results) do {:ok, results |> Stream.map(&normalise2_result/1)} end def normalise2_results(results) do new_error_result(m: "results invalid", v: results) end @doc ~S""" `validate_results/1` takes an *enum* and confirms each value is a *result*, returning `{:ok, enum}`. ## Examples iex> {:ok, enum} = [ ...> {:ok, 42}, ...> {:error, %BadMapError{term: :not_a_map}}, ...> ] |> validate_results ...> enum |> Enum.to_list [{:ok, 42}, {:error, %BadMapError{term: :not_a_map}}] iex> {:error, error} = [ ...> {:ok, 42}, ...> {:error, %BadMapError{term: :not_a_map}}, ...> "HelloWorld" ...> ] |> validate_results ...> error |> Exception.message "result invalid, got: \"HelloWorld\"" iex> {:error, error} = [ ...> {:ok, 42}, ...> {:error, %BadMapError{term: :not_a_map}}, ...> "HelloWorld", :not_a_result ...> ] |> validate_results ...> error |> Exception.message "results invalid, got: [\"HelloWorld\", :not_a_result]" """ @since "0.1.0" @spec validate_results(any) :: result def validate_results(results) do results |> Enum.reject(fn {:ok, _} -> true {:error, error} -> error |> Exception.exception?() _ -> false end) |> case do [] -> {:ok, results} not_results -> not_results |> length |> case do 1 -> new_runtime_error_result("result invalid, got: #{inspect(hd(not_results))}") _ -> new_runtime_error_result("results invalid, got: #{inspect(not_results)}") end end end @doc false def realise_results(results) def realise_results(results) when is_list(results) do results |> validate_results end def realise_results(results) do try do results |> Enum.to_list() |> validate_results rescue error -> {:error, error} end end @doc false @since "0.1.0" def result_strip_ok_or_raise_error(result) def result_strip_ok_or_raise_error({:ok, value}) do value end def result_strip_ok_or_raise_error({:error, error}) do raise error end def result_strip_ok_or_raise_error(result) do new_error_result(m: "result invalid", v: result) |> result_strip_ok_or_raise_error end @doc false @since "0.1.0" def result_strip_ok_or_passthru(result) def result_strip_ok_or_passthru({:ok, value}) do value end def result_strip_ok_or_passthru(value) do value end end
lib/fontais/result/result.ex
0.914734
0.45308
result.ex
starcoder
defmodule XDR.VariableOpaque do @moduledoc """ This module manages the `Variable-Length Opaque Data` type based on the RFC4506 XDR Standard. """ @behaviour XDR.Declaration alias XDR.{FixedOpaque, UInt, VariableOpaqueError} defstruct [:opaque, :max_size] @type opaque :: binary() | nil @typedoc """ `XDR.VariableOpaque` structure type specification. """ @type t :: %XDR.VariableOpaque{opaque: opaque(), max_size: integer()} @doc """ Create a new `XDR.VariableOpaque` structure with the `opaque` and `max_size` passed. """ @spec new(opaque :: opaque(), max_size :: integer()) :: t() def new(opaque, max_size \\ 4_294_967_295) def new(opaque, max_size), do: %XDR.VariableOpaque{opaque: opaque, max_size: max_size} @doc """ Encode a `XDR.VariableOpaque` structure into a XDR format. """ @impl true def encode_xdr(%{opaque: opaque}) when not is_binary(opaque), do: {:error, :not_binary} def encode_xdr(%{max_size: max_size}) when not is_integer(max_size), do: {:error, :not_number} def encode_xdr(%{max_size: max_size}) when max_size <= 0, do: {:error, :exceed_lower_bound} def encode_xdr(%{max_size: max_size}) when max_size > 4_294_967_295, do: {:error, :exceed_upper_bound} def encode_xdr(%{opaque: opaque, max_size: max_size}) when byte_size(opaque) > max_size, do: {:error, :invalid_length} def encode_xdr(%{opaque: opaque}) do length = byte_size(opaque) opaque_length = length |> UInt.new() |> UInt.encode_xdr!() fixed_opaque = FixedOpaque.new(opaque, length) |> FixedOpaque.encode_xdr!() {:ok, opaque_length <> fixed_opaque} end @doc """ Encode a `XDR.VariableOpaque` structure into a XDR format. If the `opaque` is not valid, an exception is raised. """ @impl true def encode_xdr!(opaque) do case encode_xdr(opaque) do {:ok, binary} -> binary {:error, reason} -> raise(VariableOpaqueError, reason) end end @doc """ Decode the Variable-Length Opaque Data in XDR format to a `XDR.VariableOpaque` structure. """ @impl true def decode_xdr(bytes, opaque \\ %{max_size: 4_294_967_295}) def decode_xdr(bytes, _opaque) when not is_binary(bytes), do: {:error, :not_binary} def decode_xdr(_bytes, %{max_size: max_size}) when not is_integer(max_size), do: {:error, :not_number} def decode_xdr(_bytes, %{max_size: max_size}) when max_size <= 0, do: {:error, :exceed_lower_bound} def decode_xdr(_bytes, %{max_size: max_size}) when max_size > 4_294_967_295, do: {:error, :exceed_upper_bound} def decode_xdr(bytes, %{max_size: max_size}) do {uint, rest} = UInt.decode_xdr!(bytes) uint.datum |> get_decoded_value(rest, max_size) end @doc """ Decode the Variable-Length Opaque Data in XDR format to a `XDR.VariableOpaque` structure. If the binaries are not valid, an exception is raised. """ @impl true def decode_xdr!(bytes, opaque \\ %{max_size: 4_294_967_295}) def decode_xdr!(bytes, opaque) do case decode_xdr(bytes, opaque) do {:ok, result} -> result {:error, reason} -> raise(VariableOpaqueError, reason) end end @spec get_decoded_value(length :: integer(), rest :: binary(), max :: integer()) :: {:ok, {t(), binary()}} defp get_decoded_value(length, _rest, max) when length > max, do: {:error, :length_over_max} defp get_decoded_value(length, rest, _max) when length > byte_size(rest), do: {:error, :length_over_rest} defp get_decoded_value(length, rest, max) do {fixed_opaque, rest} = FixedOpaque.decode_xdr!(rest, %XDR.FixedOpaque{length: length}) decoded_variable_array = fixed_opaque.opaque |> new(max) {:ok, {decoded_variable_array, rest}} end end
lib/xdr/variable_opaque.ex
0.918763
0.660456
variable_opaque.ex
starcoder
defmodule Multi do @moduledoc """ A simple GenServer to run ConfigCat examples. The ConfigCat GenServer is started by our application supervisor in `simple/application.ex`. In the first ConfigCat config there is a 'keySampleText' setting with the following rules: 1. If the User's country is Hungary, the value should be 'Dog' 2. If the User's custom property - SubscriptionType - is unlimited, the value should be 'Lion' 3. In other cases there is a percentage rollout configured with 50% 'Falcon' and 50% 'Horse' rules. 4. There is also a default value configured: 'Cat' In the second ConfigCat config there are `isPOCFeatureEnabled` and `isAwesomeFeatureEnabled` settings. """ use GenServer, restart: :transient alias ConfigCat.User def start_link(_options) do GenServer.start_link(__MODULE__, []) end @impl GenServer def init(_initial_state) do run_first_examples() run_second_examples() {:ok, %{}} end defp run_first_examples do # 1. As the passed User's country is Hungary this will print 'Dog' my_setting_value = ConfigCat.get_value("keySampleText", "default value", User.new("key", country: "Hungary"), client: :first ) print("keySampleText", my_setting_value) # 2. As the passed User's custom attribute - SubscriptionType - is unlimited this will print 'Lion' my_setting_value = ConfigCat.get_value( "keySampleText", "default value", User.new("key", custom: %{"SubscriptionType" => "unlimited"}), client: :first ) print("keySampleText", my_setting_value) # 3/a. As the passed User doesn't fill in any rules, this will serve 'Falcon' or 'Horse'. my_setting_value = ConfigCat.get_value("keySampleText", "default value", User.new("key"), client: :first) print("keySampleText", my_setting_value) # 3/b. As this is the same user from 3/a., this will print the same value as the previous one ('Falcon' or 'Horse') my_setting_value = ConfigCat.get_value("keySampleText", "default value", User.new("key"), client: :first) print("keySampleText", my_setting_value) # 4. As we don't pass an User object to this call, this will print the setting's default value - 'Cat' my_setting_value = ConfigCat.get_value("keySampleText", "default value", client: :first) print("keySampleText", my_setting_value) # 'myKeyNotExists' setting doesn't exist in the project configuration and the client returns default value ('default value') my_setting_value = ConfigCat.get_value("myKeyNotExists", "default value", client: :first) print("myKeyNotExists", my_setting_value) end def run_second_examples do user = User.new("Some UserID", email: "<EMAIL>", custom: %{version: "1.0.0"} ) value = ConfigCat.get_value("isPOCFeatureEnabled", "default value", user, client: :second) print("isPOCFeatureEnabled", value) value = ConfigCat.get_value("isAwesomeFeatureEnabled", "default value", client: :second) print("isAwesomeFeatureEnabled", value) end defp print(key, value) do IO.puts("'#{key}' value from ConfigCat: #{value}") end end
samples/multi/lib/multi.ex
0.825836
0.497986
multi.ex
starcoder
defmodule Militerm.Systems.Commands.Binder do # %{ # command: ["look", "at", "the", "lit", "lamp", "through", "the", "big", "telescope"], # adverbs: [], # direct: [{:object, :singular, [:me, :near], ["the", "lit", "lamp"]}], # instrument: [{:object, :singular, [:me, :near], ["the", "big", "telescope"]}], # syntax: VerbSyntax.parse("at <direct:object'thing> through <instrument:object>") # } alias Militerm.Components alias Militerm.Services alias Militerm.Systems @obj_slots ~w[direct indirect instrument] @predefined_env ~w[me near here]a @doc """ Takes the context and command. Returns a new context and the command with slots bound to the entities that match the words. Further processing is needed to know if the bound entities can be used in the slot for the set of events. """ @spec bind(map, map) :: {map, map} def bind(context, command) do slots = command |> Map.get(:slots, %{}) {_, bound_slots} = slots |> Map.take(@obj_slots) |> ordered_slots() |> Enum.reduce({context, %{}}, fn slot, acc -> bind_slot(slot, Map.get(slots, slot), acc) end) bound_slots = slots |> Map.drop(@obj_slots) |> Enum.reduce(bound_slots, fn {slot, v}, acc -> Map.put(acc, slot, v) end) Map.put(command, :slots, bound_slots) # Map.merge(bound_command, Map.take(command, @not_slots)) end def bind_slot(slot, list, info) when is_list(list) do {context, new_bindings} = Enum.reduce(list, info, fn item, info -> bind_slot(slot, item, info) end) {context, Map.put(new_bindings, slot, Enum.reverse(Map.get(new_bindings, slot, [])))} end def bind_slot(slot, string, {context, bindings}) when is_binary(string) do { context, Map.put(bindings, slot, [string | Map.get(bindings, slot, [])]) } end def bind_slot(slot, {type, number, envs, words}, {context, bindings}) do # the -> ignored - can be used with singular and plural sets # a/an -> indicates that if there's more than one, select one at random # ordinal -> order entities reliably and drop the first few up to the ordinal # cardinal -> take the indicated number after processing any ordinal # pronouns -> my, its, her, their, his - refocus environment based on context # we expect at most one ordinal, one cardinal, one article # first, split on prepositions and then match up the chain # the env entities are the things we can look in to find what should be visible to us # so no delving into containers - no 'in', 'on', etc., that indicates narrative containment env_entities = gather_environments(envs, context, bindings) # we run through the envs list and see if we can match based on the env # rather than translate them into entities and then match in the entities # we need to handle distant-living matches = case parse_noun_phrase(words) do {:ok, parses} -> parses |> Enum.flat_map(fn %{} = parse -> find_objects(parse, env_entities) end) _ -> [] end {context, Map.put(bindings, slot, matches)} end def bind_slot(_, nil, info), do: info defp find_objects(_, []), do: [] defp find_objects(%{words: words} = parse, [env | rest]) do # look in env - if we find nothing, go to rest - otherwise, return what we find match = env |> Services.Location.find_in(:infinite) |> Enum.filter(fn thing -> Systems.Identity.parse_match?(thing, words) end) case match do [] -> find_objects(parse, rest) otherwise -> match end end defp gather_environments(envs, context, bindings, acc \\ []) defp gather_environments([], _, _, acc), do: Enum.reverse(acc) defp gather_environments([:me | rest], %{actor: entity_id} = context, bindings, acc) do gather_environments(rest, context, bindings, [entity_id | acc]) end defp gather_environments([:near | rest], %{actor: entity_id} = context, bindings, acc) do {_, loc} = Services.Location.where(entity_id) loc = case Services.Location.where(loc) do {_, loc_loc} -> loc_loc nil -> loc end gather_environments(rest, context, bindings, [loc | acc]) end defp gather_environments([:here | rest], %{actor: entity_id} = context, bindings, acc) do {_, {:thing, loc_id, _}} = Services.Location.where(entity_id) gather_environments(rest, context, bindings, [{:thing, loc_id} | acc]) end defp gather_environments([slot | rest], context, bindings, acc) do gather_environments(rest, context, bindings, Map.get(bindings, slot, []) ++ acc) end @doc """ Parses the noun phrase into parts that can be matched against things. ## Examples iex> Binder.parse_noun_phrase(~s[duck]) {:ok, [%{words: ["duck"]}]} iex> Binder.parse_noun_phrase(~s[all ducks]) {:ok, [%{quantity: :all, words: ["ducks"]}]} iex> Binder.parse_noun_phrase(~s[the letter in the envelope]) {:ok, [%{article: "the", words: ["envelope"], relation: {"in", %{article: "the", words: ["letter"]}}}]} iex> Binder.parse_noun_phrase(~s[twenty six grams of flour]) {:ok, [%{words: ["flour"], relation: {"of", %{quantity: 26, words: ["grams"]}}}]} """ def parse_noun_phrase(words) do # split words on prepositions lex = words |> String.to_charlist() |> :command_lexer.string() case lex do {:ok, tokens, _} -> parse = tokens |> Enum.reject(fn {:space, _} -> true _ -> false end) |> :command_parser.parse() case parse do {:ok, structure} -> {:ok, cleanup_parse(structure)} otherwise -> {:error, "Unrecognizable phrase"} end {:error, {_, _, reason}} -> {:error, reason} {:error, _, _} -> {:error, "bad parse"} end end defp cleanup_parse(structure, acc \\ []) defp cleanup_parse([], acc), do: Enum.reverse(acc) defp cleanup_parse([tuple | rest], acc) when is_tuple(tuple) do cleanup_parse(rest, [reduce_parse(tuple, %{}) | acc]) end defp cleanup_parse([object | rest], acc) do map = object |> Enum.reduce(%{}, &reduce_parse/2) cleanup_parse(rest, [map | acc]) end defp reduce_parse({:relation, {left, prep, right}}, acc) do [right] |> cleanup_parse() |> List.first() |> Map.put(:relation, {prep, List.first(cleanup_parse([left]))}) end defp reduce_parse({k, v}, map) do Map.put(map, k, v) end defp reduce_parse(list, map) when is_list(list) do list |> Enum.reduce(map, &reduce_parse/2) end defp ordered_slots(mapping) do sort = mapping |> Enum.reduce(%{}, fn {slot, refs}, acc -> referenced_slots = refs |> to_list() |> Enum.flat_map(fn {_, _, envs} -> envs _ -> [] end) |> Enum.uniq() case referenced_slots do [] -> acc _ -> Map.put(acc, slot, referenced_slots -- @predefined_env) end end) |> topological_sort sort ++ (@obj_slots -- sort) end defp topological_sort(map, acc \\ []) defp topological_sort(map, acc) when map_size(map) == 0, do: Enum.reverse(acc) defp topological_sort(map, acc) do case Enum.filter(map, fn {_, []} -> true _ -> false end) do [_ | _] = available -> map |> Map.drop(available) |> Enum.map(fn {k, v} -> {k, v -- available} end) |> Enum.into(%{}) |> topological_sort(available ++ acc) _ -> :error end end def to_list(nil), do: [] def to_list(list) when is_list(list), do: list def to_list(thing), do: [thing] end
lib/militerm/systems/commands/binder.ex
0.614047
0.470919
binder.ex
starcoder
defmodule Cldr.DateTime.Format do @moduledoc """ Manages the Date, TIme and DateTime formats defined by CLDR. The functions in `Cldr.DateTime.Format` are primarily concerned with encapsulating the data from CLDR in functions that are used during the formatting process. """ alias Cldr.Calendar, as: Kalendar alias Cldr.Locale alias Cldr.LanguageTag alias Cldr.Config @standard_formats [:short, :medium, :long, :full] @type standard_formats :: %{ full: String.t(), long: String.t(), medium: String.t(), short: String.t() } @type formats :: Map.t() @type calendar :: atom @doc """ Returns a list of all formats defined for the configured locales. """ def format_list do ((known_formats(&all_date_formats/1) ++ known_formats(&all_time_formats/1) ++ known_formats(&all_date_time_formats/1)) ++ configured_precompile_list()) |> Enum.reject(&is_atom/1) |> Enum.uniq() end def configured_precompile_list do Application.get_env(Config.app_name(), :precompile_datetime_formats, []) end @doc """ Returns a list of calendars defined for a given locale. ## Arguments * `locale` is any valid locale name returned by `Cldr.known_locale_names/0` or a `Cldr.LanguageTag` struct. The default is `Cldr.get_current_locale/0` ## Example iex> Cldr.DateTime.Format.calendars_for "en" {:ok, [:buddhist, :chinese, :coptic, :dangi, :ethiopic, :ethiopic_amete_alem, :generic, :gregorian, :hebrew, :indian, :islamic, :islamic_civil, :islamic_rgsa, :islamic_tbla, :islamic_umalqura, :japanese, :persian, :roc]} """ @spec calendars_for(Locale.name() | LanguageTag.t()) :: [calendar, ...] def calendars_for(locale, backend), do: backend.calendars_for(locale) @doc """ Returns the GMT offset format list for a for a timezone offset for a given locale. ## Arguments * `locale` is any locale returned by `Cldr.known_locale_names/0` ## Example iex> Cldr.DateTime.Format.gmt_format "en" {:ok, ["GMT", 0]} """ @spec gmt_format(Locale.name() | LanguageTag) :: [non_neg_integer | String.t(), ...] def gmt_format(locale, backend), do: backend.gmt_format(locale) @doc """ Returns the GMT format string for a for a timezone with an offset of zero for a given locale. ## Arguments * `locale` is any locale returned by `Cldr.known_locale_names/0` ## Example iex> Cldr.DateTime.Format.gmt_zero_format "en" {:ok, "GMT"} """ @spec gmt_zero_format(Locale.name() | LanguageTag) :: String.t() def gmt_zero_format(locale, backend), do: backend.gmt_zero_format(locale) @doc """ Returns the postive and negative hour format for a timezone offset for a given locale. ## Arguments * `locale` is any locale returned by `Cldr.known_locale_names/0` ## Example iex> Cldr.DateTime.Format.hour_format "en" {:ok, {"+HH:mm", "-HH:mm"}} """ @spec hour_format(Locale.name() | LanguageTag) :: {String.t(), String.t()} def hour_format(locale, backend), do: backend.hour_format(locale) @doc """ Returns a map of the standard date formats for a given locale and calendar. ## Arguments * `locale` is any locale returned by `Cldr.known_locale_names/0` * `calendar` is any calendar returned by `Cldr.DateTime.Format.calendars_for/1` The default is `:gregorian` ## Examples: iex> Cldr.DateTime.Format.date_formats "en" {:ok, %Cldr.Date.Formats{ full: "EEEE, MMMM d, y", long: "MMMM d, y", medium: "MMM d, y", short: "M/d/yy" }} iex> Cldr.DateTime.Format.date_formats "en", :buddhist {:ok, %Cldr.Date.Formats{ full: "EEEE, MMMM d, y G", long: "MMMM d, y G", medium: "MMM d, y G", short: "M/d/y GGGGG" }} """ @spec date_formats(Locale.name() | LanguageTag.t(), calendar) :: standard_formats def date_formats(locale, calendar, backend), do: backend.date_formats(locale, calendar) @doc """ Returns a map of the standard time formats for a given locale and calendar. ## Arguments * `locale` is any locale returned by `Cldr.known_locale_names/0` * `calendar` is any calendar returned by `Cldr.DateTime.Format.calendars_for/1` The default is `:gregorian` ## Examples: iex> Cldr.DateTime.Format.time_formats "en" {:ok, %Cldr.Time.Formats{ full: "h:mm:ss a zzzz", long: "h:mm:ss a z", medium: "h:mm:ss a", short: "h:mm a" }} iex> Cldr.DateTime.Format.time_formats "en", :buddhist {:ok, %Cldr.Time.Formats{ full: "h:mm:ss a zzzz", long: "h:mm:ss a z", medium: "h:mm:ss a", short: "h:mm a" }} """ @spec time_formats(Locale.name() | LanguageTag, calendar) :: standard_formats def time_formats(locale, calendar, backend), do: backend.time_formats(locale, calendar) @doc """ Returns a map of the standard datetime formats for a given locale and calendar. ## Arguments * `locale` is any locale returned by `Cldr.known_locale_names/0` * `calendar` is any calendar returned by `Cldr.DateTime.Format.calendars_for/1` The default is `:gregorian` ## Examples: iex> Cldr.DateTime.Format.date_time_formats "en" {:ok, %Cldr.DateTime.Formats{ full: "{1} 'at' {0}", long: "{1} 'at' {0}", medium: "{1}, {0}", short: "{1}, {0}" }} iex> Cldr.DateTime.Format.date_time_formats "en", :buddhist {:ok, %Cldr.DateTime.Formats{ full: "{1} 'at' {0}", long: "{1} 'at' {0}", medium: "{1}, {0}", short: "{1}, {0}" }} """ @spec date_time_formats(Locale.name() | LanguageTag, calendar) :: standard_formats def date_time_formats(locale, calendar, backend), do: backend.date_time_formats(locale, calendar) @doc """ Returns a map of the available non-standard datetime formats for a given locale and calendar. ## Arguments * `locale` is any locale returned by `Cldr.known_locale_names/0` * `calendar` is any calendar returned by `Cldr.DateTime.Format.calendars_for/1` The default is `:gregorian` ## Examples: iex> Cldr.DateTime.Format.date_time_available_formats "en" {:ok, %{ yw_count_other: "'week' w 'of' Y", mmm: "LLL", d: "d", ehm: "E h:mm a", y_mmm: "MMM y", mm_md: "MMM d", gy_mm_md: "MMM d, y G", e_bhm: "E h:mm B", ed: "d E", mmm_md: "MMMM d", ehms: "E h:mm:ss a", y_qqq: "QQQ y", y_qqqq: "QQQQ y", m_ed: "E, M/d", md: "M/d", bhm: "h:mm B", hmv: "HH:mm v", y_m: "M/y", gy_mmm: "MMM y G", mmm_ed: "E, MMM d", y_m_ed: "E, M/d/y", y_mm_md: "MMM d, y", gy_mmm_ed: "E, MMM d, y G", e_hms: "E HH:mm:ss", e: "ccc", e_hm: "E HH:mm", yw_count_one: "'week' w 'of' Y", mmmmw_count_one: "'week' W 'of' MMMM", e_bhms: "E h:mm:ss B", hms: "HH:mm:ss", y_mmm_ed: "E, MMM d, y", y_md: "M/d/y", ms: "mm:ss", hmsv: "HH:mm:ss v", hm: "HH:mm", h: "HH", mmmmw_count_other: "'week' W 'of' MMMM", bh: "h B", m: "L", bhms: "h:mm:ss B", y_mmmm: "MMMM y", y: "y", gy: "y G" }} """ @spec date_time_available_formats(Locale.name() | LanguageTag, calendar) :: formats def date_time_available_formats(locale, calendar, backend), do: backend.date_time_available_formats(locale, calendar) @doc """ Returns a list of the date_time format types that are available in all locales. The format types returned by `common_date_time_format_names` are guaranteed to be available in all known locales, ## Example: iex> Cldr.DateTime.Format.common_date_time_format_names [:bh, :bhm, :bhms, :d, :e, :e_bhm, :e_bhms, :e_hm, :e_hms, :ed, :ehm, :ehms, :gy, :gy_mm_md, :gy_mmm, :gy_mmm_ed, :h, :hm, :hms, :hmsv, :hmv, :m, :m_ed, :md, :mm_md, :mmm, :mmm_ed, :mmm_md, :mmmmw_count_other, :ms, :y, :y_m, :y_m_ed, :y_md, :y_mm_md, :y_mmm, :y_mmm_ed, :y_mmmm, :y_qqq, :y_qqqq, :yw_count_other] """ def common_date_time_format_names do Cldr.known_locale_names() |> Enum.map(&date_time_available_formats/1) |> Enum.map(&elem(&1, 1)) |> Enum.map(&Map.keys/1) |> Enum.map(&MapSet.new/1) |> intersect_mapsets |> MapSet.to_list() |> Enum.sort() end defp known_formats(list) do Cldr.known_locale_names() |> Enum.map(&list.(&1)) |> List.flatten() |> Enum.uniq() end defp all_date_formats(locale) do all_formats_for(locale, &date_formats/2) end defp all_time_formats(locale) do all_formats_for(locale, &time_formats/2) end defp all_date_time_formats(locale) do all_formats_for(locale, &date_time_formats/2) ++ all_formats_for(locale, &date_time_available_formats/2) end defp all_formats_for(locale, type_function) do with {:ok, calendars} <- calendars_for(locale) do Enum.map(calendars, fn calendar -> {:ok, calendar_formats} = type_function.(locale, calendar) Map.values(calendar_formats) end) |> List.flatten() |> Enum.uniq() end end defp intersect_mapsets([a, b | []]) do MapSet.intersection(a, b) end defp intersect_mapsets([a, b | tail]) do intersect_mapsets([MapSet.intersection(a, b) | tail]) end end
lib/cldr/datetime/datetime_format.ex
0.946658
0.541227
datetime_format.ex
starcoder
defmodule BrDocs.Utils do @moduledoc ~S""" Utility module to hold all the calculations functions used to generate and validate data. """ @docs_digits_ranges %{ cpf: %{ # first digit 9 => [10, 9, 8, 7, 6, 5, 4, 3, 2], # second digit 10 => [11, 10, 9, 8, 7, 6, 5, 4, 3, 2] }, cnpj: %{ # first digit 12 => [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2], # second digit 13 => [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] } } @doc ~S""" Calculates the MOD11 verification digit of a value. Range length must be the equals to the value length. ## Examples iex> BrDocs.Utils.mod11("123", [1, 2, 3]) 8 iex> BrDocs.Utils.mod11("111444777", [10, 9, 8, 7, 6, 5, 4, 3, 2]) 3 iex> BrDocs.Utils.mod11("1114447773", [11, 10, 9, 8, 7, 6, 5, 4, 3, 2]) 5 """ @spec mod11(String.t(), list(integer())) :: integer() def mod11(value, range) do numbers = value |> String.split("", trim: true) |> Enum.map(&String.to_integer(&1)) remainder = numbers |> Enum.zip(range) |> Enum.map(fn {num, r} -> num * r end) |> Enum.sum() |> rem(11) if remainder < 2, do: 0, else: 11 - remainder end @doc ~S""" Generates a string with random numbers. ## Examples iex> BrDocs.Utils.generate_random_numbers(3) "599" iex> BrDocs.Utils.generate_random_numbers(8) "79052943" iex> BrDocs.Utils.generate_random_numbers(12) "064766405673" """ @spec generate_random_numbers(integer()) :: String.t() def generate_random_numbers(size) do Enum.reduce(1..size, "", fn _, acc -> acc <> to_string(Enum.random(0..9)) end) end @doc ~S""" Generates a verification digit based on the value's length of the doc. ## Value's length * `9` - 1st verification digit for a `BrDocs.CPF` value * `10` - 2nd verification digit for a `BrDocs.CPF` value * `12` - 1st verification digit for a `BrDocs.CNPJ` value * `13` - 2nd verification digit for a `BrDocs.CNPJ` value ## Examples iex> BrDocs.Utils.make_digit("123456789") "0" iex> BrDocs.Utils.make_digit("1234567890") "9" iex> BrDocs.Utils.make_digit("114447770001") "6" iex> BrDocs.Utils.make_digit("1144477700016") "1" """ @spec make_digit(String.t()) :: String.t() def make_digit(value) do range = case String.length(value) do size when size in [9, 10] -> @docs_digits_ranges[:cpf][size] size when size in [12, 13] -> @docs_digits_ranges[:cnpj][size] _ -> [] end value |> mod11(range) |> to_string() end end
lib/brdocs/utils.ex
0.828696
0.585368
utils.ex
starcoder
defmodule ElixirRigidPhysics.Collision.Intersection.SphereSphere do @moduledoc """ Module for sphere-sphere intersection tests. """ require ElixirRigidPhysics.Dynamics.Body, as: Body require ElixirRigidPhysics.Geometry.Sphere, as: Sphere require ElixirRigidPhysics.Collision.Contact, as: Contact alias Graphmath.Vec3 @verysmol 1.0e-12 @doc """ Tests intersections of two bodies. ## Examples iex> # Check disjoint spheres iex> alias ElixirRigidPhysics.Collision.Intersection.SphereSphere iex> require ElixirRigidPhysics.Dynamics.Body, as: Body iex> require ElixirRigidPhysics.Geometry.Sphere, as: Sphere iex> a = Body.body( shape: Sphere.sphere(radius: 2), position: {0.0, 0.0, 0.0}) iex> b = Body.body( shape: Sphere.sphere(radius: 2) , position: {5.0, 0.0, 0.0}) iex> SphereSphere.check(a,b) :no_intersection iex> # Check coincident spheres iex> alias ElixirRigidPhysics.Collision.Intersection.SphereSphere iex> require ElixirRigidPhysics.Dynamics.Body, as: Body iex> require ElixirRigidPhysics.Geometry.Sphere, as: Sphere iex> a = Body.body( shape: Sphere.sphere(radius: 2), position: {0.0, 0.0, 0.0}) iex> b = Body.body( shape: Sphere.sphere(radius: 2) , position: {0.0, 0.0, 0.0}) iex> SphereSphere.check(a,b) :coincident iex> # Check grazing spheres of equal size iex> alias ElixirRigidPhysics.Collision.Intersection.SphereSphere iex> require ElixirRigidPhysics.Dynamics.Body, as: Body iex> require ElixirRigidPhysics.Geometry.Sphere, as: Sphere iex> a = Body.body( shape: Sphere.sphere(radius: 1), position: {0.0, 0.0, 0.0}) iex> b = Body.body( shape: Sphere.sphere(radius: 1) , position: {2.0, 0.0, 0.0}) iex> SphereSphere.check(a,b) {:contact_manifold, {{:contact_point, {1.0, 0.0, 0.0}, 0.0}}, {1.0, 0.0, 0.0}} iex> # Check grazing spheres of different size iex> alias ElixirRigidPhysics.Collision.Intersection.SphereSphere iex> require ElixirRigidPhysics.Dynamics.Body, as: Body iex> require ElixirRigidPhysics.Geometry.Sphere, as: Sphere iex> a = Body.body( shape: Sphere.sphere(radius: 1), position: {0.0, 0.0, 0.0}) iex> b = Body.body( shape: Sphere.sphere(radius: 3) , position: {4.0, 0.0, 0.0}) iex> SphereSphere.check(a,b) {:contact_manifold, {{:contact_point, {1.0, 0.0, 0.0}, 0.0}}, {1.0, 0.0, 0.0}} iex> # Check overlapping spheres of same size iex> alias ElixirRigidPhysics.Collision.Intersection.SphereSphere iex> require ElixirRigidPhysics.Dynamics.Body, as: Body iex> require ElixirRigidPhysics.Geometry.Sphere, as: Sphere iex> a = Body.body( shape: Sphere.sphere(radius: 2), position: {0.0, 0.0, 0.0}) iex> b = Body.body( shape: Sphere.sphere(radius: 2) , position: {3.0, 0.0, 0.0}) iex> SphereSphere.check(a,b) {:contact_manifold, {{:contact_point, {1.5, 0.0, 0.0}, 1.0}}, {1.0, 0.0, 0.0}} iex> # Check overlapping spheres of different size iex> alias ElixirRigidPhysics.Collision.Intersection.SphereSphere iex> require ElixirRigidPhysics.Dynamics.Body, as: Body iex> require ElixirRigidPhysics.Geometry.Sphere, as: Sphere iex> a = Body.body( shape: Sphere.sphere(radius: 4), position: {0.0, 0.0, 0.0}) iex> b = Body.body( shape: Sphere.sphere(radius: 2) , position: {5.0, 0.0, 0.0}) iex> SphereSphere.check(a,b) {:contact_manifold, {{:contact_point, {3.5, 0.0, 0.0}, 1.0}}, {1.0, 0.0, 0.0}} """ @spec check(Body.body(), Body.body()) :: Contact.contact_result() def check( Body.body(shape: Sphere.sphere(radius: r_a), position: p_a), Body.body(shape: Sphere.sphere(radius: r_b), position: p_b) ) do a_to_b = Vec3.subtract(p_b, p_a) a_to_b_dist_squared = Vec3.length_squared(a_to_b) if a_to_b_dist_squared > @verysmol do a_to_b_dist = Vec3.length(a_to_b) overlap = a_to_b_dist - (r_a + r_b) if overlap <= @verysmol do penetration_depth = abs(overlap) direction = Vec3.normalize(a_to_b) Contact.contact_manifold( contacts: {Contact.contact_point( world_point: direction |> Vec3.scale(r_a - penetration_depth / 2) |> Vec3.add(p_a), depth: penetration_depth )}, world_normal: direction ) else :no_intersection end else # coincident spheres have no sensible contact point or normal, so just give up. :coincident end end end
lib/collision/intersection/sphere_sphere.ex
0.852245
0.489992
sphere_sphere.ex
starcoder
defmodule OffBroadwayBeanstalkd.Producer do @moduledoc """ A GenStage producer that continuously polls messages from a beanstalkd queue and acknowledge them after being successfully processed. By default this producer uses `OffBroadwayBeanstalkd.BeanstixClient` to talk to beanstalkd but you can provide your client by implementing the `OffBroadwayBeanstalkd.BeanstalkdClient` behaviour. ## Options for `OffBroadwayBeanstalkd.BeanstixClient` * `:host` - Optional. The host beanstalkd is running on, default is '127.0.0.1' * `:port` - Optional. The port beanstalkd is running on, default is 11300 * `:tube` - Optional. The name of the tube, default is "default" * `:requeue` - Optional. Defines a strategy for requeuing failed messages. Possible values are: `:always`, `:never`, `:once` or can be an integer for the number of to requeue eg. if requeue is 5 a message will be tried 6 times before being deleted Default is `:always`. * `:requeue_delay_min` - The minimum requeue delay in seconds (default: `10`) * `:requeue_delay_max` - The maximum requeue delay in seconds (default: `60`) ## Producer Options These options applies to all producers, regardless of client implementation: * `:receive_interval` - Optional. The duration (in milliseconds) for which the producer waits before making a request for more messages. Default is 1000. * `:beanstalkd_client` - Optional. A module that implements the `OffBroadwayBeanstalkd.BeanstalkdClient` behaviour. This module is responsible for fetching and acknowledging the messages. Pay attention that all options passed to the producer will be forwarded to the client. It's up to the client to normalize the options it needs. Default is `OffBroadwayBeanstalkd.BeanstixClient`. ## Acknowledgments In case of successful processing, the message is deleted from the queue. In case of failures, the message is released back to the ready queue or deleted depanding on the requeue option. ### Batching Bathcing with Broadway is done using the `handle_batch/3` callback ## Example Broadway.start_link(MyBroadway, name: MyBroadway, producer: [ module: {OffBroadwayBeanstalkd.Producer, host: "192.168.0.10", port: 11300, tube: "my_queue", requeue: :once concurrency: 5 ], processors: [ default: [] ] ) The above configuration will set up a producer that continuously receives messages from `"my_queue"` and sends them downstream. ## Retrieving Metadata By default the following information is added to the `metadata` field in the `%Message{}` struct: * `id` - The job id received when the message was sent to the queue You can access any of that information directly while processing the message: def handle_message(_, message, _) do job_id message.metadata.id, # Do something with the job_id end """ use GenStage @default_receive_interval 1000 @impl true def init(opts) do client = opts[:beanstalkd_client] || OffBroadwayBeanstalkd.BeanstixClient receive_interval = opts[:receive_interval] || @default_receive_interval case client.init(opts) do {:error, message} -> raise ArgumentError, "invalid options given to #{inspect(client)}.init/1, " <> message {:ok, opts} -> {:producer, %{ demand: 0, receive_timer: nil, receive_interval: receive_interval, beanstalkd_client: {client, opts} }} end end @impl true def handle_demand(incoming_demand, %{demand: demand} = state) do handle_receive_messages(%{state | demand: demand + incoming_demand}) end @impl true def handle_info(:receive_messages, state) do handle_receive_messages(%{state | receive_timer: nil}) end @impl true def handle_info(_, state) do {:noreply, [], state} end defp handle_receive_messages(%{receive_timer: nil, demand: demand} = state) when demand > 0 do messages = receive_messages_from_beanstalkd(state, demand) new_demand = demand - length(messages) receive_timer = case {messages, new_demand} do {[], _} -> schedule_receive_messages(state.receive_interval) {_, 0} -> nil _ -> schedule_receive_messages(0) end {:noreply, messages, %{state | demand: new_demand, receive_timer: receive_timer}} end defp handle_receive_messages(state) do {:noreply, [], state} end defp receive_messages_from_beanstalkd(state, total_demand) do %{beanstalkd_client: {client, opts}} = state client.receive_messages(total_demand, opts) end defp schedule_receive_messages(interval) do Process.send_after(self(), :receive_messages, interval) end end
lib/off_broadway_beanstalkd/producer.ex
0.883651
0.467149
producer.ex
starcoder
defmodule PollutionData do @moduledoc false def importLinesFromCSV(name \\ "pollution.csv", minCount \\ 5900) do lines = File.read!(name) |> String.split("\n") if length(lines) < minCount do {:error, "Problem with importing, Wrong number of lines!"} end lines end def convertLine(line) do [date, time, longitude, latitude, value] = String.split(line, ",") parsedDate = date |> String.split("-") |> Enum.reverse() |> Enum.map( fn(x) -> elem(Integer.parse(x), 0) end) |> :erlang.list_to_tuple() parsedTime = time |> String.split(":") |> Enum.map( fn(x) -> elem(Integer.parse(x), 0) end) |> :erlang.list_to_tuple() {{x, _}, {y, _}} = {Float.parse(longitude), Float.parse(latitude)} location = {x, y} {numValue, _} = Float.parse(value) %{:datetime => {parsedDate, parsedTime}, :location => location, :pollutionLevel => numValue} end def identifyStations(mappedLines) do Enum.uniq_by(mappedLines, fn(m) -> m[:location] end) end def loadStations([]) do :ok end def loadStations([line | tail]) do :pollution_gen_server.addStation("station_#{elem(line[:location], 0)}_#{elem(line[:location], 1)}", line[:location]) loadStations(tail) end def loadMeasurements([]) do :ok end def loadMeasurements([line | t]) do :pollution_gen_server.addValue(line[:location], line[:datetime], "PM10", line[:pollutionLevel]) loadMeasurements(t) end def test do lines = importLinesFromCSV() converted = Enum.map(lines, fn(x) -> convertLine(x) end) stations = identifyStations(converted) loadingStations = fn -> loadStations(stations) end |> :timer.tc |> elem(0) loadingMeasurements = fn -> loadMeasurements(converted) end |> :timer.tc() |> elem(0) stationMean = fn -> :pollution_gen_server.getStationMean({20.06, 49.986}, "PM10") end |> :timer.tc |> elem(0) dailyMean = fn -> :pollution_gen_server.getDailyMean({2017, 5, 3}, "PM10") end |> :timer.tc |> elem(0) {"Stations: ", loadingStations, "Measurements: ", loadingMeasurements, "Station Mean: ", stationMean, "Daily Mean: ", dailyMean} end end
src/pollution_data.ex
0.636014
0.45048
pollution_data.ex
starcoder
defmodule PolyPartition.Geometry do alias PolyPartition.Helpers @moduledoc """ Geometry functions for PolyPartition """ @doc """ Calculate the squared length of a segment Returns float regardless of input ## Examples iex> PolyPartition.Geometry.sq_length([[0,0], [1,1]]) 2.0 """ def sq_length(seg) do [[x1, y1], [x2, y2]] = seg :math.pow((x2 - x1), 2) + :math.pow((y2 - y1), 2) end @doc """ Finds the midpoint of a segment Returns float regardless of input ## Examples iex> PolyPartition.Geometry.midpoint([[0,0], [4,4]]) [2.0, 2.0] """ def midpoint(seg) do [[x1, y1], [x2, y2]] = seg [(x1 + x2) / 2, (y1 + y2) / 2] end @doc """ Calculate the slope of a line through two given points Returns float if slope is defined, returns "vert" if line is degenerate or vertical. ## Examples iex> PolyPartition.Geometry.slope([0,0], [4,4]) 1.0 iex> PolyPartition.Geometry.slope([0,0], [4,0]) 0.0 iex> PolyPartition.Geometry.slope([0,0], [0,4]) "vert" iex> PolyPartition.Geometry.slope([0,0], [0,0]) "vert" """ def slope(point1, point2) do [x1, y1] = point1 [x2, y2] = point2 case x2 - x1 do 0 -> "vert" 0.0 -> "vert" _ -> (y2 - y1) / (x2 - x1) end end defp deg_to_rad(deg) do deg * 2 * :math.pi / 360 end @doc """ Approximate (miles/degree)^2 of longitude for a given latitude (in radians) ## Examples iex> PolyPartition.Geometry.lat_factor(1.4) 1629.2417131835887 """ def lat_factor(lat_rad) do :math.pow(((69.0 * :math.cos(lat_rad)) + 69.0) / 2.0, 2) end @doc """ Approximate area (square miles) of polygon (long/lat) ## Examples iex> poly = [ [ -106.19590759277344, 39.35182131761711 ], [ -106.30714416503905, 39.26894242038886 ], [ -106.08879089355467, 39.25671479372372 ] ] iex> PolyPartition.Geometry.area(poly) 36.41104908437559 """ def area(poly) do factor = poly |> hd |> List.last |> deg_to_rad |> lat_factor get_segments(poly) |> Enum.map(fn(x) -> Helpers.det_seg(x) end) |> List.foldr(0, fn(x, acc) -> x + acc end) |> Kernel./(2.0) |> abs |> Kernel.*(factor) end defp rotate90(point) do [x, y] = point [-y, x] end defp rotate90_seg(seg) do Enum.map(seg, fn(x) -> rotate90(x) end) end @doc """ Determine which side of a line a given point is on A line is determined by the `sample` point and slope `m`. Two `given` points that are on opposite sides of this line will yield numbers with opposite signs from `point_score`. ## Examples iex> PolyPartition.Geometry.point_score([0,1], [1,1], 1) 1 iex> PolyPartition.Geometry.point_score([1,0], [1,1], 1) -1 """ def point_score(given, sample, m) do [h, k] = sample [x, y] = given case m do "vert" -> h - x _ -> y - (m * x) - k + (m * h) end end @doc """ Returns a list of segments representing the sides of the polygon ## Examples iex> PolyPartition.Geometry.get_segments([[0,1], [0,0], [1,0]]) [[[0,1], [0,0]], [[0,0], [1,0]], [[1,0], [0,1]]] """ def get_segments(poly) do poly ++ [hd(poly)] |> Stream.with_index |> Enum.map(fn(x) -> {point, index} = x cond do index != 0 -> [Enum.at(poly, index - 1), point] true -> nil end end) |> List.delete(nil) end @doc """ Determine if two segments perpendicular to the axes intersect ## Examples iex> PolyPartition.Geometry.perp_intersect?([[0,0], [0,1]], [[-1,0.5], [1,0.5]]) true iex> PolyPartition.Geometry.perp_intersect?([[0,0], [0,1]], [[-1,1.5], [1,1.5]]) false """ def perp_intersect?(seg1, seg2) do [[x11, y11], [x12, y12]] = seg1 [[x21, y21], [x22, _]] = seg2 cond do x11 != x12 -> perp_intersect?(seg2, seg1) true -> horiz = (x21 - x11) * (x22 - x11) vert = (y11 - y21) * (y12 - y21) !(horiz >= 0 || vert >= 0) end end @doc """ Determine if two segments share an endpoint ## Examples iex> PolyPartition.Geometry.share_endpoint?([[1,0], [0,0]], [[1,0], [1,1]]) true iex> PolyPartition.Geometry.share_endpoint?([[1,0], [0,0]], [[5,0], [1,1]]) false """ def share_endpoint?(seg1, seg2) do [p11, p12] = seg1 [p21, p22] = seg2 p11 == p21 || p11 == p22 || p12 == p21 || p12 == p22 end defp one_side_intersect?(seg1, seg2) do cond do share_endpoint?(seg1, seg2) -> false true -> [p11, p12] = seg1 [p21, p22] = seg2 m = slope(p21, p22) k1 = point_score(p11, p21, m) k2 = point_score(p12, p22, m) Helpers.sgn_to_bool(k1, k2) end end @doc """ Determine if two segments non-trivially (i.e., excluding endpoints) intersect ## Examples iex> PolyPartition.Geometry.intersect?([[0,0], [1,1]], [[0,1],[1,0]]) true iex> PolyPartition.Geometry.intersect?([[0,1], [1,1]], [[0,1],[1,0]]) false iex> PolyPartition.Geometry.intersect?([[0,1], [1,1]], [[0,0],[1,0]]) false """ def intersect?(seg1, seg2) do one_side_intersect?(seg1, seg2) && one_side_intersect?(seg2, seg1) end @doc """ Determine if a segment intersects a side of the polygon. Determine if a segment non-trivially (i.e., excluding endpoints) intersects a side of the given polygon _excepting the sides incident to the first vertex_. ## Examples iex> poly = [[0,1], [1,1], [1,0], [0,0]] iex> PolyPartition.Geometry.intersect_side?(poly, [[0.5,0.5], [1.5,0.5]]) true iex> poly = [[0,1], [1,1], [1,0], [0,0]] iex> PolyPartition.Geometry.intersect_side?(poly, [[1.5,1.5], [5.5,1.5]]) false """ def intersect_side?(poly, seg) do poly |> get_segments |> Enum.slice(1..length(poly) - 1) |> Enum.map(fn(x) -> intersect?(seg, x) end) |> List.foldl(false, fn(x, acc) -> x || acc end) end @doc """ Determine if a segment is a valid partition boundary in the polygon Given `opp_index`, determine if the segment from the first vertex to the vertex at `opp_index` forms a valid partition boundary. iex> poly = [[0,1], [1, 0], [2, 0], [3,1], [2,2], [2,0.5]] iex> PolyPartition.Geometry.good_cut?(poly, 2) true iex> poly = [[0,1], [1, 0], [2, 0], [3,1], [2,2], [2,0.5]] iex> PolyPartition.Geometry.good_cut?(poly, 3) false """ def good_cut?(poly, opp_index) do new1 = [hd(poly), Enum.at(poly, opp_index)] ++ Enum.slice(poly, (opp_index + 1)..length(poly)) new2 = Enum.slice(poly, 0..opp_index - 1) ++ [Enum.at(poly, opp_index)] cond do opp_index == 1 || opp_index == length(poly) - 1 -> false intersect_side?(poly, [hd(poly), Enum.at(poly, opp_index)]) -> false area(new1) > area(poly) || area(new2) > area(poly) -> false true -> true end end end
lib/Geometry.ex
0.928141
0.830181
Geometry.ex
starcoder
defmodule GiftCardDemo.GiftCard do @moduledoc """ A gift card is a prepaid stored-value money card, usually issued by a retailer or bank, to be used as an alternative to cash for purchases within a particular store or related businesses. A card is issued with an amount and can be redeemed many times until the amount is zero, and it is empty. """ alias GiftCardDemo.GiftCard alias GiftCardDemo.GiftCard.Commands.{IssueGiftCard, RedeemGiftCard} alias GiftCardDemo.GiftCard.Events.{GiftCardEmptied, GiftCardIssued, GiftCardRedeemed} defstruct [:id, :balance] def execute(%GiftCard{id: nil}, %IssueGiftCard{} = command) do %IssueGiftCard{id: id, amount: amount} = command if is_number(amount) and amount > 0 do %GiftCardIssued{id: id, amount: amount, balance: amount} else {:erorr, {:invalid_amount, amount}} end end def execute(%GiftCard{}, %IssueGiftCard{}), do: {:error, :gift_card_exists} def execute(%GiftCard{id: nil}, %RedeemGiftCard{}), do: {:error, :invalid_gift_card} def execute(%GiftCard{} = gift_card, %RedeemGiftCard{} = command) do %GiftCard{balance: balance} = gift_card %RedeemGiftCard{id: id, amount: amount} = command if is_number(amount) and amount > 0 do balance = balance - amount cond do balance < 0 -> {:error, :insufficient_balance} balance > 0 -> %GiftCardRedeemed{id: id, amount: amount, balance: balance} balance == 0 -> [ %GiftCardRedeemed{id: id, amount: amount, balance: 0}, %GiftCardEmptied{id: id} ] end else {:erorr, {:invalid_amount, amount}} end end def apply(%GiftCard{}, %GiftCardIssued{} = event) do %GiftCardIssued{id: id, balance: balance} = event %GiftCard{id: id, balance: balance} end def apply(%GiftCard{} = gift_card, %GiftCardRedeemed{} = event) do %GiftCardRedeemed{balance: balance} = event %GiftCard{gift_card | balance: balance} end def apply(%GiftCard{} = gift_card, %GiftCardEmptied{}), do: gift_card end
lib/gift_card_demo/gift_card/gift_card.ex
0.67971
0.465266
gift_card.ex
starcoder
defmodule FloUI.SelectionListItem do @moduledoc """ ## Usage in SnapFramework A selection list item used by SelectionList. data is a tuple in the form of ``` elixir {label, value, id} ``` ``` elixir <%= graph font_size: 20 %> <%= component FloUI.SelectionListItem, {@label, @value, @key} %> ``` """ @default_theme FloUI.Theme.preset(:primary) use SnapFramework.Component, name: :selection_list_item, template: "lib/selection_list/selection_list_item.eex", controller: FloUI.SelectionListItemController, assigns: [ hovered: false, width: 500, height: 50 ], opts: [] defcomponent(:selection_list_item, :tuple) watch([:hovered]) use_effect([assigns: [selected: :any]], run: [:on_selected_change] ) @impl true def setup(%{assigns: %{data: {label, value, key}, hovered: hovered, opts: opts}} = scene) do # request_input(scene, [:cursor_pos]) assign(scene, label: label, value: value, key: key, width: opts[:width] || 500, selected: opts[:selected] || false, hovered: hovered, theme: get_theme(opts) ) end @impl true def bounds(_data, opts) do {0.0, 0.0, opts[:width] || 500, 50} end @impl true def process_input({:cursor_pos, _}, :box, scene) do capture_input(scene, :cursor_pos) {:noreply, assign(scene, hovered: true)} end def process_input({:cursor_pos, _}, _, scene) do release_input(scene, :cursor_pos) {:noreply, assign(scene, hovered: false)} end def process_input( {:cursor_button, {:btn_left, 1, _, _}}, :box, %{assigns: %{key: key, label: label, value: value, selected: false}} = scene ) do send_parent_event(scene, {:select, {label, value, key}}) {:noreply, assign(scene, selected: true)} end def process_input( {:cursor_button, {:btn_left, 1, _, _}}, :box, %{assigns: %{selected: true}} = scene ) do send_parent_event(scene, :deselect) {:noreply, assign(scene, selected: false)} end def process_input(_, _, scene) do {:noreply, scene} end @impl true def process_call(:deselect, _, scene) do {:reply, :ok, assign(scene, selected: false)} end defp get_theme(opts) do case opts[:theme] do nil -> @default_theme :dark -> @default_theme :light -> @default_theme theme -> theme end |> FloUI.Theme.normalize() end end
lib/selection_list/selection_list_item.ex
0.757884
0.627438
selection_list_item.ex
starcoder
defmodule Edeliver.Relup.Instructions.Sleep do @moduledoc """ This upgrade instruction is intended for testing only and just sleeps the given amount of seconds. This can be used to test instructions which suspend processes at the beginning of the upgrade before the new code is installed. Usage: ``` Edeliver.Relup.Instructions.Sleep.modify_relup(config, _seconds = 30) ``` It prints a countown in the upgrade script which was started by the `$APP/bin/$APP upgarde $RELEASE` command. """ use Edeliver.Relup.RunnableInstruction @spec modify_relup(instructions::Instructions.t, config::Edeliver.Relup.Config.t, seconds::integer) :: Instructions.t def modify_relup(instructions = %Instructions{}, _config = %{}, seconds \\ 30) do call_this_instruction = call_this(max(0, seconds)) insert_where_fun = insert_where() instructions |> insert_where_fun.(call_this_instruction) |> ensure_module_loaded_before_instruction(call_this_instruction, __MODULE__) end @doc """ Appends this instruction to the instructions after the "point of no return" but before any instruction which loads or unloads new code, (re-)starts or stops any running processes, or (re-)starts or stops any application or the emulator. """ def insert_where, do: &append_after_point_of_no_return/2 @doc """ Waits the given amount of seconds and prints a countdown in the upgrade script which was started by the `$APP/bin/$APP upgarde $RELEASE` command. """ @spec run(seconds::integer) :: :ok def run(seconds) do Logger.info "Waiting #{inspect seconds} seconds..." wait(seconds, seconds) Logger.info "Waited #{inspect seconds} seconds." end defp wait(_remaining_seconds = 0, seconds) do format_in_upgrade_script '\r---> Waited ~b seconds. ~n', [seconds] end defp wait(remaining_seconds, seconds) do format_in_upgrade_script '\r---> Waiting ~b seconds... ', [remaining_seconds] receive do after 1000 -> wait(remaining_seconds - 1, seconds) end end end
lib/edeliver/relup/instructions/sleep.ex
0.666605
0.756132
sleep.ex
starcoder
defmodule Stripe.Plans do @moduledoc """ Basic List, Create, Delete API for Plans """ @endpoint "plans" @doc """ Creates a Plan. Note that `currency` and `interval` are required parameters, and are defaulted to "USD" and "month" ## Example ``` {:ok, plan} = Stripe.Plans.create [id: "test-plan", name: "Test Plan", amount: 1000, interval: "month"] ``` """ def create(params) do create params, Stripe.config_or_env_key end @doc """ Creates a Plan using a given key. Note that `currency` and `interval` are required parameters, and are defaulted to "USD" and "month" ## Example ``` {:ok, plan} = Stripe.Plans.create [id: "test-plan", name: "Test Plan", amount: 1000, interval: "month"], key ``` """ def create(params, key) do #default the currency and interval params = Keyword.put_new params, :currency, "USD" params = Keyword.put_new params, :interval, "month" Stripe.make_request_with_key(:post, @endpoint, key, params) |> Stripe.Util.handle_stripe_response end @doc """ Returns a list of Plans. """ def list(limit \\ 10) do list Stripe.config_or_env_key, limit end @doc """ Returns a list of Plans using the given key. """ def list(key, limit) do Stripe.make_request_with_key(:get, "#{@endpoint}?limit=#{limit}", key) |> Stripe.Util.handle_stripe_response end @doc """ Deletes a Plan with the specified ID. ## Example ``` {:ok, res} = Stripe.Plans.delete "test-plan" ``` """ def delete(id) do delete id, Stripe.config_or_env_key end @doc """ Deletes a Plan with the specified ID using the given key. ## Example ``` {:ok, res} = Stripe.Plans.delete "test-plan", key ``` """ def delete(id, key) do Stripe.make_request_with_key(:delete, "#{@endpoint}/#{id}", key) |> Stripe.Util.handle_stripe_response end @doc """ Changes Plan information. See Stripe docs as to what you can change. ## Example ``` {:ok, plan} = Stripe.Plans.change("test-plan",[name: "Other Plan"]) ``` """ def change(id, params) do change(id, params, Stripe.config_or_env_key) end def change(id, params, key) do Stripe.make_request_with_key(:post, "#{@endpoint}/#{id}", key, params) |> Stripe.Util.handle_stripe_response end def count do count Stripe.config_or_env_key end def count(key) do Stripe.Util.count "#{@endpoint}", key end @max_fetch_size 100 @doc """ List all plans. ##Example ``` {:ok, plans} = Stripe.Plans.all ``` """ def all( accum \\ [], startingAfter \\ "") do all Stripe.config_or_env_key, accum, startingAfter end @max_fetch_size 100 @doc """ List all plans w/ given key. ##Example ``` {:ok, plans} = Stripe.Plans.all key ``` """ def all( key, accum, startingAfter) do case Stripe.Util.list_raw("#{@endpoint}",key, @max_fetch_size, startingAfter) do {:ok, resp} -> case resp[:has_more] do true -> last_sub = List.last( resp[:data] ) all( key, resp[:data] ++ accum, last_sub["id"] ) false -> result = resp[:data] ++ accum {:ok, result} end end end @doc """ Deletes all Plans ## Example ``` Stripe.Plans.delete_all ``` """ def delete_all do delete_all Stripe.config_or_env_key end @doc """ Deletes all Plans w/given key ## Example ``` Stripe.Plans.delete_all key ``` """ def delete_all key do case all() do {:ok, plans} -> Enum.each plans, fn p -> delete(p["id"], key) end {:error, err} -> raise err end {:ok} end end
lib/stripe/plans.ex
0.876416
0.913638
plans.ex
starcoder
defmodule LifeGame.World do @moduledoc """ The Game of Life implemented in funcional style in Elixir. https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life """ @author "<NAME>" defstruct [:grid, :width, :height] @width 300 @height 300 @cell_size 5 @cell_color {0, 100, 0} @bg_color {255, 255, 255} @interval 10 # Milliseconds. @init_density 0.1 # From 0 to 1. alias LifeGame.World alias LifeGame.Screen # The following macros are defined to improve the code performace. defmacro cell(world, {x, y}) do quote do elem(unquote(world).grid, unquote(y) * unquote(world).width + unquote(x)) end end defmacro cell(grid, width, {x, y}) do quote do elem(unquote(grid), unquote(y) * unquote(width) + unquote(x)) end end defmacro is_alive(cell), do: quote do: unquote(cell) defmacro is_alive(world, {x, y}) do quote do: is_alive(cell(unquote(world), {unquote(x), unquote(y)})) end def start_link(name) do {:ok, pid} = Task.start_link(&start/0) Process.register pid, name {:ok, pid} end def start do screen = Screen.init("Game of Life", @width * @cell_size, @height * @cell_size) world = create_random(@width, @height, @init_density) run world, screen end def run(world, screen) do Screen.update screen, @bg_color, &(render &1, world, @cell_size, @cell_color) Process.sleep @interval world |> next_step |> run(screen) end def create_random(width, height, init_density) do %World{ width: width, height: height, grid: random_grid(width, height, init_density) } end def random_grid(width, height, init_density) do coords = grid_coords(width, height) coords |> random_cells(init_density) |> to_grid end def random_cells(coords, init_density) do Enum.map coords, fn(coord) -> random_cell(coord, init_density) end end def random_cell(_coord, probability) do :rand.uniform() <= probability end @doc """ Returns the world at the next step. """ def next_step(world) do %{world | grid: next_grid_state(world)} end def next_grid_state(world) do to_grid( for {x, y} <- grid_coords(world) do next_cell_state cell(world, {x, y}), neighbours(world, {x, y}) end ) end @doc """ Get the cell state for the next step of the world time. """ def next_cell_state(cell, neighbours) do # Enum.count is not used for speed optimisation. alive_count = Enum.reduce(neighbours, 0, fn(cell, count) -> if is_alive(cell), do: count + 1, else: count end) # Choice next value. if is_alive(cell) do alive_count >= 2 and alive_count <= 3 else alive_count == 3 end end @doc """ Returns grid internal representation. The grid is represented as tuple. """ def to_grid(list) when is_list(list) do # Grid is represented as one-dimensional tuple. List.to_tuple list end @doc """ More efficient version of Enum.count. http://stackoverflow.com/questions/41175829/why-enum-map-is-more-efficient-than-enum-count-in-elixir/41177073#41177073 https://github.com/elixir-lang/elixir/commit/9d39ebca079350ead3cec55d002937bbb836980a TODO: replace with Enum.count when new Elixir version released (current v1.3.4) """ def count(enumerable, fun) when is_function(fun, 1) do Enum.reduce enumerable, 0, fn(entry, acc) -> if fun.(entry), do: acc + 1, else: acc end end def grid_coords(world), do: grid_coords(world.width, world.height) def grid_coords(width, height) do Stream.unfold {0, 0}, fn # End of grid. {0, ^height} -> nil; # End of line. {x, y} when x == width - 1 -> {{x, y}, {0, y + 1}}; # Limits are not reached. {x, y} -> {{x, y}, {x + 1, y}}; end end @doc """ Get the neighbour cells. This function is optimized for speed. """ def neighbours(%{grid: grid, width: width, height: height}, {x, y}) do x1 = if x == 0, do: width - 1, else: x - 1 y1 = if y == 0, do: height - 1, else: y - 1 y3 = if y == height - 1, do: 0, else: y + 1 x3 = if x == width - 1, do: 0, else: x + 1 x2 = x y2 = y [cell(grid, width, {x1, y1}), cell(grid, width, {x1, y2}), cell(grid, width, {x1, y3}), cell(grid, width, {x2, y1}), cell(grid, width, {x2, y3}), cell(grid, width, {x3, y1}), cell(grid, width, {x3, y2}), cell(grid, width, {x3, y3})] end def render(context, world, cell_size, cell_color) do for {x, y} <- grid_coords(world), is_alive(world, {x, y}) do Screen.draw_rectangle( context, cell_color, {x * cell_size, y * cell_size}, {cell_size, cell_size}) end end end
elixir/lib/life_game/world.ex
0.620737
0.766905
world.ex
starcoder
defmodule Epicenter.Test.RevisionAssertions do import ExUnit.Assertions def assert_audit_logged(%{id: model_id}) do if Epicenter.AuditingRepo.entries_for(model_id) == [], do: flunk("Expected schema to have an audit log entry, but found none.") end def assert_revision_count(%{id: model_id}, count) do entries = Epicenter.AuditingRepo.entries_for(model_id) if length(entries) != count, do: flunk("Expected #{count} revisions but found #{length(entries)}") end def assert_recent_audit_log(model, author, action: action, event: event) do entry = recent_audit_log(model) assert entry != nil assert entry.author_id == author.id assert entry.reason_action == action assert entry.reason_event == event end def assert_recent_audit_log(model, author, change) do entry = recent_audit_log(model) if entry == nil, do: flunk("Expected schema to have an audit log entry, but found none.") if entry.author_id != author.id, do: flunk("Expected revision to have author #{author.tid} but it did not") change = Euclid.Extra.Map.stringify_keys(change) assert ^change = Map.take(entry.change |> remove_ids(), Map.keys(change)) end def assert_semi_recent_audit_log(model, author, action, event, change) do entry = audit_log_that_matches(model, action, event) assert entry.author_id == author.id for {key, expected_value} <- change do assert ^expected_value = entry.change[key] end end def assert_recent_audit_log_snapshots(model, author, expected_before, expected_after) do entry = recent_audit_log(model) if entry == nil, do: flunk("Expected schema to have an audit log entry, but found none.") if entry.author_id != author.id, do: flunk("Expected revision to have author #{author.tid} but it did not") assert ^expected_before = Map.take(entry.before_change |> remove_ids(), Map.keys(expected_before)) assert ^expected_after = Map.take(entry.after_change |> remove_ids(), Map.keys(expected_after)) end def recent_audit_log(%{id: model_id}) do Epicenter.AuditingRepo.entries_for(model_id) |> List.last() end def audit_log_that_matches(model, action, event) do Epicenter.AuditingRepo.entries_for(model.id) |> Enum.find(&(&1.reason_action == action && &1.reason_event == event)) end defp remove_ids(map) when is_map(map) do map |> Map.drop(["id"]) |> Enum.map(fn {k, v} -> {k, remove_ids(v)} end) |> Enum.into(%{}) end defp remove_ids(list) when is_list(list), do: Enum.map(list, &remove_ids/1) defp remove_ids(other), do: other end
test/support/revision_assertions.ex
0.614741
0.512815
revision_assertions.ex
starcoder
defmodule Granulix.Math do @compile {:autoload, false} @on_load :load_nifs @pi :math.pi() @doc "A useful number" @spec pi() :: float() def pi(), do: @pi @twopi @pi * 2 @doc "A useful number times two" @spec twopi() :: float() def twopi(), do: @twopi @pi2 @pi * 0.5 @doc "A useful number times 0.5" @spec pi2() :: float() def pi2(), do: @pi2 @rtwopi 1.0 / @twopi @doc "1 / twopi()" @spec rtwopi() :: float() def rtwopi(), do: @rtwopi @doc """ Multiply binary arrays of 32 bit floats with a scalar value or binary array """ @spec mul(binary() | [binary()], binary() | float()) :: binary() def mul(l, y) when is_list(l), do: Enum.map(l, fn x -> mul(x, y) end) def mul(x, y) when is_binary(y), do: crossnif(x, y) def mul(x, y), do: mulnif(x, y) @doc "Add binary arrays of 32 bit floats with binary array" @spec add(binary() | [binary()], binary() | float()) :: binary() def add(l, y) when is_list(l), do: Enum.map(l, fn x -> add(x, y) end) def add(x, y) when is_binary(x), do: addnif(x, y) @doc "Subtract binary arrays of 32 bit floats with binary array" @spec subtract(binary() | [binary()], binary() | float()) :: binary() def subtract(l, y) when is_list(l), do: Enum.map(l, fn x -> subtract(x, y) end) def subtract(x, y) when is_binary(x), do: subtractnif(x, y) # ----------------------------------------------------------- def load_nifs do case :erlang.load_nif(:code.priv_dir(:granulix) ++ '/granulix_math', 0) do :ok -> :ok {:error, {:reload, _}} -> :ok {:error, reason} -> :logger.warning('Failed to load granulix_math nif: ~p', [reason]) end end @spec mulnif(binary(), binary() | float()) :: binary() defp mulnif(_x, _y) do raise "NIF mul/2 not loaded" end # @doc "Multiply 2 binary arrays of 32 bit floats" @spec crossnif(binary(), binary()) :: binary() defp crossnif(_x, _y) do raise "NIF cross/2 not loaded" end @spec addnif(binary(), binary()) :: binary() defp addnif(_x, _y) do raise "NIF add/2 not loaded" end @spec subtractnif(binary(), binary()) :: binary() defp subtractnif(_x, _y) do raise "NIF subtract/2 not loaded" end @doc "Convert a list of (Erlang) floats to a binary of 32 bit (C) floats" @spec float_list_to_binary([float()]) :: binary() def float_list_to_binary(_fl) do raise "NIF float_list_to_binary/1 not loaded" end @doc "Convert a binary of 32 bit (C) floats to a list of (Erlang) floats" @spec binary_to_float_list(binary) :: [float()] def binary_to_float_list(_bin) do raise "NIF binary_to_float_list/1 not loaded" end # ----------------------------------------------------------- end
lib/granulix/math.ex
0.824709
0.478529
math.ex
starcoder
defmodule Plymio.Funcio.Enum.Map.Gather do @moduledoc ~S""" Map and Gather Patterns for Enumerables. These functions map the elements of an *enum* and gather the results according to one of the defined *patterns*. Gathering means collecting all the `:ok` and `:error` results into a *opts* with keys `:ok` and `:error`. The value of each key will be a list of 2tuples where the first element is the *enum* element and the second is either the `value` from {`:ok, value}` or `error` from `{:error, error}`. If there are no `:ok` or `:error` results, the key will not be present in the final *opts*. See `Plymio.Funcio` for overview and documentation terms. """ use Plymio.Funcio.Attribute @type error :: Plymio.Funcio.error() @type stream :: Plymio.Funcio.stream() @type opts :: Plymio.Funcio.opts() import Plymio.Funcio.Error, only: [ new_error_result: 1 ] import Plymio.Fontais.Result, only: [ normalise0_result: 1 ], warn: false import Plymio.Funcio.Map.Utility, only: [ reduce_map1_funs: 1 ] @doc ~S""" `map_gather0_enum/2` take an *enum* and *map/1* and applies the *map/1* to each element of the *enum* and then gathers the results according to *pattern 0*. ## Examples iex> fun = fn v -> {:ok, v * v} end ...> [1,2,3] |> map_gather0_enum(fun) {:ok, [ok: [{1,1},{2,4},{3,9}]]} iex> fun = fn ...> 3 -> {:error, %ArgumentError{message: "argument is 3"}} ...> v -> {:ok, v + 42} ...> end ...> [1,2,3] |> map_gather0_enum(fun) {:ok, [ok: [{1,43},{2,44}], error: [{3, %ArgumentError{message: "argument is 3"}}]]} iex> fun = :not_a_fun ...> {:error, error} = [1,2,3] |> map_gather0_enum(fun) ...> error |> Exception.message "map/1 function invalid, got: :not_a_fun" iex> fun = fn v -> {:ok, v} end ...> {:error, error} = 42 |> map_gather0_enum(fun) ...> error |> Exception.message ...> |> String.starts_with?("protocol Enumerable not implemented for 42") true """ @since "0.1.0" @spec map_gather0_enum(any, any) :: {:ok, opts} | {:error, error} def map_gather0_enum(enum, fun) do with {:ok, fun} <- [fun, &normalise0_result/1] |> reduce_map1_funs do try do enum |> Enum.reduce_while( {[], []}, fn element, {oks, errors} -> element |> fun.() |> case do {:error, %{__struct__: _} = error} -> {:cont, {oks, [{element, error} | errors]}} {:ok, value} -> {:cont, {[{element, value} | oks], errors}} value -> with {:error, error} <- new_error_result(m: "pattern0 result invalid", v: value) do {:cont, {oks, [{element, error} | errors]}} else {:error, %{__struct__: _}} = result -> {:halt, result} end end end ) |> case do {:error, %{__exception__: true}} = result -> result {oks, []} -> {:ok, [ok: oks |> Enum.reverse()]} {[], errors} -> {:ok, [error: errors |> Enum.reverse()]} {oks, errors} -> {:ok, [ok: oks |> Enum.reverse(), error: errors |> Enum.reverse()]} end rescue error -> {:error, error} end else {:error, %{__exception__: true}} = result -> result end end end
lib/funcio/enum/map/gather.ex
0.804943
0.684185
gather.ex
starcoder
defmodule Membrane.Core.Child.PadModel do @moduledoc false # Utility functions for veryfying and manipulating pads and their data. use Bunch alias Bunch.Type alias Membrane.Core.Child alias Membrane.Pad @type pads_data_t :: %{Pad.ref_t() => Pad.Data.t()} @type pad_info_t :: %{ required(:accepted_caps) => any, required(:availability) => Pad.availability_t(), required(:direction) => Pad.direction_t(), required(:mode) => Pad.mode_t(), required(:name) => Pad.name_t(), optional(:demand_unit) => Membrane.Buffer.Metric.unit_t(), optional(:other_demand_unit) => Membrane.Buffer.Metric.unit_t() } @type pads_info_t :: %{Pad.name_t() => pad_info_t} @type pads_t :: %{ data: pads_data_t, info: pads_info_t, dynamic_currently_linking: [Pad.ref_t()] } @type unknown_pad_error_t :: {:error, {:unknown_pad, Pad.name_t()}} @spec assert_instance(Child.state_t(), Pad.ref_t()) :: :ok | unknown_pad_error_t def assert_instance(state, pad_ref) do if state.pads.data |> Map.has_key?(pad_ref) do :ok else {:error, {:unknown_pad, pad_ref}} end end @spec assert_instance!(Child.state_t(), Pad.ref_t()) :: :ok def assert_instance!(state, pad_ref) do :ok = assert_instance(state, pad_ref) end defmacro assert_data(state, pad_ref, pattern) do quote do with {:ok, data} <- unquote(__MODULE__).get_data(unquote(state), unquote(pad_ref)) do if match?(unquote(pattern), data) do :ok else {:error, {:invalid_pad_data, ref: unquote(pad_ref), pattern: unquote(pattern), data: data}} end end end end defmacro assert_data!(state, pad_ref, pattern) do quote do :ok = unquote(__MODULE__).assert_data(unquote(state), unquote(pad_ref), unquote(pattern)) end end @spec filter_refs_by_data(Child.state_t(), constraints :: map) :: [Pad.ref_t()] def filter_refs_by_data(state, constraints \\ %{}) def filter_refs_by_data(state, constraints) when constraints == %{} do state.pads.data |> Map.keys() end def filter_refs_by_data(state, constraints) do state.pads.data |> Enum.filter(fn {_name, data} -> data |> constraints_met?(constraints) end) |> Keyword.keys() end @spec filter_data(Child.state_t(), constraints :: map) :: %{atom => Pad.Data.t()} def filter_data(state, constraints \\ %{}) def filter_data(state, constraints) when constraints == %{} do state.pads.data end def filter_data(state, constraints) do state.pads.data |> Enum.filter(fn {_name, data} -> data |> constraints_met?(constraints) end) |> Map.new() end @spec get_data(Child.state_t(), Pad.ref_t(), keys :: atom | [atom]) :: {:ok, Pad.Data.t() | any} | unknown_pad_error_t def get_data(state, pad_ref, keys \\ []) do with :ok <- assert_instance(state, pad_ref) do state |> Bunch.Access.get_in(data_keys(pad_ref, keys)) ~> {:ok, &1} end end @spec get_data!(Child.state_t(), Pad.ref_t(), keys :: atom | [atom]) :: Pad.Data.t() | any def get_data!(state, pad_ref, keys \\ []) do {:ok, pad_data} = get_data(state, pad_ref, keys) pad_data end @spec set_data(Child.state_t(), Pad.ref_t(), keys :: atom | [atom], value :: term()) :: Type.stateful_t(:ok | unknown_pad_error_t, Child.state_t()) def set_data(state, pad_ref, keys \\ [], value) do with {:ok, state} <- {assert_instance(state, pad_ref), state} do state |> Bunch.Access.put_in(data_keys(pad_ref, keys), value) ~> {:ok, &1} end end @spec set_data!(Child.state_t(), Pad.ref_t(), keys :: atom | [atom], value :: term()) :: Child.state_t() def set_data!(state, pad_ref, keys \\ [], value) do {:ok, state} = set_data(state, pad_ref, keys, value) state end @spec update_data( Child.state_t(), Pad.ref_t(), keys :: atom | [atom], (data -> {:ok | error, data}) ) :: Type.stateful_t(:ok | error | unknown_pad_error_t, Child.state_t()) when data: Pad.Data.t() | any, error: {:error, reason :: any} def update_data(state, pad_ref, keys \\ [], f) do with {:ok, state} <- {assert_instance(state, pad_ref), state}, {:ok, state} <- state |> Bunch.Access.get_and_update_in(data_keys(pad_ref, keys), f) do {:ok, state} else {{:error, reason}, state} -> {{:error, reason}, state} end end @spec update_data!(Child.state_t(), Pad.ref_t(), keys :: atom | [atom], (data -> data)) :: Child.state_t() when data: Pad.Data.t() | any def update_data!(state, pad_ref, keys \\ [], f) do :ok = assert_instance(state, pad_ref) state |> Bunch.Access.update_in(data_keys(pad_ref, keys), f) end @spec get_and_update_data( Child.state_t(), Pad.ref_t(), keys :: atom | [atom], (data -> {success | error, data}) ) :: Type.stateful_t(success | error | unknown_pad_error_t, Child.state_t()) when data: Pad.Data.t() | any, success: {:ok, data}, error: {:error, reason :: any} def get_and_update_data(state, pad_ref, keys \\ [], f) do with {:ok, state} <- {assert_instance(state, pad_ref), state}, {{:ok, out}, state} <- state |> Bunch.Access.get_and_update_in(data_keys(pad_ref, keys), f) do {{:ok, out}, state} else {{:error, reason}, state} -> {{:error, reason}, state} end end @spec get_and_update_data!( Child.state_t(), Pad.ref_t(), keys :: atom | [atom], (data -> {data, data}) ) :: Type.stateful_t(data, Child.state_t()) when data: Pad.Data.t() | any def get_and_update_data!(state, pad_ref, keys \\ [], f) do :ok = assert_instance(state, pad_ref) state |> Bunch.Access.get_and_update_in(data_keys(pad_ref, keys), f) end @spec pop_data(Child.state_t(), Pad.ref_t()) :: Type.stateful_t({:ok, Pad.Data.t()} | unknown_pad_error_t, Child.state_t()) def pop_data(state, pad_ref) do with {:ok, state} <- {assert_instance(state, pad_ref), state} do {data, state} = state |> Bunch.Access.pop_in(data_keys(pad_ref)) {{:ok, data}, state} end end @spec pop_data!(Child.state_t(), Pad.ref_t()) :: Type.stateful_t(Pad.Data.t(), Child.state_t()) def pop_data!(state, pad_ref) do {{:ok, pad_data}, state} = pop_data(state, pad_ref) {pad_data, state} end @spec delete_data(Child.state_t(), Pad.ref_t()) :: Type.stateful_t(:ok | unknown_pad_error_t, Child.state_t()) def delete_data(state, pad_ref) do with {{:ok, _out}, state} <- pop_data(state, pad_ref) do {:ok, state} end end @spec delete_data!(Child.state_t(), Pad.ref_t()) :: Child.state_t() def delete_data!(state, pad_ref) do {:ok, state} = delete_data(state, pad_ref) state end @spec constraints_met?(Pad.Data.t(), map) :: boolean defp constraints_met?(data, constraints) do constraints |> Enum.all?(fn {k, v} -> data[k] === v end) end @spec data_keys(Pad.ref_t(), keys :: atom | [atom]) :: [atom] defp data_keys(pad_ref, keys \\ []) do [:pads, :data, pad_ref | Bunch.listify(keys)] end end
lib/membrane/core/child/pad_model.ex
0.89458
0.655019
pad_model.ex
starcoder
defmodule Resourceful.Type.Relationship do @moduledoc """ Relationships come in one of two types: `:one` or `:many`. Things like foreign keys and how the relationships map are up to the underlying data source. For the purposes of mapping things in `Resourceful`, it simply needs to understand whether it's working with a single thing or multiple things. A natural opinion of relationships is that graphing is simply not allowed on `:many` relationships. What this means is that you can only do graphed filters and sorts against `:one` relationships. For example, a song can sort and filter on an album and its artist because a song has one album which has one artist. The reverse is not possible because an artist has many albums which have many songs. Sorting and filtering on relationships makes sense when data can be represented as a table. In situations where it's a tree, multiple queries are necessary and the client is responsible for putting the data together. It makes sense to filter and sort a song by an album or artist's attribute. It does not make sense to sort an artist by a song's attribute. """ # TODO: Indicate if must be present for some query optimization? To # distinguish if inner or left join. alias __MODULE__ alias Resourceful.Type @type type() :: :many | :one @enforce_keys [ :map_to, :name, :graph?, :related_type, :type ] defstruct @enforce_keys @doc """ Creates a new relationship, coerces values, and sets defaults. """ @spec new(type(), String.t() | atom(), keyword()) :: %Relationship{} def new(type, name, opts \\ []) do map_to = Keyword.get(opts, :map_to) || String.to_existing_atom(name) type = check_type!(type) related_type = Keyword.get(opts, :related_type, name) graph = type == :one && Keyword.get(opts, :graph?, true) %Relationship{ graph?: graph, name: Type.validate_name!(name), map_to: Type.validate_map_to!(map_to), related_type: related_type, type: type } end @doc """ Sets the name for the relationship. This is the "edge" name that clients will interact with. It can be any string as long as it doesn't contain dots. This will also serve as its key name if used in conjunction with a `Resourceful.Type` which is important in that names must be unique within a type. """ @spec name(%Relationship{}, String.t() | atom()) :: %Relationship{} def name(%Relationship{} = rel, name) do Map.put(rel, :name, Type.validate_name!(name)) end defp check_type!(type) when type in [:many, :one], do: type end
lib/resourceful/type/relationship.ex
0.682997
0.734572
relationship.ex
starcoder
defmodule Rock.ClusterMergeCriterion do alias Rock.Struct.Point alias Rock.Struct.Cluster @moduledoc false def measure(%Cluster{size: size1}, %Cluster{size: size2}, theta, cross_link_count) do power = 1 + 2 * f_theta(theta) summand1 = :math.pow(size1 + size2, power) summand2 = :math.pow(size1, power) summand3 = :math.pow(size2, power) measure = cross_link_count / (summand1 - summand2 - summand3) measure end def measure( link_matrix, %Cluster{} = cluster1, %Cluster{} = cluster2, theta ) do cross_link_count = count_cross_links(link_matrix, cluster1, cluster2) measure = measure(cluster1, cluster2, theta, cross_link_count) {measure, cross_link_count} end def count_cross_links( link_matrix, %Cluster{points: points1}, %Cluster{points: points2} ) do count_cross_links(link_matrix, points1, points2, 0) end defp count_cross_links( link_matrix, [point1 | []], second_cluster_points, count ) do count_cross_links(link_matrix, point1, second_cluster_points, count) end defp count_cross_links( link_matrix, [point1 | tail], second_cluster_points, count ) do new_count = count + count_cross_links(link_matrix, point1, second_cluster_points, count) count_cross_links(link_matrix, tail, second_cluster_points, new_count) end defp count_cross_links( link_matrix, %Point{index: index1}, [%Point{index: index2} | []], count ) do count + number_of_links(link_matrix, index1, index2) end defp count_cross_links( link_matrix, %Point{index: index1} = point1, [%Point{index: index2} | tail], count ) do new_count = count + number_of_links(link_matrix, index1, index2) count_cross_links(link_matrix, point1, tail, new_count) end defp number_of_links(link_matrix, index1, index2) do # because our link matrix is symmetric and we have zeros under main diagonal {index1, index2} = if index1 > index2, do: {index2, index1}, else: {index1, index2} link_matrix |> Enum.at(index1) |> Enum.at(index2) end defp f_theta(theta) do (1 - theta) / (1 + theta) end end
lib/rock/cluster_merge_criterion.ex
0.671901
0.601389
cluster_merge_criterion.ex
starcoder
defmodule Crux.Structs.Overwrite do @moduledoc """ Represents a Discord [Overwrite Object](https://discordapp.com/developers/docs/resources/channel#overwrite-object-overwrite-structure). """ @behaviour Crux.Structs alias Crux.Structs alias Crux.Structs.{Overwrite, Role, Snowflake, User, Util} require Util Util.modulesince("0.1.0") defstruct( id: nil, type: nil, allow: 0, deny: 0 ) Util.typesince("0.1.0") @type t :: %__MODULE__{ id: Snowflake.t(), type: String.t(), allow: integer(), deny: integer() } @typedoc """ All available types that can be resolved into a target for a permission overwrite """ Util.typesince("0.2.1") @type target_resolvable() :: Overwrite.t() | Role.t() | User.id_resolvable() @doc """ Resolves a `t:target_resolvable/0` into an overwrite target. > Note that an id or string of it returns `:unknown` as type. ## Examples ```elixir iex> %Crux.Structs.Overwrite{type: "member", id: 218348062828003328} ...> |> Crux.Structs.Overwrite.resolve_target() {"member", 218348062828003328} iex> %Crux.Structs.Role{id: 376146940762783746} ...> |> Crux.Structs.Overwrite.resolve_target() {"role", 376146940762783746} iex> %Crux.Structs.User{id: 218348062828003328} ...> |> Crux.Structs.Overwrite.resolve_target() {"member", 218348062828003328} iex> %Crux.Structs.Member{user: 218348062828003328} ...> |> Crux.Structs.Overwrite.resolve_target() {"member", 218348062828003328} iex> %Crux.Structs.Message{author: %Crux.Structs.User{id: 218348062828003328}} ...> |> Crux.Structs.Overwrite.resolve_target() {"member", 218348062828003328} iex> %Crux.Structs.VoiceState{user_id: 218348062828003328} ...> |> Crux.Structs.Overwrite.resolve_target() {"member", 218348062828003328} iex> 218348062828003328 ...> |> Crux.Structs.Overwrite.resolve_target() {:unknown, 218348062828003328} iex> "218348062828003328" ...> |> Crux.Structs.Overwrite.resolve_target() {:unknown, 218348062828003328} iex> nil ...> |> Crux.Structs.Overwrite.resolve_target() nil ``` """ @spec resolve_target(target_resolvable()) :: {String.t() | :unknown, Snowflake.t()} def resolve_target(%Overwrite{id: id, type: type}), do: {type, id} def resolve_target(%Role{id: id}), do: {"role", id} def resolve_target(resolvable) do case Structs.resolve_id(resolvable, User) do nil -> nil id when is_map(resolvable) -> {"member", id} id -> {:unknown, id} end end @doc """ Creates a `t:Crux.Structs.Overwrite.t/0` struct from raw data. > Automatically invoked by `Crux.Structs.create/2`. """ @spec create(data :: map()) :: t() Util.since("0.1.0") def create(data) do overwrite = data |> Util.atomify() |> Map.update!(:id, &Snowflake.to_snowflake/1) struct(__MODULE__, overwrite) end end
lib/structs/overwrite.ex
0.813313
0.561065
overwrite.ex
starcoder
defmodule Quarry do @moduledoc """ A data-driven ecto query builder for nested associations. Quarry allows you to interact with your database thinking only about your data, and generates queries for exactly what you need. You can specify all the filters, loads, and sorts with any level of granularity and at any association level, and Quarry will build a query for you that optimizes for joining just the data that is necessary and no more. To optimize has_many associations, subqueries are used for preloading the entity. This is generally more optimal than joining and selecting all the data because it avoids pulling n*m records into memory. """ require Ecto.Query alias Quarry.{From, Filter, Load, Sort} @type operation :: :lt | :gt | :lte | :gte | :starts_with | :ends_with @type filter_param :: String.t() | number @type tuple_filter_param :: {operation(), filter_param()} @type filter :: %{optional(atom()) => filter_param() | tuple_filter_param()} @type load :: atom() | [atom() | keyword(load())] @type sort :: atom() | [atom() | [atom()] | {:asc | :desc, atom() | [atom()]}] @type opts :: [ filter: filter(), load: load(), sort: sort(), limit: integer(), offset: integer() ] @type error :: %{type: :filter | :load, path: [atom()], message: String.t()} @doc """ Builds a query for an entity type from parameters ## Examples ```elixir # Top level attribute iex> Quarry.build!(Quarry.Post, filter: %{title: "Value"}) #Ecto.Query<from p0 in Quarry.Post, as: :post, where: as(:post).title == ^"Value"> # Field on nested belongs_to relationship iex> Quarry.build!(Quarry.Post, filter: %{author: %{publisher: "Publisher"}}) #Ecto.Query<from p0 in Quarry.Post, as: :post, join: a1 in assoc(p0, :author), as: :post_author, where: as(:post_author).publisher == ^"Publisher"> # Field on nested has_many relationship iex> Quarry.build!(Quarry.Post, filter: %{comments: %{body: "comment body"}}) #Ecto.Query<from p0 in Quarry.Post, as: :post, join: c1 in assoc(p0, :comments), as: :post_comments, where: as(:post_comments).body == ^"comment body"> # Can filter by explicit operation iex> Quarry.build!(Quarry.Post, filter: %{author: %{user: %{login_count: {:eq, 1}}}}) iex> Quarry.build!(Quarry.Post, filter: %{author: %{user: %{login_count: {:lt, 1}}}}) iex> Quarry.build!(Quarry.Post, filter: %{author: %{user: %{login_count: {:gt, 1}}}}) iex> Quarry.build!(Quarry.Post, filter: %{author: %{user: %{login_count: {:lte, 1}}}}) iex> Quarry.build!(Quarry.Post, filter: %{author: %{user: %{login_count: {:gte, 1}}}}) iex> Quarry.build!(Quarry.Post, filter: %{title: {:starts_with, "How to"}}) iex> Quarry.build!(Quarry.Post, filter: %{title: {:ends_with, "learn vim"}}) ``` ### Load examples ```elixir # Single atom iex> Quarry.build!(Quarry.Post, load: :author) #Ecto.Query<from p0 in Quarry.Post, as: :post, join: a1 in assoc(p0, :author), as: :post_author, preload: [author: a1]> # List of atoms iex> Quarry.build!(Quarry.Post, load: [:author, :comments]) #Ecto.Query<from p0 in Quarry.Post, as: :post, join: a1 in assoc(p0, :author), as: :post_author, preload: [comments: #Ecto.Query<from c0 in Quarry.Comment, as: :post_comment>], preload: [author: a1]> # Nested entities iex> Quarry.build!(Quarry.Post, load: [comments: :user]) #Ecto.Query<from p0 in Quarry.Post, as: :post, preload: [comments: #Ecto.Query<from c0 in Quarry.Comment, as: :post_comment, join: u1 in assoc(c0, :user), as: :post_comment_user, preload: [user: u1]>]> # List of nested entities iex> Quarry.build!(Quarry.Post, load: [author: [:user, :posts]]) #Ecto.Query<from p0 in Quarry.Post, as: :post, join: a1 in assoc(p0, :author), as: :post_author, join: u2 in assoc(a1, :user), as: :post_author_user, preload: [author: [posts: #Ecto.Query<from p0 in Quarry.Post, as: :post_author_post>]], preload: [author: {a1, [user: u2]}]> # Use Quarry on nested has_many association iex> Quarry.build!(Quarry.Post, load: [comments: [filter: %{body: "comment"}, load: :user]]) #Ecto.Query<from p0 in Quarry.Post, as: :post, preload: [comments: #Ecto.Query<from c0 in Quarry.Comment, as: :post_comment, join: u1 in assoc(c0, :user), as: :post_comment_user, where: as(:post_comment).body == ^"comment", preload: [user: u1]>]> ``` ### Sort examples ```elixir # Single field iex> Quarry.build!(Quarry.Post, sort: :title) #Ecto.Query<from p0 in Quarry.Post, as: :post, order_by: [asc: as(:post).title]> # Multiple fields iex> Quarry.build!(Quarry.Post, sort: [:title, :body]) #Ecto.Query<from p0 in Quarry.Post, as: :post, order_by: [asc: as(:post).title], order_by: [asc: as(:post).body]> # Nested fields iex> Quarry.build!(Quarry.Post, sort: [[:author, :publisher], :title, [:author, :user, :name]]) #Ecto.Query<from p0 in Quarry.Post, as: :post, join: a1 in assoc(p0, :author), as: :post_author, join: u2 in assoc(a1, :user), as: :post_author_user, order_by: [asc: as(:post_author).publisher], order_by: [asc: as(:post).title], order_by: [asc: as(:post_author_user).name]> # Descending sort iex> Quarry.build!(Quarry.Post, sort: [:title, desc: :body, desc: [:author, :publisher]]) #Ecto.Query<from p0 in Quarry.Post, as: :post, join: a1 in assoc(p0, :author), as: :post_author, order_by: [asc: as(:post).title], order_by: [desc: as(:post).body], order_by: [desc: as(:post_author).publisher]> ``` ### Limit example ```elixir iex> Quarry.build!(Quarry.Post, limit: 10) #Ecto.Query<from p0 in Quarry.Post, as: :post, limit: ^10> ``` ### Offset example ```elixir iex> Quarry.build!(Quarry.Post, limit: 10, offset: 20) #Ecto.Query<from p0 in Quarry.Post, as: :post, limit: ^10, offset: ^20> ``` """ @spec build!(atom(), opts()) :: Ecto.Query.t() def build!(schema, opts \\ []) do {query, _errors} = build(schema, opts) query end @spec build(atom(), opts()) :: {Ecto.Query.t(), [error()]} def build(schema, opts \\ []) do default_opts = %{ binding_prefix: nil, load_path: [], filter: %{}, load: [], sort: [], limit: nil, offset: nil } opts = Map.merge(default_opts, Map.new(opts)) {schema, []} |> From.build(opts.binding_prefix) |> Filter.build(opts.filter, opts.load_path) |> Load.build(opts.load, opts.load_path) |> Sort.build(opts.sort, opts.load_path) |> limit(opts.limit) |> offset(opts.offset) end defp limit({query, errors}, value) when is_integer(value), do: {Ecto.Query.limit(query, ^value), errors} defp limit(token, _limit), do: token defp offset({query, errors}, value) when is_integer(value), do: {Ecto.Query.offset(query, ^value), errors} defp offset(token, _value), do: token end
lib/quarry.ex
0.805632
0.813313
quarry.ex
starcoder
if Code.ensure_loaded?(Plug) do defmodule BtrzAuth.Plug.VerifyToken do @moduledoc """ It depends on `BtrzAuth.Plug.VerifyApiKey`, looks for a token in the `Authorization` header and verify it using first the account's private key, if not valid, then main and secondary secrets provided by your app for internal token cases. In the case where: a. The session is not loaded b. A token is already found for `:key` This plug will not do anything. This, like all other Guardian plugs, requires a Guardian pipeline to be setup. It requires an error handler. These can be set either: 1. Upstream on the connection with `plug Guardian.Pipeline` 2. Upstream on the connection with `Guardian.Pipeline.{put_module, put_error_handler, put_key}` 3. Inline with an option of `:module`, `:error_handler`, `:key` If a token is found but is invalid, the error handler will be called with `auth_error(conn, {:invalid_token, reason})` Once a token has been found it will be decoded, the token and claims will be put onto the connection. They will be available using `Guardian.Plug.current_claims/2` and `Guardian.Plug.current_token/2` Options: * `claims` - The literal claims to check to ensure that a token is valid * `realm` - The prefix for the token in the Authorization header. Defaults to `Bearer`. `:none` will not use a prefix. * `key` - The location to store the information in the connection. Defaults to: `default` ### Example ```elixir # setup the upstream pipeline plug BtrzAuth.Plug.VerifyHeaderInternal, claims: %{typ: "access"} ``` This will check the authorization header for a token `Authorization Bearer: <token>` This token will be placed into the connection depending on the key and can be accessed with `Guardian.Plug.current_token` and `Guardian.Plug.current_claims` OR `MyApp.ImplementationModule.current_token` and `MyApp.ImplementationModule.current_claims` """ import Plug.Conn alias Guardian.Plug, as: GPlug alias GPlug.Pipeline require Logger @spec init(Keyword.t()) :: Keyword.t() def init(opts \\ []) do opts = Keyword.put( opts, :main_secret, Keyword.get(Application.get_env(:btrz_ex_auth_api, :token, []), :main_secret, "") ) opts = Keyword.put( opts, :secondary_secret, Keyword.get(Application.get_env(:btrz_ex_auth_api, :token, []), :secondary_secret, "") ) realm = Keyword.get(opts, :realm, "Bearer") case realm do "" -> opts :none -> opts _realm -> {:ok, reg} = Regex.compile("#{realm}\:?\s+(.*)$", "i") Keyword.put(opts, :realm_reg, reg) end end @spec call(Plug.Conn.t(), Keyword.t()) :: Plug.Conn.t() def call(conn, opts) do Logger.debug("accessing VerifyToken plug..") verify(Mix.env(), conn, opts) end @spec verify(atom, Plug.Conn.t(), Keyword.t()) :: Plug.Conn.t() defp verify(:test, conn, opts) do case fetch_token_from_header(conn, opts) do :no_token_found -> response_error(conn, :no_token_found, opts) {:ok, "test-token"} -> Logger.debug("using test-token mode") conn |> GPlug.put_current_token("test-token") |> GPlug.put_current_claims(%{}) |> put_private(:btrz_token_type, :test) {:ok, _local_test_token} -> Logger.debug("using local test mode") verify(:local_test, conn, opts) end end defp verify(_env, conn, opts) do with nil <- GPlug.current_token(conn, opts), {:ok, token} <- fetch_token_from_header(conn, opts), claims_to_check <- Keyword.get(opts, :claims, %{}), key <- storage_key(conn, opts), {:ok, btrz_token_type, claims} <- decode_and_verify(conn, token, claims_to_check, opts) do Logger.debug("passing VerifyToken plug..") conn |> put_private(:user_id, claims["id"]) |> put_private(:btrz_token_type, btrz_token_type) |> GPlug.put_current_token(token, key: key) |> GPlug.put_current_claims(claims, key: key) else :no_token_found -> response_error(conn, :no_token_found, opts) {:error, reason} -> response_error(conn, reason, opts) _ -> conn end end @spec response_error(Plug.Conn.t(), any, Keyword.t()) :: Plug.Conn.t() defp response_error(conn, reason, opts) do conn |> Pipeline.fetch_error_handler!(opts) |> apply(:auth_error, [conn, {:unauthenticated, reason}]) |> halt() end @spec decode_and_verify( Plug.Conn.t(), Guardian.Token.token(), Guardian.Token.claims(), Keyword.t() ) :: {:ok, BtrzTokenType.t(), Guardian.Token.claims()} | {:error, any} defp decode_and_verify(conn, token, claims_to_check, opts) do opts = Keyword.put(opts, :secret, conn.private.account["private_key"]) case Guardian.decode_and_verify(BtrzAuth.GuardianUser, token, claims_to_check, opts) do {:ok, claims} -> {:ok, :user, claims} _ -> Logger.debug("token not valid as user token, checking if it is an internal token..") opts = Keyword.put(opts, :secret, opts[:main_secret]) opts = Keyword.put(opts, :verify_issuer, true) case Guardian.decode_and_verify(BtrzAuth.Guardian, token, claims_to_check, opts) do {:ok, claims} -> {:ok, :internal, claims} _ -> Logger.debug( "main secret is not valid for internal auth, using the secondary secret.." ) opts = Keyword.put(opts, :secret, opts[:secondary_secret]) case Guardian.decode_and_verify(BtrzAuth.Guardian, token, claims_to_check, opts) do {:ok, claims} -> {:ok, :internal, claims} {:error, reason} -> Logger.debug("secondary secret is not valid for internal auth") {:error, reason} end end end end @spec fetch_token_from_header(Plug.Conn.t(), Keyword.t()) :: :no_token_found | {:ok, String.t()} defp fetch_token_from_header(conn, opts) do headers = get_req_header(conn, "authorization") fetch_token_from_header(conn, opts, headers) end @spec fetch_token_from_header(Plug.Conn.t(), Keyword.t(), Keyword.t()) :: :no_token_found | {:ok, String.t()} defp fetch_token_from_header(_, _, []), do: :no_token_found defp fetch_token_from_header(conn, opts, [token | tail]) do reg = Keyword.get(opts, :realm_reg, ~r/^(.*)$/) trimmed_token = String.trim(token) case Regex.run(reg, trimmed_token) do [_, match] -> {:ok, String.trim(match)} _ -> fetch_token_from_header(conn, opts, tail) end end @spec storage_key(Plug.Conn.t(), Keyword.t()) :: String.t() defp storage_key(conn, opts), do: Pipeline.fetch_key(conn, opts) end end
lib/plug/verify_token.ex
0.810779
0.805403
verify_token.ex
starcoder
defmodule Terp.AST do @moduledoc """ Interface for working with the Terp.AST. """ alias RoseTree.Zipper alias Terp.Parser @doc """ Parse source code and convert it to an ast. """ @spec from_src(String.t) :: [RoseTree.t] def from_src(str) do str |> Parser.parse() |> Enum.flat_map(&to_tree/1) |> filter_nodes(:__comment) end @doc """ `to_tree/1` takes a tokenized expression and builds a parse tree. ## Examples iex> [:__apply, [:+, 1, 2, 3]] ...> |> Terp.AST.to_tree() [ %RoseTree{node: :__apply, children: []}, [ %RoseTree{node: :+, children: []}, %RoseTree{node: 1, children: []}, %RoseTree{node: 2, children: []}, %RoseTree{node: 3, children: []}, ] ] iex> [:+, 1, 2, [:*, 2, 3]] ...> |> Terp.AST.to_tree() [ %RoseTree{node: :+, children: []}, %RoseTree{node: 1, children: []}, %RoseTree{node: 2, children: []}, [ %RoseTree{node: :*, children: []}, %RoseTree{node: 2, children: []}, %RoseTree{node: 3, children: []}, ] ] """ def to_tree([]), do: [] def to_tree(expr) when is_list(expr) do for v <- expr do case v do {s, x} when is_atom(s) -> RoseTree.new(s, to_tree(x)) val when is_list(val) -> to_tree(val) _ -> RoseTree.new(v) end end end def to_tree(x), do: RoseTree.new(x) @doc """ Converts an AST into a string that (should) represent the function encapsulated by the AST. NOTE: This does not currently re-sugar desugared expressions (e.g. defn and defrec), so the resulting string is that of the desugared expression. ## Examples iex> "(+ 1 2 3 (* 2 3))" ...> |> Terp.Parser.parse() ...> |> Terp.AST.to_tree() ...> |> Terp.AST.stringify() "(+ 1 2 3 (* 2 3))" iex> "(data (Maybe a) [Just a] [Nothing])" ...> |> Terp.Parser.parse() ...> |> Terp.AST.to_tree() ...> |> Terp.AST.stringify() "(data (Maybe a) [Just a] [Nothing])" iex> "(defn plusFive (x) (+ x 5))" ...> |> Terp.Parser.parse() ...> |> Terp.AST.to_tree() ...> |> Terp.AST.stringify() "(let plusFive (lambda (x) (+ x 5)))" """ @spec stringify(RoseTree.t | [RoseTree.t]) :: String.t def stringify(%RoseTree{node: node, children: children}) do case node do :__apply -> "(#{stringify(children)})" :__data -> [type_constructor | [value_constructors | []]] = children type_string = stringify(type_constructor) value_strings = value_constructors.node |> Enum.reduce("", fn (constructor, acc) -> s = constructor |> Enum.map(&stringify/1) |> Enum.join(" ") if acc == "", do: "[#{s}]", else: "#{acc} [#{s}]" end) "(data #{type_string} #{value_strings})" :__match -> "(match #{stringify(children)})" :__string -> raw_string = children |> List.wrap() |> Enum.map(&stringify/1) |> Enum.join() "\"#{raw_string}\"" :__quote -> raw_string = children |> Enum.map(&stringify/1) |> Enum.join(", ") "'(#{raw_string})" x when is_list(x) -> res = x |> Enum.map(&stringify/1) |> Enum.join(" ") "(#{res})" x -> with true <- is_atom(x), s <- Atom.to_string(x), true <- String.starts_with?(s, "__") do String.trim(s, "__") else %RoseTree{node: n, children: cs} -> res = cs |> Enum.map(&stringify/1) |> Enum.join(" ") "(#{stringify(n)} #{res})" _ -> Kernel.to_string(x) end end end def stringify(trees) when is_list(trees) do trees |> Enum.map(&stringify/1) |> Enum.join(" ") end @doc """ Filters nodes out of the AST. """ def filter_nodes(trees, node_name) do Enum.reject(trees, fn %RoseTree{node: node} -> node == node_name end) end @spec fn_name(RoseTree.t) :: {:ok, String.t} | {:error, :no_fn_name} def fn_name(expr) do z = Zipper.from_tree(expr) with {:ok, {%RoseTree{node: t}, _history}} = expr_type <- Zipper.first_child(z), true <- Enum.member?([:__let, :__letrec], t), {:ok, {%RoseTree{node: name}, _history}} <- Zipper.lift(expr_type, &Zipper.next_sibling/1) do {:ok, name} else _ -> {:error, :no_fn_name} end end end
lib/terp/ast.ex
0.766687
0.524638
ast.ex
starcoder
defmodule Cb.Bot do use Slacker use Slacker.Matcher match ~r/^c(ultivate)?? help/i, :help match ~r/^c(ultivate)?? hi/i, :say_hello match ~r/^c(ultivate)?? where are you/i, :show_inet_addr match ~r/^c(ultivate)?? (forward|reverse|back|left|right|stop)/i, :control match ~r/^c(cultivate)?? step (\d+)/i, :set_step_rate match ~r/^c(ultivate)?? pin test\s*$/i, :start_pin_test match ~r/^c(ultivate)?? pin test end/i, :stop_pin_test alias CbLocomotion.Locomotion alias CbLocomotion.PinTest def say_hello(_bot, msg, _ \\ nil) do say self, msg["channel"], "¡Hola!" end def help(_bot, msg, _ \\ nil) do say self, msg["channel"], """ Hello, I am the controller. Here is what you do. `cultivate help`: show this message. `cultivate hi`: say hello. `cultivate where are you?`: display the IP addresses to which I'm connected. `cultivate forward`: drive forward. `cultivate reverse`: reverse. `cultivate back`: reverse. `cultivate left`: turn left. `cultivate right`: turn right. `cultivate stop`: stop. `cultivate step (number)`: set the rate at which the stepper motors turn. The maximum is 0 (and pretty slow), and is also the default. 50 is incredibly slow. `cultivate pin test`: flash all the GPIO pins every 0.5 seconds. This won't don't much with the motors but is handy for testing your GPIO header soldering. `cultivate pin test end`: stop all that annoying GPIO flashing. It is possible that you will get fed up with our brand placement. You can just write `c` instead of `cultivate`. (I do.) """ end def show_inet_addr(_bot, msg, _ \\ nil) do case :inet.getifaddrs do {:ok, addrs} -> say self, msg["channel"], addrs_to_msg(addrs) {:error, posix} -> say self, msg["channel"], "That did not work out #{inspect(posix)}" end end def control(bot, msg, _, direction), do: control(bot, msg, direction) def control(_bot, msg, "forward") do Locomotion.forward say self, msg["channel"], "Forward!" end def control(_bot, msg, "reverse") do Locomotion.reverse say self, msg["channel"], "Reverse!" end def control(bot, msg, "back"), do: control(bot, msg, "reverse") def control(_bot, msg, "left") do Locomotion.turn_left say self, msg["channel"], "Left!" end def control(_bot, msg, "right") do Locomotion.turn_right say self, msg["channel"], "Right!" end def control(_bot, msg, "stop") do Locomotion.stop say self, msg["channel"], "Stop!" end def set_step_rate(_bot, msg, _ \\ nil, rate_str) do {rate, _} = Integer.parse(rate_str) Locomotion.set_step_rate(rate) say self, msg["channel"], "Stepping at #{rate}!" end def start_pin_test(_bot, msg, _ \\ nil) do PinTest.start_test say self, msg["channel"], "Testing pins!" end def stop_pin_test(_bot, msg, _ \\ nil) do PinTest.finish_test say self, msg["channel"], "Stopping pin test!" end defp addrs_to_msg(addrs) do addrs |> Enum.map(fn {iface, properties} -> { List.to_string(iface), Keyword.get(properties, :addr) } end) |> Enum.map( fn {iface, {a1,a2,a3,a4}} -> "#{iface}: #{a1}.#{a2}.#{a3}.#{a4}" _ -> nil end) |> Enum.filter(&(&1)) |> Enum.join("\n") end end
apps/cb_slack/lib/cb_slack/cb_bot.ex
0.557604
0.47171
cb_bot.ex
starcoder
defmodule Dependency do @moduledoc """ Fuctions to build soft dependencies between modules. This is useful when you want to test different implementations in test mode. The resolution is dynamic in test mode (uses a `Registry`). In dev and production modes, the dependency in compiled inline. """ @doc """ Starts the dependency registry. This is done for you if you add `:dependency` to list of apps in your `mix.exs`. Returns `{:ok, pid}` """ @spec start_link :: {:ok, pid()} | {:error, atom()} def start_link do Registry.start_link(keys: :unique, name: Dependency.Registry) end @doc """ Register an implementation for a module. Returns `{:ok, module}` ## Examples iex> Dependency.register(Foo, Bar) {:ok, Bar} """ @spec register(module(), module()) :: {:ok, module()} def register(mod, implementation) do case Registry.register(Dependency.Registry, mod, implementation) do {:ok, _pid} -> {:ok, implementation} {:error, {:already_registered, _pid}} -> :ok = Registry.unregister(Dependency.Registry, mod) register(mod, implementation) end end @doc """ Resolve the implementation for a module. Returns `module` ## Examples iex> Dependency.register(Foo, Bar) {:ok, Bar} iex> Dependency.resolve(Foo) Bar """ @spec resolve(module()) :: module() defmacro resolve(mod) do quote do if Mix.env() == :test do Dependency.dynamically_resolve(unquote(mod)) else unquote(mod) end end end @doc """ Defines a public constant Returns `module` ## Examples iex> defmodule Bar do iex> def value, do: 123 iex> end iex> iex> defmodule Foo do iex> import Dependency iex> iex> defconst :bar, Bar iex> end iex> iex> Foo.bar().value() 123 """ @spec defconst(atom() | String.t, module()) :: module() defmacro defconst(name, module) do quote do def unquote(name)() do resolve(unquote module) end end end @doc """ Defines a private constant Returns `module` ## Examples iex> defmodule Baz do iex> def value, do: 123 iex> end iex> iex> defmodule Qux do iex> import Dependency iex> iex> defconstp :baz, Baz iex> iex> def value, do: baz().value iex> end iex> iex> Qux.value() 123 """ @spec defconstp(atom() | String.t, module()) :: module() defmacro defconstp(name, module) do quote do defp unquote(name)() do resolve(unquote module) end end end @doc false def dynamically_resolve(mod) do case Registry.lookup(Dependency.Registry, mod) do [{_pid, implementation}] -> implementation [] -> mod end end end
lib/dependency.ex
0.867457
0.484441
dependency.ex
starcoder
defmodule TicTacToe.Game do @moduledoc """ Functions to modify the game state. """ alias TicTacToe.Ai alias TicTacToe.Board alias TicTacToe.Scoring defstruct( board: Board.new(), winner: nil, current_player: nil, game_mode: :original ) @type t :: %__MODULE__{ board: Board.t(), winner: Scoring.t(), current_player: nil | Board.player(), game_mode: mode() } @type mode :: :original | :notakto | :misere @spec new(mode()) :: t() def new(game_mode \\ :original) do %TicTacToe.Game{current_player: Enum.random([:player1, :computer]), game_mode: game_mode} end @spec score(t()) :: t() def score(game) do winner = Scoring.winner(game) update_winner(game, winner) end @spec player_move(t(), Board.position()) :: t() def player_move(game, position), do: make_move(game, :player1, position, game.current_player == :player1) @spec computer_move(t()) :: t() def computer_move(game = %{winner: nil}) do position = Ai.choose_next_position(game) computer_move(game, position) end def computer_move(game), do: game @spec computer_move(t(), Board.position()) :: t() def computer_move(game, position), do: make_move(game, :computer, position, game.current_player == :computer) @spec over?(t()) :: boolean() def over?(%{winner: nil}), do: false def over?(_), do: true @spec make_move(t(), Board.player(), Board.position(), boolean()) :: t() defp make_move(game, _, _, false), do: game defp make_move(game = %{board: board, winner: nil}, player, position, _player_can_move) do new_board = board |> Board.receive_move(player, position) update_board(game, new_board) |> score end defp make_move(game, _, _, _), do: game @spec update_winner(t(), Scoring.t()) :: t() defp update_winner(game, winner) do %{game | winner: winner} end @spec update_board(t(), Board.t()) :: t() defp update_board(game = %{board: board}, new_board) do valid_move = board != new_board update_board(game, new_board, valid_move) end @spec update_board(t(), Board.t(), boolean()) :: t() defp update_board(game, _, false), do: game defp update_board(game = %{current_player: :player1}, new_board, _valid_move) do %{game | board: new_board, current_player: :computer} end defp update_board(game = %{current_player: :computer}, new_board, _valid_move) do %{game | board: new_board, current_player: :player1} end end
lib/tic_tac_toe/game.ex
0.813794
0.426441
game.ex
starcoder
defmodule ShiftRegister do @moduledoc """ Controls a 74hc595 shift register Connect GPIO pins on your PI to pins 11, 12, 14 of the 74hc595. For an 74hc595n, if you put the package pins down, the pin layout looks like this (`U` is the notch on the end of the package.) ``` output1 -> 1 U 16 <- 5V power in output2 -> 2 15 <- output0 output3 3 14 <- data output4 4 13 <- connect to ground output5 5 12 <- latch output6 6 11 <- clock output7 7 10 <- Master Reset (connect to ground) ground -> 8 9 <- Q7S (?) ``` To start it up, pass in the latch pin, the clock pin, and the data pin. latch pin connects to STCP (pin 12) of the 74hc595 clock pin connects to SHCP (pin 11) of the 74hc595 data pin connects to DS (pin 14) of the 74hc595 """ use GenServer use Bitwise @latch_pin 5 @clock_pin 6 @data_pin 4 @type pin() :: non_neg_integer() defmodule State do @moduledoc "Container for the ShiftRegister's state" defstruct [:latch_pin, :clock_pin, :data_pin] end alias ShiftRegister.State @doc """ Takes the 3 pin numbers that are needed to operate the shift register. See module documentation for detail. """ def start_link(latch_pin \\ @latch_pin, clock_pin \\ @clock_pin, data_pin \\ @data_pin) do GenServer.start_link(__MODULE__, {latch_pin, clock_pin, data_pin}) end @spec init({pin, pin, pin}) :: {:ok, %State{}} def init({latch_pin_num, clock_pin_num, data_pin_num}) do {:ok, latch_pin} = Gpio.start_link(latch_pin_num, :output) {:ok, clock_pin} = Gpio.start_link(clock_pin_num, :output) {:ok, data_pin} = Gpio.start_link(data_pin_num, :output) {:ok, %State{latch_pin: latch_pin, clock_pin: clock_pin, data_pin: data_pin}} end @doc """ Sends data into the shift register """ @spec shift_out(pid(), non_neg_integer()) :: :ok def shift_out(pid, value) do GenServer.call(pid, {:shift_out, value}) end # Junk def display(pid, 0), do: ShiftRegister.shift_out(pid, 0b11111100) def display(pid, 1), do: ShiftRegister.shift_out(pid, 0b00110000) def display(pid, 2), do: ShiftRegister.shift_out(pid, 0b01101110) def display(pid, 3), do: ShiftRegister.shift_out(pid, 0b01111010) def display(pid, 4), do: ShiftRegister.shift_out(pid, 0b10110010) def display(pid, 5), do: ShiftRegister.shift_out(pid, 0b11011010) def display(pid, 6), do: ShiftRegister.shift_out(pid, 0b11011110) def display(pid, 7), do: ShiftRegister.shift_out(pid, 0b01110000) def display(pid, 8), do: ShiftRegister.shift_out(pid, 0b11111110) def display(pid, 9), do: ShiftRegister.shift_out(pid, 0b11111010) def handle_call({:shift_out, value}, _from, state) do require Logger Logger.info("Setting latch pin to 0") Gpio.write(state.latch_pin, 0) Enum.each(0..7, fn n -> mask = 1 <<< n overlap = value &&& mask pin_val = if overlap == 0 do 0 else 1 end Logger.info("setting data pin to #{pin_val}") Gpio.write(state.data_pin, pin_val) # Cycle the clock Logger.info "Clock Cycle" Gpio.write(state.clock_pin, 1) Gpio.write(state.clock_pin, 0) end) Logger.info("Setting latch pin to 1") Gpio.write(state.latch_pin, 1) {:reply, :ok, state} end end
apps/ui/lib/ui/shift_register.ex
0.83128
0.89765
shift_register.ex
starcoder
defmodule Jaxon.Decoders.Values do alias Jaxon.{ParseError} def values(event_stream) do event_stream |> Stream.transform(&initial_fun/1, fn events, fun -> do_resume_stream_values(events, fun, []) end) end defp initial_fun(events) do do_stream_value(events, [], []) end defp do_resume_stream_values(events, fun, acc) do events |> fun.() |> case do {:ok, values, []} -> {:lists.reverse(values ++ acc), &initial_fun/1} {:ok, values, events} -> do_resume_stream_values(events, &initial_fun/1, values ++ acc) {:yield, values, fun} -> {:lists.reverse(values ++ acc), fun} {:error, error} when is_binary(error) -> raise ParseError.syntax_error(error) {:error, error} -> raise error end end defp do_stream_value([:start_object | events], path, acc) do events_to_object(events, path, [{path, :start_object} | acc]) end defp do_stream_value([:start_array | events], path, acc) do events_to_array(events, 0, path, [{path, :start_array} | acc]) end defp do_stream_value([{event, value} | events], path, acc) when event in [:string, :decimal, :integer, :boolean] do {:ok, [{path, value} | acc], events} end defp do_stream_value([nil | events], path, acc) do {:ok, [{path, nil} | acc], events} end defp do_stream_value([], path, acc) do {:yield, acc, &do_stream_value(&1, path, [])} end defp do_stream_value([{:incomplete, _}, :end_stream], _, _) do {:error, ParseError.unexpected_event(:end_stream, [:value])} end defp do_stream_value([event | _], _, _) do {:error, ParseError.unexpected_event(event, [:value])} end # Object defp add_value_to_object({:ok, acc, rest}, path) do events_to_object(rest, path, acc) end defp add_value_to_object({:yield, acc, inner}, path) do {:yield, acc, &add_value_to_object(inner.(&1), path)} end defp add_value_to_object(result, _) do result end defp events_to_object_key_value([{:string, key}], path, acc) do {:yield, acc, &events_to_object_key_value([{:string, key} | &1], path, [])} end defp events_to_object_key_value([{:string, key} | rest], path, acc) do new_path = path ++ [key] with {:ok, rest} <- events_expect(rest, :colon) do add_value_to_object(do_stream_value(rest, new_path, acc), path) end end defp events_to_object_key_value([], path, acc) do {:yield, acc, &events_to_object_key_value(&1, path, [])} end defp events_to_object_key_value([event | _], _, _) do {:error, ParseError.unexpected_event(event, [:key])} end defp events_to_object(events = [{:string, _} | _], path, acc) do events_to_object_key_value(events, path, acc) end defp events_to_object(events = [{:incomplete, _} | _], path, acc) do events_to_object_key_value(events, path, acc) end defp events_to_object([:comma | events], path, acc) do events_to_object_key_value(events, path, acc) end defp events_to_object([:end_object | events], path, acc) do {:ok, [{path, :end} | acc], events} end defp events_to_object([], path, acc) do {:yield, acc, &events_to_object(&1, path, [])} end defp events_to_object([event | _], _, _) do {:error, ParseError.unexpected_event(event, [:key, :end_object, :comma])} end # Array defp add_value_to_array({:ok, acc, rest}, index, path) do events_to_array(rest, index, path, acc) end defp add_value_to_array({:yield, acc, inner}, index, path) do {:yield, acc, &add_value_to_array(inner.(&1), index, path)} end defp add_value_to_array(result, _, _) do result end defp events_to_array([:comma | events], index, path, acc) do events_to_array(events, index + 1, path, acc) end defp events_to_array([:end_array | events], _, path, acc) do {:ok, [{path, :end} | acc], events} end defp events_to_array([], index, path, acc) do {:yield, acc, &events_to_array(&1, index, path, [])} end defp events_to_array(events, index, path, acc) do add_value_to_array(do_stream_value(events, path ++ [index], acc), index, path) end # Helpers defp events_expect([event | events], event) do {:ok, events} end defp events_expect([{event, _} | _], expected) do {:error, ParseError.unexpected_event(event, [expected])} end defp events_expect([event | _], expected) do {:error, ParseError.unexpected_event(event, [expected])} end end
lib/jaxon/decoders/values.ex
0.677474
0.544922
values.ex
starcoder
defmodule Dactyl do @moduledoc """ Very much inspired by the [Dactyl Keyboard](https://github.com/adereth/dactyl-keyboard). This is an attempt to provide a complex example for my [OpenSCAD](https://github.com/joedevivo/open_scad) library by porting that clojure model. I've made personal changes where I saw fit, because I do intend to riff on this model after it's ported. It's also very much a work in progress """ use OpenSCAD # This import due to my aggressive use of module attributes. I need to rethink # this as a concept. import Keyboards # Parameters # Math.pi() / 12 @alpha 15 # Math.pi() / 36 @beta 5 @extra %{ height: -0.5, width: 2.5 } @plate_thickness 4 @cherry_mx %{ height: 14.4, width: 14.4, thickness: 4, margin: 3 } @sa %{ height: 12.7 + @plate_thickness } @switch @cherry_mx @cap @sa @mount_height @switch.height + @switch.margin @mount_width @switch.width + @switch.margin @row_radius (@mount_height + @extra.height) / 2 / sin(@alpha / 2) + @cap.height @column_radius (@mount_width + @extra.width) / 2 / sin(@beta / 2) + @cap.height @layout [ [1, 0, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 1, 1, 0] ] defp layout() do center_row = @layout |> Enum.count() |> halvesies() center_column = @layout |> Enum.map(&Enum.count/1) |> Enum.sum() |> div(Enum.count(@layout)) |> halvesies() @layout |> Enum.with_index(-center_row) |> Enum.reduce([], fn {row, r}, acc -> acc ++ row_coords(r, center_column, row) end) end defp halvesies(x) do Float.floor(x / 2 - 0.00001) |> Kernel.trunc() end defp row_coords(r, center_col, row) do row |> Enum.with_index(-center_col) |> Enum.reduce( [], fn {0, _}, acc -> acc {1, col}, acc -> [{r, col} | acc] end ) end def sin(x) do x |> Math.deg2rad() |> Math.sin() end # This one is the dactyl codebase way defp single_plate(:cherry) do top = cube( size: [@switch.width + 3, 1.5, @plate_thickness], center: true ) |> translate(v: [0, 1.5 / 2 + @cherry_mx.height / 2, @plate_thickness / 2]) side = cube( size: [1.5, @cherry_mx.height + 3, @plate_thickness], center: true ) |> translate(v: [1.5 / 2 + @cherry_mx.width / 2, 0, @plate_thickness / 2]) side_nub = hull([ cylinder(h: 1, d: 2.75, center: true, _fn: 30) |> rotate(a: 90, v: [1, 0, 0]) |> translate(v: [@cherry_mx.width / 2, 0, 1]), cube(size: [1.5, 2.75, @plate_thickness], center: true) |> translate(v: [1.5 / 2 + @cherry_mx.width / 2, 0, @plate_thickness / 2]) ]) half = union([top, side, side_nub]) union([ mirror(half, v: [1, 0, 0]), mirror(half, v: [0, 1, 0]) ]) end # I'm tracking rows and column ids differently that the original dactyl. 0 == # center, so on the left half d = 0,0 # +------+------+------+------+------+------+------+ # |-3,-2 |-2,-2 |-1,-2 | 0,-2 | 1,-2 | 2,-2 | 3,-2 | # +------+------+------+------+------+------+------+ # |-3,-1 |-2,-1 |-1,-1 | 0,-1 | 1,-1 | 2,-1 | 3,-1 | # +------+------+------+------+------+------+------+ # |-3, 0 |-2, 0 |-1, 0 | 0, 0 | 1, 0 | 2, 0 | # +------+------+------+------+------+------+ # |-3, 1 |-2, 1 |-1, 1 | 0, 1 | 1, 1 | 2, 1 | # +------+------+------+------+------+------+ # |-3, 2 |-2, 2 |-1, 2 | 0, 2 | 1, 2 | 2, 2 | # +------+------+------+------+------+------+ defp key_angle(key, col, row) do key |> translate(v: [0, 0, -@row_radius]) |> rotate(a: @alpha * -row, v: [1, 0, 0]) |> translate(v: [0, 0, @row_radius]) |> translate(v: [0, 0, -@column_radius]) |> rotate(a: @beta * -col, v: [0, 1, 0]) |> translate(v: [0, 0, @column_radius]) |> translate(v: column_offset(col)) end defp column_offset(0), do: [0, 0, 0] defp column_offset(index) when index < 0, do: [0, -2.82, 3] defp column_offset(ring) when ring == 1, do: [0, -2.82, 3] defp column_offset(pinky) when pinky > 1, do: [0, -8.62, 5.64] # triangle-hulls is a union of 4 triangles a,b,c b,c,d c,d,a d,a,b defp triangle_hulls([first, second | _] = objects) do triangle_hulls_( objects, %{ first: first, second: second, hulls: [] } ) end defp triangle_hulls_([last], acc) do union([hull([last, acc.first, acc.second]) | acc.hulls]) end defp triangle_hulls_([pen, last], acc) do triangle_hulls_( [last], %{acc | hulls: [hull([pen, last, acc.first]) | acc.hulls]} ) end defp triangle_hulls_([a, b, c | _] = objects, acc) do triangle_hulls_( tl(objects), %{acc | hulls: [hull([a, b, c]) | acc.hulls]} ) end @post_size 0.1 @post_adj @post_size / 2 defp web_post(:tr) do web_post() |> translate(v: [@mount_width / 2 - @post_adj, @mount_height / 2 - @post_adj, 0]) end defp web_post(:tl) do web_post() |> translate(v: [@mount_width / -2 + @post_adj, @mount_height / 2 - @post_adj, 0]) end defp web_post(:bl) do web_post() |> translate(v: [@mount_width / -2 + @post_adj, @mount_height / -2 + @post_adj, 0]) end defp web_post(:br) do web_post() |> translate(v: [@mount_width / 2 - @post_adj, @mount_height / -2 + @post_adj, 0]) end defp web_post(), do: cube(size: [@post_size, @post_size, 4]) def row_connector({row, col}) do [ web_post(:br) |> key_angle(col, row), web_post(:bl) |> key_angle(col + 1, row), web_post(:tr) |> key_angle(col, row), web_post(:tl) |> key_angle(col + 1, row) ] |> triangle_hulls() end def col_connector({row, col}) do [ web_post(:br) |> key_angle(col, row), web_post(:bl) |> key_angle(col, row), web_post(:tr) |> key_angle(col, row + 1), web_post(:tl) |> key_angle(col, row + 1) ] |> triangle_hulls() end def diagonal_connector({row, col}) do [ web_post(:br) |> key_angle(col, row), web_post(:bl) |> key_angle(col + 1, row), web_post(:tr) |> key_angle(col, row + 1), web_post(:tl) |> key_angle(col + 1, row + 1) ] |> triangle_hulls() end # TODO: has to be in a function def main() do l = layout() (for {row, col} <- l do single_plate(:cherry) |> key_angle(col, row) end ++ Enum.reduce( l, [], fn {x, y}, acc -> [ row_connector({x, y}), row_connector({x, y - 1}), col_connector({x, y}), col_connector({x - 1, y}), diagonal_connector({x, y}), diagonal_connector({x - 1, y}), diagonal_connector({x, y - 1}), diagonal_connector({x - 1, y - 1}) ] ++ acc end )) |> union() |> write("./output/single_plate.scad") end end
models/dactyl.ex
0.68458
0.487856
dactyl.ex
starcoder
defmodule FusionDsl.Impl do @moduledoc """ Implementation module for FusionDsl. This module helps with developing packages for fusion dsl. Read [packages](packages.html) docs for more info. """ alias FusionDsl.Runtime.Executor alias FusionDsl.Runtime.Environment defmacro __using__(_opts) do quote do import FusionDsl.Impl @behaviour FusionDsl.Impl end end @doc """ Should return list of function names this package provides as atoms. ## Example ```elixir @impl true def __list_fusion_functions__, do: [:foo, :bar] ``` """ @callback __list_fusion_functions__() :: [atom()] @doc """ Puts or updates value of a key of assigns in environment. Every package in Fusion can have their assigns in the runtime environment of script (Somehow like assigns in plug). The assigns are not accessible directly by fusion code and is meant for packages to hold any elixir data type in them. ## Keys Keys of assigns are recommended to be atoms which start with projects short otp name. e.g. `:fusion_dsl_assgn1` ## Values Values of the assigns can be any elixir data type. But putting large amounts of data into assigns is **not** recommended. ## Examples ```elixir # Put some value into environment assigns env = FusionDsl.Impl.put_assign(env, :fusion_dsl_engine_state, :rocks) %Environment{...} # Get that value from environment assigns FusionDsl.Impl.get_assign(env, :fusion_dsl_engine_state) {:ok, :rocks} ``` """ @spec put_assign(Environment.t(), atom() | String.t(), any()) :: Environment.t() def put_assign(env, key, value), do: %{env | assigns: Map.put(env.assigns, key, value)} @doc """ Gets the value of an assign with given key, `:error` in case of unset key """ @spec get_assign(Environment.t(), atom() | String.t()) :: {:ok, any()} | :error def get_assign(env, key), do: Map.fetch(env.assigns, key) @doc """ Ensures that all asts in arguments (such as functions values in args) are converted to terms (raw values) For example an argument list may look like: `[1, {:rand, [ln: 2], [5, 10]}]` When called with prep_arg(env, args) the output of prep_args will be: ``` iex> prep_arg(env, [1, {:rand, [ln: 2], [5, 10]}]) {:ok, [1, 6], env} ``` ## Parameters - args: list of arguments or just one argument - env: the Environment struct """ @spec prep_arg(Environment.t(), list() | any()) :: {:ok, list() | any(), Environment.t()} def prep_arg(%Environment{} = env, args) when is_list(args) do do_prep_args(args, env, []) end def prep_arg(%Environment{} = env, arg) do case Executor.execute_ast(arg, env) do {:ok, result, env} -> {:ok, result, env} {:error, msg} -> {:error, "argument execute resulted in an error: #{msg}"} end end @doc """ Returns value of a variable in environment """ @spec get_var(Environment.t(), String.t()) :: {:ok, any(), Environment.t()} def get_var(env, var) when is_binary(var) do case do_get_var(env.prog, nil, String.split(var, "."), env) do {:ok, acc, env} -> {:ok, acc, env} {:error, :not_initialized} -> {:error, :not_initialized} end end # Runs prep_arg on each argument in the list and returns the # result in same order defp do_prep_args([h | t], env, acc) do case prep_arg(env, h) do {:ok, res, env} -> do_prep_args(t, env, [res | acc]) {:error, msg} -> {:error, msg} end end defp do_prep_args([], env, acc), do: {:ok, Enum.reverse(acc), env} defp do_get_var(prog, nil, [var | t], env) do case Map.fetch(env.vars, var) do :error -> {:error, :not_initialized} {:ok, v} -> do_get_var(prog, v, t, env) end end defp do_get_var(prog, acc, [var | t], env) when is_map(acc) do case Map.fetch(acc, var) do :error -> {:error, :not_initialized} {:ok, v} -> do_get_var(prog, v, t, env) end end defp do_get_var(_prog, acc, [], env) do {:ok, acc, env} end end
lib/fusion_dsl/impl.ex
0.877706
0.877267
impl.ex
starcoder
defmodule Strukt.Test.Fixtures do use Strukt defmodule Classic do @moduledoc "This module uses Kernel.defstruct/1, even though our defstruct/1 is in scope, since it is given only a list of field names" use Strukt defstruct [:name] end defmodule Simple do @moduledoc "This module represents the simplest possible use of defstruct/1" use Strukt defstruct do field(:name, :string, default: "") end end defmodule CustomFields do @moduledoc "This module represents the params keys are not snake case" use Strukt defstruct do field(:name, :string, source: :NAME) field(:camel_case_key, :string, source: :camelCaseKey) end end defmodule CustomFieldsWithBoolean do @moduledoc "This module represents the params keys are not snake case with boolean value" use Strukt defstruct do field(:enabled, :boolean, source: :Enabled) end end defmodule CustomFieldsWithEmbeddedSchema do @moduledoc "This module shows the struct with embedded schema that have custom keys" use Strukt defstruct do field(:name, :string, source: :NAME) embeds_many :items, Item do field(:name, :string, source: :itemName) end embeds_one :meta, Meta do field(:source, :string, source: :SOURCE) field(:status, :integer, source: :Status) end end end defmodule EmbeddedParentSchema do @moduledoc "This module represents the embedded one parent schema" use Strukt alias Strukt.Test.Fixtures.ProfileSchema alias Strukt.Test.Fixtures.WalletSchema defstruct do embeds_one(:profile, ProfileSchema) embeds_many(:wallets, WalletSchema) end end defmodule ProfileSchema do @moduledoc "This module is an embedded schema for the EmbeddedParentSchema" use Strukt defstruct do field(:name, :string) field(:email, :string) end end defmodule WalletSchema do @moduledoc "This module is an embedded schema for the EmbeddedParentSchema" use Strukt defstruct do field(:currency, :string) field(:amount, :integer) end end defmodule VirtualField do @moduledoc "This module shows params can parse into the virtual field" use Strukt defstruct do field(:name, :string, virtual: true) field(:phone, :string) end end defmodule EmbeddedInlineModuleWithVirtualField do @moduledoc "This module demonstrate parsing the virtual field into embedded struct" use Strukt defstruct do embeds_one :profile, Profile do field(:name, :any, virtual: true, required: true) end embeds_many :wallets, Wallet do field(:currency, :any, virtual: true, required: true) end end end defmodule EmbeddedWithVirtualField do @moduledoc "This module shows parsing params with virtual required field." use Strukt alias Strukt.Test.Fixtures.ProfileWithVirtualField alias Strukt.Test.Fixtures.WalletWithVirtualField defstruct do embeds_one(:profile, ProfileWithVirtualField) embeds_many(:wallets, WalletWithVirtualField) end end defmodule ProfileWithVirtualField do @moduledoc "This is the embedded one module with required virtual field" use Strukt defstruct do field(:name, :any, virtual: true, required: true) field(:phone, :string, source: :PHONE) end end defmodule WalletWithVirtualField do @moduledoc "This is the embedded many module with required virtual field" use Strukt defstruct do field(:currency, :string) field(:amount, :integer) field(:native_currency, :any, virtual: true, required: true) end end defstruct Inline do @moduledoc "This module represents the simplest possible use of defstruct/2, i.e. inline definition of a struct and its module" field(:name, :string, default: "") @doc "This function is defined in the Inline module" def test, do: true end defstruct InlineVirtualField do field(:name, :string, virtual: true) field(:phone, :string) end defstruct Embedded do @moduledoc "This module demonstrates that embedding structs inline works just like the top-level" embeds_many :items, Item do field(:name, :string, required: [message: "must provide item name"]) end end defstruct AltPrimaryKey do @moduledoc "This module demonstrates the use of a custom primary key, rather than the default of :uuid" field(:id, :integer, primary_key: true) field(:name, :string, default: "") end defstruct AttrPrimaryKey do @moduledoc "This module demonstrates the use of a custom primary key, using the @primary_key attribute" @primary_key {:id, :integer, autogenerate: {System, :unique_integer, []}} field(:name, :string, default: "") end defstruct JSON do @moduledoc "This module demonstrates how to derive JSON serialization for your struct" @timestamps_opts [type: :utc_datetime_usec] @derives [Jason.Encoder] field(:name, :string, default: "") timestamps(autogenerate: {DateTime, :utc_now, []}) end defmodule OuterAttrs do use Strukt @derives [Jason.Encoder] @timestamps_opts [type: :utc_datetime_usec, autogenerate: {DateTime, :utc_now, []}] defstruct do field(:name, :string, default: "") timestamps() end end defmodule OuterScope do # This imports defstruct and sets up shared defaults in the outer scope use Strukt.Test.Macros defstruct InnerScope do # Since this is a new module scope, we want to set up defaults # like we did in the outer scope. If working properly, # this macro should be expanded before the schema definition use Strukt.Test.Macros field(:name, :string, default: "") timestamps() end end defstruct Validations do @moduledoc "This module uses a variety of validation rules in various combinations" field(:name, :string, default: "", required: true) field(:email, :string, required: [message: "must provide an email"], format: ~r/^.+@.+$/) field(:age, :integer, number: [greater_than: 0]) field(:status, Ecto.Enum, values: [:red, :green, :blue]) @doc "This is an override of the validate/1 callback, where you can fully control how validations are applied" def validate(changeset) do changeset |> super() |> validate_length(:name, min: 2, max: 100) end end defstruct ValidateRequiredEmbed do embeds_one :embedded, Embed, required: [message: "embed must be set"] do field(:name, :string, required: true) end end defstruct ValidateLengths do @moduledoc "This module exercises validations on string length" field(:exact, :string, required: [message: "must be 3 characters"], length: [is: 3, message: "must be 3 characters"] ) field(:bounded_graphemes, :string, required: [message: "must be between 1 and 3 graphemes"], length: [min: 1, max: 3, message: "must be between 1 and 3 graphemes"] ) field(:bounded_bytes, :string, required: [message: "must be between 1 and 3 bytes"], length: [count: :bytes, min: 1, max: 3, message: "must be between 1 and 3 bytes"] ) end defstruct ValidateSets do @moduledoc "This module exercises validations based on set membership" field(:one_of, :string, one_of: [values: ["a", "b", "c"], message: "must be one of [a, b, c]"]) field(:none_of, :string, none_of: [values: ["a", "b", "c"], message: "cannot be one of [a, b, c]"] ) field(:subset_of, {:array, :string}, subset_of: [values: ["a", "b", "c"]]) end defstruct ValidateNumbers do @moduledoc "This module exercises validations on numbers" field(:bounds, :integer, number: [greater_than: 1, less_than: 100]) field(:bounds_inclusive, :integer, number: [greater_than_or_equal_to: 1, less_than_or_equal_to: 100] ) field(:eq, :integer, number: [equal_to: 1]) field(:neq, :integer, number: [not_equal_to: 1]) field(:range, :integer, range: 1..100) end defstruct ValidationPipelines do @moduledoc "This module exercises validation pipeline functionality" @allowed_content_types ["application/json", "application/pdf", "text/csv"] field(:filename, :string, required: true, format: ~r/.+\.([a-z][a-z0-9])+/) field(:content_type, :string, required: true) field(:content, :binary, default: <<>>) validation(:validate_filename) validation( :validate_content_type when changeset.action == :update and is_map_key(changeset.changes, :content_type) ) validation(Strukt.Test.Validators.ValidateFileAndContentType, @allowed_content_types) defp validate_filename(changeset, _opts), do: changeset defp validate_content_type(changeset, _opts), do: Ecto.Changeset.add_error(changeset, :content_type, "cannot change content type") end end
test/support/defstruct_fixtures.ex
0.859221
0.527195
defstruct_fixtures.ex
starcoder
defmodule Que do use Application @moduledoc """ `Que` is a simple background job processing library backed by `Mnesia`. Que doesn't depend on any external services like Redis for persisting job state, instead uses the built-in erlang application [`mnesia`](http://erlang.org/doc/man/mnesia.html). This makes it extremely easy to use as you don't need to install anything other than Que itself. ## Installation First add it as a dependency in your `mix.exs` and run `mix deps.get`: ``` defp deps do [{:que, "~> #{Que.Mixfile.project[:version]}"}] end ``` Then run `$ mix deps.get` and add it to your list of applications: ``` def application do [applications: [:que]] end ``` ## Usage Define a [`Worker`](Que.Worker.html) to process your jobs: ``` defmodule App.Workers.ImageConverter do use Que.Worker def perform(image) do ImageTool.save_resized_copy!(image, :thumbnail) ImageTool.save_resized_copy!(image, :medium) ImageTool.save_resized_copy!(image, :large) end end ``` You can now add jobs to be processed by the worker: ``` Que.add(App.Workers.ImageConverter, some_image) #=> :ok ``` Read the `Que.Worker` documentation for other callbacks and concurrency options. ## Persist to Disk By default, `Que` uses an in-memory `Mnesia` database so jobs are NOT persisted across application restarts. To do that, you first need to specify a path for your mnesia database in you `config.exs`. ``` config :mnesia, dir: 'mnesia/\#{Mix.env}/\#{node()}' # Notice the single quotes ``` You can now call the `que.setup` mix task to create the job database: ```bash $ mix que.setup ``` For compiled releases, see the `Que.Persistence.Mnesia` documentation. """ @doc """ Starts the Que Application (and its Supervision Tree) """ def start(_type, _args) do Que.Helpers.log("Booting Que", :low) Que.Supervisor.start_link end @doc """ Enqueues a Job to be processed by Que. Accepts the worker module name and a term to be passed to the worker as arguments. ## Example ``` Que.add(App.Workers.FileDownloader, {"http://example.com/file/path.zip", "/some/local/path.zip"}) #=> :ok Que.add(App.Workers.SignupMailer, to: "<EMAIL>", message: "Thank you for Signing up!") #=> :ok ``` """ @spec add(worker :: module, arguments :: term) :: {:ok, %Que.Job{}} defdelegate add(worker, arguments), to: Que.ServerSupervisor @spec add(priority :: atom, worker :: module, arguments :: term) :: :ok defdelegate add(priority, worker, arguments), to: Que.ServerSupervisor @spec remote_add(node :: any, worker :: module, arguments :: term) :: :ok defdelegate remote_add(node, worker, arguments), to: Que.ServerSupervisor @spec remote_add(node :: any, priority :: atom, worker :: module, arguments :: term) :: :ok defdelegate remote_add(node, priority, worker, arguments), to: Que.ServerSupervisor @spec remote_async_add(node :: any, worker :: module, arguments :: term) :: :ok defdelegate remote_async_add(node, worker, arguments), to: Que.ServerSupervisor @spec remote_async_add(node :: any, priority :: atom, worker :: module, arguments :: term) :: :ok defdelegate remote_async_add(node, priority, worker, arguments), to: Que.ServerSupervisor @spec pri0(worker :: module, arguments :: term) :: :ok defdelegate pri0(worker, arguments), to: Que.ServerSupervisor @spec pri1(worker :: module, arguments :: term) :: :ok defdelegate pri1(worker, arguments), to: Que.ServerSupervisor @spec pri2(worker :: module, arguments :: term) :: :ok defdelegate pri2(worker, arguments), to: Que.ServerSupervisor @spec pri3(worker :: module, arguments :: term) :: :ok defdelegate pri3(worker, arguments), to: Que.ServerSupervisor end
lib/que.ex
0.787032
0.862468
que.ex
starcoder
defmodule Credo.Check.Refactor.ABCSize do @moduledoc false @checkdoc """ The ABC size describes a metric based on assignments, branches and conditions. A high ABC size is a hint that a function might be doing "more" than it should. As always: Take any metric with a grain of salt. Since this one was originally introduced for C, C++ and Java, we still have to see whether or not this can be a useful metric in a declarative language like Elixir. """ @explanation [ check: @checkdoc, params: [ max_size: "The maximum ABC size a function should have.", excluded_functions: "All functions listed will be ignored." ] ] @default_params [ max_size: 30, excluded_functions: [] ] @ecto_functions ["where", "from", "select", "join"] @def_ops [:def, :defp, :defmacro] @branch_ops [:.] @condition_ops [:if, :unless, :for, :try, :case, :cond, :and, :or, :&&, :||] @non_calls [:==, :fn, :__aliases__, :__block__, :if, :or, :|>, :%{}] use Credo.Check @doc false def run(source_file, params \\ []) do ignore_ecto? = imports_ecto_query?(source_file) issue_meta = IssueMeta.for(source_file, params) max_abc_size = Params.get(params, :max_size, @default_params) excluded_functions = Params.get(params, :excluded_functions, @default_params) excluded_functions = if ignore_ecto? do @ecto_functions ++ excluded_functions else excluded_functions end Credo.Code.prewalk( source_file, &traverse(&1, &2, issue_meta, max_abc_size, excluded_functions) ) end defp imports_ecto_query?(source_file), do: Credo.Code.prewalk(source_file, &traverse_for_ecto/2, false) defp traverse_for_ecto(_, true), do: {nil, true} defp traverse_for_ecto({:import, _, [{:__aliases__, _, [:Ecto, :Query]} | _]}, false), do: {nil, true} defp traverse_for_ecto(ast, false), do: {ast, false} defp traverse( {:defmacro, _, [{:__using__, _, _}, _]} = ast, issues, _issue_meta, _max_abc_size, _excluded_functions ) do {ast, issues} end for op <- @def_ops do defp traverse( {unquote(op), meta, arguments} = ast, issues, issue_meta, max_abc_size, excluded_functions ) when is_list(arguments) do abc_size = ast |> abc_size_for(excluded_functions) |> round if abc_size > max_abc_size do fun_name = Credo.Code.Module.def_name(ast) {ast, [ issue_for(issue_meta, meta[:line], fun_name, max_abc_size, abc_size) | issues ]} else {ast, issues} end end end defp traverse(ast, issues, _issue_meta, _max_abc_size, _excluded_functions) do {ast, issues} end @doc """ Returns the ABC size for the block inside the given AST, which is expected to represent a function or macro definition. iex> {:def, [line: 1], ...> [ ...> {:first_fun, [line: 1], nil}, ...> [do: {:=, [line: 2], [{:x, [line: 2], nil}, 1]}] ...> ] ...> } |> Credo.Check.Refactor.ABCSize.abc_size 1.0 """ def abc_size_for({_def_op, _meta, arguments}, excluded_functions) when is_list(arguments) do arguments |> Credo.Code.Block.do_block_for!() |> abc_size_for(arguments, excluded_functions) end @doc false def abc_size_for(nil, _arguments, _excluded_functions), do: 0 def abc_size_for(ast, arguments, excluded_functions) do initial_acc = [a: 0, b: 0, c: 0, var_names: get_parameters(arguments)] [a: a, b: b, c: c, var_names: _] = Credo.Code.prewalk(ast, &traverse_abc(&1, &2, excluded_functions), initial_acc) :math.sqrt(a * a + b * b + c * c) end defp get_parameters(arguments) do case Enum.at(arguments, 0) do {_name, _meta, nil} -> [] {_name, _meta, parameters} -> Enum.map(parameters, &var_name/1) end end for op <- @def_ops do defp traverse_abc({unquote(op), _, arguments} = ast, abc, _excluded_functions) when is_list(arguments) do {ast, abc} end end # Ignore string interpolation defp traverse_abc({:<<>>, _, _}, acc, _excluded_functions) do {nil, acc} end # A - assignments defp traverse_abc( {:=, _meta, [lhs | rhs]}, [a: a, b: b, c: c, var_names: var_names], _excluded_functions ) do var_names = case var_name(lhs) do nil -> var_names false -> var_names name -> var_names ++ [name] end {rhs, [a: a + 1, b: b, c: c, var_names: var_names]} end # B - branch defp traverse_abc( {:->, _meta, arguments} = ast, [a: a, b: b, c: c, var_names: var_names], _excluded_functions ) do var_names = var_names ++ fn_parameters(arguments) {ast, [a: a, b: b + 1, c: c, var_names: var_names]} end for op <- @branch_ops do defp traverse_abc( {unquote(op), _meta, [{_, _, nil}, _] = arguments} = ast, [a: a, b: b, c: c, var_names: var_names], _excluded_functions ) when is_list(arguments) do {ast, [a: a, b: b, c: c, var_names: var_names]} end defp traverse_abc( {unquote(op), _meta, arguments} = ast, [a: a, b: b, c: c, var_names: var_names], _excluded_functions ) when is_list(arguments) do {ast, [a: a, b: b + 1, c: c, var_names: var_names]} end end defp traverse_abc( {fun_name, _meta, arguments} = ast, [a: a, b: b, c: c, var_names: var_names], excluded_functions ) when is_atom(fun_name) and not (fun_name in @non_calls) and is_list(arguments) do if Enum.member?(excluded_functions, to_string(fun_name)) do {nil, [a: a, b: b, c: c, var_names: var_names]} else {ast, [a: a, b: b + 1, c: c, var_names: var_names]} end end defp traverse_abc( {fun_or_var_name, _meta, nil} = ast, [a: a, b: b, c: c, var_names: var_names], _excluded_functions ) do is_variable = Enum.member?(var_names, fun_or_var_name) if is_variable do {ast, [a: a, b: b, c: c, var_names: var_names]} else {ast, [a: a, b: b + 1, c: c, var_names: var_names]} end end # C - conditions for op <- @condition_ops do defp traverse_abc( {unquote(op), _meta, arguments} = ast, [a: a, b: b, c: c, var_names: var_names], _excluded_functions ) when is_list(arguments) do {ast, [a: a, b: b, c: c + 1, var_names: var_names]} end end defp traverse_abc(ast, abc, _excluded_functions) do {ast, abc} end defp var_name({name, _, nil}) when is_atom(name), do: name defp var_name(_), do: nil defp fn_parameters([params, tuple]) when is_list(params) and is_tuple(tuple) do fn_parameters(params) end defp fn_parameters([[{:when, _, params}], _]) when is_list(params) do fn_parameters(params) end defp fn_parameters(params) when is_list(params) do params |> Enum.map(&var_name/1) |> Enum.reject(&is_nil/1) end defp issue_for(issue_meta, line_no, trigger, max_value, actual_value) do format_issue( issue_meta, message: "Function is too complex (ABC size is #{actual_value}, max is #{max_value}).", trigger: trigger, line_no: line_no, severity: Severity.compute(actual_value, max_value) ) end end
lib/credo/check/refactor/abc_size.ex
0.825449
0.503479
abc_size.ex
starcoder
defmodule AdventOfCode.Day17 do @moduledoc ~S""" [Advent Of Code day 17](https://adventofcode.com/2018/day/17). """ @sand "." @clay "#" @flow "|" @rest "~" import AdventOfCode.Utils, only: [map_increment: 2] def solve("1", input) do with %{"~" => a, "|" => b} <- do_solve(input), do: a + b end def solve("2", input) do with %{"~" => a} <- do_solve(input), do: a end defp do_solve(input) do {start_point, grid} = parse_input(input) {min_y, max_y} = Enum.map(grid, fn {{_x, y}, _} -> y end) |> Enum.min_max() grid |> drop_water(start_point, max_y) |> Enum.reduce(%{}, fn {{_x, y}, value}, acc -> if y >= min_y && y <= max_y do map_increment(acc, value) else acc end end) end defp drop_water(grid, {_x, y}, max_y) when y >= max_y, do: grid defp drop_water(grid, {x, y}, max_y) do [:down, :left, :right, :fill] |> Enum.reduce(grid, fn dir, acc -> do_drop_water(dir, acc, {x, y}, max_y) end) end defp do_drop_water(:fill, grid, current, max_y), do: flow(:fill, grid, max_y, {current, nil}, nil) defp do_drop_water(dir, grid, {x, y}, max_y) do next = next(dir, grid, {x, y}) bottom_value = Map.get(grid, {x, y + 1}, @sand) flow(dir, grid, max_y, next, bottom_value) end defp next(:down, grid, {x, y}), do: {{x, y + 1}, Map.get(grid, {x, y + 1}, @sand)} defp next(:left, grid, {x, y}), do: {{x - 1, y}, Map.get(grid, {x - 1, y}, @sand)} defp next(:right, grid, {x, y}), do: {{x + 1, y}, Map.get(grid, {x + 1, y}, @sand)} defp flow(:down, grid, max_y, {next, @sand}, _) do Map.put(grid, next, @flow) |> drop_water(next, max_y) end defp flow(:left, grid, max_y, {next, @sand}, bottom) when bottom in [@clay, @rest] do Map.put(grid, next, @flow) |> drop_water(next, max_y) end defp flow(:right, grid, max_y, {next, @sand}, bottom) when bottom in [@clay, @rest] do Map.put(grid, next, @flow) |> drop_water(next, max_y) end defp flow(:fill, grid, _max_y, {current, _}, _) do if inside_reservoir?(grid, current), do: rest_line(grid, current), else: grid end defp flow(_, grid, _, _, _), do: grid defp inside_reservoir?(grid, {x, y}) do grid[{x, y}] in [@flow, @sand] && do_check_inside_reservoir(grid, x, y, -1) && do_check_inside_reservoir(grid, x, y, +1) end defp do_check_inside_reservoir(grid, x, y, step) do bottom_ok = grid[{x, y + 1}] in [@clay, @rest] next = grid[{x + step, y}] cond do bottom_ok && next == @clay -> x + step bottom_ok && next == @flow -> do_check_inside_reservoir(grid, x + step, y, step) true -> false end end defp rest_line(grid, {x, y}) do from_x = do_check_inside_reservoir(grid, x, y, -1) to_x = do_check_inside_reservoir(grid, x, y, +1) Enum.reduce((from_x + 1)..(to_x - 1), grid, &Map.put(&2, {&1, y}, @rest)) end defp parse_input(input) do input |> Enum.reduce(%{}, fn line, map -> parse_line(line) |> Enum.reduce(map, fn point, acc -> Map.put(acc, point, @clay) end) end) |> normalize_grid() end defp normalize_grid(grid) do {{min_x, _}, _} = Enum.min_by(grid, fn {{x, _}, _} -> x end) normalized = Enum.into(grid, %{}, fn {{x, y}, value} -> {{x - min_x, y}, value} end) |> Map.put({500 - min_x, 0}, "+") {{500 - min_x, 0}, normalized} end defp parse_line(line) do map = %{} = Regex.named_captures(~r/(?<a>x|y)=(?<a_value>\d+), (?<b>x|y)=(?<b_from>\d+)\.\.(?<b_to>\d+)/, line) for coord <- String.to_integer(map["b_from"])..String.to_integer(map["b_to"]) do a_value = String.to_integer(map["a_value"]) if map["a"] == "x" do {a_value, coord} else {coord, a_value} end end end defp print_grid(grid, max_y) do {min_x, max_x} = Enum.map(grid, fn {{x, _y}, _} -> x end) |> Enum.min_max() Enum.map(0..max_y, fn y -> Enum.map(min_x..max_x, fn x -> Map.get(grid, {x, y}, @sand) end) |> Enum.join() end) |> Enum.join("\n") end end
lib/advent_of_code/day_17.ex
0.715424
0.687931
day_17.ex
starcoder
defmodule AWS.Chime do @moduledoc """ The Amazon Chime API (application programming interface) is designed for developers to perform key tasks, such as creating and managing Amazon Chime accounts, users, and Voice Connectors. This guide provides detailed information about the Amazon Chime API, including operations, types, inputs and outputs, and error codes. It also includes API actions for use with the Amazon Chime SDK, which developers use to build their own communication applications. For more information about the Amazon Chime SDK, see [ Using the Amazon Chime SDK ](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. You can use an AWS SDK, the AWS Command Line Interface (AWS CLI), or the REST API to make API calls. We recommend using an AWS SDK or the AWS CLI. Each API operation includes links to information about using it with a language-specific AWS SDK or the AWS CLI. ## Definitions ### Using an AWS SDK You don't need to write code to calculate a signature for request authentication. The SDK clients authenticate your requests by using access keys that you provide. For more information about AWS SDKs, see the [AWS Developer Center](http://aws.amazon.com/developer/). ### Using the AWS CLI Use your access keys with the AWS CLI to make API calls. For information about setting up the AWS CLI, see [Installing the AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/installing.html) in the *AWS Command Line Interface User Guide*. For a list of available Amazon Chime commands, see the [Amazon Chime commands](https://docs.aws.amazon.com/cli/latest/reference/chime/index.html) in the *AWS CLI Command Reference*. ### Using REST APIs If you use REST to make API calls, you must authenticate your request by providing a signature. Amazon Chime supports signature version 4. For more information, see [Signature Version 4 Signing Process](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) in the *Amazon Web Services General Reference*. When making REST API calls, use the service name `chime` and REST endpoint `https://service.chime.aws.amazon.com`. Administrative permissions are controlled using AWS Identity and Access Management (IAM). For more information, see [Identity and Access Management for Amazon Chime](https://docs.aws.amazon.com/chime/latest/ag/security-iam.html) in the *Amazon Chime Administration Guide*. """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: nil, api_version: "2018-05-01", content_type: "application/x-amz-json-1.1", credential_scope: "us-east-1", endpoint_prefix: "chime", global?: true, protocol: "rest-json", service_id: "Chime", signature_version: "v4", signing_name: "chime", target_prefix: nil } end @doc """ Associates a phone number with the specified Amazon Chime user. """ def associate_phone_number_with_user( %Client{} = client, account_id, user_id, input, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users/#{AWS.Util.encode_uri(user_id)}?operation=associate-phone-number" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Associates phone numbers with the specified Amazon Chime Voice Connector. """ def associate_phone_numbers_with_voice_connector( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}?operation=associate-phone-numbers" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Associates phone numbers with the specified Amazon Chime Voice Connector group. """ def associate_phone_numbers_with_voice_connector_group( %Client{} = client, voice_connector_group_id, input, options \\ [] ) do url_path = "/voice-connector-groups/#{AWS.Util.encode_uri(voice_connector_group_id)}?operation=associate-phone-numbers" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Associates the specified sign-in delegate groups with the specified Amazon Chime account. """ def associate_signin_delegate_groups_with_account( %Client{} = client, account_id, input, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}?operation=associate-signin-delegate-groups" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Creates up to 100 new attendees for an active Amazon Chime SDK meeting. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def batch_create_attendee(%Client{} = client, meeting_id, input, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/attendees?operation=batch-create" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Adds a specified number of users to a channel. """ def batch_create_channel_membership(%Client{} = client, channel_arn, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/memberships?operation=batch-create" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Adds up to 50 members to a chat room in an Amazon Chime Enterprise account. Members can be users or bots. The member role designates whether the member is a chat room administrator or a general chat room member. """ def batch_create_room_membership(%Client{} = client, account_id, room_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/rooms/#{AWS.Util.encode_uri(room_id)}/memberships?operation=batch-create" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Moves phone numbers into the **Deletion queue**. Phone numbers must be disassociated from any users or Amazon Chime Voice Connectors before they can be deleted. Phone numbers remain in the **Deletion queue** for 7 days before they are deleted permanently. """ def batch_delete_phone_number(%Client{} = client, input, options \\ []) do url_path = "/phone-numbers?operation=batch-delete" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Suspends up to 50 users from a `Team` or `EnterpriseLWA` Amazon Chime account. For more information about different account types, see [Managing Your Amazon Chime Accounts](https://docs.aws.amazon.com/chime/latest/ag/manage-chime-account.html) in the *Amazon Chime Administration Guide*. Users suspended from a `Team` account are disassociated from the account,but they can continue to use Amazon Chime as free users. To remove the suspension from suspended `Team` account users, invite them to the `Team` account again. You can use the `InviteUsers` action to do so. Users suspended from an `EnterpriseLWA` account are immediately signed out of Amazon Chime and can no longer sign in. To remove the suspension from suspended `EnterpriseLWA` account users, use the `BatchUnsuspendUser` action. To sign out users without suspending them, use the `LogoutUser` action. """ def batch_suspend_user(%Client{} = client, account_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users?operation=suspend" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Removes the suspension from up to 50 previously suspended users for the specified Amazon Chime `EnterpriseLWA` account. Only users on `EnterpriseLWA` accounts can be unsuspended using this action. For more information about different account types, see [ Managing Your Amazon Chime Accounts ](https://docs.aws.amazon.com/chime/latest/ag/manage-chime-account.html) in the account types, in the *Amazon Chime Administration Guide*. Previously suspended users who are unsuspended using this action are returned to `Registered` status. Users who are not previously suspended are ignored. """ def batch_unsuspend_user(%Client{} = client, account_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users?operation=unsuspend" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates phone number product types or calling names. You can update one attribute at a time for each `UpdatePhoneNumberRequestItem`. For example, you can update the product type or the calling name. For toll-free numbers, you cannot use the Amazon Chime Business Calling product type. For numbers outside the U.S., you must use the Amazon Chime SIP Media Application Dial-In product type. Updates to outbound calling names can take up to 72 hours to complete. Pending updates to outbound calling names must be complete before you can request another update. """ def batch_update_phone_number(%Client{} = client, input, options \\ []) do url_path = "/phone-numbers?operation=batch-update" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates user details within the `UpdateUserRequestItem` object for up to 20 users for the specified Amazon Chime account. Currently, only `LicenseType` updates are supported for this action. """ def batch_update_user(%Client{} = client, account_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Creates an Amazon Chime account under the administrator's AWS account. Only `Team` account types are currently supported for this action. For more information about different account types, see [Managing Your Amazon Chime Accounts](https://docs.aws.amazon.com/chime/latest/ag/manage-chime-account.html) in the *Amazon Chime Administration Guide*. """ def create_account(%Client{} = client, input, options \\ []) do url_path = "/accounts" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates an Amazon Chime SDK messaging `AppInstance` under an AWS account. Only SDK messaging customers use this API. `CreateAppInstance` supports idempotency behavior as described in the AWS API Standard. """ def create_app_instance(%Client{} = client, input, options \\ []) do url_path = "/app-instances" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Promotes an `AppInstanceUser` to an `AppInstanceAdmin`. The promoted user can perform the following actions. * `ChannelModerator` actions across all channels in the `AppInstance`. * `DeleteChannelMessage` actions. Only an `AppInstanceUser` can be promoted to an `AppInstanceAdmin` role. """ def create_app_instance_admin(%Client{} = client, app_instance_arn, input, options \\ []) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}/admins" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a user under an Amazon Chime `AppInstance`. The request consists of a unique `appInstanceUserId` and `Name` for that user. """ def create_app_instance_user(%Client{} = client, input, options \\ []) do url_path = "/app-instance-users" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a new attendee for an active Amazon Chime SDK meeting. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def create_attendee(%Client{} = client, meeting_id, input, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/attendees" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a bot for an Amazon Chime Enterprise account. """ def create_bot(%Client{} = client, account_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/bots" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a channel to which you can add users and send messages. **Restriction**: You can't change a channel's privacy. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def create_channel(%Client{} = client, input, options \\ []) do url_path = "/channels" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Permanently bans a member from a channel. Moderators can't add banned members to a channel. To undo a ban, you first have to `DeleteChannelBan`, and then `CreateChannelMembership`. Bans are cleaned up when you delete users or channels. If you ban a user who is already part of a channel, that user is automatically kicked from the channel. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def create_channel_ban(%Client{} = client, channel_arn, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/bans" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Adds a user to a channel. The `InvitedBy` response field is derived from the request header. A channel member can: * List messages * Send messages * Receive messages * Edit their own messages * Leave the channel Privacy settings impact this action as follows: * Public Channels: You do not need to be a member to list messages, but you must be a member to send messages. * Private Channels: You must be a member to list or send messages. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def create_channel_membership(%Client{} = client, channel_arn, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/memberships" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a new `ChannelModerator`. A channel moderator can: * Add and remove other members of the channel. * Add and remove other moderators of the channel. * Add and remove user bans for the channel. * Redact messages in the channel. * List messages in the channel. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def create_channel_moderator(%Client{} = client, channel_arn, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/moderators" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a media capture pipeline. """ def create_media_capture_pipeline(%Client{} = client, input, options \\ []) do url_path = "/media-capture-pipelines" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a new Amazon Chime SDK meeting in the specified media Region with no initial attendees. For more information about specifying media Regions, see [Amazon Chime SDK Media Regions](https://docs.aws.amazon.com/chime/latest/dg/chime-sdk-meetings-regions.html) in the *Amazon Chime Developer Guide* . For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide* . """ def create_meeting(%Client{} = client, input, options \\ []) do url_path = "/meetings" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Uses the join token and call metadata in a meeting request (From number, To number, and so forth) to initiate an outbound call to a public switched telephone network (PSTN) and join them into a Chime meeting. Also ensures that the From number belongs to the customer. To play welcome audio or implement an interactive voice response (IVR), use the `CreateSipMediaApplicationCall` action with the corresponding SIP media application ID. """ def create_meeting_dial_out(%Client{} = client, meeting_id, input, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/dial-outs" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a new Amazon Chime SDK meeting in the specified media Region, with attendees. For more information about specifying media Regions, see [Amazon Chime SDK Media Regions](https://docs.aws.amazon.com/chime/latest/dg/chime-sdk-meetings-regions.html) in the *Amazon Chime Developer Guide* . For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide* . """ def create_meeting_with_attendees(%Client{} = client, input, options \\ []) do url_path = "/meetings?operation=create-attendees" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates an order for phone numbers to be provisioned. For toll-free numbers, you cannot use the Amazon Chime Business Calling product type. For numbers outside the U.S., you must use the Amazon Chime SIP Media Application Dial-In product type. """ def create_phone_number_order(%Client{} = client, input, options \\ []) do url_path = "/phone-number-orders" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a proxy session on the specified Amazon Chime Voice Connector for the specified participant phone numbers. """ def create_proxy_session(%Client{} = client, voice_connector_id, input, options \\ []) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/proxy-sessions" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a chat room for the specified Amazon Chime Enterprise account. """ def create_room(%Client{} = client, account_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/rooms" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Adds a member to a chat room in an Amazon Chime Enterprise account. A member can be either a user or a bot. The member role designates whether the member is a chat room administrator or a general chat room member. """ def create_room_membership(%Client{} = client, account_id, room_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/rooms/#{AWS.Util.encode_uri(room_id)}/memberships" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a SIP media application. """ def create_sip_media_application(%Client{} = client, input, options \\ []) do url_path = "/sip-media-applications" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates an outbound call to a phone number from the phone number specified in the request, and it invokes the endpoint of the specified `sipMediaApplicationId`. """ def create_sip_media_application_call( %Client{} = client, sip_media_application_id, input, options \\ [] ) do url_path = "/sip-media-applications/#{AWS.Util.encode_uri(sip_media_application_id)}/calls" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a SIP rule which can be used to run a SIP media application as a target for a specific trigger type. """ def create_sip_rule(%Client{} = client, input, options \\ []) do url_path = "/sip-rules" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates a user under the specified Amazon Chime account. """ def create_user(%Client{} = client, account_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users?operation=create" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates an Amazon Chime Voice Connector under the administrator's AWS account. You can choose to create an Amazon Chime Voice Connector in a specific AWS Region. Enabling `CreateVoiceConnectorRequest$RequireEncryption` configures your Amazon Chime Voice Connector to use TLS transport for SIP signaling and Secure RTP (SRTP) for media. Inbound calls use TLS transport, and unencrypted outbound calls are blocked. """ def create_voice_connector(%Client{} = client, input, options \\ []) do url_path = "/voice-connectors" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Creates an Amazon Chime Voice Connector group under the administrator's AWS account. You can associate Amazon Chime Voice Connectors with the Amazon Chime Voice Connector group by including `VoiceConnectorItems` in the request. You can include Amazon Chime Voice Connectors from different AWS Regions in your group. This creates a fault tolerant mechanism for fallback in case of availability events. """ def create_voice_connector_group(%Client{} = client, input, options \\ []) do url_path = "/voice-connector-groups" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Deletes the specified Amazon Chime account. You must suspend all users before deleting `Team` account. You can use the `BatchSuspendUser` action to dodo. For `EnterpriseLWA` and `EnterpriseAD` accounts, you must release the claimed domains for your Amazon Chime account before deletion. As soon as you release the domain, all users under that account are suspended. Deleted accounts appear in your `Disabled` accounts list for 90 days. To restore deleted account from your `Disabled` accounts list, you must contact AWS Support. After 90 days, deleted accounts are permanently removed from your `Disabled` accounts list. """ def delete_account(%Client{} = client, account_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes an `AppInstance` and all associated data asynchronously. """ def delete_app_instance(%Client{} = client, app_instance_arn, input, options \\ []) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Demotes an `AppInstanceAdmin` to an `AppInstanceUser`. This action does not delete the user. """ def delete_app_instance_admin( %Client{} = client, app_instance_admin_arn, app_instance_arn, input, options \\ [] ) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}/admins/#{AWS.Util.encode_uri(app_instance_admin_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the streaming configurations of an `AppInstance`. """ def delete_app_instance_streaming_configurations( %Client{} = client, app_instance_arn, input, options \\ [] ) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}/streaming-configurations" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes an `AppInstanceUser`. """ def delete_app_instance_user(%Client{} = client, app_instance_user_arn, input, options \\ []) do url_path = "/app-instance-users/#{AWS.Util.encode_uri(app_instance_user_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes an attendee from the specified Amazon Chime SDK meeting and deletes their `JoinToken`. Attendees are automatically deleted when a Amazon Chime SDK meeting is deleted. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def delete_attendee(%Client{} = client, attendee_id, meeting_id, input, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/attendees/#{AWS.Util.encode_uri(attendee_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Immediately makes a channel and its memberships inaccessible and marks them for deletion. This is an irreversible process. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def delete_channel(%Client{} = client, channel_arn, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Removes a user from a channel's ban list. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def delete_channel_ban(%Client{} = client, channel_arn, member_arn, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/bans/#{AWS.Util.encode_uri(member_arn)}" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Removes a member from a channel. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def delete_channel_membership(%Client{} = client, channel_arn, member_arn, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/memberships/#{AWS.Util.encode_uri(member_arn)}" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes a channel message. Only admins can perform this action. Deletion makes messages inaccessible immediately. A background process deletes any revisions created by `UpdateChannelMessage`. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def delete_channel_message(%Client{} = client, channel_arn, message_id, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/messages/#{AWS.Util.encode_uri(message_id)}" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes a channel moderator. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def delete_channel_moderator( %Client{} = client, channel_arn, channel_moderator_arn, input, options \\ [] ) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/moderators/#{AWS.Util.encode_uri(channel_moderator_arn)}" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the events configuration that allows a bot to receive outgoing events. """ def delete_events_configuration(%Client{} = client, account_id, bot_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/bots/#{AWS.Util.encode_uri(bot_id)}/events-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the media capture pipeline. """ def delete_media_capture_pipeline(%Client{} = client, media_pipeline_id, input, options \\ []) do url_path = "/media-capture-pipelines/#{AWS.Util.encode_uri(media_pipeline_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the specified Amazon Chime SDK meeting. The operation deletes all attendees, disconnects all clients, and prevents new clients from joining the meeting. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def delete_meeting(%Client{} = client, meeting_id, input, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Moves the specified phone number into the **Deletion queue**. A phone number must be disassociated from any users or Amazon Chime Voice Connectors before it can be deleted. Deleted phone numbers remain in the **Deletion queue** for 7 days before they are deleted permanently. """ def delete_phone_number(%Client{} = client, phone_number_id, input, options \\ []) do url_path = "/phone-numbers/#{AWS.Util.encode_uri(phone_number_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the specified proxy session from the specified Amazon Chime Voice Connector. """ def delete_proxy_session( %Client{} = client, proxy_session_id, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/proxy-sessions/#{AWS.Util.encode_uri(proxy_session_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes a chat room in an Amazon Chime Enterprise account. """ def delete_room(%Client{} = client, account_id, room_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/rooms/#{AWS.Util.encode_uri(room_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Removes a member from a chat room in an Amazon Chime Enterprise account. """ def delete_room_membership( %Client{} = client, account_id, member_id, room_id, input, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/rooms/#{AWS.Util.encode_uri(room_id)}/memberships/#{AWS.Util.encode_uri(member_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes a SIP media application. """ def delete_sip_media_application( %Client{} = client, sip_media_application_id, input, options \\ [] ) do url_path = "/sip-media-applications/#{AWS.Util.encode_uri(sip_media_application_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes a SIP rule. You must disable a SIP rule before you can delete it. """ def delete_sip_rule(%Client{} = client, sip_rule_id, input, options \\ []) do url_path = "/sip-rules/#{AWS.Util.encode_uri(sip_rule_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the specified Amazon Chime Voice Connector. Any phone numbers associated with the Amazon Chime Voice Connector must be disassociated from it before it can be deleted. """ def delete_voice_connector(%Client{} = client, voice_connector_id, input, options \\ []) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the emergency calling configuration details from the specified Amazon Chime Voice Connector. """ def delete_voice_connector_emergency_calling_configuration( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/emergency-calling-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the specified Amazon Chime Voice Connector group. Any `VoiceConnectorItems` and phone numbers associated with the group must be removed before it can be deleted. """ def delete_voice_connector_group( %Client{} = client, voice_connector_group_id, input, options \\ [] ) do url_path = "/voice-connector-groups/#{AWS.Util.encode_uri(voice_connector_group_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the origination settings for the specified Amazon Chime Voice Connector. If emergency calling is configured for the Amazon Chime Voice Connector, it must be deleted prior to deleting the origination settings. """ def delete_voice_connector_origination( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/origination" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the proxy configuration from the specified Amazon Chime Voice Connector. """ def delete_voice_connector_proxy(%Client{} = client, voice_connector_id, input, options \\ []) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/programmable-numbers/proxy" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the streaming configuration for the specified Amazon Chime Voice Connector. """ def delete_voice_connector_streaming_configuration( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/streaming-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the termination settings for the specified Amazon Chime Voice Connector. If emergency calling is configured for the Amazon Chime Voice Connector, it must be deleted prior to deleting the termination settings. """ def delete_voice_connector_termination( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/termination" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes the specified SIP credentials used by your equipment to authenticate during call termination. """ def delete_voice_connector_termination_credentials( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/termination/credentials?operation=delete" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 204 ) end @doc """ Returns the full details of an `AppInstance`. """ def describe_app_instance(%Client{} = client, app_instance_arn, options \\ []) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the full details of an `AppInstanceAdmin`. """ def describe_app_instance_admin( %Client{} = client, app_instance_admin_arn, app_instance_arn, options \\ [] ) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}/admins/#{AWS.Util.encode_uri(app_instance_admin_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the full details of an `AppInstanceUser`. """ def describe_app_instance_user(%Client{} = client, app_instance_user_arn, options \\ []) do url_path = "/app-instance-users/#{AWS.Util.encode_uri(app_instance_user_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the full details of a channel in an Amazon Chime `AppInstance`. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def describe_channel(%Client{} = client, channel_arn, chime_bearer \\ nil, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the full details of a channel ban. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def describe_channel_ban( %Client{} = client, channel_arn, member_arn, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/bans/#{AWS.Util.encode_uri(member_arn)}" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the full details of a user's channel membership. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def describe_channel_membership( %Client{} = client, channel_arn, member_arn, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/memberships/#{AWS.Util.encode_uri(member_arn)}" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the details of a channel based on the membership of the specified `AppInstanceUser`. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def describe_channel_membership_for_app_instance_user( %Client{} = client, channel_arn, app_instance_user_arn, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}?scope=app-instance-user-membership" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] query_params = if !is_nil(app_instance_user_arn) do [{"app-instance-user-arn", app_instance_user_arn} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the full details of a channel moderated by the specified `AppInstanceUser`. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def describe_channel_moderated_by_app_instance_user( %Client{} = client, channel_arn, app_instance_user_arn, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}?scope=app-instance-user-moderated-channel" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] query_params = if !is_nil(app_instance_user_arn) do [{"app-instance-user-arn", app_instance_user_arn} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the full details of a single ChannelModerator. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def describe_channel_moderator( %Client{} = client, channel_arn, channel_moderator_arn, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/moderators/#{AWS.Util.encode_uri(channel_moderator_arn)}" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Disassociates the primary provisioned phone number from the specified Amazon Chime user. """ def disassociate_phone_number_from_user( %Client{} = client, account_id, user_id, input, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users/#{AWS.Util.encode_uri(user_id)}?operation=disassociate-phone-number" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Disassociates the specified phone numbers from the specified Amazon Chime Voice Connector. """ def disassociate_phone_numbers_from_voice_connector( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}?operation=disassociate-phone-numbers" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Disassociates the specified phone numbers from the specified Amazon Chime Voice Connector group. """ def disassociate_phone_numbers_from_voice_connector_group( %Client{} = client, voice_connector_group_id, input, options \\ [] ) do url_path = "/voice-connector-groups/#{AWS.Util.encode_uri(voice_connector_group_id)}?operation=disassociate-phone-numbers" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Disassociates the specified sign-in delegate groups from the specified Amazon Chime account. """ def disassociate_signin_delegate_groups_from_account( %Client{} = client, account_id, input, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}?operation=disassociate-signin-delegate-groups" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Retrieves details for the specified Amazon Chime account, such as account type and supported licenses. """ def get_account(%Client{} = client, account_id, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Retrieves account settings for the specified Amazon Chime account ID, such as remote control and dialout settings. For more information about these settings, see [Use the Policies Page](https://docs.aws.amazon.com/chime/latest/ag/policies.html) in the *Amazon Chime Administration Guide*. """ def get_account_settings(%Client{} = client, account_id, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/settings" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Gets the retention settings for an `AppInstance`. """ def get_app_instance_retention_settings(%Client{} = client, app_instance_arn, options \\ []) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}/retention-settings" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Gets the streaming settings for an `AppInstance`. """ def get_app_instance_streaming_configurations( %Client{} = client, app_instance_arn, options \\ [] ) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}/streaming-configurations" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Gets the Amazon Chime SDK attendee details for a specified meeting ID and attendee ID. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide* . """ def get_attendee(%Client{} = client, attendee_id, meeting_id, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/attendees/#{AWS.Util.encode_uri(attendee_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves details for the specified bot, such as bot email address, bot type, status, and display name. """ def get_bot(%Client{} = client, account_id, bot_id, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/bots/#{AWS.Util.encode_uri(bot_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Gets the full details of a channel message. The x-amz-chime-bearer request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def get_channel_message( %Client{} = client, channel_arn, message_id, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/messages/#{AWS.Util.encode_uri(message_id)}" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Gets details for an events configuration that allows a bot to receive outgoing events, such as an HTTPS endpoint or Lambda function ARN. """ def get_events_configuration(%Client{} = client, account_id, bot_id, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/bots/#{AWS.Util.encode_uri(bot_id)}/events-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves global settings for the administrator's AWS account, such as Amazon Chime Business Calling and Amazon Chime Voice Connector settings. """ def get_global_settings(%Client{} = client, options \\ []) do url_path = "/settings" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Gets an existing media capture pipeline. """ def get_media_capture_pipeline(%Client{} = client, media_pipeline_id, options \\ []) do url_path = "/media-capture-pipelines/#{AWS.Util.encode_uri(media_pipeline_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Gets the Amazon Chime SDK meeting details for the specified meeting ID. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide* . """ def get_meeting(%Client{} = client, meeting_id, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ The details of the endpoint for the messaging session. """ def get_messaging_session_endpoint(%Client{} = client, options \\ []) do url_path = "/endpoints/messaging-session" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves details for the specified phone number ID, such as associations, capabilities, and product type. """ def get_phone_number(%Client{} = client, phone_number_id, options \\ []) do url_path = "/phone-numbers/#{AWS.Util.encode_uri(phone_number_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Retrieves details for the specified phone number order, such as the order creation timestamp, phone numbers in E.164 format, product type, and order status. """ def get_phone_number_order(%Client{} = client, phone_number_order_id, options \\ []) do url_path = "/phone-number-orders/#{AWS.Util.encode_uri(phone_number_order_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves the phone number settings for the administrator's AWS account, such as the default outbound calling name. """ def get_phone_number_settings(%Client{} = client, options \\ []) do url_path = "/settings/phone-number" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Gets the specified proxy session details for the specified Amazon Chime Voice Connector. """ def get_proxy_session(%Client{} = client, proxy_session_id, voice_connector_id, options \\ []) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/proxy-sessions/#{AWS.Util.encode_uri(proxy_session_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Gets the retention settings for the specified Amazon Chime Enterprise account. For more information about retention settings, see [Managing Chat Retention Policies](https://docs.aws.amazon.com/chime/latest/ag/chat-retention.html) in the *Amazon Chime Administration Guide*. """ def get_retention_settings(%Client{} = client, account_id, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/retention-settings" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Retrieves room details, such as the room name, for a room in an Amazon Chime Enterprise account. """ def get_room(%Client{} = client, account_id, room_id, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/rooms/#{AWS.Util.encode_uri(room_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves the information for a SIP media application, including name, AWS Region, and endpoints. """ def get_sip_media_application(%Client{} = client, sip_media_application_id, options \\ []) do url_path = "/sip-media-applications/#{AWS.Util.encode_uri(sip_media_application_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the logging configuration for the specified SIP media application. """ def get_sip_media_application_logging_configuration( %Client{} = client, sip_media_application_id, options \\ [] ) do url_path = "/sip-media-applications/#{AWS.Util.encode_uri(sip_media_application_id)}/logging-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves the details of a SIP rule, such as the rule ID, name, triggers, and target endpoints. """ def get_sip_rule(%Client{} = client, sip_rule_id, options \\ []) do url_path = "/sip-rules/#{AWS.Util.encode_uri(sip_rule_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves details for the specified user ID, such as primary email address, license type,and personal meeting PIN. To retrieve user details with an email address instead of a user ID, use the `ListUsers` action, and then filter by email address. """ def get_user(%Client{} = client, account_id, user_id, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users/#{AWS.Util.encode_uri(user_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves settings for the specified user ID, such as any associated phone number settings. """ def get_user_settings(%Client{} = client, account_id, user_id, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users/#{AWS.Util.encode_uri(user_id)}/settings" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves details for the specified Amazon Chime Voice Connector, such as timestamps,name, outbound host, and encryption requirements. """ def get_voice_connector(%Client{} = client, voice_connector_id, options \\ []) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Gets the emergency calling configuration details for the specified Amazon Chime Voice Connector. """ def get_voice_connector_emergency_calling_configuration( %Client{} = client, voice_connector_id, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/emergency-calling-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves details for the specified Amazon Chime Voice Connector group, such as timestamps,name, and associated `VoiceConnectorItems`. """ def get_voice_connector_group(%Client{} = client, voice_connector_group_id, options \\ []) do url_path = "/voice-connector-groups/#{AWS.Util.encode_uri(voice_connector_group_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves the logging configuration details for the specified Amazon Chime Voice Connector. Shows whether SIP message logs are enabled for sending to Amazon CloudWatch Logs. """ def get_voice_connector_logging_configuration( %Client{} = client, voice_connector_id, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/logging-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves origination setting details for the specified Amazon Chime Voice Connector. """ def get_voice_connector_origination(%Client{} = client, voice_connector_id, options \\ []) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/origination" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Gets the proxy configuration details for the specified Amazon Chime Voice Connector. """ def get_voice_connector_proxy(%Client{} = client, voice_connector_id, options \\ []) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/programmable-numbers/proxy" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves the streaming configuration details for the specified Amazon Chime Voice Connector. Shows whether media streaming is enabled for sending to Amazon Kinesis. It also shows the retention period, in hours, for the Amazon Kinesis data. """ def get_voice_connector_streaming_configuration( %Client{} = client, voice_connector_id, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/streaming-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves termination setting details for the specified Amazon Chime Voice Connector. """ def get_voice_connector_termination(%Client{} = client, voice_connector_id, options \\ []) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/termination" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves information about the last time a SIP `OPTIONS` ping was received from your SIP infrastructure for the specified Amazon Chime Voice Connector. """ def get_voice_connector_termination_health( %Client{} = client, voice_connector_id, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/termination/health" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Sends email to a maximum of 50 users, inviting them to the specified Amazon Chime `Team` account. Only `Team` account types are currently supported for this action. """ def invite_users(%Client{} = client, account_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users?operation=add" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Lists the Amazon Chime accounts under the administrator's AWS account. You can filter accounts by account name prefix. To find out which Amazon Chime account a user belongs to, you can filter by the user's email address, which returns one account result. """ def list_accounts( %Client{} = client, max_results \\ nil, name \\ nil, next_token \\ nil, user_email \\ nil, options \\ [] ) do url_path = "/accounts" headers = [] query_params = [] query_params = if !is_nil(user_email) do [{"user-email", user_email} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(name) do [{"name", name} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Returns a list of the administrators in the `AppInstance`. """ def list_app_instance_admins( %Client{} = client, app_instance_arn, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}/admins" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ List all `AppInstanceUsers` created under a single `AppInstance`. """ def list_app_instance_users( %Client{} = client, app_instance_arn, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/app-instance-users" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end query_params = if !is_nil(app_instance_arn) do [{"app-instance-arn", app_instance_arn} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists all Amazon Chime `AppInstance`s created under a single AWS account. """ def list_app_instances(%Client{} = client, max_results \\ nil, next_token \\ nil, options \\ []) do url_path = "/app-instances" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the tags applied to an Amazon Chime SDK attendee resource. """ def list_attendee_tags(%Client{} = client, attendee_id, meeting_id, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/attendees/#{AWS.Util.encode_uri(attendee_id)}/tags" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the attendees for the specified Amazon Chime SDK meeting. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def list_attendees( %Client{} = client, meeting_id, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/attendees" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the bots associated with the administrator's Amazon Chime Enterprise account ID. """ def list_bots( %Client{} = client, account_id, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/bots" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists all the users banned from a particular channel. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def list_channel_bans( %Client{} = client, channel_arn, max_results \\ nil, next_token \\ nil, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/bans" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists all channel memberships in a channel. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def list_channel_memberships( %Client{} = client, channel_arn, max_results \\ nil, next_token \\ nil, type \\ nil, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/memberships" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] query_params = if !is_nil(type) do [{"type", type} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists all channels that a particular `AppInstanceUser` is a part of. Only an `AppInstanceAdmin` can call the API with a user ARN that is not their own. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def list_channel_memberships_for_app_instance_user( %Client{} = client, app_instance_user_arn \\ nil, max_results \\ nil, next_token \\ nil, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels?scope=app-instance-user-memberships" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end query_params = if !is_nil(app_instance_user_arn) do [{"app-instance-user-arn", app_instance_user_arn} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ List all the messages in a channel. Returns a paginated list of `ChannelMessages`. By default, sorted by creation timestamp in descending order. Redacted messages appear in the results as empty, since they are only redacted, not deleted. Deleted messages do not appear in the results. This action always returns the latest version of an edited message. Also, the x-amz-chime-bearer request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def list_channel_messages( %Client{} = client, channel_arn, max_results \\ nil, next_token \\ nil, not_after \\ nil, not_before \\ nil, sort_order \\ nil, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/messages" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] query_params = if !is_nil(sort_order) do [{"sort-order", sort_order} | query_params] else query_params end query_params = if !is_nil(not_before) do [{"not-before", not_before} | query_params] else query_params end query_params = if !is_nil(not_after) do [{"not-after", not_after} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists all the moderators for a channel. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def list_channel_moderators( %Client{} = client, channel_arn, max_results \\ nil, next_token \\ nil, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/moderators" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists all Channels created under a single Chime App as a paginated list. You can specify filters to narrow results. ## Functionality & restrictions * Use privacy = `PUBLIC` to retrieve all public channels in the account. * Only an `AppInstanceAdmin` can set privacy = `PRIVATE` to list the private channels in an account. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def list_channels( %Client{} = client, app_instance_arn, max_results \\ nil, next_token \\ nil, privacy \\ nil, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] query_params = if !is_nil(privacy) do [{"privacy", privacy} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end query_params = if !is_nil(app_instance_arn) do [{"app-instance-arn", app_instance_arn} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ A list of the channels moderated by an `AppInstanceUser`. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def list_channels_moderated_by_app_instance_user( %Client{} = client, app_instance_user_arn \\ nil, max_results \\ nil, next_token \\ nil, chime_bearer \\ nil, options \\ [] ) do url_path = "/channels?scope=app-instance-user-moderated-channels" headers = [] headers = if !is_nil(chime_bearer) do [{"x-amz-chime-bearer", chime_bearer} | headers] else headers end query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end query_params = if !is_nil(app_instance_user_arn) do [{"app-instance-user-arn", app_instance_user_arn} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns a list of media capture pipelines. """ def list_media_capture_pipelines( %Client{} = client, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/media-capture-pipelines" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the tags applied to an Amazon Chime SDK meeting resource. """ def list_meeting_tags(%Client{} = client, meeting_id, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/tags" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists up to 100 active Amazon Chime SDK meetings. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def list_meetings(%Client{} = client, max_results \\ nil, next_token \\ nil, options \\ []) do url_path = "/meetings" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the phone number orders for the administrator's Amazon Chime account. """ def list_phone_number_orders( %Client{} = client, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/phone-number-orders" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the phone numbers for the specified Amazon Chime account, Amazon Chime user, Amazon Chime Voice Connector, or Amazon Chime Voice Connector group. """ def list_phone_numbers( %Client{} = client, filter_name \\ nil, filter_value \\ nil, max_results \\ nil, next_token \\ nil, product_type \\ nil, status \\ nil, options \\ [] ) do url_path = "/phone-numbers" headers = [] query_params = [] query_params = if !is_nil(status) do [{"status", status} | query_params] else query_params end query_params = if !is_nil(product_type) do [{"product-type", product_type} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end query_params = if !is_nil(filter_value) do [{"filter-value", filter_value} | query_params] else query_params end query_params = if !is_nil(filter_name) do [{"filter-name", filter_name} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Lists the proxy sessions for the specified Amazon Chime Voice Connector. """ def list_proxy_sessions( %Client{} = client, voice_connector_id, max_results \\ nil, next_token \\ nil, status \\ nil, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/proxy-sessions" headers = [] query_params = [] query_params = if !is_nil(status) do [{"status", status} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the membership details for the specified room in an Amazon Chime Enterprise account, such as the members' IDs, email addresses, and names. """ def list_room_memberships( %Client{} = client, account_id, room_id, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/rooms/#{AWS.Util.encode_uri(room_id)}/memberships" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the room details for the specified Amazon Chime Enterprise account. Optionally, filter the results by a member ID (user ID or bot ID) to see a list of rooms that the member belongs to. """ def list_rooms( %Client{} = client, account_id, max_results \\ nil, member_id \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/rooms" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(member_id) do [{"member-id", member_id} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the SIP media applications under the administrator's AWS account. """ def list_sip_media_applications( %Client{} = client, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/sip-media-applications" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the SIP rules under the administrator's AWS account. """ def list_sip_rules( %Client{} = client, max_results \\ nil, next_token \\ nil, sip_media_application_id \\ nil, options \\ [] ) do url_path = "/sip-rules" headers = [] query_params = [] query_params = if !is_nil(sip_media_application_id) do [{"sip-media-application", sip_media_application_id} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists supported phone number countries. """ def list_supported_phone_number_countries(%Client{} = client, product_type, options \\ []) do url_path = "/phone-number-countries" headers = [] query_params = [] query_params = if !is_nil(product_type) do [{"product-type", product_type} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the tags applied to an Amazon Chime SDK meeting resource. """ def list_tags_for_resource(%Client{} = client, resource_arn, options \\ []) do url_path = "/tags" headers = [] query_params = [] query_params = if !is_nil(resource_arn) do [{"arn", resource_arn} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Lists the users that belong to the specified Amazon Chime account. You can specify an email address to list only the user that the email address belongs to. """ def list_users( %Client{} = client, account_id, max_results \\ nil, next_token \\ nil, user_email \\ nil, user_type \\ nil, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users" headers = [] query_params = [] query_params = if !is_nil(user_type) do [{"user-type", user_type} | query_params] else query_params end query_params = if !is_nil(user_email) do [{"user-email", user_email} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the Amazon Chime Voice Connector groups for the administrator's AWS account. """ def list_voice_connector_groups( %Client{} = client, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/voice-connector-groups" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the SIP credentials for the specified Amazon Chime Voice Connector. """ def list_voice_connector_termination_credentials( %Client{} = client, voice_connector_id, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/termination/credentials" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the Amazon Chime Voice Connectors for the administrator's AWS account. """ def list_voice_connectors( %Client{} = client, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/voice-connectors" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Logs out the specified user from all of the devices they are currently logged into. """ def logout_user(%Client{} = client, account_id, user_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users/#{AWS.Util.encode_uri(user_id)}?operation=logout" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 204 ) end @doc """ Sets the amount of time in days that a given `AppInstance` retains data. """ def put_app_instance_retention_settings( %Client{} = client, app_instance_arn, input, options \\ [] ) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}/retention-settings" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ The data streaming configurations of an `AppInstance`. """ def put_app_instance_streaming_configurations( %Client{} = client, app_instance_arn, input, options \\ [] ) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}/streaming-configurations" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Creates an events configuration that allows a bot to receive outgoing events sent by Amazon Chime. Choose either an HTTPS endpoint or a Lambda function ARN. For more information, see `Bot`. """ def put_events_configuration(%Client{} = client, account_id, bot_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/bots/#{AWS.Util.encode_uri(bot_id)}/events-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 201 ) end @doc """ Puts retention settings for the specified Amazon Chime Enterprise account. We recommend using AWS CloudTrail to monitor usage of this API for your account. For more information, see [Logging Amazon Chime API Calls with AWS CloudTrail](https://docs.aws.amazon.com/chime/latest/ag/cloudtrail.html) in the *Amazon Chime Administration Guide*. To turn off existing retention settings, remove the number of days from the corresponding **RetentionDays** field in the **RetentionSettings** object. For more information about retention settings, see [Managing Chat Retention Policies](https://docs.aws.amazon.com/chime/latest/ag/chat-retention.html) in the *Amazon Chime Administration Guide*. """ def put_retention_settings(%Client{} = client, account_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/retention-settings" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 204 ) end @doc """ Updates the logging configuration for the specified SIP media application. """ def put_sip_media_application_logging_configuration( %Client{} = client, sip_media_application_id, input, options \\ [] ) do url_path = "/sip-media-applications/#{AWS.Util.encode_uri(sip_media_application_id)}/logging-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Puts emergency calling configuration details to the specified Amazon Chime Voice Connector, such as emergency phone numbers and calling countries. Origination and termination settings must be enabled for the Amazon Chime Voice Connector before emergency calling can be configured. """ def put_voice_connector_emergency_calling_configuration( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/emergency-calling-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Adds a logging configuration for the specified Amazon Chime Voice Connector. The logging configuration specifies whether SIP message logs are enabled for sending to Amazon CloudWatch Logs. """ def put_voice_connector_logging_configuration( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/logging-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Adds origination settings for the specified Amazon Chime Voice Connector. If emergency calling is configured for the Amazon Chime Voice Connector, it must be deleted prior to turning off origination settings. """ def put_voice_connector_origination( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/origination" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Puts the specified proxy configuration to the specified Amazon Chime Voice Connector. """ def put_voice_connector_proxy(%Client{} = client, voice_connector_id, input, options \\ []) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/programmable-numbers/proxy" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, nil ) end @doc """ Adds a streaming configuration for the specified Amazon Chime Voice Connector. The streaming configuration specifies whether media streaming is enabled for sending to Indonesians. It also sets the retention period, in hours, for the Amazon Kinesis data. """ def put_voice_connector_streaming_configuration( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/streaming-configuration" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Adds termination settings for the specified Amazon Chime Voice Connector. If emergency calling is configured for the Amazon Chime Voice Connector, it must be deleted prior to turning off termination settings. """ def put_voice_connector_termination( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/termination" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Adds termination SIP credentials for the specified Amazon Chime Voice Connector. """ def put_voice_connector_termination_credentials( %Client{} = client, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/termination/credentials?operation=put" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 204 ) end @doc """ Redacts message content, but not metadata. The message exists in the back end, but the action returns null content, and the state shows as redacted. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def redact_channel_message(%Client{} = client, channel_arn, message_id, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/messages/#{AWS.Util.encode_uri(message_id)}?operation=redact" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Redacts the specified message from the specified Amazon Chime conversation. """ def redact_conversation_message( %Client{} = client, account_id, conversation_id, message_id, input, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/conversations/#{AWS.Util.encode_uri(conversation_id)}/messages/#{AWS.Util.encode_uri(message_id)}?operation=redact" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Redacts the specified message from the specified Amazon Chime channel. """ def redact_room_message( %Client{} = client, account_id, message_id, room_id, input, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/rooms/#{AWS.Util.encode_uri(room_id)}/messages/#{AWS.Util.encode_uri(message_id)}?operation=redact" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Regenerates the security token for a bot. """ def regenerate_security_token(%Client{} = client, account_id, bot_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/bots/#{AWS.Util.encode_uri(bot_id)}?operation=regenerate-security-token" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Resets the personal meeting PIN for the specified user on an Amazon Chime account. Returns the `User` object with the updated personal meeting PIN. """ def reset_personal_pin(%Client{} = client, account_id, user_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users/#{AWS.Util.encode_uri(user_id)}?operation=reset-personal-pin" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Moves a phone number from the **Deletion queue** back into the phone number **Inventory**. """ def restore_phone_number(%Client{} = client, phone_number_id, input, options \\ []) do url_path = "/phone-numbers/#{AWS.Util.encode_uri(phone_number_id)}?operation=restore" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Searches for phone numbers that can be ordered. For US numbers, provide at least one of the following search filters: `AreaCode`, `City`, `State`, or `TollFreePrefix`. If you provide `City`, you must also provide `State`. Numbers outside the US only support the `PhoneNumberType` filter, which you must use. """ def search_available_phone_numbers( %Client{} = client, area_code \\ nil, city \\ nil, country \\ nil, max_results \\ nil, next_token \\ nil, phone_number_type \\ nil, state \\ nil, toll_free_prefix \\ nil, options \\ [] ) do url_path = "/search?type=phone-numbers" headers = [] query_params = [] query_params = if !is_nil(toll_free_prefix) do [{"toll-free-prefix", toll_free_prefix} | query_params] else query_params end query_params = if !is_nil(state) do [{"state", state} | query_params] else query_params end query_params = if !is_nil(phone_number_type) do [{"phone-number-type", phone_number_type} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"next-token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max-results", max_results} | query_params] else query_params end query_params = if !is_nil(country) do [{"country", country} | query_params] else query_params end query_params = if !is_nil(city) do [{"city", city} | query_params] else query_params end query_params = if !is_nil(area_code) do [{"area-code", area_code} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Sends a message to a particular channel that the member is a part of. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. Also, `STANDARD` messages can contain 4KB of data and the 1KB of metadata. `CONTROL` messages can contain 30 bytes of data and no metadata. """ def send_channel_message(%Client{} = client, channel_arn, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/messages" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Starts transcription for the specified `meetingId`. """ def start_meeting_transcription(%Client{} = client, meeting_id, input, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/transcription?operation=start" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Stops transcription for the specified `meetingId`. """ def stop_meeting_transcription(%Client{} = client, meeting_id, input, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/transcription?operation=stop" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Applies the specified tags to the specified Amazon Chime SDK attendee. """ def tag_attendee(%Client{} = client, attendee_id, meeting_id, input, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/attendees/#{AWS.Util.encode_uri(attendee_id)}/tags?operation=add" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 204 ) end @doc """ Applies the specified tags to the specified Amazon Chime SDK meeting. """ def tag_meeting(%Client{} = client, meeting_id, input, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/tags?operation=add" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 204 ) end @doc """ Applies the specified tags to the specified Amazon Chime SDK meeting resource. """ def tag_resource(%Client{} = client, input, options \\ []) do url_path = "/tags?operation=tag-resource" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 204 ) end @doc """ Untags the specified tags from the specified Amazon Chime SDK attendee. """ def untag_attendee(%Client{} = client, attendee_id, meeting_id, input, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/attendees/#{AWS.Util.encode_uri(attendee_id)}/tags?operation=delete" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 204 ) end @doc """ Untags the specified tags from the specified Amazon Chime SDK meeting. """ def untag_meeting(%Client{} = client, meeting_id, input, options \\ []) do url_path = "/meetings/#{AWS.Util.encode_uri(meeting_id)}/tags?operation=delete" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 204 ) end @doc """ Untags the specified tags from the specified Amazon Chime SDK meeting resource. """ def untag_resource(%Client{} = client, input, options \\ []) do url_path = "/tags?operation=untag-resource" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 204 ) end @doc """ Updates account details for the specified Amazon Chime account. Currently, only account name and default license updates are supported for this action. """ def update_account(%Client{} = client, account_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates the settings for the specified Amazon Chime account. You can update settings for remote control of shared screens, or for the dial-out option. For more information about these settings, see [Use the Policies Page](https://docs.aws.amazon.com/chime/latest/ag/policies.html) in the *Amazon Chime Administration Guide*. """ def update_account_settings(%Client{} = client, account_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/settings" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 204 ) end @doc """ Updates `AppInstance` metadata. """ def update_app_instance(%Client{} = client, app_instance_arn, input, options \\ []) do url_path = "/app-instances/#{AWS.Util.encode_uri(app_instance_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates the details of an `AppInstanceUser`. You can update names and metadata. """ def update_app_instance_user(%Client{} = client, app_instance_user_arn, input, options \\ []) do url_path = "/app-instance-users/#{AWS.Util.encode_uri(app_instance_user_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates the status of the specified bot, such as starting or stopping the bot from running in your Amazon Chime Enterprise account. """ def update_bot(%Client{} = client, account_id, bot_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/bots/#{AWS.Util.encode_uri(bot_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Update a channel's attributes. **Restriction**: You can't change a channel's privacy. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def update_channel(%Client{} = client, channel_arn, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates the content of a message. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def update_channel_message(%Client{} = client, channel_arn, message_id, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/messages/#{AWS.Util.encode_uri(message_id)}" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ The details of the time when a user last read messages in a channel. The `x-amz-chime-bearer` request header is mandatory. Use the `AppInstanceUserArn` of the user that makes the API call as the value in the header. """ def update_channel_read_marker(%Client{} = client, channel_arn, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(channel_arn)}/readMarker" {headers, input} = [ {"ChimeBearer", "x-amz-chime-bearer"} ] |> Request.build_params(input) query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates global settings for the administrator's AWS account, such as Amazon Chime Business Calling and Amazon Chime Voice Connector settings. """ def update_global_settings(%Client{} = client, input, options \\ []) do url_path = "/settings" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 204 ) end @doc """ Updates phone number details, such as product type or calling name, for the specified phone number ID. You can update one phone number detail at a time. For example, you can update either the product type or the calling name in one action. For toll-free numbers, you cannot use the Amazon Chime Business Calling product type. For numbers outside the U.S., you must use the Amazon Chime SIP Media Application Dial-In product type. Updates to outbound calling names can take 72 hours to complete. Pending updates to outbound calling names must be complete before you can request another update. """ def update_phone_number(%Client{} = client, phone_number_id, input, options \\ []) do url_path = "/phone-numbers/#{AWS.Util.encode_uri(phone_number_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates the phone number settings for the administrator's AWS account, such as the default outbound calling name. You can update the default outbound calling name once every seven days. Outbound calling names can take up to 72 hours to update. """ def update_phone_number_settings(%Client{} = client, input, options \\ []) do url_path = "/settings/phone-number" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 204 ) end @doc """ Updates the specified proxy session details, such as voice or SMS capabilities. """ def update_proxy_session( %Client{} = client, proxy_session_id, voice_connector_id, input, options \\ [] ) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}/proxy-sessions/#{AWS.Util.encode_uri(proxy_session_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Updates room details, such as the room name, for a room in an Amazon Chime Enterprise account. """ def update_room(%Client{} = client, account_id, room_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/rooms/#{AWS.Util.encode_uri(room_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates room membership details, such as the member role, for a room in an Amazon Chime Enterprise account. The member role designates whether the member is a chat room administrator or a general chat room member. The member role can be updated only for user IDs. """ def update_room_membership( %Client{} = client, account_id, member_id, room_id, input, options \\ [] ) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/rooms/#{AWS.Util.encode_uri(room_id)}/memberships/#{AWS.Util.encode_uri(member_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates the details of the specified SIP media application. """ def update_sip_media_application( %Client{} = client, sip_media_application_id, input, options \\ [] ) do url_path = "/sip-media-applications/#{AWS.Util.encode_uri(sip_media_application_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Invokes the AWS Lambda function associated with the SIP media application and transaction ID in an update request. The Lambda function can then return a new set of actions. """ def update_sip_media_application_call( %Client{} = client, sip_media_application_id, transaction_id, input, options \\ [] ) do url_path = "/sip-media-applications/#{AWS.Util.encode_uri(sip_media_application_id)}/calls/#{AWS.Util.encode_uri(transaction_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 202 ) end @doc """ Updates the details of the specified SIP rule. """ def update_sip_rule(%Client{} = client, sip_rule_id, input, options \\ []) do url_path = "/sip-rules/#{AWS.Util.encode_uri(sip_rule_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 202 ) end @doc """ Updates user details for a specified user ID. Currently, only `LicenseType` updates are supported for this action. """ def update_user(%Client{} = client, account_id, user_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users/#{AWS.Util.encode_uri(user_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates the settings for the specified user, such as phone number settings. """ def update_user_settings(%Client{} = client, account_id, user_id, input, options \\ []) do url_path = "/accounts/#{AWS.Util.encode_uri(account_id)}/users/#{AWS.Util.encode_uri(user_id)}/settings" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 204 ) end @doc """ Updates details for the specified Amazon Chime Voice Connector. """ def update_voice_connector(%Client{} = client, voice_connector_id, input, options \\ []) do url_path = "/voice-connectors/#{AWS.Util.encode_uri(voice_connector_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates details of the specified Amazon Chime Voice Connector group, such as the name and Amazon Chime Voice Connector priority ranking. """ def update_voice_connector_group( %Client{} = client, voice_connector_group_id, input, options \\ [] ) do url_path = "/voice-connector-groups/#{AWS.Util.encode_uri(voice_connector_group_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 202 ) end end
lib/aws/generated/chime.ex
0.859884
0.577674
chime.ex
starcoder
defmodule Commanded.Commands.Router do @moduledoc """ Command routing macro to allow configuration of each command to its command handler. ## Example Define a router module which uses `Commanded.Commands.Router` and configures available commands to dispatch: defmodule BankRouter do use Commanded.Commands.Router dispatch OpenAccount, to: OpenAccountHandler, aggregate: BankAccount, identity: :account_number end The `to` option determines which module receives the command being dispatched. This command handler module must implement a `handle/2` function. It receives the aggregate's state and the command to execute. Usually the command handler module will forward the command to the aggregate. Once configured, you can either dispatch a command using the module by and specify the application: command = %OpenAccount{account_number: "ACC123", initial_balance: 1_000} :ok = BankRouter.dispatch(command, application: BankApp) Or, more simply you should include the router module in your application: defmodule BankApp do use Commanded.Application, otp_app: :my_app router MyApp.Router end Then dispatch commands using the app: command = %OpenAccount{account_number: "ACC123", initial_balance: 1_000} :ok = BankApp.dispatch(command) ## Dispatch command directly to an aggregate You can route a command directly to an aggregate, without requiring an intermediate command handler. ### Example defmodule BankRouter do use Commanded.Commands.Router dispatch OpenAccount, to: BankAccount, identity: :account_number end The aggregate must implement an `execute/2` function that receives the aggregate's state and the command being executed. ## Define aggregate identity You can define the identity field for an aggregate once using the `identify` macro. The configured identity will be used for all commands registered to the aggregate, unless overridden by a command registration. ### Example defmodule BankRouter do use Commanded.Commands.Router identify BankAccount, by: :account_number, prefix: "bank-account-" dispatch OpenAccount, to: BankAccount end An optional identity prefix can be used to distinguish between different aggregates that would otherwise share the same identity. As an example you might have a `User` and a `UserPreferences` aggregate that you wish to share the same identity. In this scenario you should specify a `prefix` for each aggregate (e.g. "user-" and "user-preference-"). The prefix is used as the stream identity when appending and reading the aggregate's events: "<identity_prefix><aggregate_uuid>". It can be a string or a zero arity function returning a string. ## Consistency You can choose the consistency guarantee when dispatching a command. The available options are: - `:eventual` (default) - don't block command dispatch while waiting for event handlers :ok = BankApp.dispatch(command) :ok = BankApp.dispatch(command, consistency: :eventual) - `:strong` - block command dispatch until all strongly consistent event handlers and process managers have successfully processed all events created by the command. Use this when you have event handlers that update read models you need to query immediately after dispatching the command. :ok = BankApp.dispatch(command, consistency: :strong) - Provide an explicit list of event handler and process manager modules (or their configured names), containing only those handlers you'd like to wait for. No other handlers will be awaited on, regardless of their own configured consistency setting. ```elixir :ok = BankApp.dispatch(command, consistency: [ExampleHandler, AnotherHandler]) :ok = BankApp.dispatch(command, consistency: ["ExampleHandler", "AnotherHandler"]) ``` Note you cannot opt-in to strong consistency for a handler that has been configured as eventually consistent. ## Dispatch return By default a successful command dispatch will return `:ok`. You can change this behaviour by specifying a `returning` option. The supported options are: - `:aggregate_state` - to return the update aggregate state. - `:aggregate_version` - to return only the aggregate version. - `:execution_result` - to return a `Commanded.Commands.ExecutionResult` struct containing the aggregate's identity, state, version, and any events produced from the command along with their associated metadata. - `false` - don't return anything except an `:ok`. ### Aggregate state Return the updated aggregate state as part of the dispatch result: {:ok, %BankAccount{}} = BankApp.dispatch(command, returning: :aggregate_state) This is useful when you want to immediately return fields from the aggregate's state without requiring an read model projection and waiting for the event(s) to be projected. It may also be appropriate to use this feature for unit tests. However, be warned that tightly coupling an aggregate's state with read requests may be harmful. It's why CQRS enforces the separation of reads from writes by defining two separate and specialised models. ### Aggregate version You can optionally choose to return the aggregate's version as part of the dispatch result: {:ok, aggregate_version} = BankApp.dispatch(command, returning: :aggregate_version) This is useful when you need to wait for an event handler, such as a read model projection, to be up-to-date before querying its data. ### Execution results You can also choose to return the execution result as part of the dispatch result: alias Commanded.Commands.ExecutionResult {:ok, %ExecutionResult{} = result} = BankApp.dispatch(command, returning: :execution_result) Or by setting the `default_dispatch_return` in your application config file: # config/config.exs config :commanded, default_dispatch_return: :execution_result Use the execution result struct to get information from the events produced from the command. ## Metadata You can associate metadata with all events created by the command. Supply a map containing key/value pairs comprising the metadata: :ok = BankApp.dispatch(command, metadata: %{"ip_address" => "127.0.0.1"}) """ @callback dispatch(struct, keyword()) :: :ok | {:ok, non_neg_integer()} | {:ok, struct} | {:error, term} defmacro __using__(opts) do quote do require Logger import unquote(__MODULE__) @before_compile unquote(__MODULE__) @application Keyword.get(unquote(opts), :application) @registered_commands [] @registered_identities %{} @registered_middleware [] @default [ middleware: [ Commanded.Middleware.ExtractAggregateIdentity, Commanded.Middleware.ConsistencyGuarantee ], consistency: get_opt(unquote(opts), :default_consistency, :eventual), returning: get_default_dispatch_return(unquote(opts)), dispatch_timeout: 5_000, lifespan: Commanded.Aggregates.DefaultLifespan, metadata: %{}, retry_attempts: 10 ] end end @doc """ Include the given middleware module to be called before and after success or failure of each command dispatch The middleware module must implement the `Commanded.Middleware` behaviour. Middleware modules are executed in the order they are defined. ## Example defmodule BankRouter do use Commanded.Commands.Router middleware CommandLogger middleware MyCommandValidator middleware AuthorizeCommand dispatch [OpenAccount, DepositMoney], to: BankAccount, identity: :account_number end """ defmacro middleware(middleware_module) do quote do @registered_middleware @registered_middleware ++ [unquote(middleware_module)] end end @doc """ Define an aggregate's identity You can define the identity field for an aggregate using the `identify` macro. The configured identity will be used for all commands registered to the aggregate, unless overridden by a command registration. ## Example defmodule BankRouter do use Commanded.Commands.Router identify BankAccount, by: :account_number, prefix: "bank-account-" end """ defmacro identify(aggregate_module, opts) do quote location: :keep, bind_quoted: [aggregate_module: aggregate_module, opts: opts] do case Map.get(@registered_identities, aggregate_module) do nil -> by = case Keyword.get(opts, :by) do nil -> raise "#{inspect(aggregate_module)} aggregate identity is missing the `by` option" by when is_atom(by) -> by by when is_function(by, 1) -> by invalid -> raise "#{inspect(aggregate_module)} aggregate identity has an invalid `by` option: #{ inspect(invalid) }" end prefix = case Keyword.get(opts, :prefix) do nil -> nil prefix when is_function(prefix, 0) -> prefix prefix when is_binary(prefix) -> prefix invalid -> raise "#{inspect(aggregate_module)} aggregate has an invalid identity prefix: #{ inspect(invalid) }" end @registered_identities Map.put(@registered_identities, aggregate_module, by: by, prefix: prefix ) config -> raise "#{inspect(aggregate_module)} aggregate has already been identified by: `#{ inspect(Keyword.get(config, :by)) }`" end end end @doc """ Configure the command, or list of commands, to be dispatched to the corresponding handler for a given aggregate. ## Example defmodule BankRouter do use Commanded.Commands.Router dispatch [OpenAccount, DepositMoney], to: BankAccount, identity: :account_number end """ defmacro dispatch(command_module_or_modules, opts) do opts = parse_opts(opts, []) command_module_or_modules |> List.wrap() |> Enum.map(fn command_module -> quote do register(unquote(command_module), unquote(opts)) end end) end @register_params [ :to, :function, :aggregate, :identity, :identity_prefix, :timeout, :lifespan, :consistency ] @doc false defmacro register(command_module, to: handler, function: function, aggregate: aggregate, identity: identity, identity_prefix: identity_prefix, timeout: timeout, lifespan: lifespan, consistency: consistency ) do quote location: :keep do if Enum.member?(@registered_commands, unquote(command_module)) do raise ArgumentError, message: "Command `#{inspect(unquote(command_module))}` has already been registered in router `#{ inspect(__MODULE__) }`" end # sanity check the configured modules exist ensure_module_exists(unquote(aggregate)) ensure_module_exists(unquote(command_module)) ensure_module_exists(unquote(handler)) case unquote(lifespan) do nil -> :ok module when is_atom(module) -> ensure_module_exists(unquote(lifespan)) unless function_exported?(unquote(lifespan), :after_event, 1) do raise ArgumentError, message: "Aggregate lifespan `#{inspect(unquote(lifespan))}` does not define a callback function: `after_event/1`" end unless function_exported?(unquote(lifespan), :after_command, 1) do raise ArgumentError, message: "Aggregate lifespan `#{inspect(unquote(lifespan))}` does not define a callback function: `after_command/1`" end unless function_exported?(unquote(lifespan), :after_error, 1) do raise ArgumentError, message: "Aggregate lifespan `#{inspect(unquote(lifespan))}` does not define a callback function: `after_error/1`" end invalid -> raise ArgumentError, message: "Invalid `lifespan` configured for #{inspect(unquote(aggregate))}: " <> inspect(invalid) end unless function_exported?(unquote(handler), unquote(function), 2) do raise ArgumentError, message: "Command handler `#{inspect(unquote(handler))}` does not define a `#{ unquote(function) }/2` function" end @registered_commands [unquote(command_module) | @registered_commands] def dispatch(command) def dispatch(%unquote(command_module){} = command), do: do_dispatch(command, []) def dispatch(command, timeout_or_opts) def dispatch(%unquote(command_module){} = command, :infinity), do: do_dispatch(command, timeout: :infinity) def dispatch(%unquote(command_module){} = command, timeout) when is_integer(timeout), do: do_dispatch(command, timeout: timeout) def dispatch(%unquote(command_module){} = command, opts), do: do_dispatch(command, opts) defp do_dispatch(%unquote(command_module){} = command, opts) do unless application = Keyword.get(opts, :application, @application) do raise ArgumentError, message: "no :application provided" end causation_id = Keyword.get(opts, :causation_id) correlation_id = Keyword.get(opts, :correlation_id) || UUID.uuid4() consistency = Keyword.get(opts, :consistency) || unquote(consistency) || @default[:consistency] metadata = Keyword.get(opts, :metadata) || @default[:metadata] timeout = Keyword.get(opts, :timeout) || unquote(timeout) || @default[:dispatch_timeout] returning = cond do (returning = Keyword.get(opts, :returning)) in [ :aggregate_state, :aggregate_version, :execution_result, false ] -> returning Keyword.get(opts, :include_execution_result) == true -> :execution_result Keyword.get(opts, :include_aggregate_version) == true -> :aggregate_version true -> @default[:returning] end lifespan = Keyword.get(opts, :lifespan) || unquote(lifespan) || @default[:lifespan] retry_attempts = Keyword.get(opts, :retry_attempts) || @default[:retry_attempts] {identity, identity_prefix} = case Map.get(@registered_identities, unquote(aggregate)) do nil -> {unquote(identity), unquote(identity_prefix)} config -> identity = Keyword.get(config, :by) || unquote(identity) prefix = Keyword.get(config, :prefix) || unquote(identity_prefix) {identity, prefix} end alias Commanded.Commands.Dispatcher alias Commanded.Commands.Dispatcher.Payload payload = %Payload{ application: application, command: command, command_uuid: UUID.uuid4(), causation_id: causation_id, correlation_id: correlation_id, consistency: consistency, handler_module: unquote(handler), handler_function: unquote(function), aggregate_module: unquote(aggregate), identity: identity, identity_prefix: identity_prefix, returning: returning, timeout: timeout, lifespan: lifespan, metadata: metadata, middleware: @registered_middleware ++ @default[:middleware], retry_attempts: retry_attempts } Dispatcher.dispatch(payload) end end end defmacro __before_compile__(_env) do quote generated: true do @doc false def __registered_commands__, do: @registered_commands @doc """ Dispatch the given command to the registered handler. Returns `:ok` on success, or `{:error, reason}` on failure. """ @spec dispatch(command :: struct) :: :ok | {:ok, aggregate_state :: struct} | {:ok, aggregate_version :: non_neg_integer()} | {:ok, execution_result :: Commanded.Commands.ExecutionResult.t()} | {:error, :unregistered_command} | {:error, :consistency_timeout} | {:error, reason :: term} def dispatch(command), do: unregistered_command(command) @doc """ Dispatch the given command to the registered handler providing a timeout. - `timeout_or_opts` is either an integer timeout or a keyword list of options. The timeout must be an integer greater than zero which specifies how many milliseconds to allow the command to be handled, or the atom `:infinity` to wait indefinitely. The default timeout value is five seconds. Alternatively, an options keyword list can be provided, it supports the following options. Options: - `causation_id` - an optional UUID used to identify the cause of the command being dispatched. - `correlation_id` - an optional UUID used to correlate related commands/events together. - `consistency` - one of `:eventual` (default) or `:strong`. By setting the consistency to `:strong` a successful command dispatch will block until all strongly consistent event handlers and process managers have handled all events created by the command. - `metadata` - an optional map containing key/value pairs comprising the metadata to be associated with all events created by the command. - `returning` - to choose what response is returned from a successful command dispatch. The default is to return an `:ok`. The available options are: - `:aggregate_state` - to return the update aggregate state in the successful response: `{:ok, aggregate_state}`. - `:aggregate_version` - to include the aggregate stream version in the successful response: `{:ok, aggregate_version}`. - `:execution_result` - to return a `Commanded.Commands.ExecutionResult` struct containing the aggregate's identity, version, and any events produced from the command along with their associated metadata. - `false` - don't return anything except an `:ok`. - `timeout` - as described above. Returns `:ok` on success unless the `:returning` option is specified where it returns one of `{:ok, aggregate_state}`, `{:ok, aggregate_version}`, or `{:ok, %Commanded.Commands.ExecutionResult{}}`. Returns `{:error, reason}` on failure. """ @spec dispatch(command :: struct, timeout_or_opts :: integer | :infinity | keyword()) :: :ok | {:ok, aggregate_state :: struct} | {:ok, aggregate_version :: non_neg_integer()} | {:ok, execution_result :: Commanded.Commands.ExecutionResult.t()} | {:error, :unregistered_command} | {:error, :consistency_timeout} | {:error, reason :: term} def dispatch(command, _opts), do: unregistered_command(command) defp unregistered_command(command) do _ = Logger.error(fn -> "attempted to dispatch an unregistered command: " <> inspect(command) end) {:error, :unregistered_command} end end end @doc false def ensure_module_exists(module) do unless Code.ensure_compiled?(module) do raise "module `#{inspect(module)}` does not exist, perhaps you forgot to `alias` the namespace" end end @doc false def get_opt(opts, name, default \\ nil) do Keyword.get(opts, name) || Application.get_env(:commanded, name) || default end @doc false def get_default_dispatch_return(opts) do cond do (default_dispatch_return = get_opt(opts, :default_dispatch_return)) in [ :aggregate_state, :aggregate_version, :execution_result, false ] -> default_dispatch_return get_opt(opts, :include_execution_result) == true -> :execution_result get_opt(opts, :include_aggregate_version) == true -> :aggregate_version true -> false end end defp parse_opts([{:to, aggregate_or_handler} | opts], result) do case Keyword.pop(opts, :aggregate) do {nil, opts} -> aggregate = aggregate_or_handler parse_opts(opts, [function: :execute, to: aggregate, aggregate: aggregate] ++ result) {aggregate, opts} -> handler = aggregate_or_handler parse_opts(opts, [function: :handle, to: handler, aggregate: aggregate] ++ result) end end defp parse_opts([{param, value} | opts], result) when param in @register_params do parse_opts(opts, [{param, value} | result]) end defp parse_opts([{param, _value} | _opts], _result) do raise """ unexpected dispatch parameter "#{param}" available params are: #{@register_params |> Enum.map(&to_string/1) |> Enum.join(", ")} """ end defp parse_opts([], result) do Enum.map(@register_params, fn key -> {key, Keyword.get(result, key)} end) end end
lib/commanded/commands/router.ex
0.940674
0.711782
router.ex
starcoder
defmodule Axon.Losses do @moduledoc """ Loss functions. Loss functions evaluate predictions with respect to true data, often to measure the divergence between a model's representation of the data-generating distribution and the true representation of the data-generating distribution. Each loss function is implemented as an element-wise function measuring the loss with respect to the input target `y_true` and input prediction `y_pred`. As an example, the `mean_squared_error/2` loss function produces a tensor whose values are the mean squared error between targets and predictions: iex> y_true = Nx.tensor([[0.0, 1.0], [0.0, 0.0]], type: {:f, 32}) iex> y_pred = Nx.tensor([[1.0, 1.0], [1.0, 0.0]], type: {:f, 32}) iex> Axon.Losses.mean_squared_error(y_true, y_pred) #Nx.Tensor< f32[2] [0.5, 0.5] > It's common to compute the loss across an entire minibatch. You can easily do so by specifying a `:reduction` mode, or by composing one of these with an `Nx` reduction method: iex> y_true = Nx.tensor([[0.0, 1.0], [0.0, 0.0]], type: {:f, 32}) iex> y_pred = Nx.tensor([[1.0, 1.0], [1.0, 0.0]], type: {:f, 32}) iex> Axon.Losses.mean_squared_error(y_true, y_pred, reduction: :mean) #Nx.Tensor< f32 0.5 > You can even compose loss functions: defn my_strange_loss(y_true, y_pred) do y_true |> Axon.mean_squared_error(y_pred) |> Axon.binary_cross_entropy(y_pred) |> Nx.sum() end Or, more commonly, you can combine loss functions with penalties for regularization: defn regularized_loss(params, y_true, y_pred) do loss = Axon.mean_squared_error(y_true, y_pred) penalty = l2_penalty(params) Nx.sum(loss) + penalty end All of the functions in this module are implemented as numerical functions and can be JIT or AOT compiled with any supported `Nx` compiler. """ import Nx.Defn import Axon.Shared @doc ~S""" Binary cross-entropy loss function. $$l_i = -\frac{1}{2}(\hat{y_i} \cdot \log(y_i) + (1 - \hat{y_i}) \cdot \log(1 - y_i))$$ ## Argument Shapes * `y_true` - $\(d_0, d_1, ..., d_n\)$ * `y_pred` - $\(d_0, d_1, ..., d_n\)$ ## Options * `:reduction` - reduction mode. One of `:mean`, `:sum`, or `:none`. Defaults to `:none`. ## Examples iex> y_true = Nx.tensor([[0, 1], [1, 0], [1, 0]]) iex> y_pred = Nx.tensor([[0.6811, 0.5565], [0.6551, 0.4551], [0.5422, 0.2648]]) iex> Axon.Losses.binary_cross_entropy(y_true, y_pred) #Nx.Tensor< f32[3] [0.8644828796386719, 0.5150601863861084, 0.4598664939403534] > """ defn binary_cross_entropy(y_true, y_pred, opts \\ []) do assert_shape!(y_true, y_pred) opts = keyword!(opts, reduction: :none) loss = Nx.mean(-xlogy(y_true, y_pred) - xlogy(1 - y_true, 1 - y_pred), axes: [-1]) transform( {opts[:reduction], loss}, fn {:mean, loss} -> Nx.mean(loss) {:sum, loss} -> Nx.sum(loss) {:none, loss} -> loss end ) end @doc ~S""" Categorical cross-entropy loss function. $$l_i = -\sum_i^C \hat{y_i} \cdot \log(y_i)$$ ## Argument Shapes * `y_true` - $\(d_0, d_1, ..., d_n\)$ * `y_pred` - $\(d_0, d_1, ..., d_n\)$ ## Options * `:reduction` - reduction mode. One of `:mean`, `:sum`, or `:none`. Defaults to `:none`. ## Examples iex> y_true = Nx.tensor([[0, 1, 0], [0, 0, 1]], type: {:s, 8}) iex> y_pred = Nx.tensor([[0.05, 0.95, 0], [0.1, 0.8, 0.1]]) iex> Axon.Losses.categorical_cross_entropy(y_true, y_pred) #Nx.Tensor< f32[2] [0.051293306052684784, 2.3025851249694824] > """ defn categorical_cross_entropy(y_true, y_pred, opts \\ []) do assert_shape!(y_true, y_pred) opts = keyword!(opts, reduction: :none) loss = y_true |> xlogy(y_pred) |> Nx.sum(axes: [-1]) |> Nx.negate() transform( {opts[:reduction], loss}, fn {:mean, loss} -> Nx.mean(loss) {:sum, loss} -> Nx.sum(loss) {:none, loss} -> loss end ) end @doc ~S""" Categorical hinge loss function. ## Argument Shapes * `y_true` - $\(d_0, d_1, ..., d_n\)$ * `y_pred` - $\(d_0, d_1, ..., d_n\)$ ## Options * `:reduction` - reduction mode. One of `:mean`, `:sum`, or `:none`. Defaults to `:none`. ## Examples iex> y_true = Nx.tensor([[1, 0, 0], [0, 0, 1]], type: {:s, 8}) iex> y_pred = Nx.tensor([[0.05300799, 0.21617081, 0.68642382], [0.3754382 , 0.08494169, 0.13442067]]) iex> Axon.Losses.categorical_hinge(y_true, y_pred) #Nx.Tensor< f32[2] [1.6334158182144165, 1.2410175800323486] > """ defn categorical_hinge(y_true, y_pred, opts \\ []) do opts = keyword!(opts, reduction: :none) loss = 1 |> Nx.subtract(y_true) |> Nx.multiply(y_pred) |> Nx.reduce_max(axes: [-1]) |> Nx.subtract(Nx.sum(Nx.multiply(y_true, y_pred), axes: [-1])) |> Nx.add(1) |> Nx.max(0) transform( {opts[:reduction], loss}, fn {:mean, loss} -> Nx.mean(loss) {:sum, loss} -> Nx.sum(loss) {:none, loss} -> loss end ) end @doc ~S""" Hinge loss function. $$\frac{1}{C}\max_i(1 - \hat{y_i} * y_i, 0)$$ ## Options * `:reduction` - reduction mode. One of `:mean`, `:sum`, or `:none`. Defaults to `:none`. ## Argument Shapes * `y_true` - $\(d_0, d_1, ..., d_n\)$ * `y_pred` - $\(d_0, d_1, ..., d_n\)$ ## Examples iex> y_true = Nx.tensor([[ 1, 1, -1], [ 1, 1, -1]], type: {:s, 8}) iex> y_pred = Nx.tensor([[0.45440044, 0.31470688, 0.67920924], [0.24311459, 0.93466766, 0.10914676]]) iex> Axon.Losses.hinge(y_true, y_pred) #Nx.Tensor< f32[2] [0.9700339436531067, 0.6437881588935852] > """ defn hinge(y_true, y_pred, opts \\ []) do assert_shape!(y_true, y_pred) opts = keyword!(opts, reduction: :none) loss = y_true |> Nx.multiply(y_pred) |> Nx.negate() |> Nx.add(1) |> Nx.max(0) |> Nx.mean(axes: [-1]) transform( {opts[:reduction], loss}, fn {:mean, loss} -> Nx.mean(loss) {:sum, loss} -> Nx.sum(loss) {:none, loss} -> loss end ) end @doc ~S""" Kullback-Leibler divergence loss function. $$l_i = \sum_i^C \hat{y_i} \cdot \log(\frac{\hat{y_i}}{y_i})$$ ## Argument Shapes * `y_true` - $\(d_0, d_1, ..., d_n\)$ * `y_pred` - $\(d_0, d_1, ..., d_n\)$ ## Options * `:reduction` - reduction mode. One of `:mean`, `:sum`, or `:none`. Defaults to `:none`. ## Examples iex> y_true = Nx.tensor([[0, 1], [0, 0]], type: {:u, 8}) iex> y_pred = Nx.tensor([[0.6, 0.4], [0.4, 0.6]]) iex> Axon.Losses.kl_divergence(y_true, y_pred) #Nx.Tensor< f32[2] [0.916289210319519, -3.080907390540233e-6] > """ defn kl_divergence(y_true, y_pred, opts \\ []) do assert_shape!(y_true, y_pred) opts = keyword!(opts, reduction: :none) epsilon = 1.0e-7 y_true = Nx.clip(y_true, epsilon, 1) y_pred = Nx.clip(y_pred, epsilon, 1) loss = y_true |> Nx.divide(y_pred) |> Nx.log() |> Nx.multiply(y_true) |> Nx.sum(axes: [-1]) transform( {opts[:reduction], loss}, fn {:mean, loss} -> Nx.mean(loss) {:sum, loss} -> Nx.sum(loss) {:none, loss} -> loss end ) end @doc ~S""" Logarithmic-Hyperbolic Cosine loss function. $$l_i = \frac{1}{C} \sum_i^C (\hat{y_i} - y_i) + \log(1 + e^{-2(\hat{y_i} - y_i)}) - \log(2)$$ ## Argument Shapes * `y_true` - $\(d_0, d_1, ..., d_n\)$ * `y_pred` - $\(d_0, d_1, ..., d_n\)$ ## Options * `:reduction` - reduction mode. One of `:mean`, `:sum`, or `:none`. Defaults to `:none`. ## Examples iex> y_true = Nx.tensor([[0.0, 1.0], [0.0, 0.0]]) iex> y_pred = Nx.tensor([[1.0, 1.0], [0.0, 0.0]]) iex> Axon.Losses.log_cosh(y_true, y_pred) #Nx.Tensor< f32[2] [0.2168903946876526, 0.0] > """ defn log_cosh(y_true, y_pred, opts \\ []) do assert_shape!(y_true, y_pred) opts = keyword!(opts, reduction: :none) x = y_pred |> Nx.subtract(y_true) loss = x |> Nx.multiply(-2) |> Nx.exp() |> Nx.log1p() |> Nx.add(x) |> Nx.subtract(Nx.log(2)) |> Nx.mean(axes: [-1]) transform( {opts[:reduction], loss}, fn {:mean, loss} -> Nx.mean(loss) {:sum, loss} -> Nx.sum(loss) {:none, loss} -> loss end ) end @doc ~S""" Margin ranking loss function. $$l_i = \max(0, -\hat{y_i} * (y^(1)_i - y^(2)_i) + \alpha)$$ ## Options * `:reduction` - reduction mode. One of `:mean`, `:sum`, or `:none`. Defaults to `:none`. ## Examples iex> y_true = Nx.tensor([1.0, 1.0, 1.0], type: {:f, 32}) iex> y_pred1 = Nx.tensor([0.6934, -0.7239, 1.1954], type: {:f, 32}) iex> y_pred2 = Nx.tensor([-0.4691, 0.2670, -1.7452], type: {:f, 32}) iex> Axon.Losses.margin_ranking(y_true, y_pred1, y_pred2) #Nx.Tensor< f32[3] [0.0, 0.9909000396728516, 0.0] > """ defn margin_ranking(y_true, y_pred1, y_pred2, opts \\ []) do assert_shape!(y_pred1, y_pred2) assert_shape!(y_true, y_pred1) opts = keyword!(opts, margin: 0.0, reduction: :none) margin = opts[:margin] loss = y_pred1 |> Nx.subtract(y_pred2) |> Nx.multiply(Nx.negate(y_true)) |> Nx.add(margin) |> Nx.max(0) transform( {opts[:reduction], loss}, fn {:mean, loss} -> Nx.mean(loss) {:sum, loss} -> Nx.sum(loss) {:none, loss} -> loss end ) end @doc ~S""" Soft margin loss function. $$l_i = \sum_i \frac{\log(1 + e^{-\hat{y_i} * y_i})}{N}$$ ## Options * `:reduction` - reduction mode. One of `:mean`, `:sum`, or `:none`. Defaults to `:none`. ## Examples iex> y_true = Nx.tensor([[-1.0, 1.0, 1.0]], type: {:f, 32}) iex> y_pred = Nx.tensor([[0.2953, -0.1709, 0.9486]], type: {:f, 32}) iex> Axon.Losses.soft_margin(y_true, y_pred) #Nx.Tensor< f32[3] [0.851658046245575, 0.7822436094284058, 0.3273470401763916] > """ defn soft_margin(y_true, y_pred, opts \\ []) do opts = keyword!(opts, reduction: :none) loss = y_true |> Nx.negate() |> Nx.multiply(y_pred) |> Nx.exp() |> Nx.log1p() |> Nx.sum(axes: [0]) transform( {opts[:reduction], loss}, fn {:mean, loss} -> Nx.mean(loss) {:sum, loss} -> Nx.sum(loss) {:none, loss} -> loss end ) end @doc ~S""" Mean-absolute error loss function. $$l_i = \sum_i |\hat{y_i} - y_i|$$ ## Argument Shapes * `y_true` - $\(d_0, d_1, ..., d_n\)$ * `y_pred` - $\(d_0, d_1, ..., d_n\)$ ## Options * `:reduction` - reduction mode. One of `:mean`, `:sum`, or `:none`. Defaults to `:none`. ## Examples iex> y_true = Nx.tensor([[0.0, 1.0], [0.0, 0.0]], type: {:f, 32}) iex> y_pred = Nx.tensor([[1.0, 1.0], [1.0, 0.0]], type: {:f, 32}) iex> Axon.Losses.mean_absolute_error(y_true, y_pred) #Nx.Tensor< f32[2] [0.5, 0.5] > """ defn mean_absolute_error(y_true, y_pred, opts \\ []) do assert_shape!(y_true, y_pred) opts = keyword!(opts, reduction: :none) loss = y_true |> Nx.subtract(y_pred) |> Nx.abs() |> Nx.mean(axes: [-1]) transform( {opts[:reduction], loss}, fn {:mean, loss} -> Nx.mean(loss) {:sum, loss} -> Nx.sum(loss) {:none, loss} -> loss end ) end @doc ~S""" Mean-squared error loss function. $$l_i = \sum_i (\hat{y_i} - y_i)^2$$ ## Argument Shapes * `y_true` - $\(d_0, d_1, ..., d_n\)$ * `y_pred` - $\(d_0, d_1, ..., d_n\)$ ## Options * `:reduction` - reduction mode. One of `:mean`, `:sum`, or `:none`. Defaults to `:none`. ## Examples iex> y_true = Nx.tensor([[0.0, 1.0], [0.0, 0.0]], type: {:f, 32}) iex> y_pred = Nx.tensor([[1.0, 1.0], [1.0, 0.0]], type: {:f, 32}) iex> Axon.Losses.mean_squared_error(y_true, y_pred) #Nx.Tensor< f32[2] [0.5, 0.5] > """ defn mean_squared_error(y_true, y_pred, opts \\ []) do assert_shape!(y_true, y_pred) opts = keyword!(opts, reduction: :none) loss = y_true |> Nx.subtract(y_pred) |> Nx.power(2) |> Nx.mean(axes: [-1]) transform( {opts[:reduction], loss}, fn {:mean, loss} -> Nx.mean(loss) {:sum, loss} -> Nx.sum(loss) {:none, loss} -> loss end ) end @doc ~S""" Poisson loss function. $$l_i = \frac{1}{C} \sum_i^C y_i - (\hat{y_i} \cdot \log(y_i))$$ ## Argument Shapes * `y_true` - $\(d_0, d_1, ..., d_n\)$ * `y_pred` - $\(d_0, d_1, ..., d_n\)$ ## Options * `:reduction` - reduction mode. One of `:mean`, `:sum`, or `:none`. Defaults to `:none`. ## Examples iex> y_true = Nx.tensor([[0.0, 1.0], [0.0, 0.0]], type: {:f, 32}) iex> y_pred = Nx.tensor([[1.0, 1.0], [0.0, 0.0]], type: {:f, 32}) iex> Axon.Losses.poisson(y_true, y_pred) #Nx.Tensor< f32[2] [0.9999999403953552, 0.0] > """ defn poisson(y_true, y_pred, opts \\ []) do assert_shape!(y_true, y_pred) opts = keyword!(opts, reduction: :none) epsilon = 1.0e-7 loss = y_pred |> Nx.add(epsilon) |> Nx.log() |> Nx.multiply(y_true) |> Nx.negate() |> Nx.add(y_pred) |> Nx.mean(axes: [-1]) transform( {opts[:reduction], loss}, fn {:mean, loss} -> Nx.mean(loss) {:sum, loss} -> Nx.sum(loss) {:none, loss} -> loss end ) end end
lib/axon/losses.ex
0.958683
0.918187
losses.ex
starcoder
defmodule Mix.Tasks.Snoop do use Mix.Task @moduledoc """ A tool for snooping on DHCP transactions that are passing by this particular connected device. ## Usage Run this mix task on a device on the same layer-2 network as the network where you'd like to watch DHCP packets go by. It's probably a good idea to *not* have this be the same machine that you're using to serve DHCP. ```bash mix snoop ``` Defaults to listening to UDP ports 67 and 68. In order to use this feature on most Linux machines, you'll need give your erlang virtual machine permission to listen on (< 1024) port numbers. You can do this with the following command as superuser: ```bash setcap 'cap_net_bind_service,cap_net_raw=+ep' /usr/lib/erlang/erts-10.6.1/bin/beam.smp ``` Note that the path to your `beam.smp` might be different. `Ctrl-c` will exit out of this mix task ### Using without `setcap` You can use this program without changing the permissions on `beam.smp`. Instead, supply the `--port` or `-p` parameter to the mix task, like so: ```bash mix snoop -p 6767 ``` And you'll want to forward UDP port activity from 67 and 68 to the snoop port 6767, you may use `iptables` as superuser to achieve this. Note that these changes may not persist on certain network activity (such as (libvirt)[https://libvirt.org/] creating or destroying a network), and certainly not on reboot. Instrumenting these settings as permanent is beyond the scope of this guide. ```bash iptables -t nat -I PREROUTING -p udp --dport 67 -j DNAT --to :6767 iptables -t nat -I PREROUTING -p udp --dport 68 -j DNAT --to :6767 ``` This will cause DHCP packets streaming to be logged to the console. ## Options - `--bind <device>` or `-b <device>` binds this mix task to a specific network device. - `--save <prefix>` or `-s <prefix>` saves packets (as erlang term binaries) to files with the given prefix """ @shortdoc "snoop on DHCP packets as they go by" defmodule DhcpSnooper do @moduledoc false defstruct [:save] use ExDhcp require Logger def start_link(_init, opts \\ []) do ExDhcp.start_link(__MODULE__, struct(__MODULE__, opts), opts) end @impl true def init(config), do: {:ok, config} @impl true def handle_discover(packet, _, _, state) do saveinfo = save(packet, state) Logger.info(saveinfo <> inspect packet) {:norespond, state} end @impl true def handle_request(packet, _, _, state) do saveinfo = save(packet, state) Logger.info(saveinfo <> inspect packet) {:norespond, state} end @impl true def handle_decline(packet, _, _, state) do saveinfo = save(packet, state) Logger.info(saveinfo <> inspect packet) {:norespond, state} end @impl true def handle_inform(packet, _, _, state) do saveinfo = save(packet, state) Logger.info(saveinfo <> inspect packet) {:norespond, state} end @impl true def handle_release(packet, _, _, state) do saveinfo = save(packet, state) Logger.info(saveinfo <> inspect packet) {:norespond, state} end @impl true def handle_packet(packet, _, _, state) do saveinfo = save(packet, state) Logger.info(saveinfo <> inspect packet) {:norespond, state} end @impl true def handle_info({:udp, _, _, _, binary}, state) do unrolled_binary = binary |> :erlang.binary_to_list |> Enum.chunk_every(16) |> Enum.map(&Enum.join(&1, ", ")) |> Enum.join("\n") Logger.warn("untrapped udp: \n <<#{unrolled_binary}>> ") {:noreply, state} end def handle_info(info, state) do Logger.warn(inspect info) {:noreply, state} end defp save(_, %{save: nil}), do: "" defp save(packet, %{save: prefix}) do last_index = prefix |> Path.expand |> Path.dirname |> File.ls! |> Enum.filter(&String.starts_with?(&1, prefix)) |> Enum.map(fn filename -> filename |> Path.basename(".pkt") |> String.split("-") |> List.last |> String.to_integer end) |> Enum.max(fn -> 0 end) filename = "#{prefix}-#{last_index + 1}.pkt" File.write!(filename, :erlang.term_to_binary(packet)) "(saved to #{filename}) " end end @doc false def run(params) do params = parse_params(params) case params[:port] do [] -> # the default should be start up on both standard DHCP port DhcpSnooper.start_link(:ok, Keyword.put(params, :port, 67)) DhcpSnooper.start_link(:ok, Keyword.put(params, :port, 68)) lst -> Enum.map(lst, fn port -> DhcpSnooper.start_link(:ok, Keyword.put(params, :port, port)) end) end receive do after :infinity -> :ok end end @bind ~w(-b --bind) @port ~w(-p --port) @save ~w(-s --save) defp parse_params(lst, params \\ [port: []]) defp parse_params([], params), do: params defp parse_params([switch, dev | rest], params) when switch in @bind do parse_params(rest, Keyword.put(params, :bind_to_device, dev)) end defp parse_params([switch, n | rest], params) when switch in @port do port = [String.to_integer(n) | params[:port]] parse_params(rest, Keyword.put(params, :port, port)) end defp parse_params([switch, file_prefix | rest], params) when switch in @save do parse_params(rest, Keyword.put(params, :save, file_prefix)) end defp parse_params([_ | rest], params), do: parse_params(rest, params) end
lib/mix.tasks/snoop.ex
0.797557
0.760451
snoop.ex
starcoder
defmodule Protobuf.JSON.Encode do @moduledoc false alias Protobuf.JSON.{EncodeError, Utils} @compile {:inline, encode_field: 3, encode_key: 2, maybe_repeat: 3, encode_float: 1, encode_enum: 3, safe_enum_key: 2} @duration_seconds_range -315_576_000_000..315_576_000_000 @doc false @spec to_encodable(struct, keyword) :: map | {:error, EncodeError.t()} def to_encodable(struct, opts) def to_encodable(%mod{} = struct, _opts) when mod == Google.Protobuf.Duration do case struct do %{seconds: seconds} when seconds not in @duration_seconds_range -> throw({:bad_duration, :seconds_outside_of_range, seconds}) %{seconds: seconds, nanos: 0} -> Integer.to_string(seconds) <> "s" %{seconds: seconds, nanos: nanos} -> "#{seconds}.#{Utils.format_nanoseconds(nanos)}s" end end def to_encodable(%mod{} = struct, _opts) when mod == Google.Protobuf.Timestamp do %{seconds: seconds, nanos: nanos} = struct case Protobuf.JSON.RFC3339.encode(seconds, nanos) do {:ok, string} -> string {:error, reason} -> throw({:invalid_timestamp, struct, reason}) end end def to_encodable(%mod{}, _opts) when mod == Google.Protobuf.Empty do %{} end def to_encodable(%mod{kind: kind}, opts) when mod == Google.Protobuf.Value do case kind do {:string_value, string} -> string {:number_value, number} -> number {:bool_value, bool} -> bool {:null_value, :NULL_VALUE} -> nil {:list_value, list} -> to_encodable(list, opts) {:struct_value, struct} -> to_encodable(struct, opts) _other -> throw({:bad_encoding, kind}) end end def to_encodable(%mod{values: values}, opts) when mod == Google.Protobuf.ListValue do Enum.map(values, &to_encodable(&1, opts)) end def to_encodable(%mod{fields: fields}, opts) when mod == Google.Protobuf.Struct do Map.new(fields, fn {key, val} -> {key, to_encodable(val, opts)} end) end def to_encodable(%mod{value: value}, _opts) when mod in [ Google.Protobuf.Int32Value, Google.Protobuf.UInt32Value, Google.Protobuf.UInt64Value, Google.Protobuf.Int64Value, Google.Protobuf.FloatValue, Google.Protobuf.DoubleValue, Google.Protobuf.BoolValue, Google.Protobuf.StringValue ] do value end def to_encodable(%mod{value: value}, _opts) when mod == Google.Protobuf.BytesValue do Base.encode64(value) end def to_encodable(%mod{paths: paths}, _opts) when mod == Google.Protobuf.FieldMask do Enum.each(paths, fn path -> cond do String.contains?(path, "__") -> throw({:bad_field_mask, paths}) path =~ ~r/[A-Z0-9]/ -> throw({:bad_field_mask, path}) true -> {first, rest} = path |> Macro.camelize() |> String.next_codepoint() String.downcase(first) <> rest end end) Enum.join(paths, ",") end def to_encodable(%mod{} = struct, opts) do message_props = mod.__message_props__() regular = encode_regular_fields(struct, message_props, opts) oneofs = encode_oneof_fields(struct, message_props, opts) :maps.from_list(regular ++ oneofs) end defp encode_regular_fields(struct, %{field_props: field_props}, opts) do for {_field_num, %{name_atom: name, oneof: nil} = prop} <- field_props, %{^name => value} = struct, opts[:emit_unpopulated] || !default?(prop, value) do encode_field(prop, value, opts) end end defp encode_oneof_fields(struct, message_props, opts) do %{field_tags: field_tags, field_props: field_props, oneof: oneofs} = message_props for {oneof_name, _index} <- oneofs, tag_and_value = Map.get(struct, oneof_name) do {tag, value} = tag_and_value prop = field_props[field_tags[tag]] encode_field(prop, value, opts) end end # TODO: handle invalid values? check types? defp encode_field(prop, value, opts) do {encode_key(prop, opts), encode_value(value, prop, opts)} end defp encode_key(prop, opts) do if opts[:use_proto_names], do: prop.name, else: prop.json_name end @int32_types ~w(int32 sint32 sfixed32 fixed32 uint32)a @int64_types ~w(int64 sint64 sfixed64 fixed64 uint64)a @float_types [:float, :double] @raw_types [:string, :bool] ++ @int32_types defp encode_value(nil, _prop, _opts), do: nil defp encode_value(value, %{type: type} = prop, _opts) when type in @raw_types do maybe_repeat(prop, value, & &1) end defp encode_value(value, %{type: type} = prop, _opts) when type in @int64_types do maybe_repeat(prop, value, &Integer.to_string/1) end defp encode_value(value, %{type: :bytes} = prop, _opts) do maybe_repeat(prop, value, &Base.encode64/1) end defp encode_value(value, %{type: type} = prop, _opts) when type in @float_types do maybe_repeat(prop, value, &encode_float/1) end defp encode_value(value, %{type: {:enum, enum}} = prop, opts) do maybe_repeat(prop, value, &encode_enum(enum, &1, opts)) end # Map keys can be of any scalar type except float, double and bytes. Therefore, we need to # convert them to strings before encoding. Map values can be anything except another map. # According to the specs: "If you provide a key but no value for a map field, the behavior # when the field is serialized is language-dependent. In C++, Java, and Python the default # value for the type is serialized, while in other languages nothing is serialized". Here # we do serialize these values as `nil` by default. defp encode_value(map, %{map?: true, type: module}, opts) do %{field_props: field_props, field_tags: field_tags} = module.__message_props__() key_prop = field_props[field_tags[:key]] value_prop = field_props[field_tags[:value]] for {key, val} <- map, into: %{} do name = encode_value(key, key_prop, opts) value = encode_value(val, value_prop, opts) {to_string(name), value} end end defp encode_value(value, %{embedded?: true} = prop, opts) do maybe_repeat(prop, value, &to_encodable(&1, opts)) end defp encode_float(value) when is_float(value), do: value defp encode_float(:negative_infinity), do: "-Infinity" defp encode_float(:infinity), do: "Infinity" defp encode_float(:nan), do: "NaN" # TODO: maybe define a helper for all enums messages, with strict validation. defp encode_enum(Google.Protobuf.NullValue, key, _opts) when key in [0, :NULL_VALUE] do nil end defp encode_enum(enum, key, opts) when is_atom(key) do if opts[:use_enum_numbers], do: enum.value(key), else: key end defp encode_enum(enum, num, opts) when is_integer(num) do if opts[:use_enum_numbers], do: num, else: safe_enum_key(enum, num) end # proto3 allows unknown enum values, that is why we can't call enum.key(num) here. defp safe_enum_key(enum, num) do %{tags_map: tags_map, field_props: field_props} = enum.__message_props__() case field_props[tags_map[num]] do %{name_atom: key} -> key _ -> num end end defp maybe_repeat(%{repeated?: false}, val, fun), do: fun.(val) defp maybe_repeat(%{repeated?: true}, val, fun), do: Enum.map(val, fun) defp default?(_prop, value) when value in [nil, 0, false, [], "", 0.0, %{}], do: true defp default?(%{type: {:enum, enum}}, key) when is_atom(key), do: enum.value(key) == 0 defp default?(_prop, _value), do: false end
lib/protobuf/json/encode.ex
0.688364
0.434641
encode.ex
starcoder
defmodule Optimizer do @moduledoc """ Provides a optimizer for [AST](https://elixirschool.com/en/lessons/advanced/metaprogramming/) """ import SumMag @term_options [enum: true] @doc """ Optimize funcions which be enclosed `defptermay`, using `optimize_***` function. Input is funcion definitions. ``` quote do def twice_plus(list) do twice = list |> Enum.map(&(&1*2)) twice |> Enum.map(&(&1+1)) end def foo, do: "foo" end ``` """ def replace(definitions, caller) do definitions |> melt_block |> Enum.map(&optimize_func(&1)) |> iced_block |> consist_context(caller) end defp consist_context(funcs, module) do Macro.prewalk( funcs, fn {:__aliases__, [alias: false], [:ReplaceModule]} -> module other -> other end ) end @doc """ Input is one funcion definition: ``` quote do def twice_plus(list) do twice = list |> Enum.map(&(&1*2)) twice |> Enum.map(&(&1+1)) end end ``` """ def optimize_func({def_key, meta, [arg_info, exprs]}) do case def_key do :def -> {:def, meta, [arg_info, optimize_exprs(exprs)]} :defp -> {:defp, meta, [arg_info, optimize_exprs(exprs)]} _ -> raise ArgumentError end end @doc """ Input is some expresions: ``` quote do twice = list |> Enum.map(&(&1*2)) twice |> Enum.map(&(&1+1)) end ``` """ def optimize_exprs(exprs) do exprs |> melt_block |> Enum.map(&optimize_expr(&1)) |> iced_block end @doc """ Input is one expression: ``` quote do twice = list |> Enum.map(&(&1*2)) end ``` """ def optimize_expr(expr) do expr |> Macro.unpipe() |> accelerate_expr() |> pipe end defp accelerate_expr(unpiped_list) do # Delete pos expr = Enum.map(unpiped_list, fn {x, _} -> x end) optimized_expr = Enum.map(expr, &parallelize_term(&1, @term_options)) # Add pos Enum.map(optimized_expr, fn x -> {x, 0} end) end @doc """ Input is a term: ``` quote do: list quote do: list quote do: Enum.map(&(&1*2)) ``` """ def parallelize_term(term, options) when is_list(options) do Enum.reduce( options, term, fn opt, acc -> parallelize_term(acc, opt) end ) end def parallelize_term(term, {:enum, true}), do: Optimizer.Enum.parallelize_term(term) def parallelize_term(term, _), do: term end
lib/pelemay/optimizer.ex
0.793586
0.899696
optimizer.ex
starcoder