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 FlowAssertions.TabularA do
alias FlowAssertions.MiscA
import FlowAssertions.Define.BodyParts
@moduledoc """
Builders that create functions tailored to tabular tests.
Here are some tabular tests for how
`Previously.parse` copes with one of its keyword arguments:
[insert: :a ] |> expect.([een(a: Examples)])
[insert: [:a, :b ] ] |> expect.([een(a: Examples), een(b: Examples)])
[insert: [:a, b: List] ] |> expect.([een(a: Examples), een(b: List)])
[insert: :a, insert: [b: List]] |> expect.([een(a: Examples), een(b: List)])
[insert: een(a: Examples) ] |> expect.([een(a: Examples)])
The `expect` function above was created with:
expect = TabularA.run_and_assert(
&(Pnode.Previously.parse(&1) |> Pnode.EENable.eens))
There is also a function that allows assertions about exceptions to be written in a tabular style:
raises = TabularA.run_for_exception(&case_clause/2)
[3, 3] |> raises.(CaseClauseError)
For more on this style, see ["Tabular tests in Elixir"](https://www.crustofcode.com/two-formats-for-tabular-elixir-tests/).
## Related code
You can find similar builders in
`FlowAssertions.Define.Tabular`. They produce functions used to test
assertions (like the ones in this package).
## Beware the typo
I make this kind of typo a lot:
[2, 2] |> expect("The sum is 4")
There should be a period after `expect`. The result (as of Elixir 1.11) is
** (CompileError) test.exs:42: undefined function expect/2
"""
@doc """
Hide repeated code inside an `expect` function, allowing concise tabular tests.
The first argument is a function that generates a value. It may just
be the function under test:
expect = TabularA.run_and_assert(&Enum.take/2)
Quite often, however, it's a function that does some extra work for
each table row.
For example, the following
extracts just the part of the result that needs to be checked. Because of that,
the table is less cluttered.
expect = TabularA.run_and_assert(
&(Pnode.Previously.parse(&1) |> Pnode.EENable.eens))
Because the above function has a single argument, `expect` is called like
this:
:a |> expect.([een(a: Examples)])
Functions that take two or more arguments need them to be enclosed
in a list or tuple:
[:a, :b] |> expect.([een(:a, b: Examples)])
{:a, :b} |> expect.([een(:a, b: Examples)])
(I use tuples when some of the arguments are lists. It's easier to read.)
By default, correctness is checked with `===`. You can override that
by passing in a second function:
expect = TabularA.run_and_assert(
&Common.FromPairs.extract_een_values/1,
&assert_good_enough(&1, in_any_order(&2)))
In the above case, the second argument is a function that takes both a
computed and an expected value. You can instead provide a function that only
takes the computed value. In such a case, I typically call the resulting
function `pass`:
pass = TabularA.run_and_assert(
&case_clause/1,
&(assert &1 == "one passed in"))
1 |> pass.()
Beware: a common mistake is to use a predicate like `&(&1 == "one passed in")`.
Without an assertion, the generated `pass` function can never fail.
"""
def run_and_assert(result_producer, asserter \\ &MiscA.assert_equal/2) do
runner = run(result_producer)
step1 = fn input ->
try do
runner.(input)
rescue
ex in [ExUnit.AssertionError] ->
reraise ex, __STACKTRACE__
ex ->
name = ex.__struct__
msg = Exception.message(ex)
elaborate_flunk("unexpected #{inspect name}: #{msg}", left: ex)
end
end
case arity(asserter) do
1 ->
fn input ->
step1.(input) |> asserter.()
end
_ ->
fn input, expected ->
step1.(input) |> asserter.(expected)
end
end
end
@doc """
A more concise version of `ExUnit.Assertions.assert_raise/3`, suitable for tabular tests.
A typical use looks like this:
"some error value" |> raises.("some error message")
Creation looks like this:
raises = TabularA.run_for_exception(&function_under_test/1)
As with `FlowAssertions.TabularA.run_and_assert/2`, multiple arguments are
passed in a list or tuple:
[-1, 3] |> raises.(~r/no negative values/)
As shown above, the expected message may be matched by a `String` or `Regex`.
You can also check which exception was thrown:
[3, 3] |> raises.(CaseClauseError)
If you want to check both the type and message, you have to enclose them
in a list:
[3, 3] |> raises.([CaseClauseError, ~R/no case clause/])
Note that you can put multiple regular expressions in the list to check different
parts of the message.
The generated function returns the exception, so it can be piped to later
assertions:
[3, 3] |> raises.([CaseClauseError, ~R/no case clause/])
|> assert_field(term: [3, 3])
"""
def run_for_exception(result_producer) do
runner = run(result_producer)
fn
input, check when is_list(check) -> run_for_raise(runner, input, check)
input, check -> run_for_raise(runner, input, [check])
end
end
@doc """
Return the results of both `run_and_assert` and `run_for_exception`.
{expect, raises} = TabularA.runners(&case_clause/2)
The optional second argument is passed to `expect`.
"""
def runners(result_producer, asserter \\ &MiscA.assert_equal/2) do
{run_and_assert(result_producer, asserter), run_for_exception(result_producer)}
end
# ----------------------------------------------------------------------------
defp run(result_producer) do
case arity(result_producer) do
1 ->
fn arg -> apply result_producer, [arg] end
n ->
fn args -> apply_multiple(result_producer, args, n) end
end
end
defp apply_multiple(result_producer, args, n) when is_list(args) do
elaborate_assert(
length(args) == n,
arity_description(n, length(args)),
left: args)
apply result_producer, args
end
defp apply_multiple(result_producer, args, n) when is_tuple(args),
do: apply_multiple(result_producer, Tuple.to_list(args), n)
defp apply_multiple(_result_producer, args, n) do
elaborate_flunk(arity_description(n, 1), left: args)
end
defp arity_description(n, not_n),
do: "The result producer takes #{n} arguments, not #{not_n}"
defp arity(function), do: Function.info(function) |> Keyword.get(:arity)
defp run_for_raise(runner, input, checks) do
try do
{:no_raise, runner.(input)}
rescue
ex ->
for expected <- checks do
cond do
is_atom(expected) ->
actual = ex.__struct__
elaborate_assert(actual == expected,
"An unexpected exception was raised",
left: actual,
right: expected)
expected ->
msg = Exception.message(ex)
elaborate_assert(MiscA.good_enough?(msg, expected),
"The exception message was incorrect",
left: msg, right: expected)
end
end
ex
else
{:no_raise, result} ->
msg = "An exception was expected, but a value was returned"
elaborate_flunk(msg, left: result)
end
end
end
|
lib/tabular_a.ex
| 0.881283 | 0.96859 |
tabular_a.ex
|
starcoder
|
defmodule APIacAuthClientJWT do
@moduledoc """
An `APIac.Authenticator` plug that implements the client authentication part of
[RFC7523](https://tools.ietf.org/html/rfc7523) (JSON Web Token (JWT) Profile for OAuth 2.0
Client Authentication and Authorization Grants).
This method consists in sending a MACed or signed JWT in the request body to the OAuth2 token
endpoint, for instance:
```http
POST /token.oauth2 HTTP/1.1
Host: as.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&
code=n0esc3NRze7LTCu7iYzS6a5acc3f0ogp4&
client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3A
client-assertion-type%3Ajwt-bearer&
client_assertion=<KEY>.
eyJpc3Mi[...omitted for brevity...].
cC4hiUPo[...omitted for brevity...]
```
OpenID Connect further specifies the `"client_secret_jwt"` and `"private_key_jwt"`
authentication methods
([OpenID Connect Core 1.0 incorporating errata set 1 - 9. Client Authentication](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication))
refining RFC7523.
## Plug options
- `:iat_max_interval`: the maximum time interval, in seconds, before a token with an `"iat"`
field is considered too far in the past. Defaults to `30`, which means token emitted longer
than 30 seconds ago will be rejected
- `:client_callback` [**mandatory**]: a callback that returns client configuration from its
`client_id`. See below for more details
- `error_response_verbosity`: one of `:debug`, `:normal` or `:minimal`.
Defaults to `:normal`
- `:protocol`: `:rfc7523` or `:oidc`. Defaults to `:oidc`. When using OpenID Connect, the
following additional checks are performed:
- the `"iss"` JWT field must be the client id
- the `"jti"` claim must be present
- `:jti_register`: a module implementing the
[`JTIRegister`](https://hexdocs.pm/jti_register/JTIRegister.html) behaviour, to protect
against token replay. Defaults to `nil`, **mandatory** if the protocol is set to `:oidc`
- `:server_metadata_callback` [**mandatory**]: OAuth2 / OpenID Connect server metadata. The
following fields are used:
- `"token_endpoint"`: the `"aud"` claim of the JWTs must match it
- `"token_endpoint_auth_signing_alg_values_supported"`: the MAC and signing algorithms
supported for verifying JWTs
- `set_error_response`: function called when authentication failed. Defaults to
`send_error_response/3`
Options are documented in `t:opts/0`.
## Client configuration
The client callback returns a map whose keys are those documented in
[OpenID Connect Dynamic Client Registration 1.0 incorporating errata set 1](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata).
This includes the `"client_secret"` field that is used for MACed JWTs.
The `"token_endpoint_auth_method"` is mandatory and must be set to either `"client_secret_jwt"`
or `"private_key_jwt"`.
## Determining allowed signature verification algorithms and keys
Signature verification algorithms:
- if the client's `"token_endpoint_auth_signing_alg"` is set, use this algorithm if it is
allowed by the `"token_endpoint_auth_signing_alg_values_supported"` server metadata, otherwise,
the `"token_endpoint_auth_signing_alg_values_supported"` value if used
- then, the client's `"token_endpoint_auth_method"` is used to filter only relevant algorithms
(MAC algorithms if `"token_endpoint_auth_method"` is set to `"client_secret_jwt"`, signature
algorithms otherwise)
Signature verification keys: if `"token_endpoint_auth_method"` is set to:
- `"client_secret_jwt"`: both the client's `"client_secret"` (if present) and `"jwks"` (if
present) fields are used to create the list of suitable MAC verification keys
- `"private_key_jwt"`: either `"jwks"` or `"jwks_uri"` are used to retrieve suitable signature
verification keys. Note that both fields should not be configured at the same time
## Replay protection
Replay protection can be implemented to prevent a JWT from being reused. This is mandatory when
using OpenID Connect.
The `:jti_register` allows configuring a module that implements the
[`JTIRegister`](https://hexdocs.pm/jti_register/JTIRegister.html) behaviour.
The [`JTIRegister.ETS`](https://hexdocs.pm/jti_register/JTIRegister.ETS.html) implementation
provides with a basic implementation for single node servers.
## Example
```elixir
plug APIacAuthClientJWT,
client_callback: &MyApp.Client.config/1,
protocol: :rfc7523,
server_metadata_callback: &MyApp.metadata.get/0
```
"""
@assertion_type "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
@jws_mac_algs ["HS256", "HS384", "HS512"]
@jws_sig_algs [
"Ed25519",
"Ed448",
"EdDSA",
"ES256",
"ES384",
"ES512",
"Poly1305",
"PS256",
"PS384",
"PS512",
"RS256",
"RS384",
"RS512"
]
@type opts :: [opt()]
@type opt ::
{:iat_max_interval, non_neg_integer()}
| {:client_callback, (client_id :: String.t() -> client_config())}
| {:error_response_verbosity, :debug | :normal | :minimal}
| {:protocol, :rfc7523 | :oidc}
| {:jti_register, module()}
| {:server_metadata_callback, (() -> server_metadata())}
| {:set_error_response,
(Plug.Conn.t(), %APIac.Authenticator.Unauthorized{}, any() -> Plug.Conn.t())}
@type client_config :: %{required(String.t()) => any()}
@type server_metadata :: %{required(String.t()) => any()}
@behaviour Plug
@behaviour APIac.Authenticator
@impl Plug
def init(opts) do
unless opts[:client_callback] || is_function(opts[:client_callback], 1),
do: raise("missing mandatory client callback")
unless opts[:server_metadata_callback] || is_function(opts[:server_metadata_callback], 0),
do: raise("missing mandatory server metadata callback")
opts =
opts
|> Keyword.put_new(:error_response_verbosity, :normal)
|> Keyword.put_new(:iat_max_interval, 30)
|> Keyword.put_new(:jti_register, nil)
|> Keyword.put_new(:protocol, :oidc)
|> Keyword.put_new(:set_error_response, &send_error_response/3)
if opts[:protocol] == :oidc and opts[:jti_register] == nil,
do: raise("missing replay protection implementation module, mandatory when OIDC is used")
opts
end
@impl Plug
def call(conn, opts) do
if APIac.authenticated?(conn) do
conn
else
do_call(conn, opts)
end
end
defp do_call(conn, opts) do
with {:ok, conn, credentials} <- extract_credentials(conn, opts),
{:ok, conn} <- validate_credentials(conn, credentials, opts) do
conn
else
{:error, conn, %APIac.Authenticator.Unauthorized{} = error} ->
opts[:set_error_response].(conn, error, opts)
end
end
@impl APIac.Authenticator
def extract_credentials(conn, _opts) do
case conn.body_params do
%{"client_assertion_type" => @assertion_type, "client_assertion" => client_assertion} ->
{:ok, conn, client_assertion}
_ ->
{
:error,
conn,
%APIac.Authenticator.Unauthorized{
authenticator: __MODULE__,
reason: :credentials_not_found
}
}
end
end
@impl APIac.Authenticator
def validate_credentials(conn, client_assertion, opts) do
with {:ok, client_id} <- get_client_id(conn, client_assertion),
client_config = opts[:client_callback].(client_id),
server_metadata = opts[:server_metadata_callback].(),
verification_algs = verification_algs(client_config, server_metadata),
verification_keys = verification_keys(client_config, verification_algs),
{:ok, jwt_claims} <- verify_jwt(client_assertion, verification_keys, verification_algs),
:ok <- validate_claims(jwt_claims, server_metadata, opts),
:ok <- check_jwt_not_replayed(jwt_claims, opts) do
if jwt_claims["jti"] && opts[:jti_register] do
opts[:jti_register].register(jwt_claims["jti"], jwt_claims["exp"])
end
conn =
conn
|> Plug.Conn.put_private(:apiac_authenticator, __MODULE__)
|> Plug.Conn.put_private(:apiac_client, client_id)
|> Plug.Conn.put_private(:apiac_metadata, jwt_claims)
{:ok, conn}
else
{:error, reason} ->
{
:error,
conn,
%APIac.Authenticator.Unauthorized{authenticator: __MODULE__, reason: reason}
}
end
end
@spec get_client_id(Plug.Conn.t(), String.t()) :: {:ok, String.t()} | {:error, atom()}
defp get_client_id(conn, client_assertion) do
jwt_sub =
client_assertion
|> JOSE.JWS.peek_payload()
|> Jason.decode!()
|> Map.get("sub")
case conn.body_params do
%{"client_id" => client_id} when client_id != jwt_sub ->
{:error, :client_id_jwt_issuer_mismatch}
_ ->
if jwt_sub do
{:ok, jwt_sub}
else
{:error, :jwt_claims_missing_field_sub}
end
end
rescue
_ ->
{:error, :invalid_jwt_payload}
end
@spec verification_algs(client_config(), server_metadata()) :: [JOSEUtils.JWA.sig_alg()]
defp verification_algs(client_config, server_metadata) do
server_algs = server_metadata["token_endpoint_auth_signing_alg_values_supported"] || []
client_alg = client_config["token_endpoint_auth_signing_alg"]
cond do
client_alg == "none" ->
raise "illegal client `token_endpoint_auth_signing_alg` used: `none`"
client_alg in server_algs ->
[client_alg]
client_alg != nil ->
[]
true ->
server_algs
end
|> Enum.filter(fn alg ->
case client_config["token_endpoint_auth_method"] do
"client_secret_jwt" ->
alg in @jws_mac_algs
"private_key_jwt" ->
alg in @jws_sig_algs
_ ->
[]
end
end)
end
@spec verification_keys(client_config(), [JOSEUtils.JWA.sig_alg()]) :: [JOSEUtils.JWK.t()]
defp verification_keys(client_config, algs) do
case client_config["token_endpoint_auth_method"] do
"client_secret_jwt" ->
client_mac_jwks(client_config)
"private_key_jwt" ->
client_asymmetric_keys(client_config)
_ ->
[]
end
|> JOSEUtils.JWKS.verification_keys(algs)
end
@spec client_mac_jwks(client_config()) :: [JOSEUtils.JWK.t()]
defp client_mac_jwks(client_config) do
mac_jwks =
Enum.filter(
client_config["jwks"]["keys"] || [],
fn jwk -> jwk["kty"] == "oct" end
)
case client_config do
%{"client_secret" => client_secret} ->
[%{"k" => Base.url_encode64(client_secret, padding: false), "kty" => "oct"}] ++ mac_jwks
_ ->
mac_jwks
end
end
@spec client_asymmetric_keys(client_config) :: [JOSEUtils.JWK.t()]
defp client_asymmetric_keys(client_config) do
case client_config do
%{"jwks" => %{"keys" => jwks}} ->
Enum.filter(jwks, fn jwk -> jwk["kty"] != "oct" end)
%{"jwks_uri" => jwks_uri} ->
case JWKSURIUpdater.get_keys(jwks_uri) do
{:ok, jwks} ->
# no filtering, there is no reason to have symmetric key returned here
jwks
{:error, _} ->
[]
end
_ ->
raise "no jwks or jwks_uri field set in client configuration"
end
end
@spec verify_jwt(
String.t(),
[JOSEUtils.JWK.t()],
[JOSEUtils.JWA.sig_alg()]
) :: {:ok, %{required(String.t()) => any()}} | {:error, atom()}
defp verify_jwt(client_assertion, jwks, allowed_algs) do
case JOSEUtils.JWS.verify(client_assertion, jwks, allowed_algs) do
{:ok, {payload, _key}} ->
case Jason.decode(payload) do
{:ok, claims} ->
{:ok, claims}
{:error, _} ->
{:error, :invalid_jwt_payload}
end
:error ->
{:error, :invalid_mac_or_signature}
end
end
@spec validate_claims(
%{required(String.t()) => any()},
server_metadata(),
opts()
) :: :ok | {:error, atom()}
defp validate_claims(claims, server_metadata, opts) do
cond do
claims["iss"] == nil ->
{:error, :jwt_claims_missing_field_iss}
claims["sub"] == nil ->
{:error, :jwt_claims_missing_field_sub}
claims["aud"] == nil ->
{:error, :jwt_claims_missing_field_aud}
claims["exp"] == nil ->
{:error, :jwt_claims_missing_field_exp}
claims["aud"] != server_metadata["token_endpoint"] ->
{:error, :jwt_claims_invalid_audience}
claims["exp"] < now() ->
{:error, :jwt_claims_expired}
claims["iat"] != nil and now() - claims["iat"] > opts[:iat_max_interval] ->
{:error, :jwt_claims_iat_too_far_in_the_past}
claims["nbf"] != nil and claims["nbf"] > now() ->
{:error, :jwt_claims_nbf_in_the_future}
opts[:protocol] == :oidc ->
validate_claims_oidc(claims)
true ->
:ok
end
end
@spec validate_claims_oidc(%{required(String.t()) => any()}) :: :ok | {:error, atom()}
defp validate_claims_oidc(claims) do
cond do
claims["iss"] != claims["sub"] ->
{:error, :jwt_claims_iss_sub_mismatch}
claims["jti"] == nil ->
{:error, :jwt_claims_missing_field_jti}
true ->
:ok
end
end
@spec check_jwt_not_replayed(%{required(String.t()) => any()}, opts()) :: :ok | {:error, atom()}
defp check_jwt_not_replayed(jwt_claims, opts) do
# at this point:
# - any JWT used within the OIDC protocol without jti has been rejected
# - the :jti_register is necessarily set when used with OIDC
if jwt_claims["jti"] && opts[:jti_register] do
if opts[:jti_register].registered?(jwt_claims["jti"]) do
{:error, :jwt_replayed}
else
:ok
end
else
:ok
end
end
@impl APIac.Authenticator
def send_error_response(conn, error, opts) do
error_response =
case opts[:error_response_verbosity] do
:debug ->
%{"error" => "invalid_client", "error_description" => Exception.message(error)}
:normal ->
error_description =
if error.reason == :credentials_not_found do
"JWT credential not found in request"
else
"Invalid JWT credential"
end
%{"error" => "invalid_client", "error_description" => error_description}
:minimal ->
%{"error" => "invalid_client"}
end
conn
|> Plug.Conn.put_resp_header("content-type", "application/json")
|> Plug.Conn.send_resp(400, Jason.encode!(error_response))
|> Plug.Conn.halt()
end
@doc """
Saves failure in a `t:Plug.Conn.t/0`'s private field and returns the `conn`
See the `APIac.AuthFailureResponseData` module for more information.
"""
@spec save_authentication_failure_response(
Plug.Conn.t(),
%APIac.Authenticator.Unauthorized{},
opts()
) :: Plug.Conn.t()
def save_authentication_failure_response(conn, error, opts) do
error_response =
case opts[:error_response_verbosity] do
:debug ->
%{"error" => "invalid_client", "error_description" => Exception.message(error)}
:normal ->
error_description =
if error.reason == :credentials_not_found do
"JWT credential not found in request"
else
"Invalid JWT credential"
end
%{"error" => "invalid_client", "error_description" => error_description}
:minimal ->
%{"error" => "invalid_client"}
end
failure_response_data = %APIac.AuthFailureResponseData{
module: __MODULE__,
reason: error.reason,
www_authenticate_header: nil,
status_code: 400,
body: Jason.encode!(error_response)
}
APIac.AuthFailureResponseData.put(conn, failure_response_data)
end
defp now(), do: System.system_time(:second)
end
|
lib/apiac_auth_client_jwt.ex
| 0.941163 | 0.794185 |
apiac_auth_client_jwt.ex
|
starcoder
|
defmodule Rbt.Consumer.Handler do
@moduledoc """
The `Rbt.Consumer.Handler` behaviour can be used to model RabbitMQ consumers.
See the [relevant RabbitMQ tutorial](https://www.rabbitmq.com/tutorials/tutorial-five-elixir.html)
for the principles behind topic-based consumers.
To use it:
### 1. Define a consumer handler module
This is done by using the `Rbt.Consumer.Handler` behaviour, which requires implementing a `c:handle_event/2` function (see its docs for more details about its expected return values.
defmodule MyHandler do
use Rbt.Consumer.Handler
def handle_event(event, meta) do
# do something with the event
:ok
end
end
### 2. Prepare your initial configuration
The consumer will be started with a configuration map that supports quite a few attributes.
- `definitions`: this is a map which represents the RabbitMQ objects needed by this consumer (exchange, queue and bindings).
All objects are created automatically when the the consumer is started. Properties in this map are:
- `exchange_name` (string): the name of the exchange to create/use
- `queue_name` (string): the name of the queue to create/use
- `routing_keys` (list of strings): the bindings between the exchange and the queue
- `durable_objects` (boolean, default `false`): if exchanges and queues will need to be written to disk (so choosing reliability over performance)
- `max_workers` (integer, default `5`): how many messages this consumer can handle in parallel at any given time. Note that this value will be used to both a) set a prefetch count on the channel, so that RabbitMQ will not deliver a 6th message unless any of the 5 before have been acknowledged b) limit the amount of processes that the consumer can spawn to handle messages to a maximum of 5.
- `max_retries` (integer or `:infinity`, default `:infinity`): how many times to attempt to process the message before giving up. Note that re-processing happens by rejecting the message and requeuing it, so there's no guarantee that the retry would be picked up by the same consumer instance (in case of a multi-node setup).
- `forward_failures` (boolean, default `false`): after exhausting retries or encountering a `:no_retry` failure, forward the failed message to an error specific exchange that a user can bind on. This is accomplished via dead letter exchange headers, so it's controlled at the queue declaration level. To know more about this: <https://www.rabbitmq.com/dlx.html>.
### 3. Start a consumer in the Supervision tree
Given a defined handler, this is a minimum setup:
consumer_config = %{
handler: MyHandler,
definitions: %{
exchange_name: "test-exchange",
queue_name: "test-queue",
routing_keys: ["test.topic"]
},
max_retries: 3
}
children = [
{Rbt.Consumer, consumer_config}
]
For more details on the consumer itself, see `Rbt.Consumer`.
"""
@typedoc """
An event can be any serializable term (see `Rbt.Data` for details
on what's supported out of the box, but a map is recommended to improve
management of backwards compatibility.
"""
@type event :: term
@typedoc """
Metadata for incoming messages, in form of a map.
"""
@type meta :: map
@type reason :: term
@type retry_policy :: :retry | :no_retry
@callback handle_event(event, meta) :: :ok | {:error, retry_policy, reason}
defmacro __using__(_opts) do
quote do
alias Rbt.Consumer.Handler
@behaviour Handler
@spec skip?(Handler.event(), Handler.meta()) :: boolean()
def skip?(_event, _meta), do: false
defoverridable skip?: 2
end
end
end
|
lib/rbt/consumer/handler.ex
| 0.909887 | 0.774541 |
handler.ex
|
starcoder
|
defmodule Kino.Bridge do
@moduledoc false
import Kernel, except: [send: 2]
# This module encapsulates the communication with Livebook
# achieved via the group leader. For the implementation of
# that group leader see Livebook.Evaluator.IOProxy
@type request_error :: :unsupported | :terminated
@doc """
Generates a unique, reevaluation-safe token.
If obtaining the token fails, a unique term is returned
instead.
"""
@spec generate_token() :: term()
def generate_token() do
case io_request(:livebook_generate_token) do
{:ok, token} -> token
{:error, _} -> System.unique_integer()
end
end
@doc """
Sends the given output as intermediate evaluation result.
"""
@spec put_output(Kino.Output.t()) :: :ok | {:error, request_error()}
def put_output(output) do
with {:ok, reply} <- io_request({:livebook_put_output, output}), do: reply
end
@doc """
Requests the current value of input with the given id.
Note that the input must be known to Livebook, otherwise
an error is returned.
"""
@spec get_input_value(String.t()) :: {:ok, term()} | {:error, request_error()}
def get_input_value(input_id) do
with {:ok, reply} <- io_request({:livebook_get_input_value, input_id}) do
case reply do
{:ok, value} ->
{:ok, value}
{:error, :not_found} ->
raise ArgumentError,
"failed to read input value, no input found for id #{inspect(input_id)}"
end
end
end
@doc """
Associates `object` with `pid`.
Any monitoring added to `object` will be dispatched once
all of its associated pids terminate or the associated
cells reevaluate.
See `monitor_object/3` to add a monitoring.
"""
@spec reference_object(term(), pid()) :: :ok | {:error, request_error()}
def reference_object(object, pid) do
with {:ok, reply} <- io_request({:livebook_reference_object, object, pid}), do: reply
end
@doc """
Monitors an existing object to send `payload` to `target`
when all of its associated pids or the associated cells
reevaluate.
It must be called after at least one reference is added
via `reference_object/2`.
"""
@spec monitor_object(term(), Process.dest(), payload :: term()) ::
:ok | {:error, request_error()}
def monitor_object(object, destination, payload) do
with {:ok, reply} <- io_request({:livebook_monitor_object, object, destination, payload}) do
case reply do
:ok ->
:ok
{:error, :bad_object} ->
raise ArgumentError,
"failed to monitor object #{inspect(object)}, at least one reference must be added via reference_object/2 first"
end
end
end
@doc """
Broadcasts the given message in Livebook to interested parties.
"""
@spec broadcast(String.t(), String.t(), term()) :: :ok | {:error, request_error()}
def broadcast(topic, subtopic, message) do
with {:ok, reply} <- io_request(:livebook_get_broadcast_target),
{:ok, pid} <- reply do
send(pid, {:runtime_broadcast, topic, subtopic, message})
:ok
end
end
@doc """
Sends message to the given Livebook process.
"""
@spec send(pid(), term()) :: :ok
def send(pid, message) do
# For now we send directly
Kernel.send(pid, message)
:ok
end
defp io_request(request) do
gl = Process.group_leader()
ref = Process.monitor(gl)
Kernel.send(gl, {:io_request, self(), ref, request})
result =
receive do
{:io_reply, ^ref, {:error, {:request, _}}} -> {:error, :unsupported}
{:io_reply, ^ref, {:error, :request}} -> {:error, :unsupported}
{:io_reply, ^ref, reply} -> {:ok, reply}
{:DOWN, ^ref, :process, _object, _reason} -> {:error, :terminated}
end
Process.demonitor(ref, [:flush])
result
end
end
|
lib/kino/bridge.ex
| 0.793666 | 0.456773 |
bridge.ex
|
starcoder
|
defmodule Saucexages.IO.FileReader do
@moduledoc """
Reads SAUCE data from files according to the SAUCE specification.
SAUCE data is decoded decoded according to the SAUCE spec.
If you are working with small files, it is recommended to use `Saucexages.IO.BinaryReader` instead.
Files are opened with read and binary flags, and as such must be available for reading.
## General Usage
The general use-case for the file reader is to work with binaries that you cannot fit in memory or you wish to offload some of the boiler-plate IO to this module.
A general usage pattern on a local machine might be as follows:
`FileReader.sauce("LD-ACID2.ANS")`
## Layout
The layout of the binary read is assumed to be consistent with what is described in `Saucexages.IO.BinaryReader`.
The SAUCE must exist at the *end* of a file, per the SAUCE spec. As such, this reader assumes that reading should begin at the end-of-file position (eof position). Note that this is *not* the same as the *end-of-file character* (eof character). The difference lies in the fact that the eof character comes before the SAUCE data, while the eof itself is the true termination of the file.
SAUCE Block data itself is limited to 128 bytes for the SAUCE record, and 255 comment lines of 64-bytes each + 5 bytes for a comment ID. Therefore if you are not dealing with corrupted files, you can read a maximum of 128 + (255 * 64) + 5 bytes, or 16,453 bytes before you can give up scanning for a SAUCE. In practice, if you wish to scan a file in this manner, it may be better to follow the spec as this module does, or to scan up to the first eof character, starting from the eof position.
## Notes
There are many SAUCE files in the wild that have data written *after* the SAUCE record, multiple eof characters, and multiple SAUCE records. As such, these cases are dealt with universally by obeying the SAUCE specification. Multiple eof characters is very common as many SAUCE writers have naively appended eof characters on each write instead of truncating the file after the eof character or doing an in-place update.
Specifically, this reader will always read *only* from the eof position. It is possible to fix these cases using the `Saucexages.SauceBinary` module as well as some general binary matching, however these fixes should be viewed as outside the scope and concerns of this reader.
Reads often require multiple position changes using the current device. This is because the comments cannot be reliably obtained without first scanning the SAUCE record. The comments block itself is of variable size and cannot reliably be obtained otherwise. If this is a concern, consider using the binary reader and reading the entire file or a feasible chunk that will obtain the SAUCE block data.
"""
require Saucexages.Sauce
alias Saucexages.{Sauce, SauceBlock}
alias Saucexages.IO.SauceBinary
alias Saucexages.Codec.Decoder
@doc """
Reads a file containing a SAUCE record and returns decoded SAUCE information as `{:ok, sauce_block}`.
If the file does not contain a SAUCE record, `{:error, :no_sauce}` is returned.
"""
@spec sauce(Path.t()) :: {:ok, SauceBlock.t} | {:error, :no_sauce} | {:error, term()}
def sauce(path) when is_binary(path) do
case File.open(path, [:binary, :read], &do_read_sauce/1) do
{:ok, result} -> result
err -> err
end
end
@doc """
Reads a binary containing a SAUCE record and returns the raw binary in the form `{:ok, {sauce_bin, comments_bin}}`.
If the binary does not contain a SAUCE record, `{:error, :no_sauce}` is returned.
"""
@spec raw(Path.t()) :: {:ok, {binary(), binary()}} | {:error, :no_sauce} | {:error, term()}
def raw(path) when is_binary(path) do
case File.open(path, [:binary, :read], &do_read_raw/1) do
{:ok, result} -> result
err -> err
end
end
@doc """
Reads a binary and returns the contents without the SAUCE block.
It is not recommended to use this function for large files. Instead, get the index of where the SAUCE block starts and read until that point using a stream if you need the file contents.
"""
@spec contents(Path.t()) :: {:ok, binary()} | {:error, term()}
def contents(path) when is_binary(path) do
with {:ok, file_bin} <- File.read(path) do
SauceBinary.contents(file_bin)
end
end
@doc """
Reads a file containing a SAUCE record and returns the decoded SAUCE comments.
"""
@spec comments(binary()) :: {:ok, [String.t]} | {:error, :no_sauce} | {:error, :no_comments} | {:error, term()}
def comments(path) when is_binary(path) do
case File.open(path, [:binary, :read], &do_read_comments/1) do
{:ok, result} -> result
err -> err
end
end
@doc """
Reads a file with a SAUCE record and returns whether or not a SAUCE comments block exists within the SAUCE block.
Will match a comments block only if it a SAUCE record exists. Comment fragments are not considered to be valid without the presence of a SAUCE record.
"""
@spec comments?(binary()) :: boolean()
def comments?(path) when is_binary(path) do
case File.open(path, [:binary, :read], &do_comments?/1) do
{:ok, result} -> result
err -> err
end
end
@doc """
Reads a file and returns whether or not a SAUCE record exists.
"""
@spec sauce?(Path.t()) :: boolean()
def sauce?(path) when is_binary(path) do
case File.open(path, [:binary, :read], &do_sauce?/1) do
{:ok, result} -> result
err -> err
end
end
defp do_read_comments(fd) do
with {:ok, comment_lines} <- read_comment_lines(fd),
{:ok, comments} = comments_result <- read_comments_block(fd, comment_lines),
[_ | _] <- comments do
comments_result
else
[] -> {:error, :no_comments}
{:error, _reason} = err -> err
_ -> {:error, "Unable to read SAUCE comments."}
end
end
defp do_comments?(fd) do
with {:ok, comment_lines} <- read_comment_lines(fd),
{:ok, _comments} <- extract_comments_block(fd, comment_lines) do
true
else
_ ->
false
end
end
defp do_sauce?(fd) do
case extract_sauce_binary(fd) do
{:ok, _sauce_bin} -> true
_ -> false
end
end
defp do_read_sauce(fd) do
with {:ok, sauce_record_bin} <- extract_sauce_binary(fd),
{:ok, %{comment_lines: comment_lines} = sauce_record} <- Decoder.decode_record(sauce_record_bin),
{:ok, comments} <- read_comments_block(fd, comment_lines)
do
Decoder.decode_sauce(sauce_record, comments)
else
{:error, _reason} = err -> err
err -> {:error, {"Unable to read sauce", err}}
end
end
defp do_read_raw(fd) do
with {:ok, sauce_record_bin} <- extract_sauce_binary(fd),
{:ok, %{comment_lines: comment_lines} = _sauce_record} <- Decoder.decode_record(sauce_record_bin),
{:ok, comments_bin} when is_binary(comments_bin) <- extract_comments_block(fd, comment_lines)
do
{:ok, {sauce_record_bin, comments_bin}}
else
{:error, _reason} = err -> err
err -> {:error, {"Unable to read sauce", err}}
end
end
defp read_comments_block(fd, comment_lines) when is_integer(comment_lines) and comment_lines > 0 do
with {:ok, comments_bin} when is_binary(comments_bin) <- extract_comments_block(fd, comment_lines) do
Decoder.decode_comments(comments_bin, comment_lines)
else
# Here we try to be tolerant in case the comment line value from the SAUCE record was nonsense
{:error, :no_comments} -> {:ok, []}
# Here we may have failed for some other reason, like the OS so in this case we do want to be intolerant
{:error, _reason} = err -> err
_ -> {:error, "Unable to read comments block."}
end
end
defp read_comments_block(_fd, comment_lines) when is_integer(comment_lines) do
{:ok, []}
end
defp read_comment_lines(fd) do
case extract_sauce_binary(fd) do
{:ok, sauce_record_bin} ->
SauceBinary.comment_lines(sauce_record_bin)
{:error, _reason} = err ->
err
end
end
defp extract_sauce_binary(fd) do
with {:ok, file_size} <- :file.position(fd, :eof),
true <- file_size >= Sauce.sauce_record_byte_size(),
{:ok, _offset} = :file.position(fd, {:eof, -Sauce.sauce_record_byte_size()}),
{:ok, sauce_record_bin} = :file.read(fd, Sauce.sauce_record_byte_size()),
true <- SauceBinary.matches_sauce?(sauce_record_bin) do
{:ok, sauce_record_bin}
else
false -> {:error, :no_sauce}
{:error, _reason} = err -> err
_ -> {:error, "Error reading SAUCE record binary."}
end
end
defp extract_comments_block(fd, comment_lines) when is_integer(comment_lines) and comment_lines > 0 do
with comment_block_offset <- Sauce.sauce_byte_size(comment_lines),
comment_block_size <- Sauce.comment_block_byte_size(comment_lines),
# we could use cursor here, but the cursor should normally be at eof after reading the SAUCE so we might as well read from eof to be safer
{:ok, _comments_offset} = :file.position(fd, {:eof, -comment_block_offset}),
{:ok, comments_bin} = comments_result <- :file.read(fd, comment_block_size),
true <- SauceBinary.matches_comment_block?(comments_bin) do
comments_result
else
false -> {:error, :no_comments}
# We tried to read but maybe the comment line pointer was inaccurate/wrong.
# Rather than erroring out, we try to be tolerant as this case is somewhat common in the wild.
{:error, :einval} -> {:error, :no_comments}
{:error, _reason} = err -> err
err -> {:error, "Unable to read SAUCE comments.", err}
end
end
defp extract_comments_block(_bin, comment_lines) when is_integer(comment_lines) do
# no comments present but we tried to grab them anyway
{:error, :no_comments}
end
end
|
lib/saucexages/io/file_reader.ex
| 0.836454 | 0.654046 |
file_reader.ex
|
starcoder
|
defmodule Mix.Tasks.Absinthe.Gen.Scaffold do
use Mix.Task
alias AbsintheGen.{RenderTemplate, OutputFiles}
@shortdoc "Create absinthe scaffold files."
@moduledoc """
Will generate a scaffold consisting of a schema, type and resolver files. Multiple fields are accepted.
Example:
```
mix absinthe.gen.scaffold my_context my_type my_field:string my_other_field:string [OPTIONS]
Created:
lib/absinthe_app_web/schema/my_context_types.ex
lib/absinthe_app_web/schema.ex
lib/absinthe_app_web/resolvers/my_type.ex
```
Options:
* `--path PATH` - specify a path where to create the generated files
"""
def run(args) do
parent_app = AbsintheGen.parent_app()
{options, [context | [name | attrs]], _} = OptionParser.parse(args, switches: [path: :string])
path = options[:path]
create_files(path, parent_app, context, name, attrs)
end
defp create_files(path, parent_app, context, name, attrs) do
ctx = %{web_module: web_module(parent_app)}
schema = %{
alias: context |> Macro.camelize() |> String.capitalize(),
name: name,
name_plural: "#{name}s",
attrs: parse_attrs(attrs)
}
types_contents = RenderTemplate.render_types(ctx, schema)
schema_contents = RenderTemplate.render_schema(ctx, schema)
resolver_contents = RenderTemplate.render_resolver(ctx, schema)
[
{["lib", "#{parent_app}_web", path, "schema", "#{context}_types.ex"], types_contents},
{["lib", "#{parent_app}_web", path, "schema.ex"], schema_contents},
{["lib", "#{parent_app}_web", path, "resolvers", "#{context}.ex"], resolver_contents}
]
|> Enum.map(fn {path_list, content} ->
{path_list |> Enum.filter(& &1) |> Path.join(), content}
end)
|> OutputFiles.write_files()
|> AbsintheGen.print_message()
end
defp web_module(parent_app),
do:
"#{
parent_app
|> Atom.to_string()
|> Macro.camelize()
}Web"
defp parse_attrs(attrs) when is_list(attrs) do
attrs
|> Enum.map(fn attr_key_pair ->
String.split(attr_key_pair, ":")
end)
|> Enum.filter(fn
[_, _] -> true
_ -> false
end)
|> Enum.into(%{}, fn [a, b] -> {a, b} end)
end
end
|
lib/mix/absinthe.gen.scaffold.ex
| 0.798619 | 0.40539 |
absinthe.gen.scaffold.ex
|
starcoder
|
defmodule LruCacheGenServer do
@moduledoc """
This module implements a simple LRU cache that support storing any type of value,
implemented as a GenServer backed by ETS using 3 ets tables.
For using it, you need to start it:
iex> LruCacheGenServer.start_link(1000)
## Using it
iex> LruCacheGenServer.start_link(1000)
{:ok, #PID<0.60.0>}
iex> LruCacheGenServer.put("id", "value")
:ok
iex> LruCacheGenServer.get("id")
"value"
iex> LruCacheGenServer.put(:k2, 2)
:ok
iex> LruCacheGenServer.get(:k2)
2
iex> LruCacheGenServer.delete("id")
:ok
## Design
First ets table `:lrucache_info` save capacity of the cache.
Second ets set table `:lrucache_stored` save the cache content, each cached content is a tuple of
{key, time, value} where:
`key`, `value` are the cached key value pair, the `key` is used as key in this table
`time` is the last accessed/modified time. This will be updated every access or update
Third ets ordered_set table `:lru_keys`
The list is a list of tuple, where each tuple is {time, key} where:
`time` is the last accessed/modified time, updated every access or update. It is used as key in this table
`key` refer to the key in the `:lrucache_stored` ets table
The list is sorted by the `time` asc order, least used is the first of list.
Every time item evict action required, first of the list is popoff.
Every time item is touched, new `time` is replaced with old `time`(and item move to the end of list)
"""
use GenServer
@doc """
Creates an LRU cache of the given size
"""
def start_link(capacity) do
Agent.start_link(__MODULE__, :init, [capacity], name: __MODULE__)
end
@doc """
Get the value of given key from the cache. If cache already has the key,
this updates the order of LRU cache.
"""
def get(key) do
Agent.get(__MODULE__, __MODULE__, :handle_get, [key])
end
@doc """
Store the given key value pair in the cache. If cache already has the key, the stored
value is replaced by the new one. This updates the order of LRU cache.
"""
def put(key, value) do
Agent.get(__MODULE__, __MODULE__, :handle_put, [key, value])
end
@doc """
Delete the key value pair of given key from the cache.
"""
def delete(key) do
Agent.get(__MODULE__, __MODULE__, :handle_delete, [key])
end
@doc false
def init(capacity) do
:ets.new(:lrucache_info, [:named_table, :protected])
:ets.new(:lrucache_stored, [:named_table, :protected, :set])
:ets.new(:lru_keys, [:named_table, :protected, :ordered_set])
cap = if (capacity > 0), do: capacity, else: 0
:ets.insert(:lrucache_info, {:capacity, cap})
end
@doc false
def handle_get(state, key) do
if (:ets.member(:lrucache_stored, key)) do
newTime = :erlang.unique_integer([:monotonic])
[{_, oldTime, value}] = :ets.lookup(:lrucache_stored, key)
delete_existing(oldTime, key)
insert_new(newTime, key, value)
value
else
nil
end
end
@doc false
def handle_put(state, key, value) do
newTime = :erlang.unique_integer([:monotonic])
capacity = :ets.lookup(:lrucache_info, :capacity)[:capacity]
size = :ets.info(:lrucache_stored)[:size]
if size == capacity && !(:ets.member(:lrucache_stored, key)) do
lru_key_time = :ets.first(:lru_keys)
[{_, lru_key}] = :ets.lookup(:lru_keys, lru_key_time)
delete_existing(lru_key_time, lru_key)
insert_new(newTime, key, value)
else
if :ets.member(:lrucache_stored, key) do
[{_,oldTime,_}] = :ets.lookup(:lrucache_stored, key)
delete_existing(oldTime, key)
end
insert_new(newTime, key, value)
end
:ok
end
@doc false
def handle_delete(state, key) do
if (:ets.member(:lrucache_stored, key)) do
[{_,oldTime,_}] = :ets.lookup(:lrucache_stored, key)
delete_existing(oldTime, key)
:ok
else
:not_found
end
end
defp delete_existing(oldTime, oldKey) do
:ets.delete(:lru_keys, oldTime)
:ets.delete(:lrucache_stored, oldKey)
end
defp insert_new(newTime, newKey, value) do
:ets.insert(:lru_keys, {newTime, newKey})
:ets.insert(:lrucache_stored, {newKey, newTime, value})
end
end
|
lib/lru_cache_gen_server.ex
| 0.708717 | 0.494507 |
lru_cache_gen_server.ex
|
starcoder
|
defmodule Madness.Story do
@moduledoc """
Stories are a graph of areas, along with a pointer
to the starting area.
Stories are driven by choices given to a player,
rather than natural language parsing which may be frustrating.
"""
require Logger
alias Madness.Story.Areas.Supervisor, as: SArea
# Track a single story's data
defmodule Data do
@moduledoc """
Struct wrapper for story data
"""
defstruct initial: nil, title: "", id: nil
end
use GenServer
@spec start_link(binary) :: pid
def start_link(story) do
Logger.debug "Starting a story #{story}"
GenServer.start_link(__MODULE__, [story], name: via_tuple(story))
end
defp via_tuple(story) do
{:via, :gproc, {:n, :l, {:madness, :story, story}}}
end
@spec whereis(binary) :: pid
def whereis(story) do
:gproc.whereis_name({:n, :l, {:madness, :story, story}})
end
@spec get_initial(pid) :: {:ok, binary}
def get_initial(server) when is_pid(server) do
GenServer.call(server, {:initial})
end
@spec add_area(pid) :: {:ok, binary}
def add_area(server) when is_pid(server) do
GenServer.call(server, {:add_area})
end
@spec set_initial(pid, binary) :: :ok
def set_initial(server, area) when is_pid(server) do
GenServer.call(server, {:set_initial, area})
end
@spec init([binary]) :: {:ok, Data}
def init([story]) do
# TODO load from disk
{:ok, %Data{id: story}}
end
@spec handle_call(tuple, pid, Data) :: tuple
def handle_call({:initial}, _from, state) do
initial = state.initial
case initial do
nil -> {:reply, {:error, :no_initial_state}, state}
init_val -> {:reply, {:ok, init_val}, state}
end
end
def handle_call({:add_area}, _from, state) do
story = state.id
server = SArea.whereis(story)
{:ok, area} = SArea.add_area(server, story)
# TODO add to state
{:reply, {:ok, area}, state}
end
def handle_call({:set_initial, area}, _from, state) do
new_state = %{state | initial: area}
{:reply, :ok, new_state}
end
end
|
lib/madness/story.ex
| 0.564939 | 0.472014 |
story.ex
|
starcoder
|
defmodule BMP280.BMP280Calibration do
@moduledoc false
@type t() :: %{
type: :bmp280,
dig_t1: char,
dig_t2: integer,
dig_t3: integer,
dig_p1: char,
dig_p2: integer,
dig_p3: integer,
dig_p4: integer,
dig_p5: integer,
dig_p6: integer,
dig_p7: integer,
dig_p8: integer,
dig_p9: integer
}
@spec from_binary(<<_::192>>) :: t()
def from_binary(
<<dig_t1::little-16, dig_t2::little-signed-16, dig_t3::little-signed-16,
dig_p1::little-16, dig_p2::little-signed-16, dig_p3::little-signed-16,
dig_p4::little-signed-16, dig_p5::little-signed-16, dig_p6::little-signed-16,
dig_p7::little-signed-16, dig_p8::little-signed-16, dig_p9::little-signed-16>>
) do
%{
type: :bmp280,
dig_t1: dig_t1,
dig_t2: dig_t2,
dig_t3: dig_t3,
dig_p1: dig_p1,
dig_p2: dig_p2,
dig_p3: dig_p3,
dig_p4: dig_p4,
dig_p5: dig_p5,
dig_p6: dig_p6,
dig_p7: dig_p7,
dig_p8: dig_p8,
dig_p9: dig_p9
}
end
@spec raw_to_temperature(t(), integer()) :: float()
def raw_to_temperature(cal, raw_temp) do
var1 = (raw_temp / 16_384 - cal.dig_t1 / 1024) * cal.dig_t2
var2 =
(raw_temp / 131_072 - cal.dig_t1 / 8192) * (raw_temp / 131_072 - cal.dig_t1 / 8192) *
cal.dig_t3
(var1 + var2) / 5120
end
@spec raw_to_pressure(t(), number(), integer()) :: float()
def raw_to_pressure(cal, temp, raw_pressure) do
t_fine = temp * 5120
var1 = t_fine / 2 - 64_000
var2 = var1 * var1 * cal.dig_p6 / 32_768
var2 = var2 + var1 * cal.dig_p5 * 2
var2 = var2 / 4 + cal.dig_p4 * 65_536
var1 = (cal.dig_p3 * var1 * var1 / 524_288 + cal.dig_p2 * var1) / 524_288
var1 = (1 + var1 / 32_768) * cal.dig_p1
p = 1_048_576 - raw_pressure
p = (p - var2 / 4096) * 6250 / var1
var1 = cal.dig_p9 * p * p / 2_147_483_648
var2 = p * cal.dig_p8 / 32_768
p = p + (var1 + var2 + cal.dig_p7) / 16
p
end
end
|
lib/bmp280/calibration/bmp280_calibration.ex
| 0.613237 | 0.473901 |
bmp280_calibration.ex
|
starcoder
|
defmodule Mecab do
@moduledoc """
Elixir bindings for MeCab, a Japanese morphological analyzer.
Each parser function returns a list of map.
The map's keys meanings is as follows.
- `surface_form`: 表層形
- `part_of_speech`: 品詞
- `part_of_speech_subcategory1`: 品詞細分類1
- `part_of_speech_subcategory2`: 品詞細分類2
- `part_of_speech_subcategory3`: 品詞細分類3
- `conjugation_form`: 活用形
- `conjugation`: 活用型
- `lexical_form`: 原形
- `yomi`: 読み
- `pronunciation`: 発音
Note: To distinguish things clearly, we call this module "Mecab" and
a mecab command either "MeCab" or "mecab".
"""
@doc """
Parse given string and returns an list of map.
Options can also be supplied:
- `:mecab_option` --
specify MeCab options <br>(e.g. `"-d /usr/local/lib/mecab/dic/ipadic"`)
## Examples
iex> Mecab.parse("今日は晴れです")
[%{"conjugation" => "",
"conjugation_form" => "",
"lexical_form" => "今日",
"part_of_speech" => "名詞",
"part_of_speech_subcategory1" => "副詞可能",
"part_of_speech_subcategory2" => "",
"part_of_speech_subcategory3" => "",
"pronunciation" => "キョー",
"surface_form" => "今日",
"yomi" => "キョウ"},
%{"conjugation" => "",
"conjugation_form" => "",
"lexical_form" => "は",
"part_of_speech" => "助詞",
"part_of_speech_subcategory1" => "係助詞",
"part_of_speech_subcategory2" => "",
"part_of_speech_subcategory3" => "",
"pronunciation" => "ワ",
"surface_form" => "は",
"yomi" => "ハ"},
%{"conjugation" => "",
"conjugation_form" => "",
"lexical_form" => "晴れ",
"part_of_speech" => "名詞",
"part_of_speech_subcategory1" => "一般",
"part_of_speech_subcategory2" => "",
"part_of_speech_subcategory3" => "",
"pronunciation" => "ハレ",
"surface_form" => "晴れ",
"yomi" => "ハレ"},
%{"conjugation" => "基本形",
"conjugation_form" => "特殊・デス",
"lexical_form" => "です",
"part_of_speech" => "助動詞",
"part_of_speech_subcategory1" => "",
"part_of_speech_subcategory2" => "",
"part_of_speech_subcategory3" => "",
"pronunciation" => "デス",
"surface_form" => "です",
"yomi" => "デス"},
%{"conjugation" => "",
"conjugation_form" => "",
"lexical_form" => "",
"part_of_speech" => "",
"part_of_speech_subcategory1" => "",
"part_of_speech_subcategory2" => "",
"part_of_speech_subcategory3" => "",
"pronunciation" => "",
"surface_form" => "EOS",
"yomi" => ""}]
"""
@spec parse(String.t, Keyword.t) :: [Map.t, ...]
def parse(str, option \\ []) do
read_from_file = option[:from_file]
mecab_option = option[:mecab_option]
command =
case read_from_file do
true ->
"mecab '#{str}' #{mecab_option}"
x when x == nil or x == false ->
"""
cat <<'EOS.907a600613b96a88c04a' | mecab #{mecab_option}
#{str}
EOS.907a600613b96a88c04a
"""
end
command
|> to_charlist
|> :os.cmd
|> to_string
|> String.trim
|> String.split("\n")
|> Enum.map(fn line ->
Regex.named_captures(~r/
^
(?<surface_form>[^\t]+)
(?:
\s
(?<part_of_speech>[^,]+),
\*?(?<part_of_speech_subcategory1>[^,]*),
\*?(?<part_of_speech_subcategory2>[^,]*),
\*?(?<part_of_speech_subcategory3>[^,]*),
\*?(?<conjugation_form>[^,]*),
\*?(?<conjugation>[^,]*),
(?<lexical_form>[^,]*)
(?:
,(?<yomi>[^,]*)
,(?<pronunciation>[^,]*)
)?
)?
$
/x, line)
end)
end
@doc """
Parse given file and returns an list of map.
In addition to Mecab.parse(path, from_file: true),
this function checks if a given path is exists.
Options can also be supplied:
- `:mecab_option` --
specify MeCab options <br>(e.g. `"-d /usr/local/lib/mecab/dic/ipadic"`)
## Examples
iex> File.read!("sample.txt")
"今日は晴れです。\\n明日は雨でしょう。\\n"
iex> Mecab.read("sample.txt")
{:ok,
[%{"surface_form" => "今日", "part_of_speech" => "名詞", ...},
%{"surface_form" => "は", "part_of_speech" => "助詞", ...},
%{"surface_form" => "晴れ", "part_of_speech" => "名詞", ...},
%{"surface_form" => "です", "part_of_speech" => "助動詞", ...},
%{"surface_form" => "。", "part_of_speech" => "記号", ...},
%{"surface_form" => "EOS", ...},
%{"surface_form" => "明日", "part_of_speech" => "名詞", ...},
%{"surface_form" => "は", "part_of_speech" => "助詞", ...},
%{"surface_form" => "雨", "part_of_speech" => "名詞", ...},
%{"surface_form" => "でしょ", "part_of_speech" => "助動詞", ...},
%{"surface_form" => "う", "part_of_speech" => "助動詞", ...},
%{"surface_form" => "。", "part_of_speech" => "記号", ...},
%{"surface_form" => "EOS", ...}]}
iex> Mecab.read("not_found.txt")
{:error, "no such a file or directory: not_found.txt"}
"""
@spec read(String.t, Keyword.t) :: {:ok, [Map.t, ...]} | {:error, String.t}
def read(path, option \\ []) do
case File.exists?(path) do
true ->
{:ok, parse(path, [from_file: true] ++ option)}
false ->
{:error, "no such a file or directory: #{path}"}
end
end
@doc """
Parse given file and returns an list of map.
In addition to Mecab.parse(path, from_file: true),
this function checks if a given path is exists.
Options can also be supplied:
- `:mecab_option` --
specify MeCab options <br>(e.g. `"-d /usr/local/lib/mecab/dic/ipadic"`)
## Examples
iex> File.read!("sample.txt")
"今日は晴れです。\\n明日は雨でしょう。\\n"
iex> Mecab.read!("sample.txt")
[%{"surface_form" => "今日", "part_of_speech" => "名詞", ...},
%{"surface_form" => "は", "part_of_speech" => "助詞", ...},
%{"surface_form" => "晴れ", "part_of_speech" => "名詞", ...},
%{"surface_form" => "です", "part_of_speech" => "助動詞", ...},
%{"surface_form" => "。", "part_of_speech" => "記号", ...},
%{"surface_form" => "EOS", ...},
%{"surface_form" => "明日", "part_of_speech" => "名詞", ...},
%{"surface_form" => "は", "part_of_speech" => "助詞", ...},
%{"surface_form" => "雨", "part_of_speech" => "名詞", ...},
%{"surface_form" => "でしょ", "part_of_speech" => "助動詞", ...},
%{"surface_form" => "う", "part_of_speech" => "助動詞", ...},
%{"surface_form" => "。", "part_of_speech" => "記号", ...},
%{"surface_form" => "EOS", ...}]
"""
@spec read!(String.t, Keyword.t) :: [Map.t, ...]
def read!(path, option \\ []) do
if !File.exists?(path) do
raise "no such a file or directory: #{path}"
end
parse(path, [from_file: true] ++ option)
end
end
|
lib/mecab.ex
| 0.63443 | 0.438184 |
mecab.ex
|
starcoder
|
defmodule Blake3 do
@moduledoc """
Blake3 provides bindings to the rust implementaion of the BLAKE3 hashing algorithm.
See the [README](readme.html) for installation and usage examples
"""
alias Blake3.Native
@type hasher :: reference()
@doc """
computes a message digest for the given data
"""
@spec hash(data :: binary()) :: binary()
def hash(data) do
Native.hash(data)
end
@doc """
computes a message digest for the given data and key.
The key must be 32 bytes. if you need to use a key of a
diffrent size you can use `derive_key` to get a key of
a proper size.
"""
@spec keyed_hash(key :: binary(), data :: binary()) :: binary() | {:error, String.t()}
def keyed_hash(key, data) when byte_size(key) == 32 do
Native.keyed_hash(key, data)
end
def keyed_hash(_key, _data) do
{:error, "Error: Key must be 32 bytes"}
end
@doc """
returns a new reference for a Blake3 hasher to be used
for streaming calls with update/2
"""
@spec new() :: hasher()
def new() do
Native.new()
end
@doc """
returns a new reference for a Blake3 hasher using the passed key
to be used for streaming calls with update/2
"""
@spec new_keyed(key :: binary()) :: hasher() | {:error, String.t()}
def new_keyed(key) when byte_size(key) == 32 do
Native.new_keyed(key)
end
def new_keyed(_key) do
{:error, "Error: Key must be 32 bytes"}
end
@doc """
updates the hasher with the given data to be hashed the
the refernce can be continouly passed to update/2 or
when finished to finalize/1
"""
@spec update(state :: hasher(), data :: binary()) :: hasher()
def update(state, data) do
Native.update(state, data)
end
@doc """
returns the binary of the current hash state for a
given hasher
"""
@spec finalize(state :: hasher()) :: binary()
def finalize(state) do
Native.finalize(state)
end
@doc """
returns a 32 byte key for use for `hash_keyed` or `new_keyed` from
the given context and key. for more information: [crate](https://github.com/BLAKE3-team/BLAKE3#the-blake3-crate-)
"""
@spec derive_key(context :: binary(), key :: binary()) :: binary()
def derive_key(context, key) do
Native.derive_key(context, key)
end
@doc """
same as `derive_key/2` but uses an empty string for context
"""
@spec derive_key(key :: binary()) :: binary()
def derive_key(key) do
Native.derive_key("", key)
end
@doc """
reset a hasher to the default stat like when calling Blake3.new
"""
@spec derive_key(state :: hasher()) :: hasher()
def reset(state) do
Native.reset(state)
end
@doc """
updates state with the potential to multithreading. The rayon
feature needs to be enabled and the input need to be large enough.
for more information see:
[documentation](https://docs.rs/blake3/1.0.0/blake3/struct.Hasher.html#method.update_rayon)
"""
@spec update_rayon(state :: hasher(), data :: binary()) :: hasher()
def update_rayon(state, data) do
Native.update_rayon(state, data)
end
end
|
lib/blake3.ex
| 0.861407 | 0.601418 |
blake3.ex
|
starcoder
|
defmodule SvgSprite do
@moduledoc """
> Want the wonderful goodness of SVG without having the need for our SVG + JS framework at the moment? Have no fear, SVG Sprites are here. We have lovingly prepped all the icon set styles into their own SVG sprites.
This quote is taken from the Font Awesome documentation about [SVG sprites](https://fontawesome.com/how-to-use/on-the-web/advanced/svg-sprites). I love the Font Awesome icons, but I'm not particularly eager to use their JavaScript code, the CSS files or the webfont. So the "big" SVG sprite files provided by this library are just the perfect solution for me.
SvgSprite helps you to embed these SVG sprites in your Phoenix template. Instead of writing verbose code like this:
```html
<a href="https://facebook.com/fontawesome">
<svg fill="currentColor" class="w-5 h-5">
<use xlink:href="/images/brands.svg#facebook"></use>
</svg>
</a>
```
It is much nicer to just write.
```html
<a href="https://facebook.com/fontawesome">
<%= icon("brands", "facebook", class: "w-5 h-5") %>
</a>
```
Or use atoms for the icon family and name.
```html
<a href="https://facebook.com/fontawesome">
<%= icon(:brands, :facebook, class: "w-5 h-5") %>
</a>
```
This library is inspired by Font Awesome but it is not limited to it. Basically, it expects a SVG sprite file inside a base path which contains all the symbols. Every symbol has to have a unique name as its HTML id attribute.
The example above expects a file named `brands.svg` inside your `images` static path. Inside this file a symbol with the id `facebook` has to exist.
## Installation
Attrition can be installed by adding `attrition` to your list of dependencies in `mix.exs`:
```elixir
def deps do
[
{:svg_sprite, "~> 0.1.0"}
]
end
```
### Fetch the dependencies
```shell
mix deps.get
```
## Setup
Setup for attrition can be accomplished in two easy steps!
### 1. Import SvgSprite inside your view_helpers
Of course you could add the library to every view manually by adding `import SvgSprite`. A better solution is to add it to the `view_helpers` function in inside your `application_web.ex` file.
```elixir
defp view_helpers do
quote do
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
# Import LiveView helpers (live_render, live_component, live_patch, etc)
import Phoenix.LiveView.Helpers
# Import basic rendering functionality (render, render_layout, etc)
import Phoenix.View
import SvgSprite
...
end
end
```
### (Optional) 2. Environment Configuration
As mentioned above, the library searches per default inside the images path inside your static assets folder. But you can change the base path inside your `config.exs` file.
```elixir
config :svg_sprite,
base_path: "/images"
```
Of course you can also host the SVG sprites on some kind of CDN.
```elixir
config :svg_sprite,
base_path: "https://cdn.mycompany.com/svg/sprites"
```
## Font Awesome specific features
Normally, Font Awesome uses short names for the icon family like fas, far, fab, etc. in its documentation. And the icon names always have a "fa-" as a prefix.
SvgSprite maps the short names to the long names of the SVG sprite files.
| Short Name | Long Name | Filename |
| ---------- | ---------- | ----------- |
| fas | solid | solid.svg |
| far | regular | regular.svg |
| fab | brands | brands.svg |
| fal | light | light.svg |
| fad | duotone | duotone.svg |
It also removes the "fa-" prefix, because inside the SVG sprite files the names are used without the prefix. The following statements are all equivalent.
```erb
<%= icon("brands", "facebook", class: "w-5 h-5") %>
<%= icon("fab", "fa-facebook", class: "w-5 h-5") %>
<%= icon("brands", "fa-facebook", class: "w-5 h-5") %>
<%= icon("fab", "facebook", class: "w-5 h-5") %>
```
"""
import Phoenix.HTML.Tag
@base_path Application.get_env(:svg_sprite, :base_path, "/images/")
|> String.trim_trailing("/")
@doc """
Creates an SVG tag which references a SVG sprite from an external SVG sprite file and returns it
as a :safe HTML string.
"""
def icon(family, icon, opts \\ [])
# convert symbols to strings
def icon(family, icon, opts) when is_atom(family), do: icon(Atom.to_string(family), icon, opts)
def icon(family, icon, opts) when is_atom(icon), do: icon(family, Atom.to_string(icon), opts)
# translate from icon family shortname to longname
def icon("fas", icon, opts), do: icon("solid", icon, opts)
def icon("far", icon, opts), do: icon("regular", icon, opts)
def icon("fab", icon, opts), do: icon("brands", icon, opts)
def icon("fal", icon, opts), do: icon("light", icon, opts)
def icon("fad", icon, opts), do: icon("duotone", icon, opts)
# strip the fa- prefix from the icon name
def icon(family, "fa-" <> icon, opts), do: icon(family, icon, opts)
def icon(family, icon, opts) do
opts = Keyword.update(opts, :fill, "currentColor", &Function.identity/1)
content_tag(:svg, use_tag(family, icon), opts)
end
defp use_tag(family, icon) do
content_tag(:use, "", href: @base_path <> "/" <> family <> ".svg#" <> icon)
end
end
|
lib/svg_sprite.ex
| 0.741955 | 0.8809 |
svg_sprite.ex
|
starcoder
|
defmodule ESpec.Assertions.EnumString.Have do
@moduledoc """
Defines 'have' assertion.
it do: expect(enum).to have(value)
it do: expect(string).to have(value)
"""
use ESpec.Assertions.Interface
defp match(enum, [{_key, _value} = tuple]) do
match(enum, tuple)
end
defp match(%{} = map, {key, value}) do
result = Map.get(map, key) == value
{result, result}
end
defp match(enum, value) when is_binary(enum) do
result = String.contains?(enum, value)
{result, result}
end
defp match(enum, value) do
result = Enum.member?(enum, value)
{result, result}
end
defp success_message(enum, value, _result, positive) do
to_have = if positive, do: "has", else: "doesn't have"
value = build_success_value_string(value)
"`#{inspect(enum)}` #{to_have} #{value}."
end
defp build_success_value_string([{_, _} = tuple]) do
build_success_value_string(tuple)
end
defp build_success_value_string({key, value}) do
"`#{inspect(value)}` for key `#{inspect(key)}`"
end
defp build_success_value_string(value) do
"`#{inspect(value)}`"
end
defp error_message(enum, value, result, positive) do
build_error_message(enum, value, result, positive)
end
defp build_error_message(enum, [{_, _} = tuple], result, positive) do
build_error_message(enum, tuple, result, positive)
end
defp build_error_message(enum, {key, value}, result, positive) do
m =
"Expected `#{inspect(enum)}` #{to(positive)} have `#{inspect(value)}` for key `#{
inspect(key)
}`, but it #{has(result)}."
if positive do
actual = get_value(enum, key)
{m, %{diff_fn: fn -> ESpec.Diff.diff(actual, value) end}}
else
m
end
end
defp build_error_message(enum, value, result, positive) do
"Expected `#{inspect(enum)}` #{to(positive)} have `#{inspect(value)}`, but it #{has(result)}."
end
defp get_value(list, key) when is_list(list) do
if Keyword.keyword?(list) do
get_value_from_keyword(list, key)
else
nil
end
end
defp get_value(%{} = map, key) do
Map.get(map, key)
end
defp get_value(_, _) do
nil
end
defp get_value_from_keyword(list, key) do
list
|> Keyword.get_values(key)
|> Enum.map(&inspect/1)
|> Enum.join(" and ")
end
defp to(true), do: "to"
defp to(false), do: "not to"
defp has(true), do: "has"
defp has(false), do: "has not"
end
|
lib/espec/assertions/enum_string/have.ex
| 0.678966 | 0.604807 |
have.ex
|
starcoder
|
defmodule Helper.Validator.Schema do
@moduledoc """
validate json data by given schema, mostly used in editorjs validator
currently support boolean / string / number / enum
"""
# use Helper.Validator.Schema.Matchers, [:string, :number, :list, :boolean]
@doc """
cast data by given schema
## example
schema = %{
checked: [:boolean],
hideLabel: [:boolean],
label: [:string],
labelType: [:string],
indent: [enum: [0, 1, 2, 3, 4]],
text: [:string]
}
data = %{checked: true, label: "done"}
Schema.cast(schema, data)
"""
alias Helper.Utils
import Helper.Validator.Guards, only: [g_pos_int: 1, g_not_nil: 1]
@support_min [:string, :number]
@spec cast(map, map) :: {:ok, :pass} | {:error, map}
def cast(schema, data) do
errors_info = cast_errors(schema, data)
case errors_info do
[] -> {:ok, :pass}
_ -> {:error, errors_info}
end
end
defp cast_errors(schema, data) do
schema_fields = Map.keys(schema)
Enum.reduce(schema_fields, [], fn field, acc ->
value = get_in(data, [field])
field_schema = get_in(schema, [field])
case match(field, value, field_schema) do
{:error, error} ->
acc ++ [error]
_ ->
acc
end
end)
end
defp option_valid?(:string, {:min, v}) when is_integer(v), do: true
defp option_valid?(:number, {:min, v}) when is_integer(v), do: true
defp option_valid?(_, {:required, v}) when is_boolean(v), do: true
defp option_valid?(:string, {:starts_with, v}) when is_binary(v), do: true
defp option_valid?(:list, {:type, :map}), do: true
defp option_valid?(:string, {:allow_empty, v}) when is_boolean(v), do: true
defp option_valid?(:list, {:allow_empty, v}) when is_boolean(v), do: true
defp option_valid?(_, _), do: false
defp match(field, nil, enum: _, required: false), do: done(field, nil)
defp match(field, value, enum: enum, required: _), do: match(field, value, enum: enum)
defp match(field, value, enum: enum) do
case value in enum do
true ->
{:ok, value}
false ->
msg = %{field: field, message: "should be: #{enum |> Enum.join(" | ")}"}
{:error, msg}
end
end
defp match(field, value, [type | options]), do: match(field, value, type, options)
defp match(field, nil, _type, [{:required, false} | _options]), do: done(field, nil)
defp match(field, value, type, [{:required, _} | options]) do
match(field, value, type, options)
end
# custom validate logic
## min option for @support_min types
defp match(field, value, type, [{:min, min} | options])
when type in @support_min and g_not_nil(value) and g_pos_int(min) do
case Utils.large_than(value, min) do
true -> match(field, value, type, options)
false -> error(field, value, :min, min)
end
end
## starts_with option for string
defp match(field, value, type, [{:starts_with, starts} | options]) when is_binary(value) do
case String.starts_with?(value, starts) do
true -> match(field, value, type, options)
false -> error(field, value, :starts_with, starts)
end
end
## item type for list
defp match(field, value, type, [{:type, :map} | options]) when is_list(value) do
case Enum.all?(value, &is_map(&1)) do
true -> match(field, value, type, options)
false -> error(field, value, :list_type_map)
end
end
# allow empty for list
defp match(field, value, _type, [{:allow_empty, false} | _options])
when is_list(value) and value == [] do
error(field, value, :allow_empty)
end
# allow empty for string
defp match(field, value, _type, [{:allow_empty, false} | _options])
when is_binary(value) and byte_size(value) == 0 do
error(field, value, :allow_empty)
end
defp match(field, value, type, [{:allow_empty, _} | options])
when is_binary(value) or is_list(value) do
match(field, value, type, options)
end
# custom validate logic end
# main type
defp match(field, value, :string, []) when is_binary(value), do: done(field, value)
defp match(field, value, :number, []) when is_integer(value), do: done(field, value)
defp match(field, value, :list, []) when is_list(value), do: done(field, value)
defp match(field, value, :boolean, []) when is_boolean(value), do: done(field, value)
# main type end
# error for option
defp match(field, value, type, [option]) when is_tuple(option) do
# 如果这里不判断的话会和下面的 match 冲突,是否有更好的写法?
case option_valid?(type, option) do
true ->
error(field, value, type)
# unknow option or option not valid
false ->
{k, v} = option
error(field, value, option: "#{to_string(k)}: #{to_string(v)}")
end
end
defp match(field, value, type, _), do: error(field, value, type)
defp done(field, value), do: {:ok, %{field: field, value: value}}
# custom error hint
defp error(field, value, :min, expect) do
{:error, %{field: field |> to_string, value: value, message: "min size: #{expect}"}}
end
defp error(field, value, :starts_with, expect) do
{:error, %{field: field |> to_string, value: value, message: "should starts with: #{expect}"}}
end
defp error(field, value, :list_type_map) do
{:error, %{field: field |> to_string, value: value, message: "item should be map"}}
end
defp error(field, value, :allow_empty) do
{:error, %{field: field |> to_string, value: value, message: "empty is not allowed"}}
end
# custom error hint end
defp error(field, value, option: option) do
{:error, %{field: field |> to_string, value: value, message: "unknow option: #{option}"}}
end
defp error(field, value, schema) do
{:error, %{field: field |> to_string, value: value, message: "should be: #{schema}"}}
end
end
|
lib/helper/validator/schema.ex
| 0.781914 | 0.546617 |
schema.ex
|
starcoder
|
defmodule Blockchain.Ethash do
@moduledoc """
This module contains the logic found in Appendix J of the
yellow paper concerning the Ethash implementation for POW.
"""
use Bitwise
alias Blockchain.Ethash.{FNV, RandMemoHash}
alias ExthCrypto.Hash.Keccak
@j_epoch 30_000
@j_datasetinit round(:math.pow(2, 30))
@j_datasetgrowth round(:math.pow(2, 23))
@j_mixbytes 128
@j_cacheinit round(:math.pow(2, 24))
@j_cachegrowth round(:math.pow(2, 17))
@j_hashbytes 64
@j_cacherounds 3
@j_parents 256
@j_wordbytes 4
@j_accesses 64
@hash_words div(@j_hashbytes, @j_wordbytes)
@mix_hash div(@j_mixbytes, @j_hashbytes)
@mix_length div(@j_mixbytes, @j_wordbytes)
@parents_range Range.new(0, @j_parents - 1)
@precomputed_data_sizes [__DIR__, "ethash", "data_sizes.txt"]
|> Path.join()
|> File.read!()
|> String.split()
|> Enum.map(&String.to_integer/1)
@precomputed_cache_sizes [__DIR__, "ethash", "cache_sizes.txt"]
|> Path.join()
|> File.read!()
|> String.split()
|> Enum.map(&String.to_integer/1)
@first_epoch_seed_hash <<0::256>>
@type dataset_item :: <<_::512>>
@type dataset :: list(dataset_item)
@type cache :: %{non_neg_integer => <<_::512>>}
@type seed :: <<_::256>>
@type mix :: list(non_neg_integer)
@type mix_digest :: <<_::256>>
@type result :: <<_::256>>
@type nonce :: non_neg_integer()
def epoch(block_number) do
div(block_number, @j_epoch)
end
def dataset_size(epoch, cache \\ @precomputed_data_sizes) do
Enum.at(cache, epoch) || calculate_dataset_size(epoch)
end
defp calculate_dataset_size(epoch) do
highest_prime_below_threshold(
@j_datasetinit + @j_datasetgrowth * epoch - @j_mixbytes,
unit_size: @j_mixbytes
)
end
def cache_size(epoch, cache \\ @precomputed_cache_sizes) do
Enum.at(cache, epoch) || calculate_cache_size(epoch)
end
defp calculate_cache_size(epoch) do
highest_prime_below_threshold(
@j_cacheinit + @j_cachegrowth * epoch - @j_hashbytes,
unit_size: @j_hashbytes
)
end
def seed_hash(block_number) do
if epoch(block_number) == 0 do
@first_epoch_seed_hash
else
Keccak.kec(seed_hash(block_number - @j_epoch))
end
end
defp highest_prime_below_threshold(upper_bound, unit_size: unit_size) do
adjusted_upper_bound = div(upper_bound, unit_size)
if prime?(adjusted_upper_bound) and adjusted_upper_bound >= 0 do
upper_bound
else
highest_prime_below_threshold(upper_bound - 2 * unit_size, unit_size: unit_size)
end
end
defp prime?(num) do
one_less = num - 1
one_less..2
|> Enum.find(fn a -> rem(num, a) == 0 end)
|> is_nil
end
@doc """
Implementation of the Proof-of-work algorithm that uses the full dataset.
For more information, see Appendix J, section J.4 of the Yellow Paper.
"""
@spec pow_full(dataset(), binary(), nonce()) :: {mix_digest(), result()}
def pow_full(dataset, block_hash, nonce) do
size = length(dataset)
pow(block_hash, nonce, size, &Enum.at(dataset, &1))
end
@doc """
Implementation of the Proof-of-work algorithm that uses a cache instead of the
full dataset.
For more information, see Appendix J, section J.4 of the Yellow Paper.
"""
@spec pow_light(non_neg_integer, cache(), binary(), nonce()) :: {mix_digest(), result()}
def pow_light(full_size, cache, block_hash, nonce) do
adjusted_size = div(full_size, @j_hashbytes)
dataset_lookup = &calculate_dataset_item(cache, &1, map_size(cache))
pow(block_hash, nonce, adjusted_size, dataset_lookup)
end
defp pow(block_hash, nonce, dataset_size, dataset_lookup) do
seed_hash = combine_header_and_nonce(block_hash, nonce)
[seed_head | _rest] = binary_into_uint32_list(seed_hash)
mix =
seed_hash
|> init_mix_with_replication()
|> mix_random_dataset_nodes(seed_head, dataset_size, dataset_lookup)
|> compress_mix()
|> uint32_list_into_binary()
result = Keccak.kec(seed_hash <> mix)
{mix, result}
end
defp compress_mix(mix) do
mix
|> Enum.chunk_every(4)
|> Enum.map(fn [a, b, c, d] ->
a
|> FNV.hash(b)
|> FNV.hash(c)
|> FNV.hash(d)
end)
end
defp mix_random_dataset_nodes(init_mix, seed_head, dataset_size, dataset_lookup) do
dataset_length = div(dataset_size, @mix_hash)
Enum.reduce(0..(@j_accesses - 1), init_mix, fn j, mix ->
new_data =
j
|> bxor(seed_head)
|> FNV.hash(Enum.at(mix, Integer.mod(j, @mix_length)))
|> Integer.mod(dataset_length)
|> generate_new_data(dataset_lookup)
FNV.hash_lists(mix, new_data)
end)
end
defp generate_new_data(parent, dataset_lookup) do
0..(@mix_hash - 1)
|> Enum.reduce([], fn k, data ->
element = dataset_lookup.(@mix_hash * parent + k)
[element | data]
end)
|> Enum.reverse()
|> Enum.map(&binary_into_uint32_list/1)
|> List.flatten()
end
defp init_mix_with_replication(seed_hash) do
seed_hash
|> List.duplicate(@mix_hash)
|> List.flatten()
|> Enum.map(&binary_into_uint32_list/1)
|> List.flatten()
end
defp combine_header_and_nonce(block_hash, nonce) do
Keccak.kec512(block_hash <> nonce_into_64bit(nonce))
end
defp nonce_into_64bit(nonce) do
nonce
|> :binary.encode_unsigned(:little)
|> BitHelper.pad(8, :little)
end
@doc """
Generates the dataset, d, outlined in Appendix J section J.3.3 of the Yellow
Paper. For each element d[i] we combine data from 256 pseudorandomly selected
cache nodes, and hash that to compute the dataset.
"""
@spec generate_dataset(cache, non_neg_integer) :: dataset
def generate_dataset(cache, full_size) do
limit = div(full_size, @j_hashbytes)
cache_size = map_size(cache)
0..(limit - 1)
|> Task.async_stream(&calculate_dataset_item(cache, &1, cache_size))
|> Enum.into([], fn {:ok, value} -> value end)
end
@spec calculate_dataset_item(cache, non_neg_integer, non_neg_integer) :: dataset_item
defp calculate_dataset_item(cache, i, cache_size) do
@parents_range
|> generate_mix_of_uints(cache, cache_size, i)
|> uint32_list_into_binary()
|> Keccak.kec512()
end
@spec generate_mix_of_uints(Range.t(), cache, non_neg_integer, non_neg_integer) :: mix
defp generate_mix_of_uints(range, cache, cache_size, index) do
init_mix =
cache
|> initialize_mix(index, cache_size)
|> binary_into_uint32_list()
uint32_cache =
Enum.into(cache, %{}, fn {i, element} ->
{i, binary_into_uint32_list(element)}
end)
Enum.reduce(range, init_mix, fn j, mix ->
cache_element = fnv_cache_element(index, j, mix, uint32_cache, cache_size)
FNV.hash_lists(mix, cache_element)
end)
end
defp fnv_cache_element(index, parent, mix, uint32_cache, cache_size) do
mix_index = Integer.mod(parent, @hash_words)
cache_index =
index
|> bxor(parent)
|> FNV.hash(Enum.at(mix, mix_index))
|> Integer.mod(cache_size)
Map.fetch!(uint32_cache, cache_index)
end
defp cache_into_indexed_map(original_cache) do
original_cache
|> Enum.with_index()
|> Enum.into(%{}, fn {v, k} -> {k, v} end)
end
@spec binary_into_uint32_list(binary) :: list(non_neg_integer)
defp binary_into_uint32_list(binary) do
for <<chunk::size(32) <- binary>> do
<<chunk::size(32)>> |> :binary.decode_unsigned(:little)
end
end
@spec uint32_list_into_binary(list(non_neg_integer)) :: binary()
defp uint32_list_into_binary(list_of_uint32) do
list_of_uint32
|> Enum.map(&:binary.encode_unsigned(&1, :little))
|> Enum.map(&BitHelper.pad(&1, 4, :little))
|> Enum.join()
end
@spec initialize_mix(cache, non_neg_integer, non_neg_integer) :: binary
defp initialize_mix(cache, i, cache_size) do
index = Integer.mod(i, cache_size)
<<head::little-integer-size(32), rest::binary>> = Map.fetch!(cache, index)
new_head = bxor(head, i)
Keccak.kec512(<<new_head::little-integer-size(32)>> <> rest)
end
@doc """
Generates the cache, c, outlined in Appendix J section J.3.2 of the Yellow
Paper, by performing the RandMemoHash algorithm 3 times on the initial cache
"""
@spec generate_cache(seed(), integer()) :: cache()
def generate_cache(seed, cache_size) do
seed
|> initial_cache(cache_size)
|> cache_into_indexed_map()
|> calculate_cache(@j_cacherounds)
end
defp calculate_cache(cache, 0), do: cache
defp calculate_cache(cache, number_of_rounds) do
calculate_cache(RandMemoHash.hash(cache), number_of_rounds - 1)
end
defp initial_cache(seed, cache_size) do
adjusted_cache_size = div(cache_size, @j_hashbytes)
do_initial_cache(0, adjusted_cache_size - 1, seed, [])
end
defp do_initial_cache(limit, limit, _seed, acc = [previous | _rest]) do
result = Keccak.kec512(previous)
[result | acc] |> Enum.reverse()
end
defp do_initial_cache(0, limit, seed, []) do
result = Keccak.kec512(seed)
do_initial_cache(1, limit, seed, [result])
end
defp do_initial_cache(element, limit, seed, acc = [previous | _rest]) do
result = Keccak.kec512(previous)
do_initial_cache(element + 1, limit, seed, [result | acc])
end
end
|
apps/blockchain/lib/blockchain/ethash.ex
| 0.799403 | 0.407363 |
ethash.ex
|
starcoder
|
defmodule AbsinthePermission do
@moduledoc """
This middleware allows to restrict operations on
queries, mutations and subscriptions in declarative manner
by leveraging `meta` field.
This middleware especially useful if you have role based
access management.
There are 3 types policies:
1. You can define required permission for an operation.
Either deny or allow.
For these simple use cases you can define something like this:
```
query do
...
field(:get_todo_list, list_of(:todo)) do
meta(required_permission: "can_view_todo_list")
end
...
end
```
2. If you need some permission/policies based on
query/mutation inputs, or related objects,
you need specify fine-grained policies based on
your needs.
For example, you've a todo app and don't want
some users to update or delete other users todos.
For being able to enforce this policy you need to know
the creator of that todo object. So first you need to access it
and check it if `current_user` is the creator of that todo.
In this scenario, you can define your policy like this:
```
mutation do
...
field(:update_todo, :todo) do
meta(
pre_op_policies: [
[
remote_context: [creator__id: :current_user_id],
required_permission: "can_change_his_own_todo"
]
]
)
end
...
end
```
You can define this policy in other way around as well.
Instead of having a permission like "can_change_his_own_todo",
you can have permission like "can_change_other_users_todos".
In this case the policy would be like this:
```
meta(
pre_op_policies: [
[
remote_context: [creator__id: {:current_user_id, :neq}],
required_permission: "can_change_other_users_todo"
]
]
)
```
And additionally if you want to restrict based on input arguments,
you can add it to policies.
For instance let's add another policy to `updateTodo`.
If some users try to change other users todo name to "Danger Zone",
then they'll need to have a permission.
And define a permission for it: "can_change_other_users_todo_name_to_danger_zone".
```
meta(
pre_op_policies: [
[
remote_context: [creator__id: {:current_user_id, :neq}],
required_permission: "can_change_other_users_todo"
], # policy 1
[
remote_context: [creator__id: {:current_user_id, :neq}],
name: "Danger Zone",
required_permission: "can_change_other_users_todo_name_to_danger_zone"
] # policy 2
]
)
```
3. In some situation there's a need for policies after operation has been done.
For instance a user can view todo list.
And todo object has `creator` field on it. And `creator` field has `email` field.
Let's say you don't want users who don't have "can_view_emails" permission
to not view emails even if they have permission to view todo list.
In this case you define a policy on `email` field:
```
...
object :todo do
field(:id, :integer)
field(:name, :string)
field(:detail, :string)
field(:creator, :user)
end
object :user do
...
field(:email, :string) do
meta(
post_op_policies: [required_permission: "can_view_emails"]
)
end
...
end
...
```
"""
end
|
lib/absinthe_permission.ex
| 0.795817 | 0.780077 |
absinthe_permission.ex
|
starcoder
|
defmodule DateTimeParser.Parser.Date do
@moduledoc """
Tokenizes the string for date formats. This prioritizes the international standard for
representing dates.
"""
@behaviour DateTimeParser.Parser
import NimbleParsec
import DateTimeParser.Combinators.Date
import DateTimeParser.Formatters, only: [format_token: 2, clean: 1]
defparsecp(
:do_parse,
vocal_day()
|> optional()
|> concat(formal_date())
)
@impl DateTimeParser.Parser
def preflight(parser), do: {:ok, parser}
@impl DateTimeParser.Parser
def parse(%{string: string} = parser) do
case do_parse(string) do
{:ok, tokens, _, _, _, _} -> from_tokens(parser, tokens)
_ -> {:error, :failed_to_parse}
end
end
@doc false
def from_tokens(%{context: context, opts: opts}, tokens) do
parsed_values =
clean(%{
year: format_token(tokens, :year),
month: format_token(tokens, :month),
day: format_token(tokens, :day)
})
with {:ok, date} <-
for_context(context, parsed_values, Keyword.get(opts, :assume_date, false)),
{:ok, date} <- validate_day(date) do
{:ok, date}
end
end
@type dayable ::
DateTime.t()
| NaiveDateTime.t()
| Date.t()
| %{day: Calendar.day(), month: Calendar.month(), year: Calendar.year()}
@doc "Validate either the Date or [Naive]DateTime has a valid day"
@spec validate_day(dayable) :: {:ok, dayable} | :error
def validate_day(%{day: day, month: month} = date)
when month in [1, 3, 5, 7, 8, 10, 12] and day in 1..31,
do: {:ok, date}
def validate_day(%{day: day, month: month} = date)
when month in [4, 6, 9, 11] and day in 1..30,
do: {:ok, date}
def validate_day(%{day: day, month: 2} = date)
when day in 1..28,
do: {:ok, date}
def validate_day(%{day: 29, month: 2, year: year} = date) do
if Timex.is_leap?(year),
do: {:ok, date},
else: :error
end
def validate_day(_), do: :error
@doc false
def parsed_date?(parsed_values) do
Enum.all?([parsed_values[:year], parsed_values[:month], parsed_values[:day]])
end
defp for_context(:date, parsed_values, false) do
if parsed_date?(parsed_values) do
Date.new(parsed_values[:year], parsed_values[:month], parsed_values[:day])
else
{:error, :cannot_assume_date}
end
end
defp for_context(:date, parsed_values, true),
do: {:ok, Map.merge(Date.utc_today(), parsed_values)}
defp for_context(:date, parsed_values, %Date{} = date),
do: {:ok, Map.merge(date, parsed_values)}
defp for_context(:time, _parsed_values, _), do: {:error, "Could not parse a time out of a date"}
defp for_context(:datetime, _parsed_values, _),
do: {:error, "Could not parse a datetime out of a date"}
end
|
lib/parser/date.ex
| 0.894853 | 0.481454 |
date.ex
|
starcoder
|
defmodule Fugue.Assertions do
import ExUnit.Assertions
for call <- [:assert, :refute] do
def unquote(:"#{call}_status")(conn, status_code) do
a = conn.status
e = status_code
ExUnit.Assertions.unquote(call)(a == e, [
left: a,
message: "Expected status code #{inspect(e)}, got #{inspect(a)}"])
conn
end
def unquote(:"#{call}_success_status")(conn) do
a = conn.status
ExUnit.Assertions.unquote(call)(a < 400, [
left: a,
message: "Expected status code #{inspect(a)} to be successful (< 400)"])
conn
end
def unquote(:"#{call}_error_status")(conn) do
a = conn.status
ExUnit.Assertions.unquote(call)(a >= 400, [
left: a,
message: "Expected status code #{inspect(a)} to be an error (>= 400)"])
conn
end
def unquote(:"#{call}_body")(conn, body) do
ExUnit.Assertions.unquote(call)(conn.resp_body == body)
conn
end
def unquote(:"#{call}_body_contains")(conn, body) do
a = conn.resp_body
e = body
indented = fn ->
a
|> String.split("\n")
|> Enum.map(&(" " <> &1))
|> Enum.join("\n")
end
contains? = if Regex.regex?(body) do
Regex.match?(e, a)
else
String.contains?(a, e)
end
ExUnit.Assertions.unquote(call)(contains?, [
left: a,
right: e,
message: "Expected response body to contain #{inspect(e)}, got:\n#{indented.()}"])
conn
end
def unquote(:"#{call}_transition")(conn, "/" <> _ = path) do
unquote(:"#{call}_transition")(conn, %URI{scheme: to_string(conn.scheme), host: conn.host, port: conn.port, path: path})
end
def unquote(:"#{call}_transition")(conn, expected) when is_binary(expected) do
unquote(:"#{call}_transition")(conn, URI.parse(expected))
end
def unquote(:"#{call}_transition")(conn, expected) do
actual = case get_header(conn, "location") do
nil ->
%URI{}
actual ->
URI.parse(actual)
end
equals? = (actual.scheme || to_string(conn.scheme)) == expected.scheme &&
(actual.host || conn.host) == expected.host &&
(actual.port || conn.port) == expected.port &&
actual.path == expected.path
ExUnit.Assertions.unquote(call)(equals?, [
left: actual,
right: expected,
message: "Expected transition to #{expected} but got #{actual}"])
conn
end
defmacro unquote(:"#{call}_json")(conn, match) do
call = unquote(call)
quote do
conn = unquote(conn)
parsed_body = conn.private[:fugue_resp_json_body] || Poison.decode!(conn.resp_body)
conn = Plug.Conn.put_private(conn, :fugue_resp_json_body, parsed_body)
unquote(:"#{call}_term_match")(parsed_body, unquote(match), "Expected JSON response body to match")
conn
end
end
end
defmacro assert_term_match(actual, expected, message \\ "Term match failed") do
expected_code = expected |> Macro.escape()
{expected, vars, aliases} = format_match(expected)
quote do
actual = unquote(actual)
expected_code = unquote(expected_code)
unquote_splicing(vars)
ExUnit.Assertions.assert(match?(unquote(expected), actual), [
expr: quote do
unquote(expected_code) = unquote(Macro.escape(actual))
end,
message: unquote(message)
])
unquote(expected) = actual
unquote_splicing(aliases)
actual
end
end
defmacro refute_term_match(actual, expected, message \\ "Term match expected to fail") do
expected_code = expected |> Macro.escape()
{expected, vars, _} = format_match(expected)
quote do
actual = unquote(actual)
expected_code = unquote(expected_code)
unquote_splicing(vars)
ExUnit.Assertions.refute(match?(unquote(expected), actual), [
expr: quote do
unquote(expected_code) = unquote(Macro.escape(actual))
end,
message: unquote(message)
])
actual
end
end
defp get_header(conn, name) do
case :lists.keyfind(name, 1, conn.resp_headers) do
false ->
nil
{_, value} ->
value
end
end
@term_match :__fugue_term_match__
@term_vars :__fugue_term_vars__
defp format_match(ast) do
ast = Macro.prewalk(ast, fn
({_, [{unquote(@term_match), true} | _], _} = expr) ->
expr
({call, _, context} = expr) when is_atom(call) and is_atom(context) and call != :_ ->
acc_var(expr)
({call, _, _} = expr) when is_tuple(call) ->
acc(expr)
({call, _, _} = expr) when not call in [:{}, :%{}, :_, :|, :^, :=, :<>] ->
acc(expr)
({:^, meta, [{var, var_meta, var_context}]}) ->
{:^, meta, [{var, [{@term_match, true} | var_meta], var_context}]}
(expr) ->
expr
end)
{ast, acc(), acc_var()}
end
defp acc do
Process.delete(@term_match) || []
end
defp acc(expr) do
acc = Process.get(@term_match, [])
var = {:"_@term_#{length(acc)}", [{@term_match, true}], __MODULE__}
Process.put(@term_match, [quote do
unquote(var) = unquote(expr)
end | acc])
{:^, [{@term_match, true}], [var]}
end
defp acc_var do
Process.delete(@term_vars) || []
end
defp acc_var(var) do
acc = Process.get(@term_vars, [])
alias_var = Macro.var(:"_@term_alias_#{length(acc)}", __MODULE__)
Process.put(@term_vars, [quote do
unquote(var) = unquote(alias_var)
end | acc])
alias_var
end
end
|
lib/fugue/assertions.ex
| 0.666171 | 0.590425 |
assertions.ex
|
starcoder
|
defmodule Workflows.Activity.Wait do
@moduledoc false
alias Workflows.Activity
alias Workflows.ActivityUtil
alias Workflows.Event
alias Workflows.Path
alias Workflows.ReferencePath
@behaviour Activity
@type wait ::
{:seconds, pos_integer()}
| {:seconds_path, Path.t()}
| {:timestamp, DateTime.t()}
| {:timestamp_path, Path.t()}
@type t :: %__MODULE__{
name: Activity.name(),
wait: wait(),
transition: Activity.transition(),
input_path: Path.t() | nil,
output_path: Path.t() | nil
}
@seconds "Seconds"
@seconds_path "SecondsPath"
@timestamp "Timestamp"
@timestamp_path "TimestampPath"
defstruct [:name, :wait, :transition, :input_path, :output_path]
@impl Activity
def parse(activity_name, definition) do
with {:ok, wait} <- parse_wait(definition),
{:ok, transition} <- ActivityUtil.parse_transition(definition),
{:ok, input_path} <- ActivityUtil.parse_input_path(definition),
{:ok, output_path} <- ActivityUtil.parse_output_path(definition) do
state = %__MODULE__{
name: activity_name,
wait: wait,
transition: transition,
input_path: input_path,
output_path: output_path
}
{:ok, state}
end
end
@impl Activity
def enter(activity, _ctx, args) do
with {:ok, effective_args} <- ActivityUtil.apply_input_path(activity, args) do
event = %Event.WaitEntered{
activity: activity.name,
scope: [],
args: effective_args
}
{:ok, event}
end
end
@impl Activity
def exit(activity, _ctx, _args, result) do
with {:ok, effective_result} <- ActivityUtil.apply_output_path(activity, result) do
event = %Event.WaitExited{
activity: activity.name,
scope: [],
result: effective_result,
transition: activity.transition
}
{:ok, event}
end
end
def start_wait(activity, _ctx, args) do
with {:ok, wait} <- resolve_wait(activity.wait, args) do
event = %Event.WaitStarted{
activity: activity.name,
scope: [],
wait: wait
}
{:ok, event}
end
end
def finish_waiting(activity, _ctx) do
event = %Event.WaitSucceeded{
activity: activity.name,
scope: []
}
{:ok, event}
end
## Private
defp parse_wait(%{"Seconds" => seconds} = state) do
with :ok <- validate_no_extra_keys(state, [@seconds_path, @timestamp, @timestamp_path]) do
if is_integer(seconds) and seconds > 0 do
{:ok, {:seconds, seconds}}
else
{:error, :invalid_seconds}
end
end
end
defp parse_wait(%{"SecondsPath" => seconds_path} = state) do
with :ok <- validate_no_extra_keys(state, [@seconds, @timestamp, @timestamp_path]),
{:ok, seconds} <- ReferencePath.create(seconds_path) do
{:ok, {:seconds_path, seconds}}
end
end
defp parse_wait(%{"Timestamp" => timestamp} = state) do
with :ok <- validate_no_extra_keys(state, [@seconds, @seconds_path, @timestamp_path]),
{:ok, timestamp, _} <- DateTime.from_iso8601(timestamp) do
{:ok, {:timestamp, timestamp}}
end
end
defp parse_wait(%{"TimestampPath" => timestamp_path} = state) do
with :ok <- validate_no_extra_keys(state, [@seconds, @seconds_path, @timestamp]),
{:ok, timestamp} <- ReferencePath.create(timestamp_path) do
{:ok, {:timestamp_path, timestamp}}
end
end
defp parse_wait(_state) do
{:error, :missing_fields}
end
defp validate_no_extra_keys(state, other_keys) do
if state_has_keys(state, other_keys) do
{:error, :invalid_fields}
end
:ok
end
defp state_has_keys(state, keys) do
Enum.any?(keys, fn key -> Map.has_key?(state, key) end)
end
defp resolve_wait({:seconds_path, path}, args) do
with {:ok, seconds} <- ReferencePath.query(path, args) do
{:ok, {:seconds, seconds}}
end
end
defp resolve_wait({:timestamp_path, path}, args) do
with {:ok, timestamp} <- ReferencePath.query(path, args) do
{:ok, {:timestamp, timestamp}}
end
end
defp resolve_wait(wait, _args), do: {:ok, wait}
end
|
lib/workflows/activity/wait.ex
| 0.770939 | 0.423816 |
wait.ex
|
starcoder
|
defmodule Numbers do
require Integer
use Koans
@intro "Why is the number six so scared? Because seven eight nine!\nWe should get to know numbers a bit more!"
koan "Is an integer equal to its float equivalent?" do
assert 1 == 1.0 == ___
end
koan "Is an integer threequal to its float equivalent?" do
assert 1 === 1.0 == ___
end
koan "Revisit divison with threequal" do
assert 2 / 2 === ___
end
koan "Another way to divide" do
assert div(5, 2) == ___
end
koan "What remains or: The Case of the Missing Modulo Operator (%)" do
assert rem(5, 2) == ___
end
koan "Other math operators may produce this" do
assert 2 * 2 === ___
end
koan "Or other math operators may produce this" do
assert 2 * 2.0 === ___
end
koan "Two ways to round, are they exactly the same?" do
assert Float.round(1.2) === round(1.2) == ___
end
koan "Release the decimals into the void" do
assert trunc(5.6) === ___
end
koan "Are you odd?" do
assert Integer.is_odd(3) == ___
end
koan "Actually you might be even" do
assert Integer.is_even(4) == ___
end
koan "Let's grab the individual digits in a list" do
individual_digits = Integer.digits(58127)
assert individual_digits == ___
end
koan "Oh no! I need it back together" do
number = Integer.undigits([1, 2, 3, 4])
assert number == ___
end
koan "Actually I want my number as a string" do
string_digit = Integer.to_string(1234)
assert string_digit == ___
end
koan "The meaning of life in hexidecimal is 2A!" do
assert Integer.parse("2A", 16) == {___, ""}
end
koan "The remaining unparsable part is also returned" do
assert Integer.parse("5 years") == {5, ___}
end
koan "What if you parse a floating point value as an integer?" do
assert Integer.parse("1.2") == {___, ___}
end
koan "Just want to parse to a float" do
assert Float.parse("34.5") == {___, ""}
end
koan "Hmm, I want to parse this but it has some strings" do
assert Float.parse("1.5 million dollars") == {___, " million dollars"}
end
koan "I don't want this decimal point, let's round up" do
assert Float.ceil(34.25) == ___
end
koan "OK, I only want it to 1 decimal place" do
assert Float.ceil(34.25, 1) == ___
end
koan "Rounding down is what I need" do
assert Float.floor(99.99) == ___
end
koan "Rounding down to 2 decimal places" do
assert Float.floor(12.345, 2) == ___
end
koan "Round the number up or down for me" do
assert Float.round(5.5) == ___
assert Float.round(5.4) == ___
assert Float.round(8.94, 1) == ___
assert Float.round(-5.5674, 3) == ___
end
koan "I want the first and last in the range" do
first..last = Range.new(1, 10)
assert first == ___
assert last == ___
end
koan "Does my number exist in the range?" do
range = Range.new(1, 10)
assert 4 in range == ___
assert 10 in range == ___
assert 0 in range == ___
end
koan "Is this a range?" do
assert Range.range?(1..10) == ___
assert Range.range?(0) == ___
end
end
|
lib/koans/03_numbers.ex
| 0.808408 | 0.834744 |
03_numbers.ex
|
starcoder
|
defmodule Cldr.Substitution do
@moduledoc """
Compiles substituation formats that are of the form
"{0} something {1}" into a token list that allows for
more efficient parameter substituation at runtime.
"""
@doc """
Parses a substitution template into a list of tokens to
allow efficient parameter substitution at runtime.
* `template` is a binary that may include parameter markers that
are substituded for values at runtime.
Returns:
* A list of tokens where any substitution is marked as an integer
any any binary tokens are passed through as is.
## Examples
iex> Cldr.Substitution.parse "{0}, {1}"
[0, ", ", 1]
iex> Cldr.Substitution.parse "{0} This is something {1} or another {2}"
[0, " This is something ", 1, " or another ", 2]
This function is primarily intended to support compile-time generation
of templates that simplify and speed up parameter substitution at runtime.
"""
@spec parse(String.t()) :: [String.t() | integer, ...]
def parse("") do
[]
end
def parse(template) when is_binary(template) do
String.split(template, ~r/{[0-9]}/, include_captures: true, trim: true)
|> Enum.map(&item_from_token/1)
end
def parse(_template) do
{:error, "#{inspect(__MODULE__)}.parse/1 accepts only a binary parameter"}
end
@doc """
Substitutes a list of values into a template token list that is
created by `Cldr.Substitution.parse/1`.
* `list1` is a list of values that will be substituted into a
a template list previously created by `Cldr.Substitution.parse/1`
* `list2` is a template list previously created by
`Cldr.Substitution.parse/1`
Returns:
* A list with values substituted for parameters in the `list1` template
## Examples:
iex> template = Cldr.Substitution.parse "{0} This is something {1}"
[0, " This is something ", 1]
iex> Cldr.Substitution.substitute ["a", "b"], template
["a", " This is something ", "b"]
"""
@spec substitute(term | [term, ...], [String.t() | integer, ...]) :: [term, ...]
# Takes care of a common case where there is one parameter
def substitute([item], [0, string]) when is_binary(string) do
[item, string]
end
def substitute(item, [0, string]) when is_binary(string) do
[item, string]
end
def substitute([item], [string, 0]) when is_binary(string) do
[string, item]
end
def substitute(item, [string, 0]) when is_binary(string) do
[string, item]
end
def substitute(item, [string1, 0, string2]) when is_binary(string1) and is_binary(string2) do
[string1, item, string2]
end
# Takes care of the common case where there are two parameters separated
# by a string.
def substitute([item_0, item_1], [0, string, 1]) when is_binary(string) do
[item_0, string, item_1]
end
def substitute([item_0, item_1], [1, string, 0]) when is_binary(string) do
[item_1, string, item_0]
end
# Takes care of the common case where there are three parameters separated
# by strings.
def substitute([item_0, item_1, item_2], [0, string_1, 1, string_2, 2])
when is_binary(string_1) and is_binary(string_2) do
[item_0, string_1, item_1, string_2, item_2]
end
@digits [?0, ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9]
defp item_from_token(<<?{, digit, ?}>>) when digit in @digits do
digit - ?0
end
defp item_from_token(string) do
string
end
end
|
lib/cldr/substitution.ex
| 0.887339 | 0.686101 |
substitution.ex
|
starcoder
|
defmodule ExDiet.Food.NutritionFacts do
@moduledoc """
Calculates nutrition facts per 100g of product.
* `ExDiet.Food.Ingredient`
* `ExDiet.Food.RecipeIngredient`
* `ExDiet.Food.Meal`
* `ExDiet.Food.Calendar`
"""
@type t :: %__MODULE__{
protein: Decimal.t(),
fat: Decimal.t(),
carbonhydrate: Decimal.t(),
energy: Decimal.t()
}
@nutrients [:protein, :fat, :carbonhydrate, :energy]
defstruct(Enum.map(@nutrients, &{&1, Decimal.new(0)}))
alias ExDiet.Food.{Ingredient, Recipe, RecipeIngredient, Meal, Calendar}
alias ExDiet.Repo
def new, do: new(%{})
def new(%{__struct__: _} = struct), do: new(Map.from_struct(struct))
def new(list) when is_list(list), do: new(Enum.into(list, %{}))
def new(map) do
struct(
__MODULE__,
Enum.reduce(@nutrients, map, fn key, map ->
Map.put(map, key, Decimal.new(Map.get(map, key, 0)))
end)
)
end
def calculate(%Ingredient{} = ing), do: new(ing)
def calculate(%RecipeIngredient{} = ri) do
@nutrients
|> Enum.map(&{&1, calculate_one(ri, &1)})
|> new()
end
def calculate(%Meal{} = meal) do
meal = Repo.preload(meal, [:recipe, :ingredient])
Enum.reduce(@nutrients, calculate(entity(meal)), fn key, nf ->
%{nf | key => Decimal.mult(Map.get(nf, key), Decimal.from_float(meal.weight / 100))}
end)
end
def calculate(%Calendar{} = calendar) do
calendar = Repo.preload(calendar, meals: [:recipe, :ingredient])
sum_nutrition_facts(calendar.meals)
end
def calculate(%Recipe{weight_cooked: 0}), do: new()
def calculate(%Recipe{} = recipe) do
recipe = Repo.preload(recipe, recipe_ingredients: :ingredient)
new(
Enum.reduce(@nutrients, sum_nutrition_facts(recipe.recipe_ingredients), fn key, struct ->
value =
struct
|> Map.get(key)
|> Decimal.div(Decimal.new(recipe.weight_cooked))
|> Decimal.mult(100)
%{struct | key => value}
end)
)
end
def calculate_one(%RecipeIngredient{} = ri, key) do
ri = Repo.preload(ri, :ingredient)
ri.ingredient
|> Map.get(key)
|> Decimal.mult(ri.weight)
|> Decimal.div(100)
end
def calculate_one(struct, key), do: Map.get(calculate(struct), key)
@spec sum_nutrition_facts(list(t)) :: t
defp sum_nutrition_facts(list) do
Enum.reduce(list, new(), fn ri, acc ->
ri_data = calculate(ri)
Enum.reduce(@nutrients, acc, fn key, struct ->
%{struct | key => Decimal.add(Map.get(struct, key), Map.get(ri_data, key))}
end)
end)
end
defp entity(%Meal{} = meal) do
cond do
meal.recipe_id != nil ->
meal.recipe
meal.ingredient_id != nil ->
meal.ingredient
true ->
raise ArgumentError
end
end
end
|
lib/ex_diet/food/nutrition_facts.ex
| 0.769557 | 0.606848 |
nutrition_facts.ex
|
starcoder
|
defmodule CoursePlanner.Attendances do
@moduledoc """
This module provides custom functionality for controller over the model
"""
import Ecto.Query
alias CoursePlanner.{Repo, Courses.OfferedCourse, Attendances.Attendance, Classes}
alias CoursePlannerWeb.{Endpoint, Router.Helpers}
alias Ecto.{Multi, DateTime}
def get_course_attendances(offered_course_id) do
Repo.one(from oc in OfferedCourse,
join: c in assoc(oc, :classes),
join: a in assoc(c, :attendances),
join: as in assoc(a, :student),
join: ac in assoc(a, :class),
preload: [:term, :course, :teachers],
preload: [classes: {c, attendances: {a, student: as, class: ac}}],
where: oc.id == ^offered_course_id,
order_by: [asc: ac.date, asc: ac.starting_at, asc: as.name, asc: as.family_name])
end
def get_teacher_course_attendances(offered_course_id, teacher_id) do
Repo.one(from oc in OfferedCourse,
join: t in assoc(oc, :teachers),
join: c in assoc(oc, :classes),
join: a in assoc(c, :attendances),
join: as in assoc(a, :student),
join: ac in assoc(a, :class),
preload: [:term, :course, teachers: t],
preload: [classes: {c, attendances: {a, student: as, class: ac}}],
where: oc.id == ^offered_course_id and t.id == ^teacher_id,
order_by: [asc: ac.date, asc: ac.starting_at, asc: as.name, asc: as.family_name])
end
def get_student_attendances(offered_course_id, student_id) do
Repo.all(from a in Attendance,
join: s in assoc(a, :student),
join: c in assoc(a, :class),
join: oc in assoc(c, :offered_course),
preload: [class: {c, [offered_course: {oc, [:course, :term]}]}, student: s],
where: a.student_id == ^student_id and oc.id == ^offered_course_id,
order_by: [asc: c.date, asc: c.starting_at])
end
def get_all_offered_courses do
Repo.all(from oc in OfferedCourse,
join: te in assoc(oc, :term),
join: co in assoc(oc, :course),
join: c in assoc(oc, :classes),
join: s in assoc(oc, :students),
join: t in assoc(oc, :teachers),
preload: [term: t, course: co, teachers: t, students: s, classes: c],
order_by: [asc: te.name, asc: co.name])
end
def get_all_teacher_offered_courses(teacher_id) do
Repo.all(from oc in OfferedCourse,
join: te in assoc(oc, :term),
join: co in assoc(oc, :course),
join: t in assoc(oc, :teachers),
join: c in assoc(oc, :classes),
join: s in assoc(oc, :students),
preload: [term: t, course: co, teachers: t, students: s, classes: c],
order_by: [asc: te.name, asc: co.name],
where: t.id == ^teacher_id)
end
def get_all_student_offered_courses(student_id) do
Repo.all(from oc in OfferedCourse,
join: te in assoc(oc, :term),
join: co in assoc(oc, :course),
join: s in assoc(oc, :students),
join: c in assoc(oc, :classes),
join: t in assoc(oc, :teachers),
preload: [term: t, course: co, teachers: t, students: s, classes: c],
order_by: [asc: te.name, asc: co.name],
where: s.id == ^student_id)
end
def update_multiple_attendances(attendance_changeset_list) do
multi = Multi.new
updated_multi =
attendance_changeset_list
|> Enum.reduce(multi, fn(attendance_changeset, operation_list) ->
operation_atom =
attendance_changeset.data.id
|> Integer.to_string()
|> String.to_atom()
Multi.update(operation_list, operation_atom, attendance_changeset)
end)
Repo.transaction(updated_multi)
end
def create_class_attendance_records(class_id, students)
when is_list(students) and length(students) > 0 do
attendances_data =
students
|> Enum.map(fn(student) ->
[
class_id: class_id,
student_id: student.id,
attendance_type: "Not filled",
inserted_at: DateTime.utc(),
updated_at: DateTime.utc()
]
end)
Repo.insert_all(Attendance, attendances_data)
end
def create_class_attendance_records(_, _), do: {:ok, nil}
def create_students_attendances(offered_course_id, offered_course_students, updated_students) do
students = updated_students -- offered_course_students
offered_course_id
|> Classes.get_offered_course_classes()
|> Enum.map(fn(class) ->
create_class_attendance_records(class.id, students)
end)
end
def remove_students_attendances(offered_course_id, offered_course_students, updated_students) do
student_ids =
offered_course_students
|> Kernel.--(updated_students)
|> Enum.map(fn(student) ->
student.id
end)
class_ids =
offered_course_id
|> Classes.get_offered_course_classes()
|> Enum.map(fn(class) ->
class.id
end)
delete_query = from a in Attendance,
where: a.class_id in ^class_ids and a.student_id in ^student_ids
Repo.delete_all(delete_query)
end
def get_offered_course_fill_attendance_path(offered_course_id) do
Helpers.attendance_fill_course_url Endpoint, :fill_course, offered_course_id
end
end
|
lib/course_planner/attendances/attendances.ex
| 0.693161 | 0.707051 |
attendances.ex
|
starcoder
|
defmodule RateTheDub.DubVotes do
@moduledoc """
The DubVotes context.
"""
import Ecto.Query, warn: false
alias RateTheDub.Repo
alias RateTheDub.DubVotes.Vote
@doc """
Returns the list of dubvotes.
## Examples
iex> list_dubvotes()
[%Vote{}, ...]
"""
def list_dubvotes do
Repo.all(Vote)
end
@doc """
Gets a single vote.
Raises `Ecto.NoResultsError` if the Vote does not exist.
## Examples
iex> get_vote!(123)
%Vote{}
iex> get_vote!(456)
** (Ecto.NoResultsError)
"""
def get_vote!(id, lang), do: Repo.get_by!(Vote, mal_id: id, language: lang)
@doc """
Gets the number of votes for this anime series and language pair.
## Examples
iex> count_votes_for(1, "en")
5
"""
def count_votes_for(id, lang) do
Vote
|> where(mal_id: ^id)
|> where(language: ^lang)
|> Repo.aggregate(:count)
end
@doc """
Gets the number of votes for each language for this anime series.
## Examples
iex> count_all_votes_for(1)
%{"en" => 5, "fr" => 1}
"""
def count_all_votes_for(id) do
Vote
|> where(mal_id: ^id)
|> group_by(:language)
|> select([v], [v.language, count(v)])
|> Repo.all()
|> Enum.map(fn [k, v] -> {k, v} end)
|> Map.new()
end
@doc """
Creates a vote.
## Examples
iex> create_vote(%{field: value})
{:ok, %Vote{}}
iex> create_vote(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_vote(attrs \\ %{}) do
%Vote{}
|> Vote.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a vote.
## Examples
iex> update_vote(vote, %{field: new_value})
{:ok, %Vote{}}
iex> update_vote(vote, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_vote(%Vote{} = vote, attrs) do
vote
|> Vote.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a vote.
## Examples
iex> delete_vote(vote)
{:ok, %Vote{}}
iex> delete_vote(vote)
{:error, %Ecto.Changeset{}}
"""
def delete_vote(%Vote{} = vote) do
Repo.delete(vote)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking vote changes.
## Examples
iex> change_vote(vote)
%Ecto.Changeset{data: %Vote{}}
"""
def change_vote(%Vote{} = vote, attrs \\ %{}) do
Vote.changeset(vote, attrs)
end
@doc """
Returns true if the given IP address or snowflake has voted for this given
series and language pair.
"""
def has_voted_for(id, lang, ip, snow) do
Vote
|> where(mal_id: ^id)
|> where(language: ^lang)
|> where([v], v.user_ip == ^ip or v.user_snowflake == ^snow)
|> Repo.exists?()
end
end
|
lib/ratethedub/dub_votes.ex
| 0.82566 | 0.442817 |
dub_votes.ex
|
starcoder
|
defmodule Brando.Datasource do
@moduledoc """
Helpers to register datasources for interfacing with the block editor
### List
A set of entries is returned automatically
#### Example
list :all_posts_from_year, fn module, arg ->
{:ok, Repo.all(from t in module, where: t.year == ^arg)}
end
list :all_posts, fn _, _ -> Posts.list_posts() end
You can also supply a callback with a 3-arity function to get the currently set language (if any)
list :localized_posts, fn _, language, _arg ->
Posts.list_posts(%{filter: %{language: language}})
end
### Selection
User can pick entries manually.
Requires both a `list` function and a `get` function. The `list` function must return a list of maps in
the shape of `[%{id: 1, label: "Label"}]`.
The get function queries by a supplied list of `ids`:
```
fn _module, ids ->
results =
from t in Post,
where: t.id in ^ids,
order_by: fragment("array_position(?, ?)", ^ids, t.id)
{:ok, Repo.all(results)}
```
The `order_by: fragment(...)` sorts the returned results in the same order as the supplied `ids`
## Example
In your schema:
use Brando.Datasource
datasources do
list :all_posts_from_year, fn module, arg ->
{:ok, Repo.all(from t in module, where: t.year == ^arg)}
end
list :all_posts, fn _, _ -> Posts.list_posts() end
selection
:featured,
fn _, arg ->
{:ok, posts} = Posts.list_posts(%{filter: %{language: arg}})
end,
fn _, ids ->
results =
from t in Post,
where: t.id in ^ids,
order_by: fragment("array_position(?, ?)", ^ids, t.id)
{:ok, Repo.all(results)}
end
end
These data source points are now available through the block editor when you create a Datasource block.
## Common issues
If your datasource fetches related items, pages using your datasource might not be updated
when these related items are created, updated or deleted.
For instance:
We have a schema `Area` that has many `Grantee`s.
The `Area` has this datasource:
list :all_areas_with_grants, fn _, _ ->
grantee_query = from(t in Areas.Grantee, where: t.status == :published, order_by: t.name)
opts = %{order: [{:asc, :name}], status: :published, preload: [{:grantees, grantee_query}]}
Areas.list_areas(opts)
end
On a page we have a `DatasourceBlock` that grabs `:all_areas_with_grants`. When deleting or
updating a grant, this Datasource will not be updated since the datasource is listening for
`Area` changes, which are not triggered.
To solve, we can add it as a callback to each mutation for `Grantee`:
mutation :create, Grantee do
fn entry ->
# update datasource that references :all_areas_with_grants
Brando.Datasource.update_datasource({Area, :list, :all_areas_with_grants}, entry)
end
end
mutation :update, Grantee do
fn entry ->
# update datasource that references :all_areas_with_grants
Brando.Datasource.update_datasource({Area, :list, :all_areas_with_grants}, entry)
end
end
mutation :delete, Grantee do
fn entry ->
# update datasource that references :all_areas_with_grants
Brando.Datasource.update_datasource({Area, :list, :all_areas_with_grants}, entry)
end
end
OR if you know that all changes to the `:all_areas_with_grants` are coming from `Grantee`
mutations, you can move the datasource to the `Grantee` schema instead!
"""
alias Brando.Villain
alias Brando.Blueprint.Identifier
import Brando.Query.Helpers
import Ecto.Query
@doc """
List all registered data sources
"""
defmacro __using__(_) do
quote do
import Ecto.Query
import unquote(__MODULE__)
Module.register_attribute(__MODULE__, :datasources_list, accumulate: true)
Module.register_attribute(__MODULE__, :datasources_single, accumulate: true)
Module.register_attribute(__MODULE__, :datasources_selection, accumulate: true)
@before_compile unquote(__MODULE__)
end
end
@doc false
defmacro __before_compile__(env) do
datasources_list = Module.get_attribute(env.module, :datasources_list)
datasources_single = Module.get_attribute(env.module, :datasources_single)
datasources_selection = Module.get_attribute(env.module, :datasources_selection)
[
compile(:list, datasources_list),
compile(:single, datasources_single),
compile(:selection, datasources_selection)
]
end
@doc false
def compile(:list, datasources_list) do
quote do
def __datasources__(:list) do
unquote(datasources_list)
end
end
end
@doc false
def compile(:single, datasources_single) do
quote do
def __datasources__(:single) do
unquote(datasources_single)
end
end
end
@doc false
def compile(:selection, datasources_selection) do
quote do
def __datasources__(:selection) do
unquote(datasources_selection)
end
end
end
defmacro datasources(do: block) do
quote do
unquote(block)
end
end
defmacro list(key, fun) do
quote do
Module.put_attribute(__MODULE__, :datasources_list, unquote(key))
def __datasource__(:list, unquote(key)) do
case unquote(fun) do
{:ok, []} -> {:error, :no_entries}
result -> result
end
end
end
end
@deprecated """
Use Datasource.list/2 instead.
"""
defmacro many(key, fun) do
quote do
Module.put_attribute(__MODULE__, :datasources_list, unquote(key))
def __datasource__(:list, unquote(key)) do
case unquote(fun) do
{:ok, []} -> {:error, :no_entries}
{:ok, nil} -> {:error, :no_entries}
result -> result
end
end
end
end
defmacro single(key, fun) do
quote do
Module.put_attribute(__MODULE__, :datasources_single, unquote(key))
def __datasource__(:single, unquote(key)) do
case unquote(fun) do
{:ok, nil} -> {:error, :no_entries}
result -> result
end
end
end
end
defmacro selection(key, list_fun, get_fun) do
quote do
Module.put_attribute(__MODULE__, :datasources_selection, unquote(key))
def __datasource__(:list_selection, unquote(key)) do
unquote(list_fun)
end
def __datasource__(:get_selection, unquote(key)) do
case unquote(get_fun) do
{:ok, []} -> {:error, :no_entries}
{:ok, nil} -> {:error, :no_entries}
result -> result
end
end
end
end
@doc """
Show all available datasources
"""
def list_datasources do
{:ok, modules} = :application.get_key(Brando.otp_app(), :modules)
{:ok,
modules
|> Enum.filter(&is_datasource/1)
|> Enum.map(&to_string/1)}
end
@doc """
List keys for module
"""
def list_datasource_keys(module_binary) do
module = Module.concat([module_binary])
list_keys = module.__datasources__(:list)
selection_keys = module.__datasources__(:selection)
single_keys = []
{:ok, %{list: list_keys, single: single_keys, selection: selection_keys}}
end
@doc """
Grab list of entries from database
"""
def get_list(module_binary, query, arg, language) do
module = Module.concat([module_binary])
case :erlang.fun_info(module.__datasource__(:list, String.to_atom(query)))[:arity] do
2 ->
module.__datasource__(:list, String.to_atom(query)).(module_binary, arg)
3 ->
module.__datasource__(:list, String.to_atom(query)).(module_binary, language, arg)
end
end
@doc """
List available entries in selection from database
"""
def list_selection(module_binary, query, arg) do
module = Module.concat([module_binary])
available_entries =
module.__datasource__(:list_selection, String.to_atom(query)).(module_binary, arg)
case available_entries do
{:ok, [%{label: _} | _] = options} ->
{:ok, options}
{:ok, entries} ->
Identifier.identifiers_for(entries)
end
end
@doc """
Get selection by [ids] from database
"""
def get_selection(_module_binary, _query, nil) do
{:ok, []}
end
def get_selection(module_binary, query, ids) do
module = Module.concat([module_binary])
module.__datasource__(:get_selection, String.to_atom(query)).(module_binary, ids)
end
@doc """
Grab single entry from database
"""
def get_single(module_binary, query, arg) do
module = Module.concat([module_binary])
module.__datasource__(:single, String.to_atom(query)).(module_binary, arg)
end
@doc """
Look through all villains for datasources using `schema`
"""
def update_datasource(datasource_module, entry \\ nil) do
if is_datasource(datasource_module) do
villains = Villain.list_villains()
Enum.each(villains, fn {schema, fields} ->
Enum.map(fields, &parse_fields(datasource_module, &1, schema))
end)
end
{:ok, entry}
end
defp parse_fields(datasource_module, {:villain, data_field, html_field}, schema) do
process_field(schema, datasource_module, data_field, html_field)
end
defp parse_fields(datasource_module, field, schema) do
process_field(
schema,
datasource_module,
field.name,
Villain.get_html_field(schema, field).name
)
end
defp process_field(schema, datasource_module, data_field, html_field) do
ids = list_ids_with_datasource(schema, datasource_module, data_field)
unless Enum.empty?(ids) do
Villain.rerender_html_from_ids({schema, data_field, html_field}, ids)
end
end
@doc """
List ids of `schema` records that has a datasource matching schema OR
a module containing a datasource matching schema.
"""
def list_ids_with_datasource(schema, datasource, data_field \\ :data)
def list_ids_with_datasource(
schema,
{datasource_module, datasource_type, datasource_query},
data_field
) do
ds_block = %{
type: "datasource",
data: %{
module: to_string(datasource_module),
type: datasource_type,
query: datasource_query
}
}
t = [
ds_block
]
refed_t = [
%{
type: "module",
data: %{refs: [%{data: ds_block}]}
}
]
contained_t = [
%{
type: "container",
data: %{blocks: [ds_block]}
}
]
contained_refed_t = [
%{
type: "container",
data: %{
blocks: refed_t
}
}
]
Brando.repo().all(
from s in schema,
select: s.id,
where: jsonb_contains(s, data_field, t),
or_where: jsonb_contains(s, data_field, contained_t),
or_where: jsonb_contains(s, data_field, refed_t),
or_where: jsonb_contains(s, data_field, contained_refed_t)
)
end
def list_ids_with_datasource(schema, datasource_module, data_field) do
ds_block = %{
type: "datasource",
data: %{module: to_string(datasource_module)}
}
t = [
ds_block
]
refed_t = [
%{
type: "module",
data: %{refs: [%{data: ds_block}]}
}
]
contained_t = [
%{
type: "container",
data: %{blocks: [ds_block]}
}
]
contained_refed_t = [
%{
type: "container",
data: %{
blocks: refed_t
}
}
]
Brando.repo().all(
from s in schema,
select: s.id,
where: jsonb_contains(s, data_field, t),
or_where: jsonb_contains(s, data_field, contained_t),
or_where: jsonb_contains(s, data_field, refed_t),
or_where: jsonb_contains(s, data_field, contained_refed_t)
)
end
@doc """
Check if `schema` is a datasource
"""
def is_datasource({schema, _, _}) do
{:__datasource__, 2} in schema.__info__(:functions)
end
def is_datasource(schema) do
{:__datasource__, 2} in schema.__info__(:functions)
end
end
|
lib/brando/datasource.ex
| 0.733547 | 0.677717 |
datasource.ex
|
starcoder
|
defmodule Rtmp.Handshake do
@moduledoc """
Provides functionality to handle the RTMP handshake process.
## Examples
The following is an example of handling a handshake as a server:
# Since we are a server we don't know what handshake type
# the client will send
{handshake, %RtmpHandshake.ParseResult{}} = RtmpHandshake.new(:unknown)
c0_and_c1 = get_packets_0_and_1_from_client()
{handshake, %RtmpHandshake.ParseResult{
bytes_to_send: bytes,
current_state: :waiting_for_data
}} = RtmpHandshake.process_bytes(handshake, c0_and_c1)
send_bytes_to_client(bytes)
c2 = get_packet_c2_from_client()
{handshake, %RtmpHandshake.ParseResult{
current_state: :success
}} = RtmpHandshake.process_bytes(handshake, c2)
"""
require Logger
alias Rtmp.Handshake.OldHandshakeFormat, as: OldHandshakeFormat
alias Rtmp.Handshake.ParseResult, as: ParseResult
alias Rtmp.Handshake.HandshakeResult, as: HandshakeResult
alias Rtmp.Handshake.DigestHandshakeFormat, as: DigestHandshakeFormat
@type handshake_state :: %__MODULE__.State{}
@type handshake_type :: :unknown | :old | :digest
@type is_valid_format_result :: :yes | :no | :unknown
@type start_time :: non_neg_integer
@type remaining_binary :: <<>>
@type binary_response :: <<>>
@type behaviour_state :: any
@type process_result :: {:success, start_time, binary_response, remaining_binary}
| {:incomplete, binary_response}
| :failure
@callback is_valid_format(<<>>) :: is_valid_format_result
@callback process_bytes(behaviour_state, <<>>) :: {behaviour_state, process_result}
@callback create_p0_and_p1_to_send(behaviour_state) :: {behaviour_state, binary}
defmodule State do
@moduledoc false
defstruct status: :pending,
handshake_state: nil,
handshake_type: :unknown,
remaining_binary: <<>>,
peer_start_timestamp: nil
end
@doc """
Creates a new finite state machine to handle the handshake process,
and preliminary parse results.
If a handshake type is specified we assume we are acting as a client
(since a server won't know what type of handshake to use until it
receives packets c0 and c1).
"""
@spec new(handshake_type) :: {handshake_state, ParseResult.t}
def new(:old) do
{handshake_state, bytes_to_send} =
OldHandshakeFormat.new()
|> OldHandshakeFormat.create_p0_and_p1_to_send()
state = %State{handshake_type: :old, handshake_state: handshake_state}
result = %ParseResult{current_state: :waiting_for_data, bytes_to_send: bytes_to_send}
{state, result}
end
def new(:digest) do
{handshake_state, bytes_to_send} =
DigestHandshakeFormat.new()
|> DigestHandshakeFormat.create_p0_and_p1_to_send()
state = %State{handshake_type: :digest, handshake_state: handshake_state}
result = %ParseResult{current_state: :waiting_for_data, bytes_to_send: bytes_to_send}
{state, result}
end
def new(:unknown) do
state = %State{handshake_type: :unknown}
{state, %ParseResult{current_state: :waiting_for_data}}
end
@doc "Reads the passed in binary to proceed with the handshaking process"
@spec process_bytes(handshake_state, <<>>) :: {handshake_state, ParseResult.t}
def process_bytes(state = %State{handshake_type: :unknown}, binary) when is_binary(binary) do
state = %{state | remaining_binary: state.remaining_binary <> binary}
is_old_format = OldHandshakeFormat.is_valid_format(state.remaining_binary)
is_digest_format = DigestHandshakeFormat.is_valid_format(state.remaining_binary)
case {is_old_format, is_digest_format} do
{_, :yes} ->
handshake_state = DigestHandshakeFormat.new()
binary = state.remaining_binary
state = %{state |
remaining_binary: <<>>,
handshake_type: :digest,
handshake_state: handshake_state
}
# Processing bytes should trigger p0 and p1 to be sent
{state, result} = process_bytes(state, binary)
result = %{result | bytes_to_send: result.bytes_to_send}
{state, result}
{:yes, _} ->
{handshake_state, bytes_to_send} =
OldHandshakeFormat.new()
|> OldHandshakeFormat.create_p0_and_p1_to_send()
binary = state.remaining_binary
state = %{state |
remaining_binary: <<>>,
handshake_type: :old,
handshake_state: handshake_state
}
{state, result} = process_bytes(state, binary)
result = %{result | bytes_to_send: bytes_to_send <> result.bytes_to_send}
{state, result}
{:no, :no} ->
# No known handhsake format
{state, %ParseResult{current_state: :failure}}
_ ->
{state, %ParseResult{}}
end
end
def process_bytes(state = %State{handshake_type: :old}, binary) when is_binary(binary) do
case OldHandshakeFormat.process_bytes(state.handshake_state, binary) do
{handshake_state, :failure} ->
state = %{state | handshake_state: handshake_state}
{state, %ParseResult{current_state: :failure}}
{handshake_state, {:incomplete, bytes_to_send}} ->
state = %{state | handshake_state: handshake_state}
{state, %ParseResult{current_state: :waiting_for_data, bytes_to_send: bytes_to_send}}
{handshake_state, {:success, start_time, response, remaining_binary}} ->
state = %{state |
handshake_state: handshake_state,
remaining_binary: remaining_binary,
peer_start_timestamp: start_time,
status: :complete
}
result = %ParseResult{current_state: :success, bytes_to_send: response}
{state, result}
end
end
def process_bytes(state = %State{handshake_type: :digest}, binary) when is_binary(binary) do
case DigestHandshakeFormat.process_bytes(state.handshake_state, binary) do
{handshake_state, :failure} ->
state = %{state | handshake_state: handshake_state}
{state, %ParseResult{current_state: :failure}}
{handshake_state, {:incomplete, bytes_to_send}} ->
state = %{state | handshake_state: handshake_state}
{state, %ParseResult{current_state: :waiting_for_data, bytes_to_send: bytes_to_send}}
{handshake_state, {:success, start_time, response, remaining_binary}} ->
state = %{state |
handshake_state: handshake_state,
remaining_binary: remaining_binary,
peer_start_timestamp: start_time,
status: :complete
}
result = %ParseResult{current_state: :success, bytes_to_send: response}
{state, result}
end
end
@doc """
After a handshake has been successfully completed this is called to
retrieve the peer's starting timestamp and any left over binary that
may need to be parsed later (not part of the handshake but instead
the beginning of the rtmp protocol).
"""
@spec get_handshake_result(handshake_state) :: {handshake_state, HandshakeResult.t}
def get_handshake_result(state = %State{status: :complete}) do
unparsed_binary = state.remaining_binary
{
%{state | remaining_binary: <<>>},
%HandshakeResult{
peer_start_timestamp: state.peer_start_timestamp,
remaining_binary: unparsed_binary
}
}
end
end
|
apps/rtmp/lib/rtmp/handshake.ex
| 0.793986 | 0.468669 |
handshake.ex
|
starcoder
|
defmodule Timex.Parse.DateTime.Tokenizers.Directive do
@moduledoc false
alias Timex.Parse.DateTime.Parsers
alias Timex.Parse.DateTime.Tokenizers.Directive
defstruct type: :literal,
value: nil,
modifiers: [],
flags: [],
width: [min: -1, max: nil],
parser: nil,
weight: 0
@type t :: %__MODULE__{}
@doc """
Gets a parsing directive for the given token name, where the token name
is an atom.
## Examples
iex> alias Timex.Parsers.Directive
...> %Directive{type: type, flags: flags} = Directive.get(:year4, "YYYY", padding: :zeros)
...> {type, flags}
{:year4, [padding: :zeros]}
"""
@spec get(atom, String.t, [{atom, term}] | []) :: Directive.t
def get(type, directive, opts \\ []) do
min_width = Keyword.get(opts, :min_width, -1)
width = Keyword.get(opts, :width, [min: min_width, max: nil])
flags = Keyword.merge(Keyword.get(opts, :flags, []), width)
modifiers = Keyword.get(opts, :modifiers, [])
get(type, directive, flags, modifiers, width)
end
@simple_types [:year4, :year2, :century, :hour24, :hour12,
:zname, :zoffs, :zoffs_colon, :zoffs_sec,
:iso_date, :iso_time, :iso_week, :iso_weekday, :iso_ordinal,
:ansic, :unix, :kitchen, :slashed, :asn1_utc_time, :asn1_generalized_time,
:strftime_iso_clock, :strftime_iso_clock_full, :strftime_kitchen, :strftime_iso_shortdate,
]
@mapped_types [iso_year4: :year4, iso_year2: :year2,
month: :month2, mshort: :month_short, mfull: :month_full,
day: :day_of_month, oday: :day_of_year,
iso_weeknum: :week_of_year, week_mon: :week_of_year, week_sun: :week_of_year_sun,
wday_mon: :weekday, wday_sun: :weekday, wdshort: :weekday_short, wdfull: :weekday_full,
min: :minute, sec: :second, sec_fractional: :second_fractional, sec_epoch: :seconds_epoch,
us: :microseconds, ms: :milliseconds, am: :ampm, AM: :ampm, zabbr: :zname,
iso_8601_extended: :iso8601_extended, iso_8601_basic: :iso8601_basic,
rfc_822: :rfc822, rfc_1123: :rfc1123, rfc_3339: :rfc3339,
strftime_iso_date: :iso_date,
]
@mapped_zulu_types [
iso_8601_extended_z: :iso8601_extended, iso_8601_basic_z: :iso8601_basic,
rfc_822z: :rfc822, rfc_1123z: :rfc1123, rfc_3339z: :rfc3339, asn1_generalized_time_z: :asn1_generalized_time
]
for type <- @simple_types do
def get(unquote(type), directive, flags, mods, width) do
%Directive{type: unquote(type),
value: directive,
flags: flags,
modifiers: mods,
width: width,
parser: apply(Parsers, unquote(type), [flags])}
end
end
for {type, parser_fun} <- @mapped_types do
def get(unquote(type), directive, flags, mods, width) do
%Directive{type: unquote(type),
value: directive,
flags: flags,
modifiers: mods,
width: width,
parser: apply(Parsers, unquote(parser_fun), [flags])}
end
end
for {type, parser_fun} <- @mapped_zulu_types do
def get(unquote(type), directive, flags, mods, width) do
%Directive{type: unquote(type),
value: directive,
flags: flags,
modifiers: mods,
width: width,
parser: apply(Parsers, unquote(parser_fun), [[{:zulu, true}|flags]])}
end
end
def get(:asn1_generalized_time_tz, directive, flags, mods, width) do
%Directive{type: :asn1_generalized_time_tz,
value: directive,
flags: flags,
modifiers: mods,
width: width,
parser: Parsers.asn1_generalized_time([{:zoffs, true}|flags])}
end
# Catch-all
def get(type, _directive, _flags, _mods, _width),
do: {:error, "Unrecognized directive type: #{type}."}
end
|
lib/parse/datetime/tokenizers/directive.ex
| 0.874238 | 0.5526 |
directive.ex
|
starcoder
|
defmodule Lonely.Result do
@moduledoc """
Composes the tuples `{:ok, a}` and `{:error, e}` as the type `Result.t`.
It is common to get either a value or `nil`. A way to apply a function to
a value letting `nil` untouched.
The following example will return `20` when `n = 2` and `nil` when `n > 3`.
import Lonely.Result
[1, 2, 3]
|> Enum.find(fn x -> x == n end)
|> wrap()
|> map(fn x -> x * 10 end)
|> unwrap()
Some functions return `{:ok, a}` or `:error`. The next example uses `wrap/1`
to normalise it to a result tagging the error appropriately.
The following example will return `30` when `i = 2` and `:out_of_bounds`
when `i > 2`.
import Lonely.Result
[1, 2, 3]
|> Enum.fetch(i)
|> wrap(with: :out_of_bounds)
|> map(fn x -> x * 10 end)
|> unwrap()
Some other times you are certain you will be receiving a result so you can
leave out `wrap/1` and just map over the value. Also, you might want to
recover from the error.
iex> import Lonely.Result
...> str = "23:50:07"
...> Time.from_iso8601(str)
...> |> map(&Time.to_erl/1)
...> |> flat_map_error(fn
...> :invalid_format -> {:ok, {0, 0, 0}}
...> reason -> {:error, {reason, str}}
...> end)
{:ok, {23, 50, 7}}
iex> import Lonely.Result
...> str = "10:11:61"
...> Time.from_iso8601(str)
...> |> map(&Time.to_erl/1)
...> |> flat_map_error(fn
...> :invalid_format -> {:ok, {0, 0, 0}}
...> reason -> {:error, {reason, str}}
...> end)
{:error, {:invalid_time, "10:11:61"}}
"""
@typep a :: any
@typep b :: any
@typep e :: any
@typedoc """
Result type.
"""
@type t :: {:ok, a} | {:error, e}
@doc """
Maps an ok value over a function.
### Identity
iex> import Lonely.Result
...> map({:ok, 1}, &(&1))
{:ok, 1}
iex> import Lonely.Result
...> map({:error, :boom}, &(&1))
{:error, :boom}
### Composition
iex> import Lonely.Result
...> f = fn x -> x + x end
...> g = fn x -> x - x end
...> {:ok, 1}
...> |> map(f)
...> |> map(g)
{:ok, 0}
iex> import Lonely.Result
...> f = fn x -> x + x end
...> g = fn x -> x - x end
...> fg = &(&1 |> f.() |> g.())
...> map({:ok, 1}, fg)
{:ok, 0}
## Applicative
iex> import Lonely.Result
...> a = {:ok, 1}
...> f = {:ok, fn x -> x + x end}
...> map(a, f)
{:ok, 2}
iex> import Lonely.Result
...> e = {:error, :boom}
...> f = {:ok, fn x -> x + x end}
...> map(e, f)
{:error, :boom}
iex> import Lonely.Result
...> a = {:ok, 1}
...> e = {:error, :boom}
...> map(a, e)
{:error, :boom}
"""
@spec map(t, {:ok, (a -> b)}) :: t
def map({:ok, a}, {:ok, f}), do:
{:ok, f.(a)}
def map({:ok, _}, e = {:error, _}), do: e
@spec map(t, (a -> b)) :: t
def map({:ok, a}, f), do:
{:ok, f.(a)}
def map(e = {:error, _}, _f), do: e
@doc """
Maps an error value over function.
iex> import Lonely.Result
...> map_error({:ok, 1}, fn x -> to_string(x) end)
{:ok, 1}
iex> import Lonely.Result
...> map_error({:error, :boom}, fn x -> to_string(x) end)
{:error, "boom"}
"""
@spec map_error(t, (a -> b)) :: t
def map_error(a = {:ok, _}, _f), do: a
def map_error({:error, e}, f), do:
{:error, f.(e)}
@doc """
Maps an ok value over a function and flattens the resulting value into a
single result.
iex> import Lonely.Result
...> flat_map({:ok, 1}, fn x -> {:ok, x} end)
{:ok, 1}
iex> import Lonely.Result
...> flat_map({:error, :boom}, fn x -> {:ok, x} end)
{:error, :boom}
"""
@spec flat_map(t, (a -> t)) :: t
def flat_map({:ok, a}, f), do:
f.(a)
def flat_map(e = {:error, _}, _f), do: e
@doc """
Maps an error value over function.
iex> import Lonely.Result
...> flat_map_error({:ok, 1}, fn x -> to_string(x) end)
{:ok, 1}
iex> import Lonely.Result
...> flat_map_error({:error, :boom}, fn _ -> {:ok, -1} end)
{:ok, -1}
"""
@spec flat_map_error(t, (a -> b)) :: t
def flat_map_error(a = {:ok, _}, _f), do: a
def flat_map_error({:error, e}, f), do:
f.(e)
@doc """
Filters a result value.
iex> import Lonely.Result
...> filter_map({:ok, 1}, fn x -> x == 1 end, fn x -> x + x end)
{:ok, 2}
iex> import Lonely.Result
...> filter_map({:ok, 1}, fn x -> x == 2 end, fn x -> x + x end)
{:ok, 1}
iex> import Lonely.Result
...> filter_map({:error, :boom}, fn x -> x == 1 end, fn x -> x + x end)
{:error, :boom}
"""
@spec filter_map(t, (a -> boolean), (t -> t)) :: t
def filter_map(a = {:ok, x}, f, g) do
if f.(x), do: map(a, g), else: a
end
def filter_map(e = {:error, _}, _f, _g), do: e
@doc """
Checks if the result is ok.
iex> import Lonely.Result
...> is_ok({:ok, 1})
true
iex> import Lonely.Result
...> is_ok({:error, 1})
false
"""
@spec is_ok(t) :: boolean
def is_ok({:ok, _}), do: true
def is_ok({:error, _}), do: false
@doc """
Checks if the result is an error.
iex> import Lonely.Result
...> is_error({:ok, 1})
false
iex> import Lonely.Result
...> is_error({:error, 1})
true
"""
@spec is_error(t) :: boolean
def is_error(a), do: !is_ok(a)
@doc """
Fits a tagged tuple into a Result.
iex> import Lonely.Result
...> fit(:ok)
{:ok, nil}
iex> import Lonely.Result
...> fit({:ok, 1})
{:ok, 1}
iex> import Lonely.Result
...> fit({:ok, 1, 2})
{:ok, {1, 2}}
iex> import Lonely.Result
...> "2017-10-11T12:13:14Z" |> DateTime.from_iso8601() |> fit()
{:ok, {%DateTime{calendar: Calendar.ISO,
day: 11,
hour: 12,
microsecond: {0, 0},
minute: 13,
month: 10,
second: 14,
std_offset: 0,
time_zone: "Etc/UTC",
utc_offset: 0,
year: 2017,
zone_abbr: "UTC"}, 0}}
iex> import Lonely.Result
...> fit({:ok, 1, 2, 3})
{:ok, {1, 2, 3}}
iex> import Lonely.Result
...> fit({:ok, 1, 2, 3, 4})
{:ok, {1, 2, 3, 4}}
iex> import Lonely.Result
...> fit({:ok, 1, 2, 3, 4, 5})
{:ok, {1, 2, 3, 4, 5}}
iex> import Lonely.Result
...> fit(:error)
{:error, nil}
iex> import Lonely.Result
...> fit({:error, 1})
{:error, 1}
iex> import Lonely.Result
...> fit(nil)
{:error, nil}
"""
@spec fit(tuple | atom | nil) :: t
def fit(:ok), do: {:ok, nil}
def fit({:ok, a, b}), do: {:ok, {a, b}}
def fit({:ok, a, b, c}), do: {:ok, {a, b, c}}
def fit({:ok, a, b, c, d}), do: {:ok, {a, b, c, d}}
def fit({:ok, a, b, c, d, e}), do: {:ok, {a, b, c, d, e}}
def fit(a), do: wrap(a)
@doc """
Wraps a value into a result.
iex> import Lonely.Result
...> wrap(nil)
{:error, nil}
iex> import Lonely.Result
...> wrap({:error, :boom})
{:error, :boom}
iex> import Lonely.Result
...> wrap({:ok, 1})
{:ok, 1}
iex> import Lonely.Result
...> wrap(1)
{:ok, 1}
"""
@spec wrap(a) :: t
def wrap(nil), do: {:error, nil}
def wrap(:error), do: {:error, nil}
def wrap(e = {:error, _}), do: e
def wrap(a = {:ok, _}), do: a
def wrap(a), do: {:ok, a}
@doc """
Wraps a value into a result or use the provided error instead of `nil`.
iex> import Lonely.Result
...> wrap(nil, with: :boom)
{:error, :boom}
"""
@spec wrap(a, with: e) :: t
def wrap(nil, with: e), do: {:error, e}
def wrap(:error, with: e), do: {:error, e}
def wrap(a, with: _), do: wrap(a)
@doc """
Returns the value of the result.
If you want to raise the error, use `unwrap!/1`.
iex> import Lonely.Result
...> unwrap({:ok, 1})
1
iex> import Lonely.Result
...> unwrap({:error, :boom})
:boom
"""
@spec unwrap(t) :: a
def unwrap({_, x}), do: x
@doc """
Returns the value of an ok result or raises the error.
iex> import Lonely.Result
...> unwrap!({:ok, 1})
1
iex> import Lonely.Result
...> assert_raise(RuntimeError, "boom", fn -> unwrap!({:error, "boom"}) end)
%RuntimeError{message: "boom"}
"""
@spec unwrap!(t) :: a
def unwrap!({:ok, a}), do: a
def unwrap!({:error, e}), do: raise e
end
|
lib/lonely/result.ex
| 0.87308 | 0.700101 |
result.ex
|
starcoder
|
defmodule Access do
@moduledoc """
Key-based access to data structures.
The `Access` module defines a behaviour for dynamically accessing
keys of any type in a data structure via the `data[key]` syntax.
`Access` supports keyword lists (`Keyword`) and maps (`Map`) out
of the box. Keywords supports only atoms keys, keys for maps can
be of any type. Both returns `nil` if the key does not exist:
iex> keywords = [a: 1, b: 2]
iex> keywords[:a]
1
iex> keywords[:c]
nil
iex> map = %{a: 1, b: 2}
iex> map[:a]
1
iex> star_ratings = %{1.0 => "★", 1.5 => "★☆", 2.0 => "★★"}
iex> star_ratings[1.5]
"★☆"
This syntax is very convenient as it can be nested arbitrarily:
iex> keywords = [a: 1, b: 2]
iex> keywords[:c][:unknown]
nil
This works because accessing anything on a `nil` value, returns
`nil` itself:
iex> nil[:a]
nil
The access syntax can also be used with the `Kernel.put_in/2`,
`Kernel.update_in/2` and `Kernel.get_and_update_in/2` macros
to allow values to be set in nested data structures:
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users["john"][:age], 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
> Attention! While the access syntax is allowed in maps via
> `map[key]`, if your map is made of predefined atom keys,
> you should prefer to access those atom keys with `map.key`
> instead of `map[key]`, as `map.key` will raise if the key
> is missing. This is important because, if a map has a predefined
> set of keys and a key is missing, it is most likely a bug
> in your software or a typo on the key name. For this reason,
> because structs are predefined in nature, they only allow
> the `struct.key` syntax and they do not allow the `struct[key]`
> access syntax. See the `Map` module for more information.
## Nested data structures
Both key-based access syntaxes can be used with the nested update
functions and macros in `Kernel`, such as `Kernel.get_in/2`,
`Kernel.put_in/3`, `Kernel.update_in/3`, `Kernel.pop_in/2`, and
`Kernel.get_and_update_in/3`.
For example, to update a map inside another map:
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users["john"].age, 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
This module provides convenience functions for traversing other
structures, like tuples and lists. These functions can be used
in all the `Access`-related functions and macros in `Kernel`.
For instance, given a user map with the `:name` and `:languages`
keys, here is how to deeply traverse the map and convert all
language names to uppercase:
iex> languages = [
...> %{name: "elixir", type: :functional},
...> %{name: "c", type: :procedural}
...> ]
iex> user = %{name: "john", languages: languages}
iex> update_in(user, [:languages, Access.all(), :name], &String.upcase/1)
%{
name: "john",
languages: [
%{name: "ELIXIR", type: :functional},
%{name: "C", type: :procedural}
]
}
See the functions `key/1`, `key!/1`, `elem/1`, and `all/0` for
some of the available accessors.
"""
@type container :: keyword | struct | map
@type nil_container :: nil
@type any_container :: any
@type t :: container | nil_container | any_container
@type key :: any
@type value :: any
@type get_fun(data, get_value) ::
(:get, data, (term -> term) ->
{get_value, new_data :: container})
@type get_and_update_fun(data, get_value) ::
(:get_and_update, data, (term -> term) ->
{get_value, new_data :: container} | :pop)
@type access_fun(data, get_value) ::
get_fun(data, get_value) | get_and_update_fun(data, get_value)
@doc """
Invoked in order to access the value stored under `key` in the given term `term`.
This function should return `{:ok, value}` where `value` is the value under
`key` if the key exists in the term, or `:error` if the key does not exist in
the term.
Many of the functions defined in the `Access` module internally call this
function. This function is also used when the square-brackets access syntax
(`structure[key]`) is used: the `fetch/2` callback implemented by the module
that defines the `structure` struct is invoked and if it returns `{:ok,
value}` then `value` is returned, or if it returns `:error` then `nil` is
returned.
See the `Map.fetch/2` and `Keyword.fetch/2` implementations for examples of
how to implement this callback.
"""
@callback fetch(term :: t, key) :: {:ok, value} | :error
@doc """
Invoked in order to access the value under `key` and update it at the same time.
The implementation of this callback should invoke `fun` with the value under
`key` in the passed structure `data`, or with `nil` if `key` is not present in it.
This function must return either `{get_value, update_value}` or `:pop`.
If the passed function returns `{get_value, update_value}`,
the return value of this callback should be `{get_value, new_data}`, where:
* `get_value` is the retrieved value (which can be operated on before being returned)
* `update_value` is the new value to be stored under `key`
* `new_data` is `data` after updating the value of `key` with `update_value`.
If the passed function returns `:pop`, the return value of this callback
must be `{value, new_data}` where `value` is the value under `key`
(or `nil` if not present) and `new_data` is `data` without `key`.
See the implementations of `Map.get_and_update/3` or `Keyword.get_and_update/3`
for more examples.
"""
@callback get_and_update(data, key, (value -> {get_value, value} | :pop)) :: {get_value, data}
when get_value: var, data: container | any_container
@doc """
Invoked to "pop" the value under `key` out of the given data structure.
When `key` exists in the given structure `data`, the implementation should
return a `{value, new_data}` tuple where `value` is the value that was under
`key` and `new_data` is `term` without `key`.
When `key` is not present in the given structure, a tuple `{value, data}`
should be returned, where `value` is implementation-defined.
See the implementations for `Map.pop/3` or `Keyword.pop/3` for more examples.
"""
@callback pop(data, key) :: {value, data} when data: container | any_container
defmacrop raise_undefined_behaviour(exception, module, top) do
quote do
exception =
case __STACKTRACE__ do
[unquote(top) | _] ->
reason = "#{inspect(unquote(module))} does not implement the Access behaviour"
%{unquote(exception) | reason: reason}
_ ->
unquote(exception)
end
reraise exception, __STACKTRACE__
end
end
@doc """
Fetches the value for the given key in a container (a map, keyword
list, or struct that implements the `Access` behaviour).
Returns `{:ok, value}` where `value` is the value under `key` if there is such
a key, or `:error` if `key` is not found.
## Examples
iex> Access.fetch(%{name: "meg", age: 26}, :name)
{:ok, "meg"}
iex> Access.fetch([ordered: true, on_timeout: :exit], :timeout)
:error
"""
@spec fetch(container, term) :: {:ok, term} | :error
@spec fetch(nil_container, any) :: :error
def fetch(container, key)
def fetch(%module{} = container, key) do
module.fetch(container, key)
rescue
exception in UndefinedFunctionError ->
raise_undefined_behaviour(exception, module, {^module, :fetch, [^container, ^key], _})
end
def fetch(map, key) when is_map(map) do
case map do
%{^key => value} -> {:ok, value}
_ -> :error
end
end
def fetch(list, key) when is_list(list) and is_atom(key) do
case :lists.keyfind(key, 1, list) do
{_, value} -> {:ok, value}
false -> :error
end
end
def fetch(list, key) when is_list(list) do
raise ArgumentError,
"the Access calls for keywords expect the key to be an atom, got: " <> inspect(key)
end
def fetch(nil, _key) do
:error
end
@doc """
Same as `fetch/2` but returns the value directly,
or raises a `KeyError` exception if `key` is not found.
## Examples
iex> Access.fetch!(%{name: "meg", age: 26}, :name)
"meg"
"""
@doc since: "1.10.0"
@spec fetch!(container, term) :: term
def fetch!(container, key) do
case fetch(container, key) do
{:ok, value} -> value
:error -> raise(KeyError, key: key, term: container)
end
end
@doc """
Gets the value for the given key in a container (a map, keyword
list, or struct that implements the `Access` behaviour).
Returns the value under `key` if there is such a key, or `default` if `key` is
not found.
## Examples
iex> Access.get(%{name: "john"}, :name, "default name")
"john"
iex> Access.get(%{name: "john"}, :age, 25)
25
iex> Access.get([ordered: true], :timeout)
nil
"""
@spec get(container, term, term) :: term
@spec get(nil_container, any, default) :: default when default: var
def get(container, key, default \\ nil)
# Reimplementing the same logic as Access.fetch/2 here is done for performance, since
# this is called a lot and calling fetch/2 means introducing some overhead (like
# building the "{:ok, _}" tuple and deconstructing it back right away).
def get(%module{} = container, key, default) do
try do
module.fetch(container, key)
rescue
exception in UndefinedFunctionError ->
raise_undefined_behaviour(exception, module, {^module, :fetch, [^container, ^key], _})
else
{:ok, value} -> value
:error -> default
end
end
def get(map, key, default) when is_map(map) do
case map do
%{^key => value} -> value
_ -> default
end
end
def get(list, key, default) when is_list(list) and is_atom(key) do
case :lists.keyfind(key, 1, list) do
{_, value} -> value
false -> default
end
end
def get(list, key, _default) when is_list(list) do
raise ArgumentError,
"the Access calls for keywords expect the key to be an atom, got: " <> inspect(key)
end
def get(nil, _key, default) do
default
end
@doc """
Gets and updates the given key in a `container` (a map, a keyword list,
a struct that implements the `Access` behaviour).
The `fun` argument receives the value of `key` (or `nil` if `key` is not
present in `container`) and must return a two-element tuple `{get_value, update_value}`:
the "get" value `get_value` (the retrieved value, which can be operated on before
being returned) and the new value to be stored under `key` (`update_value`).
`fun` may also return `:pop`, which means the current value
should be removed from the container and returned.
The returned value is a two-element tuple with the "get" value returned by
`fun` and a new container with the updated value under `key`.
## Examples
iex> Access.get_and_update([a: 1], :a, fn current_value ->
...> {current_value, current_value + 1}
...> end)
{1, [a: 2]}
"""
@spec get_and_update(data, key, (value -> {get_value, value} | :pop)) :: {get_value, data}
when get_value: var, data: container
def get_and_update(container, key, fun)
def get_and_update(%module{} = container, key, fun) do
module.get_and_update(container, key, fun)
rescue
exception in UndefinedFunctionError ->
raise_undefined_behaviour(
exception,
module,
{^module, :get_and_update, [^container, ^key, ^fun], _}
)
end
def get_and_update(map, key, fun) when is_map(map) do
Map.get_and_update(map, key, fun)
end
def get_and_update(list, key, fun) when is_list(list) do
Keyword.get_and_update(list, key, fun)
end
def get_and_update(nil, key, _fun) do
raise ArgumentError, "could not put/update key #{inspect(key)} on a nil value"
end
@doc """
Removes the entry with a given key from a container (a map, keyword
list, or struct that implements the `Access` behaviour).
Returns a tuple containing the value associated with the key and the
updated container. `nil` is returned for the value if the key isn't
in the container.
## Examples
With a map:
iex> Access.pop(%{name: "Elixir", creator: "Valim"}, :name)
{"Elixir", %{creator: "Valim"}}
A keyword list:
iex> Access.pop([name: "Elixir", creator: "Valim"], :name)
{"Elixir", [creator: "Valim"]}
An unknown key:
iex> Access.pop(%{name: "Elixir", creator: "Valim"}, :year)
{nil, %{creator: "Valim", name: "Elixir"}}
"""
@spec pop(data, key) :: {value, data} when data: container
def pop(%module{} = container, key) do
module.pop(container, key)
rescue
exception in UndefinedFunctionError ->
raise_undefined_behaviour(exception, module, {^module, :pop, [^container, ^key], _})
end
def pop(map, key) when is_map(map) do
Map.pop(map, key)
end
def pop(list, key) when is_list(list) do
Keyword.pop(list, key)
end
def pop(nil, key) do
raise ArgumentError, "could not pop key #{inspect(key)} on a nil value"
end
## Accessors
@doc """
Returns a function that accesses the given key in a map/struct.
The returned function is typically passed as an accessor to `Kernel.get_in/2`,
`Kernel.get_and_update_in/3`, and friends.
The returned function uses the default value if the key does not exist.
This can be used to specify defaults and safely traverse missing keys:
iex> get_in(%{}, [Access.key(:user, %{name: "meg"}), Access.key(:name)])
"meg"
Such is also useful when using update functions, allowing us to introduce
values as we traverse the data structure for updates:
iex> put_in(%{}, [Access.key(:user, %{}), Access.key(:name)], "Mary")
%{user: %{name: "Mary"}}
## Examples
iex> map = %{user: %{name: "john"}}
iex> get_in(map, [Access.key(:unknown, %{}), Access.key(:name, "john")])
"john"
iex> get_and_update_in(map, [Access.key(:user), Access.key(:name)], fn prev ->
...> {prev, String.upcase(prev)}
...> end)
{"john", %{user: %{name: "JOHN"}}}
iex> pop_in(map, [Access.key(:user), Access.key(:name)])
{"john", %{user: %{}}}
An error is raised if the accessed structure is not a map or a struct:
iex> get_in(nil, [Access.key(:foo)])
** (BadMapError) expected a map, got: nil
iex> get_in([], [Access.key(:foo)])
** (BadMapError) expected a map, got: []
"""
@spec key(key, term) :: access_fun(data :: struct | map, get_value :: term)
def key(key, default \\ nil) do
fn
:get, data, next ->
next.(Map.get(data, key, default))
:get_and_update, data, next ->
value = Map.get(data, key, default)
case next.(value) do
{get, update} -> {get, Map.put(data, key, update)}
:pop -> {value, Map.delete(data, key)}
end
end
end
@doc """
Returns a function that accesses the given key in a map/struct.
The returned function is typically passed as an accessor to `Kernel.get_in/2`,
`Kernel.get_and_update_in/3`, and friends.
Similar to `key/2`, but the returned function raises if the key does not exist.
## Examples
iex> map = %{user: %{name: "john"}}
iex> get_in(map, [Access.key!(:user), Access.key!(:name)])
"john"
iex> get_and_update_in(map, [Access.key!(:user), Access.key!(:name)], fn prev ->
...> {prev, String.upcase(prev)}
...> end)
{"john", %{user: %{name: "JOHN"}}}
iex> pop_in(map, [Access.key!(:user), Access.key!(:name)])
{"john", %{user: %{}}}
iex> get_in(map, [Access.key!(:user), Access.key!(:unknown)])
** (KeyError) key :unknown not found in: %{name: \"john\"}
An error is raised if the accessed structure is not a map/struct:
iex> get_in([], [Access.key!(:foo)])
** (RuntimeError) Access.key!/1 expected a map/struct, got: []
"""
@spec key!(key) :: access_fun(data :: struct | map, get_value :: term)
def key!(key) do
fn
:get, %{} = data, next ->
next.(Map.fetch!(data, key))
:get_and_update, %{} = data, next ->
value = Map.fetch!(data, key)
case next.(value) do
{get, update} -> {get, Map.put(data, key, update)}
:pop -> {value, Map.delete(data, key)}
end
_op, data, _next ->
raise "Access.key!/1 expected a map/struct, got: #{inspect(data)}"
end
end
@doc ~S"""
Returns a function that accesses the element at the given index in a tuple.
The returned function is typically passed as an accessor to `Kernel.get_in/2`,
`Kernel.get_and_update_in/3`, and friends.
The returned function raises if `index` is out of bounds.
Note that popping elements out of tuples is not possible and raises an
error.
## Examples
iex> map = %{user: {"john", 27}}
iex> get_in(map, [:user, Access.elem(0)])
"john"
iex> get_and_update_in(map, [:user, Access.elem(0)], fn prev ->
...> {prev, String.upcase(prev)}
...> end)
{"john", %{user: {"JOHN", 27}}}
iex> pop_in(map, [:user, Access.elem(0)])
** (RuntimeError) cannot pop data from a tuple
An error is raised if the accessed structure is not a tuple:
iex> get_in(%{}, [Access.elem(0)])
** (RuntimeError) Access.elem/1 expected a tuple, got: %{}
"""
@spec elem(non_neg_integer) :: access_fun(data :: tuple, get_value :: term)
def elem(index) when is_integer(index) and index >= 0 do
pos = index + 1
fn
:get, data, next when is_tuple(data) ->
next.(:erlang.element(pos, data))
:get_and_update, data, next when is_tuple(data) ->
value = :erlang.element(pos, data)
case next.(value) do
{get, update} -> {get, :erlang.setelement(pos, data, update)}
:pop -> raise "cannot pop data from a tuple"
end
_op, data, _next ->
raise "Access.elem/1 expected a tuple, got: #{inspect(data)}"
end
end
@doc ~S"""
Returns a function that accesses all the elements in a list.
The returned function is typically passed as an accessor to `Kernel.get_in/2`,
`Kernel.get_and_update_in/3`, and friends.
## Examples
iex> list = [%{name: "john"}, %{name: "mary"}]
iex> get_in(list, [Access.all(), :name])
["john", "mary"]
iex> get_and_update_in(list, [Access.all(), :name], fn prev ->
...> {prev, String.upcase(prev)}
...> end)
{["john", "mary"], [%{name: "JOHN"}, %{name: "MARY"}]}
iex> pop_in(list, [Access.all(), :name])
{["john", "mary"], [%{}, %{}]}
Here is an example that traverses the list dropping even
numbers and multiplying odd numbers by 2:
iex> require Integer
iex> get_and_update_in([1, 2, 3, 4, 5], [Access.all()], fn num ->
...> if Integer.is_even(num), do: :pop, else: {num, num * 2}
...> end)
{[1, 2, 3, 4, 5], [2, 6, 10]}
An error is raised if the accessed structure is not a list:
iex> get_in(%{}, [Access.all()])
** (RuntimeError) Access.all/0 expected a list, got: %{}
"""
@spec all() :: access_fun(data :: list, get_value :: list)
def all() do
&all/3
end
defp all(:get, data, next) when is_list(data) do
Enum.map(data, next)
end
defp all(:get_and_update, data, next) when is_list(data) do
all(data, next, _gets = [], _updates = [])
end
defp all(_op, data, _next) do
raise "Access.all/0 expected a list, got: #{inspect(data)}"
end
defp all([head | rest], next, gets, updates) do
case next.(head) do
{get, update} -> all(rest, next, [get | gets], [update | updates])
:pop -> all(rest, next, [head | gets], updates)
end
end
defp all([], _next, gets, updates) do
{:lists.reverse(gets), :lists.reverse(updates)}
end
@doc ~S"""
Returns a function that accesses the element at `index` (zero based) of a list.
The returned function is typically passed as an accessor to `Kernel.get_in/2`,
`Kernel.get_and_update_in/3`, and friends.
## Examples
iex> list = [%{name: "john"}, %{name: "mary"}]
iex> get_in(list, [Access.at(1), :name])
"mary"
iex> get_in(list, [Access.at(-1), :name])
"mary"
iex> get_and_update_in(list, [Access.at(0), :name], fn prev ->
...> {prev, String.upcase(prev)}
...> end)
{"john", [%{name: "JOHN"}, %{name: "mary"}]}
iex> get_and_update_in(list, [Access.at(-1), :name], fn prev ->
...> {prev, String.upcase(prev)}
...> end)
{"mary", [%{name: "john"}, %{name: "MARY"}]}
`at/1` can also be used to pop elements out of a list or
a key inside of a list:
iex> list = [%{name: "john"}, %{name: "mary"}]
iex> pop_in(list, [Access.at(0)])
{%{name: "john"}, [%{name: "mary"}]}
iex> pop_in(list, [Access.at(0), :name])
{"john", [%{}, %{name: "mary"}]}
When the index is out of bounds, `nil` is returned and the update function is never called:
iex> list = [%{name: "john"}, %{name: "mary"}]
iex> get_in(list, [Access.at(10), :name])
nil
iex> get_and_update_in(list, [Access.at(10), :name], fn prev ->
...> {prev, String.upcase(prev)}
...> end)
{nil, [%{name: "john"}, %{name: "mary"}]}
An error is raised if the accessed structure is not a list:
iex> get_in(%{}, [Access.at(1)])
** (RuntimeError) Access.at/1 expected a list, got: %{}
"""
@spec at(integer) :: access_fun(data :: list, get_value :: term)
def at(index) when is_integer(index) do
fn op, data, next -> at(op, data, index, next) end
end
defp at(:get, data, index, next) when is_list(data) do
data |> Enum.at(index) |> next.()
end
defp at(:get_and_update, data, index, next) when is_list(data) do
get_and_update_at(data, index, next, [], fn -> nil end)
end
defp at(_op, data, _index, _next) do
raise "Access.at/1 expected a list, got: #{inspect(data)}"
end
defp get_and_update_at([head | rest], 0, next, updates, _default_fun) do
case next.(head) do
{get, update} -> {get, :lists.reverse([update | updates], rest)}
:pop -> {head, :lists.reverse(updates, rest)}
end
end
defp get_and_update_at([_ | _] = list, index, next, updates, default_fun) when index < 0 do
list_length = length(list)
if list_length + index >= 0 do
get_and_update_at(list, list_length + index, next, updates, default_fun)
else
{default_fun.(), list}
end
end
defp get_and_update_at([head | rest], index, next, updates, default_fun) when index > 0 do
get_and_update_at(rest, index - 1, next, [head | updates], default_fun)
end
defp get_and_update_at([], _index, _next, updates, default_fun) do
{default_fun.(), :lists.reverse(updates)}
end
@doc ~S"""
Same as `at/1` except that it raises `Enum.OutOfBoundsError`
if the given index is out of bounds.
## Examples
iex> get_in([:a, :b, :c], [Access.at!(2)])
:c
iex> get_in([:a, :b, :c], [Access.at!(3)])
** (Enum.OutOfBoundsError) out of bounds error
"""
@spec at!(integer) :: access_fun(data :: list, get_value :: term)
def at!(index) when is_integer(index) do
fn op, data, next -> at!(op, data, index, next) end
end
defp at!(:get, data, index, next) when is_list(data) do
case Enum.fetch(data, index) do
{:ok, value} -> next.(value)
:error -> raise Enum.OutOfBoundsError
end
end
defp at!(:get_and_update, data, index, next) when is_list(data) do
get_and_update_at(data, index, next, [], fn -> raise Enum.OutOfBoundsError end)
end
defp at!(_op, data, _index, _next) do
raise "Access.at!/1 expected a list, got: #{inspect(data)}"
end
@doc ~S"""
Returns a function that accesses all elements of a list that match the provided predicate.
The returned function is typically passed as an accessor to `Kernel.get_in/2`,
`Kernel.get_and_update_in/3`, and friends.
## Examples
iex> list = [%{name: "john", salary: 10}, %{name: "francine", salary: 30}]
iex> get_in(list, [Access.filter(&(&1.salary > 20)), :name])
["francine"]
iex> get_and_update_in(list, [Access.filter(&(&1.salary <= 20)), :name], fn prev ->
...> {prev, String.upcase(prev)}
...> end)
{["john"], [%{name: "JOHN", salary: 10}, %{name: "francine", salary: 30}]}
`filter/1` can also be used to pop elements out of a list or
a key inside of a list:
iex> list = [%{name: "john", salary: 10}, %{name: "francine", salary: 30}]
iex> pop_in(list, [Access.filter(&(&1.salary >= 20))])
{[%{name: "francine", salary: 30}], [%{name: "john", salary: 10}]}
iex> pop_in(list, [Access.filter(&(&1.salary >= 20)), :name])
{["francine"], [%{name: "john", salary: 10}, %{salary: 30}]}
When no match is found, an empty list is returned and the update function is never called
iex> list = [%{name: "john", salary: 10}, %{name: "francine", salary: 30}]
iex> get_in(list, [Access.filter(&(&1.salary >= 50)), :name])
[]
iex> get_and_update_in(list, [Access.filter(&(&1.salary >= 50)), :name], fn prev ->
...> {prev, String.upcase(prev)}
...> end)
{[], [%{name: "john", salary: 10}, %{name: "francine", salary: 30}]}
An error is raised if the predicate is not a function or is of the incorrect arity:
iex> get_in([], [Access.filter(5)])
** (FunctionClauseError) no function clause matching in Access.filter/1
An error is raised if the accessed structure is not a list:
iex> get_in(%{}, [Access.filter(fn a -> a == 10 end)])
** (RuntimeError) Access.filter/1 expected a list, got: %{}
"""
@doc since: "1.6.0"
@spec filter((term -> boolean)) :: access_fun(data :: list, get_value :: list)
def filter(func) when is_function(func) do
fn op, data, next -> filter(op, data, func, next) end
end
defp filter(:get, data, func, next) when is_list(data) do
data |> Enum.filter(func) |> Enum.map(next)
end
defp filter(:get_and_update, data, func, next) when is_list(data) do
get_and_update_filter(data, func, next, [], [])
end
defp filter(_op, data, _func, _next) do
raise "Access.filter/1 expected a list, got: #{inspect(data)}"
end
defp get_and_update_filter([head | rest], func, next, updates, gets) do
if func.(head) do
case next.(head) do
{get, update} ->
get_and_update_filter(rest, func, next, [update | updates], [get | gets])
:pop ->
get_and_update_filter(rest, func, next, updates, [head | gets])
end
else
get_and_update_filter(rest, func, next, [head | updates], gets)
end
end
defp get_and_update_filter([], _func, _next, updates, gets) do
{:lists.reverse(gets), :lists.reverse(updates)}
end
end
|
lib/elixir/lib/access.ex
| 0.913378 | 0.672832 |
access.ex
|
starcoder
|
defmodule Pbkdf2KeyDerivation do
@doc ~S"""
Derives a key of length `key_bytes` for `pass`,
using `algo` and `salt` for `count` iterations.
To raise on error use `Pbkdf2KeyDerivation.pbkdf2!/5`
## Example
```
iex> Pbkdf2KeyDerivation.pbkdf2("password", "<PASSWORD>", :sha512, 1000, 64)
{:ok,
<<175, 230, 197, 83, 7, 133, 182, 204, 107, 28, 100, 83, 56, 71, 49, 189, 94,
228, 50, 238, 84, 159, 212, 47, 182, 105, 87, 121, 173, 138, 28, 91, 245,
157, 230, 156, 72, 247, 116, 239, 196, 0, 125, 82, 152, 249, 3, 60, _rest>>}
```
"""
@spec pbkdf2(binary, binary, :sha | :sha256 | :sha512, pos_integer, pos_integer) ::
{:error, String.t()} | {:ok, binary}
def pbkdf2(_pass, _salt, _algo, count, _key_bytes) when count <= 0 do
{:error, "count must be positive"}
end
def pbkdf2(_pass, _salt, _algo, _count, key_bytes) when key_bytes <= 0 do
{:error, "key_bytes must be positive"}
end
def pbkdf2(pass, salt, algo, count, key_bytes) do
case hash_size(algo) do
{:ok, hash_bytes} ->
if key_bytes <= (:math.pow(2, 32) - 1) * hash_bytes do
{:ok, pbkdf2(pass, salt, algo, count, key_bytes, hash_bytes)}
else
{:error, "key_bytes is too long"}
end
err ->
err
end
end
@doc ~S"""
Derives a key of length `key_bytes` for `pass`,
using `algo` and `salt` for `count` iterations.
To return a tuple instead of raising use `Pbkdf2KeyDerivation.pbkdf2/5`
## Example
```
iex> Pbkdf2KeyDerivation.pbkdf2("password", "<PASSWORD>", :sha512, 1000, 64)
<<175, 230, 197, 83, 7, 133, 182, 204, 107, 28, 100, 83, 56, 71, 49, 189, 94,
228, 50, 238, 84, 159, 212, 47, 182, 105, 87, 121, 173, 138, 28, 91, 245,
157, 230, 156, 72, 247, 116, 239, 196, 0, 125, 82, 152, 249, 3, 60, _rest>>
```
"""
@spec pbkdf2!(binary, binary, :sha | :sha256 | :sha512, pos_integer, pos_integer) :: binary
def pbkdf2!(pass, salt, algo, count, key_bytes) do
case pbkdf2(pass, salt, algo, count, key_bytes) do
{:ok, key} -> key
{:error, error} -> raise ArgumentError, message: error
end
end
defp pbkdf2(pass, salt, algo, count, key_bytes, hash_bytes) do
block_count =
(key_bytes / hash_bytes)
|> :math.ceil()
|> trunc
remaining_bytes = key_bytes - (block_count - 1) * hash_bytes
ts =
1..(block_count + 1)
|> Enum.map(fn e -> f(algo, pass, salt, count, e) end)
t_last =
List.last(ts)
|> binary_part(0, remaining_bytes)
ts
|> Enum.drop(-1)
|> Kernel.++([t_last])
|> Enum.join()
|> binary_part(0, key_bytes)
end
defp f(algo, p, s, c, i) do
u1 = :crypto.mac(:hmac, algo, p, s <> <<i::32>>)
Stream.iterate(u1, &:crypto.mac(:hmac, algo, p, &1))
|> Enum.take(c)
|> Enum.reduce(fn e, acc -> :crypto.exor(e, acc) end)
end
defp hash_size(:sha), do: {:ok, 20}
defp hash_size(:sha256), do: {:ok, 32}
defp hash_size(:sha512), do: {:ok, 64}
defp hash_size(algo), do: {:error, "Unsupported algorithm #{algo}"}
end
|
lib/pbkdf2_key_derivation.ex
| 0.882035 | 0.823328 |
pbkdf2_key_derivation.ex
|
starcoder
|
defmodule Opus.Pipeline do
@moduledoc ~S"""
Defines a pipeline.
A pipeline defines a single entry point function to start running the defined stages.
A simple pipeline module can be defined as:
defmodule ArithmeticPipeline do
use Opus.Pipeline
step :to_integer, with: &:erlang.binary_to_integer/1
step :double, with: & &1 * 2
end
# Invoke it with:
ArithmeticPipeline.call "42"
# => {:ok, 84}
The pipeline can be run calling a `call/1` function which is defined by `Opus.Pipeline`.
Pipelines are intended to have a single parameter and always return a tagged tuple `{:ok, value} | {:error, error}`.
A stage returning `{:error, error}` halts the pipeline. The error value is an `Opus.PipelineError` struct which
contains useful information to detect where the error was caused and why.
## Stage Definition
The following types of stages can be defined:
* `step` - see `Opus.Pipeline.Stage.Step`
* `tee` - see `Opus.Pipeline.Stage.Tee`
* `check` - see `Opus.Pipeline.Stage.Check`
* `link` - see `Opus.Pipeline.Stage.Link`
* `skip` - see `Opus.Pipeline.Stage.Skip`
## Stage Options
* `:with`: The function to call to fulfill this stage. It can be an Atom
referring to a public function of the module, an anonymous function or
a function reference.
* `:if`: Makes a stage conditional, it can be either an Atom referring
to a public function of the module, an anonymous function or a
function reference. For the stage to be executed, the condition *must*
return `true`. When the stage is skipped, the input is forwarded to
the next step if there's one.
* `:unless`: The opposite of the `:if` option, executes the step only
when the callback function returns `false`.
* `:raise`: A list of exceptions to not rescue. Defaults to `false`
which converts all exceptions to `{:error, %Opus.PipelineError{}}`
values halting the pipeline.
* `:error_message`: An error message to replace the original error when a
stage fails. It can be a String or Atom, which will be used directly in place
of the original message, or an anonymous function, which receives the input
of the failed stage and must return the error message to be used.
* `:retry_times`: How many times to retry a failing stage, before
halting the pipeline.
* `:retry_backoff`: A backoff function to provide delay values for
retries. It can be an Atom referring to a public function in the
module, an anonymous function or a function reference. It must return
an `Enumerable.t` yielding at least as many numbers as the
`retry_times`.
* `:instrument?`: A boolean which defaults to `true`. Set to `false` to
skip instrumentation for a stage.
## Exception Handling
All exceptions are converted to `{:error, exception}` tuples by default.
You may let a stage raise an exception by providing the `:raise` option to a stage as follows:
defmodule ArithmeticPipeline do
use Opus.Pipeline
step :to_integer, &:erlang.binary_to_integer/1, raise: [ArgumentError]
end
## Stage Filtering
You can select the stages of a pipeline to run using `call/2` with the `:except` and `:only` options.
Example:
```
# Runs only the stage with the :validate_params name
CreateUserPipeline.call(params, only: [:validate_params]
# Runs all the stages except the selected ones
CreateUserPipeline.call(params, except: :send_notification)
```
"""
@type opts :: [only: [atom], except: [atom]]
@type result :: {:ok, any} | {:error, Opus.PipelineError.t()}
defmacro __using__(opts) do
quote location: :keep do
import Opus.Pipeline
import Opus.Pipeline.Registration
import Retry.DelayStreams
Module.register_attribute(__MODULE__, :opus_stages, accumulate: true)
Module.register_attribute(__MODULE__, :opus_callbacks, accumulate: true)
@before_compile Opus.Pipeline
@opus_opts Map.new(unquote(opts))
alias Opus.PipelineError
alias Opus.Instrumentation
alias Opus.Pipeline.StageFilter
alias Opus.Pipeline.Stage.{Step, Tee, Check, Link, Skip}
alias __MODULE__, as: Pipeline
import Opus.Instrumentation, only: :macros
@doc false
def pipeline?, do: true
@doc "The entrypoint function of the pipeline"
@spec call(any, Opus.Pipeline.opts()) :: Opus.Pipeline.result()
def call(input, opts \\ []) do
instrument? = Pipeline._opus_opts()[:instrument?]
unless instrument? == false do
Instrumentation.run_instrumenters(:pipeline_started, {Pipeline, nil, nil, nil}, %{
input: input
})
end
case Pipeline.stages()
|> StageFilter.call(opts)
|> Enum.reduce_while(%{time: 0, input: input}, &run_instrumented/2) do
%{time: time, input: {:error, _} = error} ->
unless instrument? == false do
Instrumentation.run_instrumenters(:pipeline_completed, {Pipeline, nil, nil, nil}, %{
result: error,
time: time
})
end
error
%{time: time, input: val} ->
unless instrument? == false do
Instrumentation.run_instrumenters(:pipeline_completed, {Pipeline, nil, nil, nil}, %{
result: {:ok, val},
time: time
})
end
{:ok, val}
end
end
@doc false
def _opus_opts, do: @opus_opts
defp run_instrumented({type, name, opts} = stage, %{time: acc_time, input: input}) do
pipeline_opts = Pipeline._opus_opts()
instrumented_return =
Instrumentation.run_instrumented(
{Pipeline, type, name, Map.merge(pipeline_opts, opts)},
input,
fn ->
run_stage(stage, input)
end
)
case instrumented_return do
{status, %{time: time, input: :pipeline_skipped}} ->
{status, %{time: acc_time + time, input: input}}
{status, %{time: time, input: new_input}} ->
{status, %{time: acc_time + time, input: new_input}}
{status, :pipeline_skipped} ->
{status, %{time: acc_time + 0, input: input}}
{status, new_input} ->
{status, %{time: acc_time + 0, input: new_input}}
end
end
defp run_stage({type, name, opts}, input),
do: run_stage({Pipeline, type, name, opts}, input)
defp run_stage({module, :step, name, opts} = stage, input), do: Step.run(stage, input)
defp run_stage({module, :tee, name, opts} = stage, input), do: Tee.run(stage, input)
defp run_stage({module, :check, name, opts} = stage, input), do: Check.run(stage, input)
defp run_stage({module, :link, name, opts} = stage, input), do: Link.run(stage, input)
defp run_stage({module, :skip, name, opts} = stage, input), do: Skip.run(stage, input)
end
end
@doc false
defmacro __before_compile__(_env) do
default_instrumentation = Opus.Instrumentation.default_callback()
quote do
@doc false
def stages, do: @opus_stages |> Enum.reverse()
@opus_grouped_callbacks @opus_callbacks |> Enum.group_by(& &1.stage_id)
def _opus_callbacks, do: @opus_grouped_callbacks
unquote(default_instrumentation)
end
end
defmacro link(name, opts \\ []) do
stage_id = :erlang.unique_integer([:positive])
callbacks = Opus.Pipeline.Registration.maybe_define_callbacks(stage_id, name, opts)
quote do
if unquote(name) != __MODULE__ do
case Code.ensure_compiled(unquote(name)) do
{:error, _} ->
raise CompileError,
file: __ENV__.file,
line: __ENV__.line,
description:
to_string(:elixir_aliases.format_error({:unloaded_module, unquote(name)}))
_ ->
:ok
end
end
if unquote(name) == __MODULE__ || :erlang.function_exported(unquote(name), :pipeline?, 0) do
unquote(callbacks)
options =
Opus.Pipeline.Registration.normalize_opts(
unquote(opts),
unquote(stage_id),
@opus_callbacks
)
@opus_stages {:link, unquote(name), Map.new(options ++ [stage_id: unquote(stage_id)])}
end
end
end
defmacro step(name, opts \\ []) do
stage_id = :erlang.unique_integer([:positive])
callbacks = Opus.Pipeline.Registration.maybe_define_callbacks(stage_id, name, opts)
quote do
unquote(callbacks)
options =
Opus.Pipeline.Registration.normalize_opts(
unquote(opts),
unquote(stage_id),
@opus_callbacks
)
@opus_stages {:step, unquote(name), Map.new(options ++ [stage_id: unquote(stage_id)])}
end
end
defmacro tee(name, opts \\ []) do
stage_id = :erlang.unique_integer([:positive])
callbacks = Opus.Pipeline.Registration.maybe_define_callbacks(stage_id, name, opts)
quote do
unquote(callbacks)
options =
Opus.Pipeline.Registration.normalize_opts(
unquote(opts),
unquote(stage_id),
@opus_callbacks
)
@opus_stages {:tee, unquote(name), Map.new(options ++ [stage_id: unquote(stage_id)])}
end
end
defmacro check(name, opts \\ []) do
stage_id = :erlang.unique_integer([:positive])
callbacks = Opus.Pipeline.Registration.maybe_define_callbacks(stage_id, name, opts)
quote do
unquote(callbacks)
options =
Opus.Pipeline.Registration.normalize_opts(
unquote(opts),
unquote(stage_id),
@opus_callbacks
)
@opus_stages {:check, unquote(name), Map.new(options ++ [stage_id: unquote(stage_id)])}
end
end
defmacro skip(name, opts \\ []) do
stage_id = :erlang.unique_integer([:positive])
callbacks = Opus.Pipeline.Registration.maybe_define_callbacks(stage_id, name, opts)
quote do
unquote(callbacks)
options =
Opus.Pipeline.Registration.normalize_opts(
unquote(opts),
unquote(stage_id),
@opus_callbacks
)
@opus_stages {:skip, unquote(name), Map.new(options ++ [stage_id: unquote(stage_id)])}
end
end
end
|
lib/opus/pipeline.ex
| 0.914715 | 0.908456 |
pipeline.ex
|
starcoder
|
defmodule Instream.Decoder.CSV do
@moduledoc false
alias Instream.Decoder.RFC3339
NimbleCSV.define(__MODULE__.Parser, separator: ",", escape: "\"")
@doc """
Converts a full CSV response into a list of maps.
"""
@spec parse(binary) :: [map]
def parse(response) do
response
|> String.trim_trailing("\r\n\r\n")
|> String.split(["\r\n\r\n"])
|> case do
[table | []] -> parse_table(table)
[_ | _] = tables -> Enum.map(tables, &parse_table/1)
_ -> []
end
end
defp apply_defaults(row, [], []), do: row
defp apply_defaults(["" | rest], [value | defaults], acc),
do: apply_defaults(rest, defaults, [value | acc])
defp apply_defaults([value | rest], [_ | defaults], acc),
do: apply_defaults(rest, defaults, [value | acc])
defp apply_defaults([], [], acc), do: Enum.reverse(acc)
defp parse_annotations([["#datatype" | _ = datatypes] | rest], acc),
do: parse_annotations(rest, %{acc | datatypes: datatypes})
defp parse_annotations([["#default" | _ = defaults] | rest], acc),
do: parse_annotations(rest, %{acc | defaults: defaults})
defp parse_annotations([["#group" | _ = groups] | rest], acc),
do: parse_annotations(rest, %{acc | groups: groups})
defp parse_annotations(rest, acc), do: %{acc | table: rest}
defp parse_datatypes({{field, "boolean"}, "false"}), do: {field, false}
defp parse_datatypes({{field, "boolean"}, "true"}), do: {field, true}
defp parse_datatypes({{field, "double"}, value}), do: {field, String.to_float(value)}
defp parse_datatypes({{field, "long"}, value}), do: {field, String.to_integer(value)}
defp parse_datatypes({{field, "dateTime:RFC3339"}, value}),
do: {field, RFC3339.to_nanosecond(value)}
defp parse_datatypes({{field, _}, value}), do: {field, value}
defp parse_rows(%{
datatypes: [_ | _] = datatypes,
defaults: defaults,
table: [["" | _ = headers] | [_ | _] = rows]
}) do
Enum.map(rows, fn ["" | row] ->
headers
|> Enum.zip(datatypes)
|> Enum.zip(apply_defaults(row, defaults, []))
|> Enum.map(&parse_datatypes/1)
|> Map.new()
end)
end
defp parse_rows(%{
datatypes: [_ | _] = datatypes,
defaults: defaults,
table: [[_ | _] = headers | [_ | _] = rows]
}) do
Enum.map(rows, fn row ->
headers
|> Enum.zip(datatypes)
|> Enum.zip(apply_defaults(row, defaults, []))
|> Enum.map(&parse_datatypes/1)
|> Map.new()
end)
end
defp parse_rows(%{defaults: defaults, table: [["" | _ = headers] | [_ | _] = rows]}) do
Enum.map(rows, fn ["" | row] ->
headers
|> Enum.zip(apply_defaults(row, defaults, []))
|> Map.new()
end)
end
defp parse_rows(%{defaults: defaults, table: [[_ | _] = headers | [_ | _] = rows]}) do
Enum.map(rows, fn row ->
headers
|> Enum.zip(apply_defaults(row, defaults, []))
|> Map.new()
end)
end
defp parse_table(table) do
table
|> __MODULE__.Parser.parse_string(skip_headers: false)
|> parse_annotations(%{datatypes: [], defaults: [], groups: [], table: []})
|> parse_rows()
end
end
|
lib/instream/decoder/csv.ex
| 0.720762 | 0.521715 |
csv.ex
|
starcoder
|
defmodule AWS.CloudWatchEvents do
@moduledoc """
Amazon EventBridge helps you to respond to state changes in your AWS
resources. When your resources change state, they automatically send events
into an event stream. You can create rules that match selected events in
the stream and route them to targets to take action. You can also use rules
to take action on a predetermined schedule. For example, you can configure
rules to:
<ul> <li> Automatically invoke an AWS Lambda function to update DNS entries
when an event notifies you that Amazon EC2 instance enters the running
state.
</li> <li> Direct specific API records from AWS CloudTrail to an Amazon
Kinesis data stream for detailed analysis of potential security or
availability risks.
</li> <li> Periodically invoke a built-in target to create a snapshot of an
Amazon EBS volume.
</li> </ul> For more information about the features of Amazon EventBridge,
see the [Amazon EventBridge User
Guide](https://docs.aws.amazon.com/eventbridge/latest/userguide).
"""
@doc """
Activates a partner event source that has been deactivated. Once activated,
your matching event bus will start receiving events from the event source.
"""
def activate_event_source(client, input, options \\ []) do
request(client, "ActivateEventSource", input, options)
end
@doc """
Creates a new event bus within your account. This can be a custom event bus
which you can use to receive events from your custom applications and
services, or it can be a partner event bus which can be matched to a
partner event source.
"""
def create_event_bus(client, input, options \\ []) do
request(client, "CreateEventBus", input, options)
end
@doc """
Called by an SaaS partner to create a partner event source. This operation
is not used by AWS customers.
Each partner event source can be used by one AWS account to create a
matching partner event bus in that AWS account. A SaaS partner must create
one partner event source for each AWS account that wants to receive those
event types.
A partner event source creates events based on resources within the SaaS
partner's service or application.
An AWS account that creates a partner event bus that matches the partner
event source can use that event bus to receive events from the partner, and
then process them using AWS Events rules and targets.
Partner event source names follow this format:
` *partner_name*/*event_namespace*/*event_name* `
*partner_name* is determined during partner registration and identifies the
partner to AWS customers. *event_namespace* is determined by the partner
and is a way for the partner to categorize their events. *event_name* is
determined by the partner, and should uniquely identify an event-generating
resource within the partner system. The combination of *event_namespace*
and *event_name* should help AWS customers decide whether to create an
event bus to receive these events.
"""
def create_partner_event_source(client, input, options \\ []) do
request(client, "CreatePartnerEventSource", input, options)
end
@doc """
You can use this operation to temporarily stop receiving events from the
specified partner event source. The matching event bus is not deleted.
When you deactivate a partner event source, the source goes into PENDING
state. If it remains in PENDING state for more than two weeks, it is
deleted.
To activate a deactivated partner event source, use `ActivateEventSource`.
"""
def deactivate_event_source(client, input, options \\ []) do
request(client, "DeactivateEventSource", input, options)
end
@doc """
Deletes the specified custom event bus or partner event bus. All rules
associated with this event bus need to be deleted. You can't delete your
account's default event bus.
"""
def delete_event_bus(client, input, options \\ []) do
request(client, "DeleteEventBus", input, options)
end
@doc """
This operation is used by SaaS partners to delete a partner event source.
This operation is not used by AWS customers.
When you delete an event source, the status of the corresponding partner
event bus in the AWS customer account becomes DELETED.
<p/>
"""
def delete_partner_event_source(client, input, options \\ []) do
request(client, "DeletePartnerEventSource", input, options)
end
@doc """
Deletes the specified rule.
Before you can delete the rule, you must remove all targets, using
`RemoveTargets`.
When you delete a rule, incoming events might continue to match to the
deleted rule. Allow a short period of time for changes to take effect.
Managed rules are rules created and managed by another AWS service on your
behalf. These rules are created by those other AWS services to support
functionality in those services. You can delete these rules using the
`Force` option, but you should do so only if you are sure the other service
is not still using that rule.
"""
def delete_rule(client, input, options \\ []) do
request(client, "DeleteRule", input, options)
end
@doc """
Displays details about an event bus in your account. This can include the
external AWS accounts that are permitted to write events to your default
event bus, and the associated policy. For custom event buses and partner
event buses, it displays the name, ARN, policy, state, and creation time.
To enable your account to receive events from other accounts on its default
event bus, use `PutPermission`.
For more information about partner event buses, see `CreateEventBus`.
"""
def describe_event_bus(client, input, options \\ []) do
request(client, "DescribeEventBus", input, options)
end
@doc """
This operation lists details about a partner event source that is shared
with your account.
"""
def describe_event_source(client, input, options \\ []) do
request(client, "DescribeEventSource", input, options)
end
@doc """
An SaaS partner can use this operation to list details about a partner
event source that they have created. AWS customers do not use this
operation. Instead, AWS customers can use `DescribeEventSource` to see
details about a partner event source that is shared with them.
"""
def describe_partner_event_source(client, input, options \\ []) do
request(client, "DescribePartnerEventSource", input, options)
end
@doc """
Describes the specified rule.
DescribeRule does not list the targets of a rule. To see the targets
associated with a rule, use `ListTargetsByRule`.
"""
def describe_rule(client, input, options \\ []) do
request(client, "DescribeRule", input, options)
end
@doc """
Disables the specified rule. A disabled rule won't match any events, and
won't self-trigger if it has a schedule expression.
When you disable a rule, incoming events might continue to match to the
disabled rule. Allow a short period of time for changes to take effect.
"""
def disable_rule(client, input, options \\ []) do
request(client, "DisableRule", input, options)
end
@doc """
Enables the specified rule. If the rule does not exist, the operation
fails.
When you enable a rule, incoming events might not immediately start
matching to a newly enabled rule. Allow a short period of time for changes
to take effect.
"""
def enable_rule(client, input, options \\ []) do
request(client, "EnableRule", input, options)
end
@doc """
Lists all the event buses in your account, including the default event bus,
custom event buses, and partner event buses.
"""
def list_event_buses(client, input, options \\ []) do
request(client, "ListEventBuses", input, options)
end
@doc """
You can use this to see all the partner event sources that have been shared
with your AWS account. For more information about partner event sources,
see `CreateEventBus`.
"""
def list_event_sources(client, input, options \\ []) do
request(client, "ListEventSources", input, options)
end
@doc """
An SaaS partner can use this operation to display the AWS account ID that a
particular partner event source name is associated with. This operation is
not used by AWS customers.
"""
def list_partner_event_source_accounts(client, input, options \\ []) do
request(client, "ListPartnerEventSourceAccounts", input, options)
end
@doc """
An SaaS partner can use this operation to list all the partner event source
names that they have created. This operation is not used by AWS customers.
"""
def list_partner_event_sources(client, input, options \\ []) do
request(client, "ListPartnerEventSources", input, options)
end
@doc """
Lists the rules for the specified target. You can see which of the rules in
Amazon EventBridge can invoke a specific target in your account.
"""
def list_rule_names_by_target(client, input, options \\ []) do
request(client, "ListRuleNamesByTarget", input, options)
end
@doc """
Lists your Amazon EventBridge rules. You can either list all the rules or
you can provide a prefix to match to the rule names.
ListRules does not list the targets of a rule. To see the targets
associated with a rule, use `ListTargetsByRule`.
"""
def list_rules(client, input, options \\ []) do
request(client, "ListRules", input, options)
end
@doc """
Displays the tags associated with an EventBridge resource. In EventBridge,
rules and event buses can be tagged.
"""
def list_tags_for_resource(client, input, options \\ []) do
request(client, "ListTagsForResource", input, options)
end
@doc """
Lists the targets assigned to the specified rule.
"""
def list_targets_by_rule(client, input, options \\ []) do
request(client, "ListTargetsByRule", input, options)
end
@doc """
Sends custom events to Amazon EventBridge so that they can be matched to
rules.
"""
def put_events(client, input, options \\ []) do
request(client, "PutEvents", input, options)
end
@doc """
This is used by SaaS partners to write events to a customer's partner event
bus. AWS customers do not use this operation.
"""
def put_partner_events(client, input, options \\ []) do
request(client, "PutPartnerEvents", input, options)
end
@doc """
Running `PutPermission` permits the specified AWS account or AWS
organization to put events to the specified *event bus*. Amazon EventBridge
(CloudWatch Events) rules in your account are triggered by these events
arriving to an event bus in your account.
For another account to send events to your account, that external account
must have an EventBridge rule with your account's event bus as a target.
To enable multiple AWS accounts to put events to your event bus, run
`PutPermission` once for each of these accounts. Or, if all the accounts
are members of the same AWS organization, you can run `PutPermission` once
specifying `Principal` as "*" and specifying the AWS organization ID in
`Condition`, to grant permissions to all accounts in that organization.
If you grant permissions using an organization, then accounts in that
organization must specify a `RoleArn` with proper permissions when they use
`PutTarget` to add your account's event bus as a target. For more
information, see [Sending and Receiving Events Between AWS
Accounts](https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-cross-account-event-delivery.html)
in the *Amazon EventBridge User Guide*.
The permission policy on the default event bus cannot exceed 10 KB in size.
"""
def put_permission(client, input, options \\ []) do
request(client, "PutPermission", input, options)
end
@doc """
Creates or updates the specified rule. Rules are enabled by default, or
based on value of the state. You can disable a rule using `DisableRule`.
A single rule watches for events from a single event bus. Events generated
by AWS services go to your account's default event bus. Events generated by
SaaS partner services or applications go to the matching partner event bus.
If you have custom applications or services, you can specify whether their
events go to your default event bus or a custom event bus that you have
created. For more information, see `CreateEventBus`.
If you are updating an existing rule, the rule is replaced with what you
specify in this `PutRule` command. If you omit arguments in `PutRule`, the
old values for those arguments are not kept. Instead, they are replaced
with null values.
When you create or update a rule, incoming events might not immediately
start matching to new or updated rules. Allow a short period of time for
changes to take effect.
A rule must contain at least an EventPattern or ScheduleExpression. Rules
with EventPatterns are triggered when a matching event is observed. Rules
with ScheduleExpressions self-trigger based on the given schedule. A rule
can have both an EventPattern and a ScheduleExpression, in which case the
rule triggers on matching events as well as on a schedule.
When you initially create a rule, you can optionally assign one or more
tags to the rule. Tags can help you organize and categorize your resources.
You can also use them to scope user permissions, by granting a user
permission to access or change only rules with certain tag values. To use
the `PutRule` operation and assign tags, you must have both the
`events:PutRule` and `events:TagResource` permissions.
If you are updating an existing rule, any tags you specify in the `PutRule`
operation are ignored. To update the tags of an existing rule, use
`TagResource` and `UntagResource`.
Most services in AWS treat : or / as the same character in Amazon Resource
Names (ARNs). However, EventBridge uses an exact match in event patterns
and rules. Be sure to use the correct ARN characters when creating event
patterns so that they match the ARN syntax in the event you want to match.
In EventBridge, it is possible to create rules that lead to infinite loops,
where a rule is fired repeatedly. For example, a rule might detect that
ACLs have changed on an S3 bucket, and trigger software to change them to
the desired state. If the rule is not written carefully, the subsequent
change to the ACLs fires the rule again, creating an infinite loop.
To prevent this, write the rules so that the triggered actions do not
re-fire the same rule. For example, your rule could fire only if ACLs are
found to be in a bad state, instead of after any change.
An infinite loop can quickly cause higher than expected charges. We
recommend that you use budgeting, which alerts you when charges exceed your
specified limit. For more information, see [Managing Your Costs with
Budgets](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/budgets-managing-costs.html).
"""
def put_rule(client, input, options \\ []) do
request(client, "PutRule", input, options)
end
@doc """
Adds the specified targets to the specified rule, or updates the targets if
they are already associated with the rule.
Targets are the resources that are invoked when a rule is triggered.
You can configure the following as targets for Events:
<ul> <li> EC2 instances
</li> <li> SSM Run Command
</li> <li> SSM Automation
</li> <li> AWS Lambda functions
</li> <li> Data streams in Amazon Kinesis Data Streams
</li> <li> Data delivery streams in Amazon Kinesis Data Firehose
</li> <li> Amazon ECS tasks
</li> <li> AWS Step Functions state machines
</li> <li> AWS Batch jobs
</li> <li> AWS CodeBuild projects
</li> <li> Pipelines in AWS CodePipeline
</li> <li> Amazon Inspector assessment templates
</li> <li> Amazon SNS topics
</li> <li> Amazon SQS queues, including FIFO queues
</li> <li> The default event bus of another AWS account
</li> <li> Amazon API Gateway REST APIs
</li> <li> Redshift Clusters to invoke Data API ExecuteStatement on
</li> </ul> Creating rules with built-in targets is supported only in the
AWS Management Console. The built-in targets are `EC2 CreateSnapshot API
call`, `EC2 RebootInstances API call`, `EC2 StopInstances API call`, and
`EC2 TerminateInstances API call`.
For some target types, `PutTargets` provides target-specific parameters. If
the target is a Kinesis data stream, you can optionally specify which shard
the event goes to by using the `KinesisParameters` argument. To invoke a
command on multiple EC2 instances with one rule, you can use the
`RunCommandParameters` field.
To be able to make API calls against the resources that you own, Amazon
EventBridge (CloudWatch Events) needs the appropriate permissions. For AWS
Lambda and Amazon SNS resources, EventBridge relies on resource-based
policies. For EC2 instances, Kinesis data streams, AWS Step Functions state
machines and API Gateway REST APIs, EventBridge relies on IAM roles that
you specify in the `RoleARN` argument in `PutTargets`. For more
information, see [Authentication and Access
Control](https://docs.aws.amazon.com/eventbridge/latest/userguide/auth-and-access-control-eventbridge.html)
in the *Amazon EventBridge User Guide*.
If another AWS account is in the same region and has granted you permission
(using `PutPermission`), you can send events to that account. Set that
account's event bus as a target of the rules in your account. To send the
matched events to the other account, specify that account's event bus as
the `Arn` value when you run `PutTargets`. If your account sends events to
another account, your account is charged for each sent event. Each event
sent to another account is charged as a custom event. The account receiving
the event is not charged. For more information, see [Amazon EventBridge
(CloudWatch Events) Pricing](https://aws.amazon.com/eventbridge/pricing/).
<note> `Input`, `InputPath`, and `InputTransformer` are not available with
`PutTarget` if the target is an event bus of a different AWS account.
</note> If you are setting the event bus of another account as the target,
and that account granted permission to your account through an organization
instead of directly by the account ID, then you must specify a `RoleArn`
with proper permissions in the `Target` structure. For more information,
see [Sending and Receiving Events Between AWS
Accounts](https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-cross-account-event-delivery.html)
in the *Amazon EventBridge User Guide*.
For more information about enabling cross-account events, see
`PutPermission`.
**Input**, **InputPath**, and **InputTransformer** are mutually exclusive
and optional parameters of a target. When a rule is triggered due to a
matched event:
<ul> <li> If none of the following arguments are specified for a target,
then the entire event is passed to the target in JSON format (unless the
target is Amazon EC2 Run Command or Amazon ECS task, in which case nothing
from the event is passed to the target).
</li> <li> If **Input** is specified in the form of valid JSON, then the
matched event is overridden with this constant.
</li> <li> If **InputPath** is specified in the form of JSONPath (for
example, `$.detail`), then only the part of the event specified in the path
is passed to the target (for example, only the detail part of the event is
passed).
</li> <li> If **InputTransformer** is specified, then one or more specified
JSONPaths are extracted from the event and used as values in a template
that you specify as the input to the target.
</li> </ul> When you specify `InputPath` or `InputTransformer`, you must
use JSON dot notation, not bracket notation.
When you add targets to a rule and the associated rule triggers soon after,
new or updated targets might not be immediately invoked. Allow a short
period of time for changes to take effect.
This action can partially fail if too many requests are made at the same
time. If that happens, `FailedEntryCount` is non-zero in the response and
each entry in `FailedEntries` provides the ID of the failed target and the
error code.
"""
def put_targets(client, input, options \\ []) do
request(client, "PutTargets", input, options)
end
@doc """
Revokes the permission of another AWS account to be able to put events to
the specified event bus. Specify the account to revoke by the `StatementId`
value that you associated with the account when you granted it permission
with `PutPermission`. You can find the `StatementId` by using
`DescribeEventBus`.
"""
def remove_permission(client, input, options \\ []) do
request(client, "RemovePermission", input, options)
end
@doc """
Removes the specified targets from the specified rule. When the rule is
triggered, those targets are no longer be invoked.
When you remove a target, when the associated rule triggers, removed
targets might continue to be invoked. Allow a short period of time for
changes to take effect.
This action can partially fail if too many requests are made at the same
time. If that happens, `FailedEntryCount` is non-zero in the response and
each entry in `FailedEntries` provides the ID of the failed target and the
error code.
"""
def remove_targets(client, input, options \\ []) do
request(client, "RemoveTargets", input, options)
end
@doc """
Assigns one or more tags (key-value pairs) to the specified EventBridge
resource. Tags can help you organize and categorize your resources. You can
also use them to scope user permissions by granting a user permission to
access or change only resources with certain tag values. In EventBridge,
rules and event buses can be tagged.
Tags don't have any semantic meaning to AWS and are interpreted strictly as
strings of characters.
You can use the `TagResource` action with a resource that already has tags.
If you specify a new tag key, this tag is appended to the list of tags
associated with the resource. If you specify a tag key that is already
associated with the resource, the new tag value that you specify replaces
the previous value for that tag.
You can associate as many as 50 tags with a resource.
"""
def tag_resource(client, input, options \\ []) do
request(client, "TagResource", input, options)
end
@doc """
Tests whether the specified event pattern matches the provided event.
Most services in AWS treat : or / as the same character in Amazon Resource
Names (ARNs). However, EventBridge uses an exact match in event patterns
and rules. Be sure to use the correct ARN characters when creating event
patterns so that they match the ARN syntax in the event you want to match.
"""
def test_event_pattern(client, input, options \\ []) do
request(client, "TestEventPattern", input, options)
end
@doc """
Removes one or more tags from the specified EventBridge resource. In Amazon
EventBridge (CloudWatch Events, rules and event buses can be tagged.
"""
def untag_resource(client, input, options \\ []) do
request(client, "UntagResource", 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: "events"}
host = build_host("events", client)
url = build_url(host, client)
headers = [
{"Host", host},
{"Content-Type", "application/x-amz-json-1.1"},
{"X-Amz-Target", "AWSEvents.#{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/cloud_watch_events.ex
| 0.872184 | 0.498962 |
cloud_watch_events.ex
|
starcoder
|
defmodule Mudkip.Rules.Default do
@moduledoc """
Default rendering rules set. The other rendering rules may be written using this one as
an example.
Every rules set should has method `render/1` accepting the list of binary strings as
the only parameter. Then this list should be compiled to HTML in any way you prefer.
TODO: `___bold italic___`, HTML escaping
"""
alias Mudkip.Helpers, as: MH
@doc """
API method for rules set. Run compilation line-by-line.
"""
def render(data) do
MH.join(lc line inlist data do
try_render_line(line)
end)
end
@doc """
Line renderer.
Every `apply_*` method just tries to find and process Markdown elements.
"""
defp try_render_line(line) do
preline = apply_pre(line)
if line == preline do
line |> apply_header
|> apply_rulers
|> apply_images
|> apply_links
|> apply_lists
|> apply_bold
|> apply_italic
|> apply_monospace
|> apply_blockquotes
|> apply_linebreaks_fix
|> apply_paragraphs
else
preline
end
end
@doc """
Preformatted text (indented using at least 4 spaces or 1 tab from the lines start).
"""
defp apply_pre(line) do
case Regex.run(%r/^(?:\s{4}|\t)(.*)$/s, line) do
nil ->
line
[_, found] ->
MH.format(:pre, Regex.replace(%r/(?:\n\s{4}|\t)(.*)/, found, "\\1"))
end
end
@doc """
Headers (lines stared from one or more `#` character or "underlined" with `-` or `=` character).
"""
defp apply_header(line) do
case Regex.run(%r/^(#+)\s(.+)/, line) do
[_line, hsize, value] ->
MH.format("h" <> %s(#{byte_size(hsize)}), Regex.replace(%r/(.*)\s#+$/, value, "\\1"))
nil ->
line2 = Regex.replace(%r/(.+)\n===+/, line, MH.format(:h1, "\\1"))
Regex.replace(%r/(.+)\n\-\-\-+/, line2, MH.format(:h2, "\\1"))
end
end
@doc """
Rulers (a line of `.`, `-` or `*` characters, may be separated with spaces).
"""
defp apply_rulers(line) do
Regex.replace(%r/^([\.\-\*]\s*){3,100}$/, line, "<hr />")
end
@doc """
Lists (lines started from `*`, `+` or `-` character or from a number).
TODO: embedded lists
"""
defp apply_lists(line) do
uls = case Regex.run(%r/^\s?[\*\+\-]\s(.*)$/s, line) do
nil ->
line
[_, found] ->
MH.format(:ul, MH.join(lc item inlist String.split(found, %r/\n\s?[\*\+\-]\s/) do
MH.format(:li, item)
end))
end
case Regex.run(%r/^\s?[0-9]\.\s(.*)$/s, uls) do
nil ->
uls
[_, found] ->
MH.format(:ol, MH.join(lc item inlist String.split(found, %r/\n\s?[0-9]\.\s/) do
MH.format(:li, item)
end))
end
end
@doc """
Images (just a links with `!` characters beforehand).
"""
defp apply_images(line) do
line2 = Regex.replace(%r/\!\[([^\]]+)\]\(([^\)\s]+)\)/, line,
MH.format_img("src=\"\\2\" alt=\"\\1\""))
Regex.replace(%r/\!\[([^\]]+)\]\(([^\)\s]+)\s([^\)]+)\)/, line2,
MH.format_img("title=\\3 src=\"\\2\" alt=\"\\1\""))
end
@doc """
Links (`<link>`, `[text](link)` or `[text](link "alternate title")`).
TODO: reference links, shortcut references
"""
defp apply_links(line) do
line2 = Regex.replace(%r/<((?!img\s).+(\:\/\/|@).+)>/, line,
MH.format_link("href=\"\\1\"", "\\1"))
line3 = Regex.replace(%r/\[([^\]]+)\]\(([^\)\s]+)\)/, line2,
MH.format_link("href=\"\\2\"", "\\1"))
Regex.replace(%r/\[([^\]]+)\]\(([^\)\s]+)\s([^\)]+)\)/, line3,
MH.format_link("title=\\3 href=\"\\2\"", "\\1"))
end
@doc """
Bold text (`__text__` or `**text**`).
"""
defp apply_bold(line) do
line2 = Regex.replace(%r/(\*\*)([^\*]+)(\*\*)/, line, MH.format(:strong, "\\2"))
Regex.replace(%r/(__)([^_]+)(__)/, line2, MH.format(:strong, "\\2"))
end
@doc """
Italic text (`_text_` or `*text*`).
"""
defp apply_italic(line) do
line2 = Regex.replace(%r/(\*)(.+)(\*)/, line, MH.format(:em, "\\2"))
Regex.replace(%r/(_)(.+)(_)/, line2, MH.format(:em, "\\2"))
end
@doc """
Monospace text (text in ``` characters).
"""
defp apply_monospace(line) do
Regex.replace(%r/`([^`]+)`/, line, MH.format(:pre, "\\1"))
end
@doc """
Blockquotes (lines started from `>` character).
"""
defp apply_blockquotes(line) do
case Regex.run(%r/^>\s?(.*)/, line) do
nil ->
line
[_, line2] ->
Mudkip.Helpers.format(:blockquote, line2)
end
end
@doc """
Remove unnecessary `\n`.
"""
defp apply_linebreaks_fix(line) do
Regex.replace(%r/\n([^>\s].*)/, line, " \\1")
end
@doc """
If the formatted line isn't header, blockquote, list or preformatted block, mark it as
a paragraph.
"""
defp apply_paragraphs(line) do
Regex.replace(%r/^((?!(<h|<blo|<ul|<ol|<pre)).*)$/s, line, MH.format(:p, "\\1"))
end
end
|
lib/rules/default.ex
| 0.530966 | 0.456046 |
default.ex
|
starcoder
|
defmodule OpcUA.BaseNodeAttrs do
@moduledoc """
Base Node Attributes
Nodes contain attributes according to their node type. The base node
attributes are common to all node types. In the OPC UA `services`,
attributes are referred to via the `nodeid` of the containing node and
an integer `attribute-id`.
In opex62541 we set `node_id` during the node definition.
TODO: add node_id, node_class, references_size, :reference backend
"""
@doc false
def basic_nodes_attrs(), do: [:browse_name, :display_name, :description, :write_mask, :args]
end
defmodule OpcUA.VariableNode do
use IsEnumerable
use IsAccessible
import OpcUA.BaseNodeAttrs
@moduledoc """
VariableNode
Variables store values in a `value` together with metadata for introspection.
Most notably, the attributes data type, `value_rank` and array dimensions constrain the possible values the variable can take
on.
Variables come in two flavours: properties and datavariables. Properties are
related to a parent with a ``hasProperty`` reference and may not have child
nodes themselves. Datavariables may contain properties (``hasProperty``) and
also datavariables (``hasComponents``).
All variables are instances of some `variabletypenode` in return
constraining the possible data type, value rank and array dimensions
attributes.
Data Type
The (scalar) data type of the variable is constrained to be of a specific
type or one of its children in the type hierarchy. The data type is given as
a NodeId pointing to a `DataTypeNode` in the type hierarchy. See the
Section `DataTypeNode` for more details.
If the data type attribute points to ``UInt32``, then the value attribute
must be of that exact type since ``UInt32`` does not have children in the
type hierarchy. If the data type attribute points ``Number``, then the type
of the value attribute may still be ``UInt32``, but also ``Float`` or
``Byte``.
Consistency between the data type attribute in the variable and its
`VariableTypeNode` is ensured.
Value Rank
This attribute indicates whether the value attribute of the variable is an
array and how many dimensions the array has. It may have the following
values:
- ``n >= 1``: the value is an array with the specified number of dimensions
- ``n = 0``: the value is an array with one or more dimensions
- ``n = -1``: the value is a scalar
- ``n = -2``: the value can be a scalar or an array with any number of dimensions
- ``n = -3``: the value can be a scalar or a one dimensional array
Consistency between the value rank attribute in the variable and its
`variabletypenode` is ensured.
TODO:
Array Dimensions
If the value rank permits the value to be a (multi-dimensional) array, the
exact length in each dimensions can be further constrained with this
attribute.
- For positive lengths, the variable value is guaranteed to be of the same
length in this dimension.
- The dimension length zero is a wildcard and the actual value may have any
length in this dimension.
Consistency between the array dimensions attribute in the variable and its
`variabletypenode` is ensured.
Indicates whether a variable contains data inline or whether it points to an
external data source.
"""
@enforce_keys [:args]
defstruct basic_nodes_attrs() ++ [:data_type, :value_rank, :array_dimensions, :array, :value, :access_level, :minimum_sampling_interval, :historizing]
@doc """
"""
@spec new(term(), list()) :: %__MODULE__{}
def new(args, attrs \\ []) when is_list(args) do
Keyword.fetch!(args, :requested_new_node_id)
Keyword.fetch!(args, :parent_node_id)
Keyword.fetch!(args, :reference_type_node_id)
Keyword.fetch!(args, :browse_name)
Keyword.fetch!(args, :type_definition)
struct(%__MODULE__{args: args}, attrs)
end
end
defmodule OpcUA.VariableTypeNode do
use IsEnumerable
use IsAccessible
import OpcUA.BaseNodeAttrs
@moduledoc """
VariableTypeNode
VariableTypes are used to provide type definitions for variables.
VariableTypes constrain the data type, value rank and array dimensions
attributes of variable instances. Furthermore, instantiating from a specific
variable type may provide semantic information. For example, an instance from
`MotorTemperatureVariableType` is more meaningful than a float variable
instantiated from `BaseDataVariable`.
"""
@enforce_keys [:args]
defstruct basic_nodes_attrs() ++ [:data_type, :value_rank, :value, :access_level, :minimum_sampling_interval, :historizing]
@doc """
"""
@spec new(term(), list()) :: %__MODULE__{}
def new(args, attrs \\ []) when is_list(args) do
Keyword.fetch!(args, :requested_new_node_id)
Keyword.fetch!(args, :parent_node_id)
Keyword.fetch!(args, :reference_type_node_id)
Keyword.fetch!(args, :browse_name)
Keyword.fetch!(args, :type_definition)
struct(%__MODULE__{args: args}, attrs)
end
end
#TODO: add Method Node backend.
defmodule OpcUA.MethodNode do
use IsEnumerable
use IsAccessible
import OpcUA.BaseNodeAttrs
@moduledoc """
MethodNode
Methods define callable functions and are invoked using the :ref:`Call
<method-services>` service. MethodNodes may have special properties (variable
childen with a ``hasProperty`` reference) with the :ref:`qualifiedname` ``(0,
"InputArguments")`` and ``(0, "OutputArguments")``. The input and output
arguments are both described via an array of ``UA_Argument``. While the Call
service uses a generic array of :ref:`variant` for input and output, the
actual argument values are checked to match the signature of the MethodNode.
Note that the same MethodNode may be referenced from several objects (and
object types). For this, the NodeId of the method *and of the object
providing context* is part of a Call request message.
"""
@enforce_keys [:args]
defstruct basic_nodes_attrs() ++ [:executable]
@doc """
"""
@spec new(term(), list()) :: %__MODULE__{}
def new(args, attrs \\ []) when is_list(args) do
Keyword.fetch!(args, :requested_new_node_id)
Keyword.fetch!(args, :parent_node_id)
Keyword.fetch!(args, :reference_type_node_id)
Keyword.fetch!(args, :browse_name)
Keyword.fetch!(args, :type_definition)
struct(%__MODULE__{args: args}, attrs)
end
end
#TODO: eventNotifier backend
defmodule OpcUA.ObjectNode do
use IsEnumerable
use IsAccessible
import OpcUA.BaseNodeAttrs
@moduledoc """
ObjectNode
Objects are used to represent systems, system components, real-world objects
and software objects. Objects are instances of an `object
type<objecttypenode>` and may contain variables, methods and further
objects.
"""
@enforce_keys [:args]
defstruct basic_nodes_attrs() ++ [:event_notifier]
@doc """
"""
@spec new(term(), list()) :: %__MODULE__{}
def new(args, attrs \\ []) when is_list(args) do
Keyword.fetch!(args, :requested_new_node_id)
Keyword.fetch!(args, :parent_node_id)
Keyword.fetch!(args, :reference_type_node_id)
Keyword.fetch!(args, :browse_name)
Keyword.fetch!(args, :type_definition)
struct(%__MODULE__{args: args}, attrs)
end
end
defmodule OpcUA.ObjectTypeNode do
use IsEnumerable
use IsAccessible
import OpcUA.BaseNodeAttrs
@moduledoc """
ObjectTypeNode
ObjectTypes provide definitions for Objects. Abstract objects cannot be
instantiated.
"""
@enforce_keys [:args]
defstruct basic_nodes_attrs() ++ [:is_abstract]
@doc """
"""
@spec new(term(), list()) :: %__MODULE__{}
def new(args, attrs \\ []) when is_list(args) do
Keyword.fetch!(args, :requested_new_node_id)
Keyword.fetch!(args, :parent_node_id)
Keyword.fetch!(args, :reference_type_node_id)
Keyword.fetch!(args, :browse_name)
struct(%__MODULE__{args: args}, attrs)
end
end
#TODO: symmetric backend
defmodule OpcUA.ReferenceTypeNode do
use IsEnumerable
use IsAccessible
import OpcUA.BaseNodeAttrs
@moduledoc """
ReferenceTypeNode
Each reference between two nodes is typed with a ReferenceType that gives
meaning to the relation. The OPC UA standard defines a set of ReferenceTypes
as a mandatory part of OPC UA information models.
- Abstract ReferenceTypes cannot be used in actual references and are only
used to structure the ReferenceTypes hierarchy
- Symmetric references have the same meaning from the perspective of the
source and target node
"""
@enforce_keys [:args]
defstruct basic_nodes_attrs() ++ [:is_abstract, :symmetric, :inverse_name]
@doc """
"""
@spec new(term(), list()) :: %__MODULE__{}
def new(args, attrs \\ []) when is_list(args) do
Keyword.fetch!(args, :requested_new_node_id)
Keyword.fetch!(args, :parent_node_id)
Keyword.fetch!(args, :reference_type_node_id)
Keyword.fetch!(args, :browse_name)
struct(%__MODULE__{args: args}, attrs)
end
end
defmodule OpcUA.DataTypeNode do
use IsEnumerable
use IsAccessible
import OpcUA.BaseNodeAttrs
@moduledoc """
DataTypeNode
DataTypes represent simple and structured data types. DataTypes may contain
arrays. But they always describe the structure of a single instance. In
open62541, DataTypeNodes in the information model hierarchy are matched to
``UA_DataType`` type descriptions for :ref:`generic-types` via their NodeId.
Abstract DataTypes (e.g. ``Number``) cannot be the type of actual values.
They are used to constrain values to possible child DataTypes (e.g.
``UInt32``).
"""
@enforce_keys [:args]
defstruct basic_nodes_attrs() ++ [:is_abstract]
@doc """
"""
@spec new(term(), list()) :: %__MODULE__{}
def new(args, attrs \\ []) when is_list(args) do
Keyword.fetch!(args, :requested_new_node_id)
Keyword.fetch!(args, :parent_node_id)
Keyword.fetch!(args, :reference_type_node_id)
Keyword.fetch!(args, :browse_name)
struct(%__MODULE__{args: args}, attrs)
end
end
defmodule OpcUA.ViewNode do
use IsEnumerable
use IsAccessible
import OpcUA.BaseNodeAttrs
@moduledoc """
ViewNode
Each View defines a subset of the Nodes in the AddressSpace. Views can be
used when browsing an information model to focus on a subset of nodes and
references only. ViewNodes can be created and be interacted with. But their
use in the :ref:`Browse<view-services>` service is currently unsupported in
open62541.
"""
@enforce_keys [:args]
defstruct basic_nodes_attrs() ++ [:event_notifier]
@doc """
"""
@spec new(term(), list()) :: %__MODULE__{}
def new(args, attrs \\ []) when is_list(args) do
Keyword.fetch!(args, :requested_new_node_id)
Keyword.fetch!(args, :parent_node_id)
Keyword.fetch!(args, :reference_type_node_id)
Keyword.fetch!(args, :browse_name)
struct(%__MODULE__{args: args}, attrs)
end
end
defmodule OpcUA.ReferenceNode do
use IsEnumerable
use IsAccessible
import OpcUA.BaseNodeAttrs
@moduledoc """
"""
@enforce_keys [:args]
defstruct basic_nodes_attrs() ++ [:is_abstract, :symmetric, :inverse_name]
@doc """
"""
@spec new(term(), list()) :: %__MODULE__{}
def new(args, attrs \\ []) when is_list(args) do
Keyword.fetch!(args, :source_id)
Keyword.fetch!(args, :reference_type_id)
Keyword.fetch!(args, :target_id)
Keyword.fetch!(args, :is_forward)
struct(%__MODULE__{args: args}, attrs)
end
end
|
lib/opc_ua/nodestore/node_types.ex
| 0.662469 | 0.798933 |
node_types.ex
|
starcoder
|
defmodule UAInspector.Config do
@remote_release "6.0.0"
@moduledoc """
Module to simplify access to configuration values with default values.
There should be no configuration required to start using `:ua_inspector` if
you rely on the default values:
remote_database = "https://raw.githubusercontent.com/matomo-org/device-detector/#{@remote_release}/regexes"
remote_shortcode = "https://raw.githubusercontent.com/matomo-org/device-detector/#{@remote_release}"
config :ua_inspector,
database_path: Application.app_dir(:ua_inspector, "priv"),
http_opts: [],
remote_path: [
bot: remote_database,
browser_engine: remote_database <> "/client",
client: remote_database <> "/client",
device: remote_database <> "/device",
os: remote_database,
short_code_map: remote_shortcode,
vendor_fragment: remote_database
],
remote_release: "#{@remote_release}",
startup_silent: false,
startup_sync: true,
yaml_file_reader: {:yamerl_constr, :file, [[:str_node_as_binary]]}
The default `:database_path` is evaluated at runtime and not compiled into
a release!
## How to Configure
There are two ways to change the configuration values with the preferred way
depending on your environment and personal taste.
### Static Configuration
If you can ensure the configuration are static and not dependent on i.e. the
server your application is running on, you can use a static approach by
modifying your `config.exs` file:
config :ua_inspector,
database_path: "/path/to/ua_inspector/databases"
### Dynamic Configuration
If a compile time configuration is not possible or does not match the usual
approach taken in your application you can use a runtime approach.
This is done by defining an initializer module that will automatically be
called by `UAInspector.Supervisor` upon startup/restart. The configuration
is expected to consist of a `{mod, fun}` or `{mod, fun, args}` tuple:
# {mod, fun}
config :ua_inspector,
init: {MyInitModule, :my_init_mf}
# {mod, fun, args}
config :ua_inspector,
init: {MyInitModule, :my_init_mfargs, [:foo, :bar]}
defmodule MyInitModule do
@spec my_init_mf() :: :ok
def my_init_mf(), do: my_init_mfargs(:foo, :bar)
@spec my_init_mfargs(atom, atom) :: :ok
def my_init_mfargs(:foo, :bar) do
priv_dir = Application.app_dir(:my_app, "priv")
Application.put_env(:ua_inspector, :database_path, priv_dir)
end
end
The function is required to always return `:ok`.
## Startup Behaviour
By default the database files will be read during application startup.
You can change this behaviour by configuring an immediate asynchronous reload:
config :ua_inspector,
startup_sync: false
This can lead to the first parsing calls to work with an empty database
and therefore not return the results you expect.
### Starting Silently
When starting the application you will receive messages via `Logger.info/1`
if a database file fails to be parsed or has no entries. If you
want to prevent these messages you can configure the startup the be
completely silent:
config :ua_inspector,
startup_silent: true
## Database Configuration
Configuring the database to use can be done using two related values:
- `:database_path`
- `:remote_path`
The `:database_path` is the directory to look for when loading the databases.
It is also the place where `UAInspector.Downloader` stores a downloaded copy.
For the time being the detailed list of database files is not configurable.
This is a major caveat for personal database copies and short code mappings
(they have additional path information appended to the base). This behaviour
is subject to change.
The full configuration for remote paths contains the following values:
config :ua_inspector,
remote_path: [
bot: "http://example.com",
browser_engine: "http://example.com",
client: "http://example.com",
device: "http://example.com",
os: "http://example.com",
short_code_map: "http://example.com",
vendor_fragment: "http://example.com"
]
### Default Database Release Version
If you are using the default configuration the release `"#{@remote_release}"`
will be used. You can specify a different version/tag/release to be used:
config :ua_inspector,
remote_release: "v1.0.0"
Please be aware that using a non-default release can lead to unexpected
results based on the specific changes between the releases.
## Download Configuration
Using the default configuration all download requests for your database files
are done using [`:hackney`](https://hex.pm/packages/hackney). To pass custom
configuration values to hackney you can use the key `:http_opts`:
# increase download timeout to 10 seconds (default: 5 seconds)
config :ua_inspector,
http_opts: [recv_timeout: 10_000]
Please look at `:hackney.request/5` for a complete list of available options.
If you want to change the library used to download the databases you can
configure a module implementing the `UAInspector.Downloader.Adapter`
behaviour:
config :ua_inspector,
downloader_adapter: MyDownloaderAdapter
## YAML File Reader Configuration
By default the library [`:yamerl`](https://hex.pm/packages/yamerl) will
be used to read and decode the YAML database files. You can configure this
reader to be a custom module:
config :ua_inspector,
yaml_file_reader: {module, function}
config :ua_inspector,
yaml_file_reader: {module, function, extra_args}
The configured module will receive the file to read as the first argument with
any optionally configured extra arguments after that.
"""
@remote_base "https://raw.githubusercontent.com/matomo-org/device-detector/"
@remote_paths [
bot: "/regexes",
browser_engine: "/regexes/client",
client: "/regexes/client",
device: "/regexes/device",
os: "/regexes",
short_code_map: "",
vendor_fragment: "/regexes"
]
@default_downloader_adapter UAInspector.Downloader.Adapter.Hackney
@default_yaml_reader {:yamerl_constr, :file, [[:str_node_as_binary]]}
@doc """
Provides access to configuration values with optional environment lookup.
"""
@spec get(atom | [atom, ...], term) :: term
def get(key, default \\ nil)
def get(key, default) when is_atom(key) do
Application.get_env(:ua_inspector, key, default)
end
def get(keys, default) when is_list(keys) do
:ua_inspector
|> Application.get_all_env()
|> Kernel.get_in(keys)
|> maybe_use_default(default)
end
@doc """
Returns the configured database path.
If the path is not defined the `priv` dir of `:ua_inspector`
as returned by `Application.app_dir(:ua_inspector, "priv")` will be used.
"""
@spec database_path() :: String.t()
def database_path do
case get(:database_path) do
nil -> Application.app_dir(:ua_inspector, "priv")
path -> path
end
end
@doc """
Returns the remote url of a database file.
"""
@spec database_url(atom, String.t()) :: String.t()
def database_url(type, file) do
file = String.replace_leading(file, "/", "")
default = default_database_url(type)
remote =
[:remote_path, type]
|> get(default)
|> String.replace_trailing("/", "")
remote <> "/" <> file
end
@doc """
Returns whether the remote database (at least one type) matches the default.
"""
@spec default_remote_database?() :: boolean
def default_remote_database? do
Enum.any?(Keyword.keys(@remote_paths), fn type ->
default = default_database_url(type)
get([:remote_path, type], default) == default
end)
end
@doc """
Returns the configured downloader adapter module.
The modules is expected to adhere to the behaviour defined in
`UAInspector.Downloader.Adapter`.
"""
@spec downloader_adapter() :: module
def downloader_adapter, do: get(:downloader_adapter, @default_downloader_adapter)
@doc """
Calls the optionally configured init method.
"""
@spec init_env() :: :ok
def init_env do
case get(:init) do
nil -> :ok
{mod, fun} -> apply(mod, fun, [])
{mod, fun, args} -> apply(mod, fun, args)
end
end
@doc """
Returns the currently configured remote release version.
"""
@spec remote_release() :: binary
def remote_release, do: get(:remote_release, @remote_release)
@doc """
Returns the `{mod, fun, extra_args}` to be used when reading a YAML file.
"""
@spec yaml_file_reader :: {module, atom, [term]}
def yaml_file_reader do
case get(:yaml_file_reader) do
{_, _, _} = mfargs -> mfargs
{mod, fun} -> {mod, fun, []}
_ -> @default_yaml_reader
end
end
defp default_database_url(type) do
if Keyword.has_key?(@remote_paths, type) do
@remote_base <> get(:remote_release, @remote_release) <> @remote_paths[type]
else
""
end
end
defp maybe_use_default(nil, default), do: default
defp maybe_use_default(config, _), do: config
end
|
lib/ua_inspector/config.ex
| 0.868813 | 0.476701 |
config.ex
|
starcoder
|
defmodule Ewebmachine.Plug.Debug do
@moduledoc ~S"""
A ewebmachine debug UI at `/wm_debug`
Add it before `Ewebmachine.Plug.Run` in your plug pipeline when you
want debugging facilities.
```
if Mix.env == :dev, do: plug Ewebmachine.Plug.Debug
```
Then go to `http://youhost:yourport/wm_debug`, you will see the
request list since the launch of your server. Click on any to get
the ewebmachine debugging UI. The list will be automatically
updated on new query.
The ewebmachine debugging UI
- shows you the HTTP decision path taken by the request to the response. Every
- the red decisions are the one where decisions differs from the
default one because of a handler implementation :
- click on them, then select any handler available in the right
tab to see the `conn`, `state` inputs of the handler and the
response.
- The response and request right tab shows you the request and
result at the end of the ewebmachine run.
- click on "auto redirect on new query" and at every request, your
browser will navigate to the debugging UI of the new request (you
can still use back/next to navigate through requests)

"""
use Plug.Router
alias Plug.Conn
alias Ewebmachine.Log
plug Plug.Static, at: "/wm_debug/static", from: :ewebmachine
plug :match
plug :dispatch
require EEx
EEx.function_from_file :defp, :render_logs, "templates/log_list.html.eex", [:conns]
EEx.function_from_file :defp, :render_log, "templates/log_view.html.eex", [:logconn, :conn]
get "/wm_debug/log/:id" do
if (logconn=Log.get(id)) do
conn |> send_resp(200,render_log(logconn,conn)) |> halt
else
conn |> put_resp_header("location","/wm_debug") |> send_resp(302,"") |> halt
end
end
get "/wm_debug" do
html = render_logs(Log.list)
conn |> send_resp(200,html) |> halt
end
get "/wm_debug/events" do
Ewebmachine.Events.stream_chunks(conn)
end
match _ do
put_private(conn, :machine_debug, true)
end
@doc false
def to_draw(conn), do: %{
request: """
#{conn.method} #{conn.request_path} HTTP/1.1
#{html_escape format_headers(conn.req_headers)}
#{html_escape body_of(conn)}
""",
response: %{
http: """
HTTP/1.1 #{conn.status} #{Ewebmachine.Core.Utils.http_label(conn.status)}
#{html_escape format_headers(conn.resp_headers)}
#{html_escape (conn.resp_body || "some chunked body")}
""",
code: conn.status
},
trace: Enum.map(Enum.reverse(conn.private.machine_decisions), fn {decision,calls}->
%{
d: decision,
calls: Enum.map(calls,fn {module,function,[in_conn,in_state],{resp,out_conn,out_state}}->
%{
module: inspect(module),
function: "#{function}",
input: """
state = #{html_escape inspect(in_state, pretty: true)}
conn = #{html_escape inspect(in_conn, pretty: true)}
""",
output: """
response = #{html_escape inspect(resp, pretty: true)}
state = #{html_escape inspect(out_state, pretty: true)}
conn = #{html_escape inspect(out_conn, pretty: true)}
"""
}
end)
}
end)
}
defp body_of(conn) do
case Conn.read_body(conn) do
{:ok,body,_}->body
_ -> ""
end
end
defp format_headers(headers) do
headers |> Enum.map(fn {k,v}->"#{k}: #{v}\n" end) |> Enum.join
end
defp html_escape(data), do:
to_string(for(<<char::utf8<-IO.iodata_to_binary(data)>>, do: escape_char(char)))
defp escape_char(?<), do: "<"
defp escape_char(?>), do: ">"
defp escape_char(?&), do: "&"
defp escape_char(?"), do: """
defp escape_char(?'), do: "'"
defp escape_char(c), do: c
end
|
lib/ewebmachine/plug.debug.ex
| 0.665411 | 0.574932 |
plug.debug.ex
|
starcoder
|
defmodule ExRabbitMQ.Connection do
@moduledoc """
A `GenServer` implementing a long running connection to a RabbitMQ server.
Consumers and producers share connections and when a connection reaches the default limit of **65535** channels
or the maximum channels per connection that has been set in the configuration, a new connection is established.
**Warning:** To correctly monitor the open channels, users must not open channels manually (e.g., in the provided hooks).
Internally, a connection `GenServer` uses [`:pg2`](http://erlang.org/doc/man/pg2.html) and
[`:ets`](http://erlang.org/doc/man/ets.html) to handle local subscriptions of consumers and producers.
Check `ExRabbitMQ.Connection.Group` and `ExRabbitMQ.Connection.PubSub` for more information.
"""
use GenServer, restart: :transient
alias ExRabbitMQ.Config.Connection, as: ConnectionConfig
alias ExRabbitMQ.Connection.Pool.Registry, as: RegistryPool
alias ExRabbitMQ.Connection.Pool.Supervisor, as: PoolSupervisor
alias ExRabbitMQ.Connection.PubSub
require Logger
defstruct [
:connection,
:connection_pid,
:ets_consumers,
config: %ConnectionConfig{},
stale?: false
]
@doc """
Starts a new `ExRabbitMQ.Connection` process and links it with the calling one.
"""
@spec start_link(ConnectionConfig.t()) :: GenServer.on_start()
def start_link(%ConnectionConfig{} = connection_config) do
GenServer.start_link(__MODULE__, connection_config)
end
@doc """
Checks whether this process holds a usable connection to RabbitMQ.
The `connection_pid` is the `GenServer` pid implementing the called `ExRabbitMQ.Connection`.
"""
@spec get(pid) :: {:ok, AMQP.Connection.t() | nil} | {:error, term}
def get(nil) do
{:error, :nil_connection_pid}
end
def get(connection_pid) do
GenServer.call(connection_pid, :get)
catch
:exit, reason -> {:error, reason}
end
@doc """
Finds a `ExRabbitMQ.Connection` process in the `ExRabbitMQ.Connection.Group` that has the exact same `connection_config`
configuration.
If found, it subscribes the calling process via `self/0` to its `ExRabbitMQ.Connection.PubSub` for events regarding
the connection status and then returns its process ID.
If the `ExRabbitMQ.Connection.PubSub` of the connection process already contains the maximum subscribed processes,
then the subscription is not allowed so that a new connection process can be created.
In this case, a new`ExRabbitMQ.Connection` will be started and returned.
If not found then a new `ExRabbitMQ.Connection` will be started and returned.
The `connection_config` is the `ExRabbitMQ.Config.Connection` that the `ExRabbitMQ.Connection` has to be using in order to allow
the subscription.
"""
@spec get_subscribe(ConnectionConfig.t()) :: {:ok, pid} | {:error, atom}
def get_subscribe(connection_config) do
case PoolSupervisor.start_child(connection_config) do
{:error, {:already_started, pool_pid}} -> subscribe(pool_pid, connection_config)
{:ok, pool_pid} -> subscribe(pool_pid, connection_config)
end
end
@doc """
Gracefully closes the RabbitMQ connection and terminates its GenServer handler identified by `connection_pid`.
"""
@spec close(pid) :: :ok
def close(connection_pid) do
GenServer.cast(connection_pid, :close)
end
@doc false
@spec get_weight(pid) :: non_neg_integer | :full
def get_weight(connection_pid) do
timeout = ConnectionConfig.get_weight_timeout()
GenServer.call(connection_pid, :get_weight, timeout)
end
@impl true
def init(%{cleanup_after: cleanup_after} = config) do
Process.flag(:trap_exit, true)
ets_consumers = PubSub.new()
Process.send(self(), :connect, [])
schedule_cleanup(cleanup_after)
{:ok, %__MODULE__{config: config, ets_consumers: ets_consumers}}
end
@impl true
def handle_call(:get, _from, state) do
%{connection: connection} = state
reply = if connection === nil, do: {:error, :nil_connection_pid}, else: {:ok, connection}
{:reply, reply, state}
end
@impl true
def handle_call({:subscribe, consumer_pid, connection_config}, _from, state) do
%{ets_consumers: ets_consumers} = state
PubSub.subscribe(ets_consumers, connection_config, consumer_pid)
Process.monitor(consumer_pid)
{:reply, true, %{state | stale?: false}}
end
@impl true
def handle_call(:get_weight, _from, state) do
%{ets_consumers: ets_consumers, config: %{max_channels: max_channels}} = state
reply =
case PubSub.size(ets_consumers) do
connection_channels when connection_channels < max_channels -> connection_channels
_ -> :full
end
{:reply, reply, state}
end
@impl true
def handle_cast(:close, state) do
%{ets_consumers: ets_consumers, connection: connection, connection_pid: connection_pid} =
state
if connection === nil do
{:stop, :normal, state}
else
cleanup_connection(connection_pid, connection)
PubSub.publish(ets_consumers, {:xrmq_connection, {:closed, nil}})
new_state = %{state | connection: nil, connection_pid: nil}
{:stop, :normal, new_state}
end
end
@impl true
def handle_info(:connect, state) do
Logger.debug("Connecting to RabbitMQ")
%{config: config, ets_consumers: ets_consumers} = state
opts = [
username: config.username,
password: <PASSWORD>,
host: config.host,
port: config.port,
virtual_host: config.vhost,
heartbeat: config.heartbeat
]
case AMQP.Connection.open(opts) do
{:ok, %AMQP.Connection{pid: connection_pid} = connection} ->
Logger.debug("Connected to RabbitMQ")
Process.link(connection_pid)
PubSub.publish(ets_consumers, {:xrmq_connection, {:open, connection}})
new_state = %{state | connection: connection, connection_pid: connection_pid}
{:noreply, new_state}
{:error, reason} ->
Logger.error("Failed to connect to RabbitMQ: #{inspect(reason)}")
Process.send_after(self(), :connect, config.reconnect_after)
new_state = %{state | connection: nil, connection_pid: nil}
{:noreply, new_state}
end
end
@impl true
def handle_info({:EXIT, pid, _reason}, %{connection_pid: connection_pid} = state)
when pid === connection_pid do
Logger.error("Disconnected from RabbitMQ")
%{config: config, ets_consumers: ets_consumers} = state
PubSub.publish(ets_consumers, {:xrmq_connection, {:closed, nil}})
Process.send_after(self(), :connect, config.reconnect_after)
new_state = %{state | connection: nil, connection_pid: nil}
{:noreply, new_state}
end
def handle_info({:DOWN, _ref, :process, consumer_pid, _reason}, state) do
%{ets_consumers: ets_consumers} = state
PubSub.unsubscribe(ets_consumers, consumer_pid)
{:noreply, state}
end
@impl true
def handle_info(:cleanup, config: state) do
%{cleanup_after: cleanup_after} = state
%{
ets_consumers: ets_consumers,
connection: connection,
connection_pid: connection_pid,
stale?: stale?
} = state
if stale? do
cleanup_connection(connection_pid, connection)
{:stop, :normal, state}
else
new_state =
case PubSub.size(ets_consumers) do
0 -> %{state | stale?: true}
_ -> state
end
schedule_cleanup(cleanup_after)
{:noreply, new_state}
end
end
@impl true
def handle_info(_, state) do
{:noreply, state}
end
defp subscribe(pool_pid, connection_config) do
case :poolboy.checkout(pool_pid) do
status when status in [:full, :overweighted] ->
{:error, :no_available_connection}
connection_pid ->
GenServer.call(connection_pid, {:subscribe, self(), connection_config})
:poolboy.checkin(pool_pid, connection_pid)
{:ok, connection_pid}
end
end
defp schedule_cleanup(cleanup_after) do
Process.send_after(self(), :cleanup, cleanup_after)
end
defp cleanup_connection(connection_pid, connection) do
RegistryPool.unregister(connection_pid)
Process.unlink(connection_pid)
AMQP.Connection.close(connection)
end
end
|
lib/ex_rabbit_m_q/connection.ex
| 0.878555 | 0.445952 |
connection.ex
|
starcoder
|
if Code.ensure_loaded?(:telemetry) do
defmodule Tesla.Middleware.Telemetry do
@moduledoc """
Emits events using the `:telemetry` library to expose instrumentation.
## Examples
```
defmodule MyClient do
use Tesla
plug Tesla.Middleware.Telemetry
end
:telemetry.attach(
"my-tesla-telemetry",
[:tesla, :request, :stop],
fn event, measurements, meta, config ->
# Do something with the event
end,
nil
)
```
## Options
- `:metadata` - additional metadata passed to telemetry events
## Telemetry Events
* `[:tesla, :request, :start]` - emitted at the beginning of the request.
* Measurement: `%{system_time: System.system_time()}`
* Metadata: `%{env: Tesla.Env.t()}`
* `[:tesla, :request, :stop]` - emitted at the end of the request.
* Measurement: `%{duration: native_time}`
* Metadata: `%{env: Tesla.Env.t()} | %{env: Tesla.Env.t(), error: term()}`
* `[:tesla, :request, :exception]` - emitted when an exception has been raised.
* Measurement: `%{duration: native_time}`
* Metadata: `%{env: Tesla.Env.t(), kind: Exception.kind(), reason: term(), stacktrace: Exception.stacktrace()}`
## Legacy Telemetry Events
* `[:tesla, :request]` - This event is emitted for backwards compatibility only and should be considered deprecated.
This event can be disabled by setting `config :tesla, Tesla.Middleware.Telemetry, disable_legacy_event: true` in your config.
Be sure to run `mix deps.compile --force tesla` after changing this setting to ensure the change is picked up.
Please check the [telemetry](https://hexdocs.pm/telemetry/) for the further usage.
## URL event scoping with `Tesla.Middleware.PathParams` and `Tesla.Middleware.KeepRequest`
Sometimes, it is useful to have access to a template url (i.e. `"/users/:user_id"`) for grouping
Telemetry events. For such cases, a combination of the `Tesla.Middleware.PathParams`,
`Tesla.Middleware.Telemetry` and `Tesla.Middleware.KeepRequest` may be used.
```
defmodule MyClient do
use Tesla
# The KeepRequest middleware sets the template url as a Tesla.Env.opts entry
# Said entry must be used because on happy-path scenarios,
# the Telemetry middleware will receive the Tesla.Env.url resolved by PathParams.
plug Tesla.Middleware.KeepRequest
plug Tesla.Middleware.Telemetry
plug Tesla.Middleware.PathParams
end
:telemetry.attach(
"my-tesla-telemetry",
[:tesla, :request, :stop],
fn event, measurements, meta, config ->
path_params_template_url = meta.env.opts[:req_url]
# The meta.env.url key will only present the resolved URL on happy-path scenarios.
# Error cases will still return the original template url.
path_params_resolved_url = meta.env.url
end,
nil
)
```
"""
@disable_legacy_event Application.get_env(:tesla, Tesla.Middleware.Telemetry,
disable_legacy_event: false
)[:disable_legacy_event]
@behaviour Tesla.Middleware
@impl Tesla.Middleware
def call(env, next, opts) do
metadata = opts[:metadata] || %{}
start_time = System.monotonic_time()
emit_start(Map.merge(metadata, %{env: env}))
try do
Tesla.run(env, next)
catch
kind, reason ->
stacktrace = __STACKTRACE__
duration = System.monotonic_time() - start_time
emit_exception(
duration,
Map.merge(metadata, %{env: env, kind: kind, reason: reason, stacktrace: stacktrace})
)
:erlang.raise(kind, reason, stacktrace)
else
{:ok, env} = result ->
duration = System.monotonic_time() - start_time
emit_stop(duration, Map.merge(metadata, %{env: env}))
emit_legacy_event(duration, result)
result
{:error, reason} = result ->
duration = System.monotonic_time() - start_time
emit_stop(duration, Map.merge(metadata, %{env: env, error: reason}))
emit_legacy_event(duration, result)
result
end
end
defp emit_start(metadata) do
:telemetry.execute(
[:tesla, :request, :start],
%{system_time: System.system_time()},
metadata
)
end
defp emit_stop(duration, metadata) do
:telemetry.execute(
[:tesla, :request, :stop],
%{duration: duration},
metadata
)
end
if @disable_legacy_event do
defp emit_legacy_event(duration, result) do
:ok
end
else
defp emit_legacy_event(duration, result) do
duration = System.convert_time_unit(duration, :native, :microsecond)
:telemetry.execute(
[:tesla, :request],
%{request_time: duration},
%{result: result}
)
end
end
defp emit_exception(duration, metadata) do
:telemetry.execute(
[:tesla, :request, :exception],
%{duration: duration},
metadata
)
end
end
end
|
lib/tesla/middleware/telemetry.ex
| 0.866683 | 0.81648 |
telemetry.ex
|
starcoder
|
defmodule Nabo.Post do
@moduledoc """
A struct that represents a post.
This struct represents a post with its metadata, excerpt and post body, returned by
`Nabo.Repo`.
## Format
Post should be in this format:
metadata (JSON, mandatory)
---
post excerpt (Markdown, optional)
---
post body (Markdown, mandatory)
For example:
{
"title": "<NAME>",
"slug": "hello-world",
"datetime": "2017-01-01T00:00:00Z"
}
---
Welcome to my blog!
---
### Hello there!
This is the first post in my blog.
Post excerpt is optional, so if you prefer not to have any excerpt, leave it blank or
exclude it from your post.
{
"title": "<NAME>",
"slug": "hello-world",
"datetime": "2017-01-01T00:00:00Z"
}
---
### Hello there!
This is the first post in my blog.
"""
alias Nabo.FrontMatter
defstruct [:title, :slug, :datetime, :draft?, :excerpt, :excerpt_html, :body, :body_html, :metadata, :reading_time]
@type t :: %__MODULE__{
body: String.t,
body_html: String.t,
datetime: DateTime.t,
draft?: boolean,
reading_time: Float.t,
excerpt: String.t,
excerpt_html: String.t,
metadata: Map.t,
slug: String.t,
title: String.t,
}
@doc """
Builds struct from markdown content.
## Example
string = ~s(
{
"title": "<NAME>",
"slug": "hello-world",
"datetime": "2017-01-01T00:00:00Z"
}
---
Welcome to my blog!
---
### Hello there!
This is the first post in my blog.
)
{:ok, post} = Nabo.Post.from(string)
"""
@spec from_string(string :: String.t) :: {:ok, Nabo.Post.t} | {:error, any}
def from_string(string) do
case FrontMatter.from_string(string) do
{:ok, {meta, excerpt, body}} ->
reading_time = compute_reading_time(body)
{
:ok,
%__MODULE__{
title: meta.title,
slug: meta.slug,
datetime: meta.datetime,
draft?: meta.draft?,
reading_time: reading_time,
excerpt: excerpt,
body: body,
metadata: meta.extras,
},
}
{:error, reason} -> {:error, reason}
end
end
@doc """
Puts parsed excerpt content into struct.
"""
@spec put_excerpt_html(post :: __MODULE__.t, excerpt_html :: String.t) :: Nabo.Post.t
def put_excerpt_html(%__MODULE__{} = post, excerpt_html) do
%__MODULE__{post | excerpt_html: excerpt_html}
end
@doc """
Puts parsed body content into struct.
"""
@spec put_body_html(post :: __MODULE__.t, body_html :: String.t) :: Nabo.Post.t
def put_body_html(%__MODULE__{} = post, body_html) do
%__MODULE__{post | body_html: body_html}
end
@doc """
Computes reading time of the given post body string
"""
@spec compute_reading_time(body :: String.t) :: Float.t
def compute_reading_time(body) when is_binary(body) do
body
|> String.split(" ")
|> Enum.count
|> Kernel./(275)
|> Float.round(2)
end
end
|
lib/nabo/post.ex
| 0.908661 | 0.404302 |
post.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 [https://aws.amazon.com/sns](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/).
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/).
"""
@doc """
Adds a statement to a topic's access control policy, granting access for
the specified AWS accounts to the specified actions.
"""
def add_permission(client, input, options \\ []) do
request(client, "AddPermission", input, options)
end
@doc """
Accepts a phone number and indicates whether the phone holder has opted out
of receiving SMS messages from your 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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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.
<ul> <li> For `ADM`, `PlatformPrincipal` is `client id` and
`PlatformCredential` is `client secret`.
</li> <li> For `Baidu`, `PlatformPrincipal` is `API key` and
`PlatformCredential` is `secret key`.
</li> <li> For `APNS` and `APNS_SANDBOX`, `PlatformPrincipal` is `SSL
certificate` and `PlatformCredential` is `private key`.
</li> <li> For `GCM` (Firebase Cloud Messaging), there is no
`PlatformPrincipal` and the `PlatformCredential` is `API key`.
</li> <li> For `MPNS`, `PlatformPrincipal` is `TLS certificate` and
`PlatformCredential` is `private key`.
</li> <li> For `WNS`, `PlatformPrincipal` is `Package Security Identifier`
and `PlatformCredential` is `secret key`.
</li> </ul> You can use the returned `PlatformApplicationArn` as an
attribute for the `CreatePlatformEndpoint` action.
"""
def create_platform_application(client, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "CreatePlatformEndpoint", 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 [https://aws.amazon.com/sns](http://aws.amazon.com/sns/).
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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "DeletePlatformApplication", 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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "GetPlatformApplicationAttributes", input, options)
end
@doc """
Returns the settings for sending SMS messages from your account.
These settings are set with the `SetSMSAttributes` action.
"""
def get_s_m_s_attributes(client, input, options \\ []) do
request(client, "GetSMSAttributes", input, options)
end
@doc """
Returns all of the properties of a subscription.
"""
def get_subscription_attributes(client, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "ListEndpointsByPlatformApplication", 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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "ListPlatformApplications", 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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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 has been saved and Amazon SNS
will attempt to deliver it shortly.
To use the `Publish` action for sending 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).
<important> You can publish messages only to topics and endpoints in the
same AWS Region.
</important>
"""
def publish(client, input, options \\ []) do
request(client, "Publish", input, options)
end
@doc """
Removes a statement from a topic's access control policy.
"""
def remove_permission(client, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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 [Sending an SMS
Message](https://docs.aws.amazon.com/sns/latest/dg/sms_publish-to-phone.html)
in the *Amazon SNS Developer Guide*.
"""
def set_s_m_s_attributes(client, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "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 AWS
account, the endpoint owner must 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, input, options \\ []) do
request(client, "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:
<ul> <li> Adding more than 50 tags to a topic isn't recommended.
</li> <li> Tags don't have any semantic meaning. Amazon SNS interprets tags
as character strings.
</li> <li> Tags are case-sensitive.
</li> <li> A new tag with a key identical to that of an existing tag
overwrites the existing tag.
</li> <li> Tagging actions are limited to 10 TPS per AWS account, per AWS
region. If your application requires a higher throughput, file a [technical
support
request](https://console.aws.amazon.com/support/home#/case/create?issueType=technical).
</li> </ul>
"""
def tag_resource(client, input, options \\ []) do
request(client, "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 AWS 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, input, options \\ []) do
request(client, "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, input, options \\ []) do
request(client, "UntagResource", 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: "sns"}
host = build_host("sns", client)
url = build_url(host, client)
headers = [
{"Host", host},
{"Content-Type", "application/x-www-form-urlencoded"}
]
input = Map.merge(input, %{"Action" => action, "Version" => "2010-03-31"})
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, :query)
end
defp decode!(client, payload) do
AWS.Client.decode!(client, payload, :xml)
end
end
|
lib/aws/generated/sns.ex
| 0.840717 | 0.629746 |
sns.ex
|
starcoder
|
defmodule Neoscan.Vm.Disassembler do
@moduledoc ""
# credo:disable-for-lines:118
@opcodes_list %{
# An empty array of bytes is pushed onto the stack.
"00" => "PUSH0",
"PUSH0" => "PUSHF",
# 0x01-0x4B The next opcode bytes is data to be pushed onto the stack
"01" => "PUSHBYTES1",
"4b" => "PUSHBYTES75",
# The next byte contains the number of bytes to be pushed onto the stack.
"4c" => "PUSHDATA1",
# The next two bytes contain the number of bytes to be pushed onto the stack.
"4d" => "PUSHDATA2",
# The next four bytes contain the number of bytes to be pushed onto the stack.
"4e" => "PUSHDATA4",
# The number -1 is pushed onto the stack.
"4f" => "PUSHM1",
# The number 1 is pushed onto the stack.
"51" => "PUSH1",
"PUSH1" => "PUSHT",
# The number 2 is pushed onto the stack.
"52" => "PUSH2",
# The number 3 is pushed onto the stack.
"53" => "PUSH3",
# The number 4 is pushed onto the stack.
"54" => "PUSH4",
# The number 5 is pushed onto the stack.
"55" => "PUSH5",
# The number 6 is pushed onto the stack.
"56" => "PUSH6",
# The number 7 is pushed onto the stack.
"57" => "PUSH7",
# The number 8 is pushed onto the stack.
"58" => "PUSH8",
# The number 9 is pushed onto the stack.
"59" => "PUSH9",
# The number 10 is pushed onto the stack.
"5a" => "PUSH10",
# The number 11 is pushed onto the stack.
"5b" => "PUSH11",
# The number 12 is pushed onto the stack.
"5c" => "PUSH12",
# The number 13 is pushed onto the stack.
"5d" => "PUSH13",
# The number 14 is pushed onto the stack.
"5e" => "PUSH14",
# The number 15 is pushed onto the stack.
"5f" => "PUSH15",
# The number 16 is pushed onto the stack.
"60" => "PUSH16",
# Does nothing.
"61" => "NOP",
"62" => "JMP",
"63" => "JMPIF",
"64" => "JMPIFNOT",
"65" => "CALL",
"66" => "RET",
"67" => "APPCALL",
"68" => "SYSCALL",
"69" => "TAILCALL",
"6a" => "DUPFROMALTSTACK",
# Puts the input onto the top of the alt stack. Removes it from the main stack.
"6b" => "TOALTSTACK",
# Puts the input onto the top of the main stack. Removes it from the alt stack.
"6c" => "FROMALTSTACK",
"6d" => "XDROP",
"72" => "XSWAP",
"73" => "XTUCK",
# Puts the number of stack items onto the stack.
"74" => "DEPTH",
# Removes the top stack item.
"75" => "DROP",
# Duplicates the top stack item.
"76" => "DUP",
# Removes the second-to-top stack item.
"77" => "NIP",
# Copies the second-to-top stack item to the top.
"78" => "OVER",
# The item n back in the stack is copied to the top.
"79" => "PICK",
# The item n back in the stack is moved to the top.
"7a" => "ROLL",
# The top three items on the stack are rotated to the left.
"7b" => "ROT",
# The top two items on the stack are swapped.
"7c" => "SWAP",
# The item at the top of the stack is copied and inserted before the second-to-top item.
"7d" => "TUCK",
# Concatenates two strings.
"7e" => "CAT",
# Returns a section of a string.
"7f" => "SUBSTR",
# Keeps only characters left of the specified point in a string.
"80" => "LEFT",
# Keeps only characters right of the specified point in a string.
"81" => "RIGHT",
# Returns the length of the input string.
"82" => "SIZE",
# Flips all of the bits in the input.
"83" => "INVERT",
# Boolean and between each bit in the inputs.
"84" => "AND",
# Boolean or between each bit in the inputs.
"85" => "OR",
# Boolean exclusive or between each bit in the inputs.
"86" => "XOR",
# Returns 1 if the inputs are exactly equal", 0 otherwise.
"87" => "EQUAL",
# 1 is added to the input.
"8b" => "INC",
# 1 is subtracted from the input.
"8c" => "DEC",
"8d" => "SIGN",
# The sign of the input is flipped.
"8f" => "NEGATE",
# The input is made positive.
"90" => "ABS",
# If the input is 0 or 1", it is flipped. Otherwise the output will be 0.
"91" => "NOT",
# Returns 0 if the input is 0. 1 otherwise.
"92" => "NZ",
# a is added to b.
"93" => "ADD",
# b is subtracted from a.
"94" => "SUB",
# a is multiplied by b.
"95" => "MUL",
# a is divided by b.
"96" => "DIV",
# Returns the remainder after dividing a by b.
"97" => "MOD",
# Shifts a left b bits, preserving sign.
"98" => "SHL",
# Shifts a right b bits, preserving sign.
"99" => "SHR",
# If both a and b are not 0, the output is 1. Otherwise 0.
"9a" => "BOOLAND",
# If a or b is not 0, the output is 1. Otherwise 0.
"9b" => "BOOLOR",
# Returns 1 if the numbers are equal, 0 otherwise.
"9c" => "NUMEQUAL",
# Returns 1 if the numbers are not equal, 0 otherwise.
"9e" => "NUMNOTEQUAL",
# Returns 1 if a is less than b, 0 otherwise.
"9f" => "LT",
# Returns 1 if a is greater than b, 0 otherwise.
"a0" => "GT",
# Returns 1 if a is less than or equal to b, 0 otherwise.
"a1" => "LTE",
# Returns 1 if a is greater than or equal to b, 0 otherwise.
"a2" => "GTE",
# Returns the smaller of a and b.
"a3" => "MIN",
# Returns the larger of a and b.
"a4" => "MAX",
# Returns 1 if x is within the specified range (left-inclusive), 0 otherwise.
"a5" => "WITHIN",
# The input is hashed using SHA-1.
"a7" => "SHA1",
# The input is hashed using SHA-256.
"a8" => "SHA256",
"a9" => "HASH160",
"aa" => "HASH256",
"ac" => "CHECKSIG",
"ae" => "CHECKMULTISIG",
"c0" => "ARRAYSIZE",
"c1" => "PACK",
"c2" => "UNPACK",
"c3" => "PICKITEM",
"c4" => "SETITEM",
# 用作引用類型
"c5" => "NEWARRAY",
# 用作值類型
"c6" => "NEWSTRUCT",
"f0" => "THROW",
"f1" => "THROWIFNOT"
}
@extended_opcodes %{
"62" => 3,
"63" => 3,
"64" => 3,
"65" => 3
}
def parse_script(hex_string) do
hex_string
|> String.codepoints()
|> Stream.chunk(2)
|> Enum.map(&Enum.join/1)
|> make_list()
|> reduce_list_to_string()
|> String.split("\n")
|> parse_syscalls()
end
defp reduce_list_to_string(list) do
Enum.reduce(list, "", fn code, acc ->
work_code_key(code, acc)
end)
end
defp work_code_key(code, acc) do
if Map.has_key?(@opcodes_list, code) and String.length(code) == 2 do
newline = if code == "68", do: "", else: "\n"
acc <> @opcodes_list[code] <> newline
else
opcode_key = String.slice(code, 0..1)
{opcode_keyword, push_bytes} = opcode_tuple(opcode_key)
base_args = String.slice(code, 2..-1)
args =
cond do
Map.has_key?(@extended_opcodes, opcode_key) ->
get_jmp_num(base_args)
push_bytes == "PUSHBYTES" ->
"0x" <> base_args
opcode_keyword == "APPCALL" or opcode_keyword == "TAILCALL" ->
base_args
|> String.codepoints()
|> Stream.chunk(2)
|> Enum.reverse()
|> Enum.join()
true ->
base_args
end
acc <> push_bytes <> opcode_keyword <> ": " <> args <> "\n"
end
end
defp opcode_tuple(opcode_key) do
case Map.fetch(@opcodes_list, opcode_key) do
{:ok, keyword} -> {keyword, ""}
:error -> check_hex_num(opcode_key)
end
end
defp get_jmp_num(args) do
if String.ends_with?(args, "ff") do
switch_args = "ffffff" <> String.slice(args, 0..1)
{x, ""} = Integer.parse(switch_args, 16)
<<signed_jmp_num::integer-signed-32>> = <<
x::integer-unsigned-32
>>
to_string(signed_jmp_num)
else
switch_args = String.slice(args, 2..-1) <> String.slice(args, 0..1)
{jmp_num, ""} = Integer.parse(switch_args, 16)
to_string(jmp_num)
end
end
defp check_hex_num(str) do
case Integer.parse(str, 16) do
{num, _} ->
if num > 1 and num < 75 do
{to_string(num), "PUSHBYTES"}
else
{"parsing error", ""}
end
:error ->
{"parsing error", ""}
end
end
defp make_list(initial_list) do
initial_list
|> Enum.reduce({initial_list, []}, fn current, {remaining, acc} ->
remaining_head =
case length(remaining) do
0 -> nil
_ -> hd(remaining)
end
with true <- remaining_head == current,
{:ok, joins} <- extend_the_opcode(current) do
{opcodes_to_be_joined, new_remaining} =
Enum.split(
remaining,
joins
)
joined_item = Enum.join(opcodes_to_be_joined)
{new_remaining, [joined_item | acc]}
else
:error -> {tl(remaining), [current | acc]}
false -> {remaining, acc}
end
end)
|> elem(1)
|> Enum.reverse()
end
defp extend_the_opcode(current) do
case Map.fetch(@extended_opcodes, current) do
{:ok, extend_amount} -> {:ok, extend_amount}
:error -> handle_opcode_error(current)
end
end
defp handle_opcode_error(current) do
case Integer.parse(current, 16) do
{num, _} ->
cond do
num > 1 and num < 75 ->
{:ok, num + 1}
# 20 bytes
num === 103 or num === 105 ->
{:ok, 20 + 1}
true ->
:error
end
:error ->
:error
end
end
defp parse_syscalls(list) do
final_opcodes =
for line <- list do
case String.contains?(line, "SYSCALL") do
false ->
line
true ->
newline = Regex.replace(~r/PUSHBYTES[0-9]{1,3} 0x/, line, " ")
split_newline = String.split(newline, " ")
syscall_fn =
case Base.decode16(
Enum.at(split_newline, 1),
case: :lower
) do
{:ok, syscall_arg} -> syscall_arg
:error -> "error parsing syscall fn arg"
end
Enum.at(split_newline, 0) <> " " <> syscall_fn
end
end
if Enum.at(final_opcodes, length(final_opcodes) - 1) == "" do
Enum.drop(final_opcodes, -1)
else
final_opcodes
end
end
end
|
apps/neoscan/lib/neoscan/vm/disassembler.ex
| 0.570451 | 0.452415 |
disassembler.ex
|
starcoder
|
defmodule Session.Answer do
@moduledoc false
use Protobuf, syntax: :proto3
@type t :: %__MODULE__{
answer: {atom, any}
}
defstruct [:answer]
oneof(:answer, 0)
field(:answerGroup, 1, type: Session.AnswerGroup, oneof: 0)
field(:conceptMap, 2, type: Session.ConceptMap, oneof: 0)
field(:conceptList, 3, type: Session.ConceptList, oneof: 0)
field(:conceptSet, 4, type: Session.ConceptSet, oneof: 0)
field(:conceptSetMeasure, 5, type: Session.ConceptSetMeasure, oneof: 0)
field(:value, 6, type: Session.Value, oneof: 0)
end
defmodule Session.Explanation do
@moduledoc false
use Protobuf, syntax: :proto3
@type t :: %__MODULE__{
pattern: String.t(),
answers: [Session.ConceptMap.t()]
}
defstruct [:pattern, :answers]
field(:pattern, 1, type: :string)
field(:answers, 2, repeated: true, type: Session.ConceptMap)
end
defmodule Session.AnswerGroup do
@moduledoc false
use Protobuf, syntax: :proto3
@type t :: %__MODULE__{
owner: Session.Concept.t(),
answers: [Session.Answer.t()],
explanation: Session.Explanation.t()
}
defstruct [:owner, :answers, :explanation]
field(:owner, 1, type: Session.Concept)
field(:answers, 2, repeated: true, type: Session.Answer)
field(:explanation, 3, type: Session.Explanation)
end
defmodule Session.ConceptMap do
@moduledoc false
use Protobuf, syntax: :proto3
@type t :: %__MODULE__{
map: %{String.t() => Session.Concept.t()},
explanation: Session.Explanation.t()
}
defstruct [:map, :explanation]
field(:map, 1, repeated: true, type: Session.ConceptMap.MapEntry, map: true)
field(:explanation, 2, type: Session.Explanation)
end
defmodule Session.ConceptMap.MapEntry do
@moduledoc false
use Protobuf, map: true, syntax: :proto3
@type t :: %__MODULE__{
key: String.t(),
value: Session.Concept.t()
}
defstruct [:key, :value]
field(:key, 1, type: :string)
field(:value, 2, type: Session.Concept)
end
defmodule Session.ConceptList do
@moduledoc false
use Protobuf, syntax: :proto3
@type t :: %__MODULE__{
list: Session.ConceptIds.t(),
explanation: Session.Explanation.t()
}
defstruct [:list, :explanation]
field(:list, 1, type: Session.ConceptIds)
field(:explanation, 2, type: Session.Explanation)
end
defmodule Session.ConceptSet do
@moduledoc false
use Protobuf, syntax: :proto3
@type t :: %__MODULE__{
set: Session.ConceptIds.t(),
explanation: Session.Explanation.t()
}
defstruct [:set, :explanation]
field(:set, 1, type: Session.ConceptIds)
field(:explanation, 2, type: Session.Explanation)
end
defmodule Session.ConceptSetMeasure do
@moduledoc false
use Protobuf, syntax: :proto3
@type t :: %__MODULE__{
set: Session.ConceptIds.t(),
measurement: Session.Number.t(),
explanation: Session.Explanation.t()
}
defstruct [:set, :measurement, :explanation]
field(:set, 1, type: Session.ConceptIds)
field(:measurement, 2, type: Session.Number)
field(:explanation, 3, type: Session.Explanation)
end
defmodule Session.Value do
@moduledoc false
use Protobuf, syntax: :proto3
@type t :: %__MODULE__{
number: Session.Number.t(),
explanation: Session.Explanation.t()
}
defstruct [:number, :explanation]
field(:number, 1, type: Session.Number)
field(:explanation, 2, type: Session.Explanation)
end
defmodule Session.ConceptIds do
@moduledoc false
use Protobuf, syntax: :proto3
@type t :: %__MODULE__{
ids: [String.t()]
}
defstruct [:ids]
field(:ids, 1, repeated: true, type: :string)
end
defmodule Session.Number do
@moduledoc false
use Protobuf, syntax: :proto3
@type t :: %__MODULE__{
value: String.t()
}
defstruct [:value]
field(:value, 1, type: :string)
end
|
lib/proto/Answer.pb.ex
| 0.757391 | 0.544075 |
Answer.pb.ex
|
starcoder
|
defmodule TwelveDays do
# define word list using sigil ~w
# zero is only used to make the number equal to the word
@number_in_word ~w(
zero
first
second
third
fourth
fifth
sixth
seventh
eighth
ninth
tenth
eleventh
twelfth
)
# value for index 0 is not used
# zero is only used to make the number equal to the word
@gift [
"not used",
"a Partridge in a Pear Tree",
"two Turtle Doves",
"three French Hens",
"four Calling Birds",
"five Gold Rings",
"six Geese-a-Laying",
"seven Swans-a-Swimming",
"eight Maids-a-Milking",
"nine Ladies Dancing",
"ten Lords-a-Leaping",
"eleven Pipers Piping",
"twelve Drummers Drumming"
]
@doc """
Given a `number`, return the song's verse for that specific day, including
all gifts for previous days in the same line.
"""
@spec verse(number :: integer) :: String.t()
def verse(number) do
"On the " <>
Enum.at(@number_in_word, number) <>
" day of Christmas my true love gave to me: " <>
build_gift_list(number) <>
"."
end
defp build_gift_list(1) do
Enum.at(@gift, 1)
end
defp build_gift_list(2) do
Enum.at(@gift, 2) <> ", and " <> build_gift_list(1)
end
defp build_gift_list(number) do
Enum.at(@gift, number) <> ", " <> build_gift_list(number - 1)
end
@doc """
Given a `starting_verse` and an `ending_verse`, return the verses for each
included day, one per line.
"""
@spec verses(starting_verse :: integer, ending_verse :: integer) :: String.t()
def verses(starting_verse, ending_verse) do
# create range using the provided value
starting_verse..ending_verse
# range can be iterated using enum
|> Enum.map(&verse(&1))
# alternate way to write the function call
# |> Enum.map(&verse/1)
|> Enum.join("\n")
end
@doc """
Sing all 12 verses, in order, one verse per line.
"""
@spec sing() :: String.t()
def sing do
verses(1, 12)
end
end
|
twelve-days/lib/twelve_days.ex
| 0.694095 | 0.556821 |
twelve_days.ex
|
starcoder
|
defmodule Ivy.Core.Datom do
alias Ivy.Core
alias Ivy.Core.{Anomaly, Database, Transaction}
@behaviour Access
@type value :: String.t | atom | boolean | ref | DateTime.t | UUID.t | number
@type ref :: ivy_identifier | Core.temp_id
@type ivy_identifier :: eid | lookup_ref | Core.ident
@type lookup_ref :: {ivy_identifier, value}
@type eid :: Core.id
@type attr_id :: Core.id
@type index :: :eavt | :aevt | :avet | :vaet
@type components :: term
@enforce_keys [:e, :a, :v, :tx, :added?]
defstruct [:e, :a, :v, :tx, added?: true]
@type t :: %__MODULE__{
e: eid,
a: attr_id,
v: value,
tx: Core.tx_id,
added?: boolean
}
@impl Access
def fetch(datom, key) do
Map.fetch(datom, get_key(key))
end
@impl Access
def pop(datom, key) do
Map.pop(datom, get_key(key))
end
@impl Access
def get_and_update(datom, key, fun) do
Map.get_and_update(datom, get_key(key), fun)
end
@mapping %{
0 => :e,
1 => :a,
2 => :v,
3 => :tx,
4 => :added?
}
@compile {:inline, get_key: 1}
@spec get_key(integer | atom) :: atom
defp get_key(key) when key in 0..4, do: Map.get(@mapping, key)
defp get_key(key), do: key
@spec to_list(t) :: [term]
def to_list(datom) do
[datom.e, datom.a, datom.v, datom.tx, datom.added?]
end
@spec match?(t, components, index) :: boolean
def match?(_datom, nil), do: true
def match?(%{e: e}, [e], :eavt), do: true
def match?(%{e: e, a: a}, [e, a], :eavt), do: true
def match?(%{e: e, a: a, v: v}, [e, a, v], :eavt), do: true
def match?(%{e: e, a: a, v: v, tx: t}, [e, a, v, t], :eavt), do: true
def match?(%{a: a}, [a], :aevt), do: true
def match?(%{a: a, e: e}, [a, e], :aevt), do: true
def match?(%{a: a, e: e, v: v}, [a, e, v], :aevt), do: true
def match?(%{a: a, e: e, v: v, tx: t}, [a, e, v, t], :aevt), do: true
def match?(%{a: a}, [a], :aevt), do: true
def match?(%{a: a, v: v}, [a, v], :aevt), do: true
def match?(%{a: a, v: v, e: e}, [a, v, e], :aevt), do: true
def match?(%{a: a, v: v, e: e, tx: t}, [a, v, e, t], :aevt), do: true
def match?(%{v: v}, [v], :vaet), do: true
def match?(%{v: v, a: a}, [v, a], :vaet), do: true
def match?(%{v: v, a: a, e: e}, [v, a, e], :vaet), do: true
def match?(%{v: v, a: a, e: e, tx: t}, [v, a, e, t], :vaet), do: true
def match?(_, _, _), do: false
@spec validate(t, Transaction.t, Database.t) :: {:ok, :add | :retract | :swap | :noop} | {:error, Anomaly.t}
def validate(_datom, _tx, _db) do
# lookup attribute
# redundancy elimination (i.e. existing datom that differs only by tx_id)
# virtual datom handling (e.g. :db/ensure)
{:error, Anomaly.new(:unsupported, "not implemented")}
end
@spec collapse(Enumerable.t) :: {:ok, [t]} | {:error, Anomaly.t}
def collapse(datoms) do
datoms
|> Enum.group_by(&{&1.e, &1.a, &1.v})
|> Enum.map(fn {_, datoms} ->
datoms
|> Enum.reverse()
|> Enum.find(&(&1.added?))
end)
|> Enum.reject(&is_nil/1)
end
defimpl Enumerable do
def count(_datom), do: {:ok, 5}
def member?(_datom, _element), do: {:error, __MODULE__}
def slice(_datom), do: {:error, __MODULE__}
def reduce(d, acc, reducer) do
@protocol.reduce(@for.to_list(d), acc, reducer)
end
end
defimpl Inspect do
import Inspect.Algebra
def inspect(datom, opts) do
container_doc("#datom[", datom, "]", opts, &@protocol.inspect/2, break: :flex, separator: " ")
end
end
end
|
lib/core/datom.ex
| 0.779909 | 0.49048 |
datom.ex
|
starcoder
|
defmodule Graphqexl.Tokens do
@moduledoc """
Mostly a databag module containing keywords, tokens and regex patterns related to the GraphQL
spec. Also contains functions for fetching them by key.
"""
@moduledoc since: "0.1.0"
# TODO: Make the structure here more closely represent the definitions exactly as in the spec:
# In particular, the input type handling. This will probably make the DSL much cleaner.
# See if we can shake out a consistent interface for parsing the components, maybe without the
# need to collapse things into single lines.
# https://spec.graphql.org/June2018/#TypeDefinition
@built_in_types %{
Boolean: :Boolean,
Float: :Float,
Id: :Id,
Integer: :Integer,
List: :List,
Object: :Object,
String: :String,
}
@identifiers %{
enum_value: "[_A-Z0-9]+",
field_name: "[_a-z][_A-Za-z0-9]+",
name: "[_A-Z][_A-Za-z]+",
type_value: "\[?[_A-Z][_A-Za-z]+!?\]?",
}
@keywords %{
enum: "enum",
interface: "interface",
implements: "implements",
mutations: "mutations",
queries: "queries",
schema: "schema",
subscriptions: "subscriptions",
type: "type",
union: "union",
}
@operation_keywords [:enum, :interface, :schema, :type, :union]
@reserved_types [:mutation, :query, :subscription]
@scalar_types @built_in_types
|> Map.split([:Boolean, :Float, :Id, :Integer, :String])
|> elem(0)
@tokens %{
argument: %{
close: ")",
open: "(",
},
argument_delimiter: ":",
argument_placeholder_separator: ";",
assignment: "=",
comment_char: "#",
custom_scalar_placeholder: "^",
fields: %{
close: "}",
open: "{",
},
ignored_delimiter: ",",
ignored_whitespace: "\t",
list: %{
close: "]",
open: "[",
},
newline: "\n",
quote: "\"",
operations: @keywords |> Map.split(@operation_keywords) |> elem(0),
operation_delimiter: "@",
required: "!",
reserved_types: @keywords |> Map.split(@reserved_types) |> elem(0),
types: %{scalar: @scalar_types |> Map.values},
space: "\s",
union_type_delimiter: "|",
variable: "$",
}
defmodule Regex do
@moduledoc"""
Utility module with helper functions for working with `t:Regex.t/0`'s.
"""
@moduledoc since: "0.1.0"
@doc """
Escapes the given character or sequence.
Returns: `t:String.t/0`
"""
@doc since: "0.1.0"
@spec escape(String.t):: String.t
def escape(char), do: "\\#{char}"
end
@doc """
Retrieve a token by key
Returns: `t:String.t/0` | Map.t
"""
@doc since: "0.1.0"
@spec get(atom):: String.t | Map.t
def get(key), do: @tokens |> Map.get(key)
@doc """
Retrieve an identifier token by key
Returns: `t:String.t/0`
"""
@doc since: "0.1.0"
@spec identifiers(atom):: String.t
def identifiers(key), do: @identifiers |> Map.get(key)
@doc """
Retrieve a keyword token by key
Returns: `t:String.t/0`
"""
@doc since: "0.1.0"
@spec keywords(atom):: String.t
def keywords(key), do: @keywords |> Map.get(key)
@argument_pattern """
(#{@identifiers.field_name})#{@tokens.argument_delimiter}\s*?(#{@identifiers.type_value})
"""
@name_pattern "?<name>#{@identifiers.field_name}"
@type_pattern "?<type>(query|mutation|subscription)"
@patterns %{
argument: ~r/#{@argument_pattern}\n/,
comment: ~r/#{@tokens.comment_char}.*/,
custom_scalar: ~r/(#{@keywords.type}.*\s?)#{@tokens.assignment}\s?/,
field_name: ~r/(?<name>#{@identifiers.field_name})/,
implements: ~r/\s#{@keywords.implements}\s(#{@identifiers.type_value})\s/,
operation: ~r/(?<name>.*)\((?<args>.*)?\):(?<return>.*)/,
query_operation: ~r/(#{@type_pattern})?\s?(#{@name_pattern})(?<arguments>\(?\(\$?.*\))?\s\{/,
significant_whitespace: ~r/[#{@tokens.newline}|#{@tokens.space}]+/,
trailing_space: ~r/#{@tokens.space}#{@tokens.newline}/,
union: ~r/(#{@keywords.union}.*\s?)#{@tokens.assignment}\s?/,
union_type_separator: ~r/\s?#{@tokens.union_type_delimiter |> Regex.escape}\s?/,
variable_value: ~r/\"[\w|_]+\"|\d+|true|false|null/
}
@doc """
Retrieve a token pattern by key
Returns: `t:Regex.t/0`
"""
@doc since: "0.1.0"
@spec patterns(atom):: Regex.t
def patterns(key), do: @patterns |> Map.get(key)
end
|
lib/graphqexl/tokens.ex
| 0.561816 | 0.494019 |
tokens.ex
|
starcoder
|
defmodule HTMLAssertion.DSL do
@moduledoc ~S"""
Add additional syntax to passing current context inside block
### Example: pass context
```
assert_select html, ".container" do
assert_select "form", action: "/users" do
refute_select ".flash_message"
assert_select ".control_group" do
assert_select "label", class: "title", text: ~r{<NAME>}
assert_select "input", class: "control", type: "text"
end
assert_select("a", text: "Submit", class: "button")
end
assert_select ".user_list" do
assert_select "li"
end
end
```
## Example 2: print current context for debug
```
assert_select(html, ".selector") do
IO.inspect(assert_select, label: "current context html")
end
```
"""
alias HTMLAssertion, as: HTML
alias HTMLAssertion.Debug
defmacro assert_select(context, selector \\ nil, attributes \\ nil, maybe_do_block \\ nil) do
Debug.log(context: context, selector: selector, attributes: attributes, maybe_do_block: maybe_do_block)
{args, block} = extract_block([context, selector, attributes], maybe_do_block)
call_select_fn(:assert, args, block)
|> Debug.log_dsl()
end
defmacro refute_select(context, selector \\ nil, attributes \\ nil, maybe_do_block \\ nil) do
Debug.log(context: context, selector: selector, attributes: attributes, maybe_do_block: maybe_do_block)
{args, block} = extract_block([context, selector, attributes], maybe_do_block)
call_select_fn(:refute, args, block)
|> Debug.log_dsl()
end
defp call_select_fn(matcher, args, block \\ nil)
defp call_select_fn(:assert, args, nil) do
quote do
HTML.assert_select(unquote_splicing(args))
end
end
defp call_select_fn(:refute, args, nil) do
quote do
HTML.refute_select(unquote_splicing(args))
end
end
defp call_select_fn(matcher, args, block) do
block_arg =
quote do
fn unquote(context_var()) ->
unquote(Macro.prewalk(block, &postwalk/1))
end
end
call_select_fn(matcher, args ++ [block_arg])
end
# found do: block if exists
defp extract_block(args, do: do_block) do
{args, do_block}
end
defp extract_block(args, _maybe_block) do
args
|> Enum.reverse()
|> Enum.reduce({[], nil}, fn
arg, {args, block} when is_list(arg) ->
{maybe_block, updated_arg} = Keyword.pop(arg, :do)
{
(updated_arg == [] && args) || [updated_arg | args],
block || maybe_block
}
nil, {args, block} ->
{args, block}
arg, {args, block} ->
{[arg | args], block}
end)
end
# replace assert_select without arguments to context
defp postwalk({:assert_select, env, nil}) do
context_var(env)
end
defp postwalk({:assert_select, env, arguments}) do
context = context_var(env)
{args, block} = extract_block([context | arguments], nil)
call_select_fn(:assert, args, block)
end
# replace refute_select without arguments to context
defp postwalk({:refute_select, env, nil}) do
context_var(env)
end
defp postwalk({:refute_select, env, arguments}) do
context = context_var(env)
{args, block} = extract_block([context | arguments], nil)
call_select_fn(:refute, args, block)
end
defp postwalk(segment) do
segment
end
defp context_var(env \\ []) do
{:assert_select_context, env, nil}
end
end
|
lib/html_assertion/dsl.ex
| 0.813016 | 0.807005 |
dsl.ex
|
starcoder
|
defmodule HorasTrabalhadasElixir.Business do
@moduledoc """
Módulo com as Regras de Negócio da Aplicação.
"""
alias HorasTrabalhadasElixir.Utils.TimeUtils
@space_delimiters [" ", "\t"]
@doc """
Realiza o processamento do arquivo de entrada `filepath`.
"""
@spec proccess_file(String.t) :: [[String.t]]
def proccess_file(filepath) do
File.stream!(filepath)
|> Enum.map(&proccess_line/1)
# |> Enum.filter(&non_empty_list?/1)
end
@doc """
Realiza o processamento de uma linha/registro do arquivo de entrada.
"""
@spec proccess_line(String.t) :: [String.t]
defp proccess_line(line) do
# Transforma a linha "crua" da entrada vinda do Siscop em
# um vetor de campos.
# OBS.: O primeiro campo corresponde ao dia do registro
[day | fields] = parse_line line
# Remove os campos que não correspondem a horários
fields = clear_fields fields
if fields != [] do
case fields do
[h1, h2, h3, h4] ->
manha = TimeUtils.diferenca_horas(h1, h2)
tarde = TimeUtils.diferenca_horas(h3, h4)
{intervalo_manha, intervalo_tarde} = {
Enum.join([h1, h2], " às "),
Enum.join([h3, h4], " às ")
}
[
day,
intervalo_manha <> ", " <> intervalo_tarde,
TimeUtils.fmt_tempo(manha),
TimeUtils.fmt_tempo(tarde),
TimeUtils.fmt_tempo(manha + tarde)
]
[h1, h2] ->
tempo = TimeUtils.diferenca_horas(h1, h2)
[day, Enum.join(fields, " às "), "...", "...", TimeUtils.fmt_tempo(tempo)]
[h1] ->
[day, h1, "?", "?", "?"]
end
else
[day, "", "", "", ""]
end
end
@spec parse_line(String.t) :: [String.t]
defp parse_line(line) do
line
|> String.split(@space_delimiters) # Realiza um split a partir dos espaços em branco
|> Enum.filter(&non_empty_string?/1) # Filtra os campos que possuem realmente algum valor
|> Enum.map(&String.trim/1)
end
@doc """
Remove os campos que não possuem ':'
"""
@spec clear_fields([String.t]) :: [String.t]
defp clear_fields(fields) do
fields
|> Enum.filter(&contains_colon?/1)
|> Enum.flat_map(&remove_noise/1)
end
@spec non_empty_string?(String.t) :: boolean
defp non_empty_string?(string) do
string != ""
end
defp non_empty_list?(list) do
list != []
end
@spec contains_colon?(String.t) :: boolean
defp contains_colon?(field) do
String.contains? field, ":"
end
defp remove_noise(input) do
indexes = all_indexes(input)
time_from_index(input, indexes)
end
defp all_indexes(input, character \\ ":") do
input
|> String.codepoints
|> Enum.with_index
|> Enum.filter(fn {x, _} -> x == character end)
|> Enum.map(fn {_, i} -> i end)
# |> Enum.filter_map(
# fn {x, _} -> x == character end,
# fn {_, i} -> i end
# )
end
defp time_from_index(input, indexes) do
Enum.map(indexes, fn x ->
String.slice(input, x-2..x) <> String.slice(input, x+1..x+2)
end)
end
end
|
horas_trabalhadas_elixir/lib/horas_trabalhadas_elixir/business.ex
| 0.727589 | 0.436922 |
business.ex
|
starcoder
|
defmodule Similarity do
@moduledoc """
Contains basic functions for similarity calculation.
`Similarity.Cosine` - easy cosine similarity calculation
`Similarity.Simhash` - simhash similarity calculation between two strings
"""
defdelegate simhash(left, right, options \\ []), to: Similarity.Simhash, as: :similarity
@doc """
Calculates Cosine similarity between two vectors.
[https://en.wikipedia.org/wiki/Cosine_similarity#Definition](https://en.wikipedia.org/wiki/Cosine_similarity#Definition)
## Example:
Similarity.cosine([1, 2, 3], [1, 2, 8])
"""
def cosine(list_a, list_b) when length(list_a) == length(list_b) do
dot_product(list_a, list_b) / (magnitude(list_a) * magnitude(list_b))
end
@doc """
Multiplies cosine similarity with the square root of compared vectors length.
srol = square root of length
This gives better comparable numbers in real life where the number of attributes compared might differ.
Use this if the number of shared attributes between real world objects differ.
## Example:
Similarity.cosine_srol([1, 2, 3], [1, 2, 8])
"""
def cosine_srol(list_a, list_b) do
cosine(list_a, list_b) * :math.sqrt(length(list_a))
end
@doc """
Calculates Euclidean dot product of two vectors.
[https://en.wikipedia.org/wiki/Euclidean_vector#Dot_product](https://en.wikipedia.org/wiki/Euclidean_vector#Dot_product)
## Example:
iex> Similarity.dot_product([1, 2], [3, 4])
11
"""
def dot_product(list_a, list_b, acc \\ 0)
def dot_product([], [], acc) do
acc
end
def dot_product([h_a | t_a], [h_b | t_b], acc) do
new_acc = h_a * h_b + acc
dot_product(t_a, t_b, new_acc)
end
@doc """
Calculates Euclidean magnitude of one vector.
[https://en.wikipedia.org/wiki/Magnitude_(mathematics)#Euclidean_vector_space](https://en.wikipedia.org/wiki/Magnitude_(mathematics)#Euclidean_vector_space)
## Example:
iex> Similarity.magnitude([2])
2.0
"""
def magnitude(list, acc \\ 0)
def magnitude([], acc) do
:math.sqrt(acc)
end
def magnitude([h | tl], acc) do
square = :math.pow(h, 2)
new_acc = acc + square
magnitude(tl, new_acc)
end
end
|
lib/similarity.ex
| 0.920834 | 0.83901 |
similarity.ex
|
starcoder
|
defmodule HTTPEventClient do
@moduledoc """
Emits events to an HTTP event server. Events can get sent either async or inline.
Events are sent over the default http method `POST`. This can be configured with
the `default_http_method` config option. Events are sent to the url provided with
the `event_server_url` option. You may also set the `force_ssl` option to force
events to be sent over SSL. Only events with numbers or letters are allowed.
### Simple event
HTTPEventClient.emit("something happend")
### Event with data
HTTPEventClient.emit("something happend", %{username: "john doe"})
### Async event
HTTPEventClient.emit_async("something happend")
# Multiple Clients
To allow for multiple clients, you can instead pass a client object as the first
parameter to the emit methods. The client can be defined using the struct for
this module. It accepts all of the same options as the config does. Here is and example
```
client = %HTTPEventClient{
event_server_url: "https://event.example.com/events",
api_token: "<PASSWORD>"
}
HTTPEventClient.emit(client, "ping")
```
"""
require Logger
defstruct [
event_server_url: Application.get_env(:http_event_client, :event_server_url),
api_token: Application.get_env(:http_event_client, :api_token),
force_ssl: Application.get_env(:http_event_client, :force_ssl),
default_http_method: Application.get_env(:http_event_client, :default_http_method)
]
@doc """
Sends events async.
"""
def emit_async(%__MODULE__{} = client, event), do: emit_async(client, event, nil)
def emit_async(%__MODULE__{} = client, event, data) do
if event_name_valid?(event) do
Process.spawn(__MODULE__, :emit, [client, event, data], [])
:ok
else
{:error, "Event \"#{event}\" is not a valid event name"}
end
end
def emit_async(event), do: emit_async(event, nil)
def emit_async(event, data) do
client = %__MODULE__{}
emit(client, event, data)
end
@doc """
Sends events and awaits a response.
"""
def emit(%__MODULE__{} = client, event), do: emit(client, event, nil)
def emit(%__MODULE__{} = client, event, data) do
if event_name_valid?(event) do
method = http_method(client)
Logger.debug "#{event} >>> #{inspect data}", [event: event, method: method]
case send_event(client, event, event_server_url(client), method, data) do
{:ok, %HTTPoison.Response{body: result, status_code: 200}} ->
Logger.debug "#{event} <<< #{inspect result}", [event: event, method: method]
{:ok, decode_response(result)}
{:ok, %HTTPoison.Response{body: result, status_code: 400}} ->
Logger.debug "#{event} <<< #{inspect result}", [event: event, method: method]
{:error, decode_response(result)}
error -> {:error, error}
end
else
{:error, "Event \"#{event}\" is not a valid event name"}
end
end
def emit(event), do: emit(event, nil)
def emit(event, data) do
client = %__MODULE__{}
emit(client, event, data)
end
defp send_event(client, event, server_url, "POST", data) do
HTTPoison.post "#{Path.join(server_url, event)}", Poison.encode!(data), headers(client)
end
defp send_event(client, event, server_url, "PUT", data) do
HTTPoison.put "#{Path.join(server_url, event)}", Poison.encode!(data), headers(client)
end
defp send_event(client, event, server_url, "PATCH", data) do
HTTPoison.patch "#{Path.join(server_url, event)}", Poison.encode!(data), headers(client)
end
defp send_event(client, event, server_url, "GET", data) do
HTTPoison.get! "#{Path.join(server_url, event)}", Poison.encode!(data), headers(client)
end
defp send_event(client, event, server_url, "DELETE", data) do
HTTPoison.delete "#{Path.join(server_url, event)}", Poison.encode!(data), headers(client)
end
defp event_server_url(%__MODULE__{event_server_url: url} = client) do
resolve_server_url(url, client)
end
defp resolve_server_url(false, _) do
false
end
defp resolve_server_url(url, %__MODULE__{force_ssl: force_ssl}) when is_binary(url) do
if force_ssl do
"https://#{String.replace(url, ~r/(http|https):\/\//, "")}"
else
if String.match?(url, ~r/(http|https):\/\//) do
url
else
"http://#{url}"
end
end
end
defp event_name_valid?(event) do
if String.match?(event, ~r/[^a-zA-Z0-9-_]/) do
false
else
true
end
end
defp http_method(%__MODULE__{default_http_method: default_http_method}) do
method = default_http_method || :post
method = if String.valid?(method) do
method
else
Atom.to_string(method)
end
String.upcase(method)
end
defp headers(%__MODULE__{api_token: api_token}) do
[{"Authorization", "Bearer #{api_token}"}, {"Content-Type", "application/json"}]
end
defp decode_response(result) do
case Poison.decode(result) do
{:ok, data} -> data
_error -> result
end
end
end
|
lib/http_event_client.ex
| 0.837421 | 0.540803 |
http_event_client.ex
|
starcoder
|
defmodule Kaffy.Routes do
@moduledoc """
Kaffy.Routes must be "used" in your phoenix routes:
```elixir
use Kaffy.Routes, scope: "/admin", pipe_through: [:browser, :authenticate]
```
`:scope` defaults to `"/admin"`
`:pipe_through` defaults to kaffy's `[:kaffy_browser]`
"""
# use Phoenix.Router
defmacro __using__(options \\ []) do
scoped = Keyword.get(options, :scope, "/admin")
custom_pipes = Keyword.get(options, :pipe_through, [])
pipes = [:kaffy_browser] ++ custom_pipes
quote do
pipeline :kaffy_browser do
plug(:accepts, ["html", "json"])
plug(:fetch_session)
plug(:fetch_flash)
plug(:protect_from_forgery)
plug(:put_secure_browser_headers)
end
scope unquote(scoped), KaffyWeb do
pipe_through(unquote(pipes))
get("/", HomeController, :index, as: :kaffy_home)
get("/dashboard", HomeController, :dashboard, as: :kaffy_dashboard)
get("/tasks", TaskController, :index, as: :kaffy_task)
get("/p/:slug", PageController, :index, as: :kaffy_page)
get("/:context/:resource", ResourceController, :index, as: :kaffy_resource)
get(
"stock/movments/:context/:resource/:stock_location_id",
ResourceController,
:movement_index,
as: :kaffy_resource
)
post("/:context/:resource", ResourceController, :create, as: :kaffy_resource)
post("/:context/:resource/:id/action/:action_key", ResourceController, :single_action,
as: :kaffy_resource
)
post("/:context/:resource/action/:action_key", ResourceController, :list_action,
as: :kaffy_resource
)
get("/:context/:resource/new", ResourceController, :new, as: :kaffy_resource)
get("/:context/:resource/:id", ResourceController, :show, as: :kaffy_resource)
get("/:context/:product_id/:resource/:id", ResourceController, :show, as: :kaffy_resource)
put("/:context/:resource/:id", ResourceController, :update, as: :kaffy_resource)
delete("/:context/:resource/:id", ResourceController, :delete, as: :kaffy_resource)
get("/kaffy/api/:context/:resource", ResourceController, :api, as: :kaffy_api_resource)
# Product routes
get("/:context/:product_id/:resource/index", ResourceController, :index,
as: :kaffy_resource
)
get("products/:context/:product_id/:resource/index", ProductController, :index,
as: :kaffy_product
)
get("products/:context/:id/:resource/new", ProductController, :new, as: :kaffy_product)
post("products/:context/:id/:resource", ProductController, :create, as: :kaffy_product)
# get("/orders/:context/:resource/new", OrderController, :new, as: :kaffy_order)
put("products/:context/:product_id/:resource/:id", ProductController, :update,
as: :kaffy_product
)
post("/:context/:id/:resource", ResourceController, :create, as: :kaffy_resource)
post("orders/:context/:id/:resource", OrderController, :add_to_cart, as: :kaffy_order)
get("/:context/:id/:resource/new", ResourceController, :new, as: :kaffy_resource)
put("/orders/:context/:id/:resource", OrderController, :clear_cart, as: :kaffy_order)
# get("/orders/customers/:context/:order_id/:resource", OrderController, :customer,
# as: :kaffy_order
# )
get("/orders/customers/:context/:resource/:order_id", OrderController, :order_customer,
as: :kaffy_order
)
get("/orders/adjustments/:context/:resource/:order_id", OrderController, :adjustments,
as: :kaffy_order
)
get("/orders/cart/:context/:resource/:order_id", OrderController, :cart, as: :kaffy_order)
get("/orders/address/:context/:resource/:order_id", OrderController, :new_address,
as: :kaffy_order
)
post("/orders/address/:context/:resource/:order_id", OrderController, :create_address,
as: :kaffy_order
)
put("orders/customers/:context/:resource/:order_id", OrderController, :update_customer,
as: :kaffy_order
)
put("/:context/:resource/:id", ResourceController, :stock_update, as: :kaffy_resource)
# Stock movement index
end
end
end
end
|
lib/kaffy/routes.ex
| 0.708112 | 0.456168 |
routes.ex
|
starcoder
|
defmodule Taco do
@moduledoc """
Composition and error handling of sequential computations, similar to
`Ecto.Multi`
Taco allows to create a chain of actions which might either succeed,
fail, or halt the execution of further actions in the pipeline.
Let's start with an example!
number = 2
Taco.new()
|> Taco.then(:add, fn _ -> {:ok, number + 3} end)
|> Taco.then(:multiply, fn %{add: n} -> {:ok, n * 2} end)
|> Taco.run()
{:ok, :multiply, 10}
We chain two actions - `:add` and `:multiply`. Each action receives the
results of previous actions in a map (first action receives an empty map),
and (in this example) returns an `{:ok, result}` tuple, which means that
computation was successful. Calling `Taco.run/1` on such a pipeline returns
a tagged result of the last action.
Note that no actions are executed until you call `Taco.run/1`. You can pass
the taco around and run it only when the results are needed.
## Actions
Actions are functions which take a map of results of previous actions as an
argument. They are executed in the order `Taco.then/3` is called. There are
three valid return values of an action:
* `{:ok, result}` - the action was successful. `result` will be put in the
map of all the results and passed to to the next action in the pipeline,
or `Taco.run/1` will return `{:ok, tag, result}` if it was the last action
in the pipeline
* `{:halt, result}` - the action was successful, but further actions won't
be executed. `Taco.run/1` will return immediately with the
`{:ok, tag, result}` tuple
* `{:error, error}` - the action failed. `Taco.run/1` will return immediately
with the `{:error, tag, error, results_so_far}` tuple. `results_so_far` is
the map of results of all the actions completed before the failing one
## Examples
Successful pipeline
iex> number = 2
iex> Taco.new()
...> |> Taco.then(:add, fn _ -> {:ok, number + 3} end)
...> |> Taco.then(:multiply, fn %{add: n} -> {:ok, n * 2} end)
...> |> Taco.run()
{:ok, :multiply, 10}
Halting pipeline
iex> number = 2
iex> Taco.new()
...> |> Taco.then(:add, fn _ -> {:halt, number + 3} end)
...> |> Taco.then(:multiply, fn %{add: n} -> {:ok, n * 2} end)
...> |> Taco.run()
{:ok, :add, 5}
Failing pipeline
iex> number = 2
iex> Taco.new()
...> |> Taco.then(:add, fn _ -> {:ok, number + 3} end)
...> |> Taco.then(:multiply, fn _ -> {:error, "boom!"} end)
...> |> Taco.then(:subtract, fn %{multiply: n} -> {:ok, n - 2} end)
...> |> Taco.run()
{:error, :multiply, "boom!", %{add: 5}}
"""
defstruct actions: %{}, order: []
@typep actions :: %{tag => action}
@typep order :: [tag]
@opaque t :: %__MODULE__{actions: actions, order: order}
@type tag :: atom
@type result :: term
@type error :: term
@type results :: %{tag => result}
@type action :: (results_so_far :: results -> action_ret)
@type action_ret :: {:ok, result} | {:halt, result} | {:error, error}
@doc """
Returns a fresh, new taco
"""
@spec new :: t
def new, do: %__MODULE__{}
@doc """
Appends the action to the pipeline of the taco
Raises `ArgumentError` when:
* `tag` is not an atom
* `action` is not a 1-arity function
* action with the given `tag` is already present
See also "Examples" section of documentation for `Taco` module.
"""
@spec then(t, tag, action) :: t
def then(%__MODULE__{actions: actions, order: order} = taco, tag, action)
when is_function(action, 1) and is_atom(tag) do
case Map.has_key?(actions, tag) do
false ->
actions = Map.put(actions, tag, action)
order = [tag | order]
%__MODULE__{taco | actions: actions, order: order}
true ->
raise ArgumentError, "duplicate action tag"
end
end
def then(%__MODULE__{}, tag, _) when not is_atom(tag) do
raise ArgumentError, "action tag must be an atom"
end
def then(%__MODULE__{}, _, _) do
raise ArgumentError, "action must be a 1-arity function"
end
@doc """
Executes the pipeline of actions present in the taco
Raises `ArgumentError` when no actions are present in the taco.
"""
@spec run(t) :: {:ok, tag, result}
| {:error, tag, error, results_so_far :: results}
def run(taco) do
order = Enum.reverse(taco.order)
run_actions(taco.actions, order, %{})
end
@spec run_actions(actions, order, results)
:: {:ok, tag, result} | {:error, tag, error, results}
defp run_actions(_, [], _) do
raise ArgumentError, "taco passed to run/1 has no actions"
end
defp run_actions(actions, [tag | _] = order, results) do
action = Map.fetch!(actions, tag)
case action.(results) do
{:error, error} ->
{:error, tag, error, results}
{:halt, result} ->
{:ok, tag, result}
{:ok, result} ->
results = Map.put(results, tag, result)
maybe_continue(actions, order, results)
end
end
@spec maybe_continue(actions, order, results)
:: {:ok, tag, result} | {:error, tag, error, results}
defp maybe_continue(_, [last_tag], results) do
result = Map.fetch!(results, last_tag)
{:ok, last_tag, result}
end
defp maybe_continue(actions, [_ | order], results) do
run_actions(actions, order, results)
end
end
|
lib/taco.ex
| 0.904808 | 0.716987 |
taco.ex
|
starcoder
|
defmodule Isotope.Noise do
@moduledoc """
Provide functions to create and work with different types of noises.
"""
@noise_types [
:perlin,
:perlin_fractal,
:simplex,
:simplex_fractal,
:value,
:value_fractal,
:cubic,
:cubic_fractal,
:cellular,
:white
]
alias Isotope.{NIF, Options}
@typedoc """
A reference to the noise generator. This is
needed for most of the library functions.
"""
@type noise_ref() :: reference()
@typedoc """
A noise map, represented by a list
containing lists of floats (the noise values).
"""
@type noisemap() :: [[float()]]
@typedoc """
A coordinate `{x, y}` in a cartesian plane.
"""
@type coord() :: {integer(), integer()}
@typedoc """
2-element tuple containg x and y values as floats.
"""
@type point2d() :: {float(), float()}
@typedoc """
3-element tuple containg x, y and z values as floats.
"""
@type point3d() :: {float(), float(), float()}
@typedoc """
A tuple containing width and height
"""
@type size() :: {non_neg_integer(), non_neg_integer()}
@typedoc """
Options available when initializing the noise.
"""
@type options() :: Options.t()
@doc """
Returns a new noise reference using the default options.
iex> {:ok, _ref} = Isotope.Noise.new()
"""
@spec new(options()) :: {:ok, noise_ref()} | {:error, :unsupported_noise}
def new(), do: NIF.new(%Options{})
@doc """
Returns a new noise reference using the provided `options`.
iex> {:ok, _ref} = Isotope.Noise.new(%Isotope.Options{seed: 100})
iex> {:error, :unsupported_noise} = Isotope.Noise.new(%Isotope.Options{noise_type: :foobar})
"""
def new(options) when options.noise_type not in @noise_types,
do: {:error, :unsupported_noise}
def new(options), do: NIF.new(options)
@doc """
Returns a 2D noise map from `start_point` which has `width` and `height`
iex> {:ok, noise} = Isotope.Noise.new(%Isotope.Options{seed: 100})
iex> Isotope.Noise.chunk(noise, {0, 0}, 100, 100)
"""
@spec chunk(noise_ref(), coord(), non_neg_integer(), non_neg_integer()) ::
noisemap()
def chunk(noise, start_point, width, height)
def chunk(noise, {start_x, start_y}, width, height),
do: NIF.chunk(noise, start_x, start_y, width, height)
@doc """
Returns the 2D or 3D noise value depending on `axes`.
If `axes` is a 2-float tuple, it will return the 2D noise value for the point.
If `axes` is a 3-float tuple, it will return the 3D noise value for the point.
iex> {:ok, noise} = Isotope.Noise.new()
iex> Isotope.Noise.get_noise(noise, {10.0, 10.0})
-0.6350845098495483
iex> {:ok, noise} = Isotope.Noise.new()
iex> Isotope.Noise.get_noise(noise, {10.0, 10.0, 10.0})
-0.1322503685951233
"""
@spec get_noise(noise_ref(), point2d() | point3d()) :: float()
def get_noise(noise, axes)
def get_noise(noise, {x, y}), do: NIF.get_noise(noise, x, y)
def get_noise(noise, {x, y, z}), do: NIF.get_noise3d(noise, x, y, z)
@doc """
Generates a 2D noise map of `size` and returns it.
iex> {:ok, noise} = Isotope.Noise.new()
iex> Isotope.Noise.noise_map(noise, {20, 20})
"""
@spec noise_map(reference(), size()) :: noisemap()
def noise_map(noise, size)
def noise_map(noise, {w, h}), do: NIF.noise_map(noise, w, h)
end
|
lib/noise.ex
| 0.911266 | 0.779532 |
noise.ex
|
starcoder
|
defmodule ExMustang.Responders.Howdoi do
@moduledoc """
Implements [howdoi](https://github.com/gleitz/howdoi) like functionality
"""
use Hedwig.Responder
@google_base_url "https://www.google.com/search?q=site:stackoverflow.com%20"
@ua [
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/53.0.2785.143 Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:48.0) Gecko/20100101 Firefox/48.0"
]
@usage """
howdoi <query> - tries to find solution on the given query
"""
hear ~r/^howdoi\s+(?<query>.*)$/i, msg do
reply(msg, gsearch(msg.matches["query"]))
end
defp gsearch(query) do
[ua] = Enum.take_random(@ua, 1)
case HTTPoison.get("#{@google_base_url}#{URI.encode(query)}", [{"User-Agent", ua}]) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
parse_gsearch(body)
_ ->
"I encountered an error while trying to fetch result for that query"
end
end
defp parse_gsearch(body) do
if String.contains?(body, "did not match any documents.") do
no_result()
else
[so_url | _] =
body
|> Floki.find(".r a")
so_url
|> Floki.attribute("href")
|> hd
|> so_extract
end
end
defp so_extract(so_url) do
[ua] = Enum.take_random(@ua, 1)
case HTTPoison.get(so_url, [{"User-Agent", ua}]) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
extract_code(body)
_ ->
"I encountered an error while trying to fetch result for that query"
end
end
defp extract_code(body) do
answers = Floki.find(body, "div#answers div.answer")
case answers do
[first | _] ->
[answer | _] =
first
|> Floki.find("div.post-text")
author =
first
|> Floki.find(".user-info .user-details")
upvotes =
first
|> Floki.find("div.vote span.vote-count-post")
|> Floki.text()
get_data_to_send(answer, author, upvotes)
_ ->
no_result()
end
end
defp get_data_to_send(post_block, author_block, upvotes) do
code =
post_block
|> Floki.find("pre code")
case code do
[code | _] ->
"#{build_author_text(author_block, upvotes)}\n```\n#{Floki.text(code)}```"
[] ->
"#{build_author_text(author_block, upvotes)}\n```\n#{Floki.text(post_block)}\n```"
_ ->
no_result()
end
end
defp build_author_text(author_block, upvotes) do
author_name =
author_block
|> Floki.find("a")
|> Floki.text()
rep =
author_block
|> Floki.find("span.reputation-score")
|> Floki.text()
"This answer was written by #{author_name} (reputation #{rep}) and received #{upvotes} upvotes."
end
defp no_result, do: "Sorry! I could not find anything for your query"
end
|
lib/ex_mustang/responders/howdoi.ex
| 0.601477 | 0.434341 |
howdoi.ex
|
starcoder
|
defmodule Spotter.Endpoint.Dynamic do
@moduledoc """
Wrapper for a resource with the dynamic path.
"""
use Spotter.Endpoint.Base
@good_match "[^{}\/.]+"
@dynamic_parameter ~r/({\s*[\w\d_-]+\s*})/
@valid_dynamic_parameter ~r/{(?P<var>[\w][\w\d_-]*)}/
@doc """
Defines the endpoint with dynamic path.
* :regex - Regex expression for further checks with the passed path. Required.
* :base.path - Path to the recource. For example, `api.learderboard.get.{id}`. Required.
* :base.permissions - List of permissions, required for getting an access to the resource. Default is `[]`.
"""
@enforce_keys [:regex, :base]
defstruct [:regex, base: %Spotter.Endpoint.Base{}]
# Generates a regular expression for the dynamic parameter in URL if it was found. Otherwise
# will return a string as is.
@spec process_path_part(path::String.t) :: String.t
defp process_path_part(path) do
case Regex.match?(@valid_dynamic_parameter, path) do
true -> Enum.join(['(?P<', Regex.named_captures(@valid_dynamic_parameter, path)["var"], '>', @good_match, ")"], "")
false -> path
end
end
@doc """
Generates a regular expression based on the passed `path` string argument. Can raise the
Regex.CompileError in case of errors.
"""
@spec generate_regex(path::String.t) :: String.t
def generate_regex(path) do
parsed_path = Regex.split(@dynamic_parameter, path, include_captures: true)
|> Enum.map(&(process_path_part(&1)))
|> Enum.join("")
regex = Enum.join(['^', parsed_path, '$'], "")
Regex.compile!(regex)
end
@doc """
Returns a new instance of Spotter.Endpoint.Dynamic struct.
"""
@spec new(path::String.t, permissions::[String.t]) :: Spotter.Endpoint.Dynamic
def new(path, permissions) do
%Spotter.Endpoint.Dynamic{
regex: generate_regex(path),
base: %Spotter.Endpoint.Base{
path: path,
permissions: permissions
}
}
end
@doc """
Checking a match of the passed path with the endpoint path via regex search.
"""
@spec match(endpoint::Spotter.Endpoint.Dynamic, path::String.t) :: boolean()
def match(endpoint, path) do
Regex.match?(endpoint.regex, path)
end
@doc """
Checks that the passed permissions can provide an access to the certain resource.
"""
@spec has_permissions(endpoint::Spotter.Endpoint.Dynamic, permissions::[String.t]) :: boolean()
def has_permissions(endpoint, permissions) do
access_granted?(endpoint.base.permissions, permissions)
end
end
|
lib/endpoint/dynamic.ex
| 0.776538 | 0.411406 |
dynamic.ex
|
starcoder
|
defmodule Phoenix.PubSub do
@moduledoc """
Serves as a Notification and PubSub layer for broad use-cases. Used internally
by Channels for pubsub broadcast.
## PubSub Adapter Contract
PubSub adapters need to only implement `start_link/2` and respond to a few
process-based messages to integrate with Phoenix.
PubSub functions send the following messages:
* `subscribe` -
sends: `{:subscribe, pid, topic, link}`
respond with: `:ok | {:error, reason} {:perform, {m, f a}}`
* `unsubscribe` -
sends: `{:unsubscribe, pid, topic}`
respond with: `:ok | {:error, reason} {:perform, {m, f a}}`
* `broadcast` -
sends `{:broadcast, :none, topic, message}`
respond with: `:ok | {:error, reason} {:perform, {m, f a}}`
Additionally, adapters must implement `start_link/2` with the following format:
def start_link(pubsub_server_name_to_locally_register, options)
### Offloading work to clients via MFA response
The `Phoenix.PubSub` API allows any of its functions to handle a
response from the adapter matching `{:perform, {m, f a}}`. The PubSub
client will recursively invoke all MFA responses until a result is
return. This is useful for offloading work to clients without blocking
in your PubSub adapter. See `Phoenix.PubSub.PG2` for an example usage.
## Example
iex> PubSub.subscribe MyApp.PubSub, self, "user:123"
:ok
iex> Process.info(self)[:messages]
[]
iex> PubSub.broadcast MyApp.PubSub, "user:123", {:user_update, %{id: 123, name: "Shane"}}
:ok
iex> Process.info(self)[:messages]
{:user_update, %{id: 123, name: "Shane"}}
"""
defmodule BroadcastError do
defexception [:message]
def exception(msg) do
%BroadcastError{message: "Broadcast failed with #{inspect msg}"}
end
end
@doc """
Subscribes the pid to the PubSub adapter's topic
* `server` - The Pid registered name of the server
* `pid` - The subscriber pid to receive pubsub messages
* `topic` - The topic to subscribe to, ie: `"users:123"`
* `opts` - The optional list of options. Supported options
only include `:link` to link the subscriber to
the pubsub adapter
"""
def subscribe(server, pid, topic, opts \\ []),
do: call(server, {:subscribe, pid, topic, opts})
@doc """
Unsubscribes the pid from the PubSub adapter's topic
"""
def unsubscribe(server, pid, topic),
do: call(server, {:unsubscribe, pid, topic})
@doc """
Broadcasts message on given topic
"""
def broadcast(server, topic, message),
do: call(server, {:broadcast, :none, topic, message})
@doc """
Broadcasts message on given topic
raises `Phoenix.PubSub.BroadcastError` if broadcast fails
"""
def broadcast!(server, topic, message, broadcaster \\ __MODULE__) do
case broadcaster.broadcast(server, topic, message) do
:ok -> :ok
{:error, reason} -> raise BroadcastError, message: reason
end
end
@doc """
Broadcasts message to all but sender on given topic
"""
def broadcast_from(server, from_pid, topic, message),
do: call(server, {:broadcast, from_pid, topic, message})
@doc """
Broadcasts message to all but sender on given topic
raises `Phoenix.PubSub.BroadcastError` if broadcast fails
"""
def broadcast_from!(server, from_pid, topic, message, broadcaster \\ __MODULE__) do
case broadcaster.broadcast_from(server, from_pid, topic, message) do
:ok -> :ok
{:error, reason} -> raise BroadcastError, message: reason
end
end
defp call(server, msg) do
GenServer.call(server, msg) |> perform
end
defp perform({:perform, {mod, func, args}}) do
apply(mod, func, args) |> perform
end
defp perform(result), do: result
end
|
lib/phoenix/pubsub.ex
| 0.851027 | 0.558026 |
pubsub.ex
|
starcoder
|
defmodule Plug.Crypto.MessageVerifier do
@moduledoc """
`MessageVerifier` makes it easy to generate and verify messages
which are signed to prevent tampering.
For example, the cookie store uses this verifier to send data
to the client. The data can be read by the client, but cannot be
tampered with.
The message and its verification are base64url encoded and returned
to you.
The current algorithm used is HMAC-SHA, with SHA256, SHA384, and
SHA512 as supported digest types.
"""
@doc """
Signs a message according to the given secret.
"""
def sign(message, secret, digest_type \\ :sha256)
when is_binary(message) and is_binary(secret) and digest_type in [:sha256, :sha384, :sha512] do
hmac_sha2_sign(message, secret, digest_type)
rescue
e -> reraise e, Plug.Crypto.prune_args_from_stacktrace(System.stacktrace())
end
@doc """
Decodes and verifies the encoded binary was not tampered with.
"""
def verify(signed, secret) when is_binary(signed) and is_binary(secret) do
hmac_sha2_verify(signed, secret)
rescue
e -> reraise e, Plug.Crypto.prune_args_from_stacktrace(System.stacktrace())
end
## Signature Algorithms
defp hmac_sha2_to_protected(:sha256), do: "HS256"
defp hmac_sha2_to_protected(:sha384), do: "HS384"
defp hmac_sha2_to_protected(:sha512), do: "HS512"
defp hmac_sha2_to_digest_type("HS256"), do: :sha256
defp hmac_sha2_to_digest_type("HS384"), do: :sha384
defp hmac_sha2_to_digest_type("HS512"), do: :sha512
defp hmac_sha2_sign(payload, key, digest_type) do
protected = hmac_sha2_to_protected(digest_type)
plain_text = signing_input(protected, payload)
signature = :crypto.hmac(digest_type, key, plain_text)
encode_token(plain_text, signature)
end
defp hmac_sha2_verify(signed, key) when is_binary(signed) and is_binary(key) do
case decode_token(signed) do
{protected, payload, plain_text, signature} when protected in ["HS256", "HS384", "HS512"] ->
digest_type = hmac_sha2_to_digest_type(protected)
challenge = :crypto.hmac(digest_type, key, plain_text)
if Plug.Crypto.secure_compare(challenge, signature) do
{:ok, payload}
else
:error
end
_ ->
:error
end
end
## Helpers
defp encode_token(plain_text, signature)
when is_binary(plain_text) and is_binary(signature) do
plain_text <> "." <> Base.url_encode64(signature, padding: false)
end
defp decode_token(token) do
with [protected, payload, signature] <- String.split(token, ".", parts: 3),
plain_text = protected <> "." <> payload,
{:ok, protected} <- Base.url_decode64(protected, padding: false),
{:ok, payload} <- Base.url_decode64(payload, padding: false),
{:ok, signature} <- Base.url_decode64(signature, padding: false) do
{protected, payload, plain_text, signature}
else
_ -> :error
end
end
defp signing_input(protected, payload) when is_binary(protected) and is_binary(payload) do
protected
|> Base.url_encode64(padding: false)
|> Kernel.<>(".")
|> Kernel.<>(Base.url_encode64(payload, padding: false))
end
end
|
lib/plug/crypto/message_verifier.ex
| 0.834508 | 0.59705 |
message_verifier.ex
|
starcoder
|
defmodule MerklePatriciaTree.Trie.Destroyer do
@moduledoc """
Destroyer is responsible for removing keys from a
merkle trie. To remove a key, we need to make a
delta to our trie which ends up as the canonical
form of the given tree as defined in http://gavwood.com/Paper.pdf.
Note: this algorithm is non-obvious, and hence why we have a good
number of functional and invariant tests. We should add more specific
unit tests to this module.
"""
alias MerklePatriciaTree.Trie
alias MerklePatriciaTree.Trie.Node
alias MerklePatriciaTree.ListHelper
@empty_branch <<>>
@doc """
Removes a key from a given trie, if it exists.
This may radically change the structure of the trie.
"""
@spec remove_key(Node.trie_node(), Trie.key(), Trie.t()) :: Node.trie_node()
def remove_key(trie_node, key, trie) do
trie_remove_key(trie_node, key, trie)
end
# To remove this leaf, simply remove it
defp trie_remove_key({:leaf, leaf_prefix, _value}, prefix, _trie) when prefix == leaf_prefix do
:empty
end
# This key doesn't exist, do nothing.
defp trie_remove_key({:leaf, leaf_prefix, value}, _prefix, _trie) do
{:leaf, leaf_prefix, value}
end
# Shed shared prefix and continue removal operation
defp trie_remove_key({:ext, ext_prefix, node_hash}, key_prefix, trie) do
{_matching_prefix, ext_tl, remaining_tl} = ListHelper.overlap(ext_prefix, key_prefix)
if ext_tl |> Enum.empty?() do
existing_node = Node.decode_trie(node_hash |> Trie.into(trie))
updated_node = trie_remove_key(existing_node, remaining_tl, trie)
# Handle the potential cases of children
case updated_node do
:empty ->
:empty
{:leaf, leaf_prefix, leaf_value} ->
{:leaf, ext_prefix ++ leaf_prefix, leaf_value}
{:ext, new_ext_prefix, new_ext_node_hash} ->
{:ext, ext_prefix ++ new_ext_prefix, new_ext_node_hash}
els ->
{:ext, ext_prefix, els |> Node.encode_node(trie)}
end
else
# Prefix doesn't match ext, do nothing.
{:ext, ext_prefix, node_hash}
end
end
# Remove from a branch when directly on value
defp trie_remove_key({:branch, branches}, [], _trie) when length(branches) == 17 do
{:branch, List.replace_at(branches, 16, nil)}
end
# Remove beneath a branch
defp trie_remove_key({:branch, branches}, [prefix_hd | prefix_tl], trie)
when length(branches) == 17 do
updated_branches =
List.update_at(branches, prefix_hd, fn branch ->
branch_node = branch |> Trie.into(trie) |> Node.decode_trie()
branch_node |> trie_remove_key(prefix_tl, trie) |> Node.encode_node(trie)
end)
non_blank_branches =
updated_branches
|> Enum.drop(-1)
|> Enum.with_index()
|> Enum.filter(fn {branch, _} -> branch != @empty_branch end)
final_value = List.last(updated_branches)
cond do
non_blank_branches |> Enum.empty?() ->
# We just have a final value, this will need to percolate up
{:leaf, [], final_value}
Enum.count(non_blank_branches) == 1 and final_value == "" ->
# We just have a node we need to percolate up
{branch_node, i} = List.first(non_blank_branches)
decoded_branch_node = Node.decode_trie(branch_node |> Trie.into(trie))
case decoded_branch_node do
{:leaf, leaf_prefix, leaf_value} ->
{:leaf, [i | leaf_prefix], leaf_value}
{:ext, ext_prefix, ext_node_hash} ->
{:ext, [i | ext_prefix], ext_node_hash}
# TODO: Is this illegal since ext has to have at least two nibbles?
{:branch, _branches} ->
{:ext, [i], branch_node}
end
true ->
{:branch, updated_branches}
end
end
# Merge into empty to create a leaf
defp trie_remove_key(:empty, _prefix, _trie) do
:empty
end
end
|
lib/trie/destroyer.ex
| 0.67854 | 0.550366 |
destroyer.ex
|
starcoder
|
defmodule Picam.FakeCamera do
@moduledoc """
A fake version of `Picam.Camera` that can be used in test and development
when a real Raspberry Pi Camera isn't available.
All the normal configuration commands are accepted and silently ignored,
except that:
* `size` can be set to one of 1920x1080, 1280x720, or 640x480. This will
result in a static image of that size being displayed on each frame.
* `fps` can be set, which will result in the static images being displayed
at roughtly the requested rate.
In addition, a custom image can be set using `set_image/1`, which is be
displayed on each frame until a new image is set or the `size` is changed.
"""
use GenServer
require Logger
@doc false
def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
@doc false
def init(_opts) do
state = %{jpg: image_data(1280, 720), fps: 30, requests: []}
schedule_next_frame(state)
{:ok, state}
end
@doc """
Set the image that is being displayed by the fake camera on each frame.
This is intended for development or testing things that depend on the
content of the image seen by the camera.
`jpg` should be a JPEG-encoded binary, for example:
```elixir
"image.jpg"
|> File.read!()
|> Picam.FakeCamera.set_image()
```
"""
def set_image(jpg) do
GenServer.cast(__MODULE__, {:set_image, jpg})
end
# GenServer callbacks
@doc false
def handle_call(:next_frame, from, state) do
state = %{state | requests: [from | state.requests]}
{:noreply, state}
end
@doc false
def handle_cast({:set, "size=" <> size}, state) do
[width, height] =
size
|> String.split(",", limit: 2)
|> Enum.map(&String.to_integer/1)
{:noreply, %{state | jpg: image_data(width, height)}}
end
def handle_cast({:set, "fps=" <> fps}, state) do
{:noreply, %{state | fps: fps |> String.to_float() |> round()}}
end
def handle_cast({:set, _message}, state) do
{:noreply, state}
end
def handle_cast({:set_image, jpg}, state) do
{:noreply, %{state | jpg: jpg}}
end
@doc false
def handle_info(:send_frame, state) do
schedule_next_frame(state)
Task.start(fn -> dispatch(state.requests, state.jpg) end)
{:noreply, %{state | requests: []}}
end
@doc false
def terminate(reason, _state) do
Logger.warn("FakeCamera GenServer exiting: #{inspect(reason)}")
end
# Private helper functions
defp dispatch(requests, jpg) do
for req <- Enum.reverse(requests), do: GenServer.reply(req, jpg)
end
defp schedule_next_frame(%{fps: fps}) do
Process.send_after(self(), :send_frame, Integer.floor_div(1000, fps))
end
defp image_data(1920, 1080), do: image_data("1920_1080.jpg")
defp image_data(640, 480), do: image_data("640_480.jpg")
defp image_data(_, _), do: image_data("1280_720.jpg")
defp image_data(filename) when is_binary(filename) do
:code.priv_dir(:picam)
|> Path.join("fake_camera_images/#{filename}")
|> File.read!()
end
end
|
lib/picam/fake_camera.ex
| 0.901364 | 0.86681 |
fake_camera.ex
|
starcoder
|
defmodule BlueHeron.HCI.Event.CommandComplete do
use BlueHeron.HCI.Event, code: 0x0E
@moduledoc """
> The Command Complete event is used by the Controller for most commands to
> transmit return status of a command and the other event parameters that are
> specified for the issued HCI command.
Reference: Version 5.2, Vol 4, Part E, 7.7.14
"""
require BlueHeron.HCI.CommandComplete.ReturnParameters
require Logger
defparameters [:num_hci_command_packets, :opcode, :return_parameters]
defimpl BlueHeron.HCI.Serializable do
def serialize(data) do
data = BlueHeron.HCI.CommandComplete.ReturnParameters.encode(data)
bin = <<data.num_hci_command_packets, data.opcode::2-bytes, data.return_parameters::binary>>
size = byte_size(bin)
<<data.code, size, bin::binary>>
end
end
defimpl BlueHeron.HCI.CommandComplete.ReturnParameters do
def decode(cc) do
%{cc | return_parameters: do_decode(cc.opcode, cc.return_parameters)}
end
def encode(cc) do
%{cc | return_parameters: do_encode(cc.opcode, cc.return_parameters)}
end
# Generate return_parameter parsing function for all available command
# modules based on the requirements in BlueHeron.HCI.Command behaviour
for mod <- BlueHeron.HCI.Command.__modules__(), opcode = mod.__opcode__() do
defp do_decode(unquote(opcode), rp_bin) do
unquote(mod).deserialize_return_parameters(rp_bin)
end
defp do_encode(unquote(opcode), rp_map) do
unquote(mod).serialize_return_parameters(rp_map)
end
end
defp do_encode(_unknown_opcode, data) when is_binary(data), do: data
end
@impl BlueHeron.HCI.Event
def deserialize(<<@code, _size, num_hci_command_packets, opcode::binary-2, rp_bin::binary>>) do
command_complete = %__MODULE__{
num_hci_command_packets: num_hci_command_packets,
opcode: opcode,
return_parameters: rp_bin
}
maybe_decode_return_parameters(command_complete)
end
def deserialize(bin), do: {:error, bin}
def maybe_decode_return_parameters(cc) do
BlueHeron.HCI.CommandComplete.ReturnParameters.decode(cc)
catch
kind, value ->
Logger.warn("""
(#{inspect(kind)}, #{inspect(value)}) Unable to decode return_parameters for opcode #{inspect(cc.opcode, base: :hex)}
return_parameters: #{inspect(cc.return_parameters)}
#{inspect(__STACKTRACE__, limit: :infinity, pretty: true)}
""")
cc
end
end
|
lib/blue_heron/hci/events/command_complete.ex
| 0.730001 | 0.415136 |
command_complete.ex
|
starcoder
|
defmodule IntersectionController.TrafficModel do
require Logger
def get_traffic_light_state(direction, intended_state)
def get_traffic_light_state("RTG", :initial) do
0
end
def get_traffic_light_state("RTG", :transition) do
1
end
def get_traffic_light_state("RTG", :end) do
2
end
def get_traffic_light_state("GTR", :initial) do
2
end
def get_traffic_light_state("GTR", :transition) do
1
end
def get_traffic_light_state("GTR", :end) do
0
end
def get_traffic_light_state("GR", :initial) do
0
end
def get_traffic_light_state("GR", :end) do
1
end
def get_traffic_light_state("RG", :initial) do
1
end
def get_traffic_light_state("RG", :end) do
0
end
def sensor_activated?(sensors, sensor) do
group =
sensor
|> String.split("/", parts: 4)
|> Enum.slice(0, 3)
|> Enum.join("/")
sensor = String.slice(sensor, String.length(group), 9)
if Map.has_key?(sensors, group) do
group_map = Map.fetch!(sensors, group)
if Map.has_key?(group_map, sensor) do
Map.fetch!(group_map, sensor)
else
false
end
else
false
end
end
def group_exception?(traffic_model, sensors, group) do
group_map = Map.fetch!(traffic_model, group)
if tuple_size(group_map.exception) == 0 do
false
else
Tuple.to_list(group_map.exception)
|> Enum.map(fn sensor -> sensor_activated?(sensors, sensor) end)
|> Enum.any?(fn x -> x end)
end
end
def expand_associated_groups(associated_groups, traffic_model) do
associated_list = Tuple.to_list(associated_groups)
for group <- associated_list, into: %{} do
group_map = Map.fetch!(traffic_model, group)
items = group_map.items
duration = group_map.duration
{group, %{:items => items, :duration => duration}}
end
end
def associated_running?(group_associated, running_associated) do
Map.keys(group_associated)
|> Enum.any?(fn group -> group in running_associated end)
end
def messages_from_group(group, group_map, state) do
for {item_name, type_map} <- group_map.items do
actual_state =
IntersectionController.TrafficModel.get_traffic_light_state(type_map.type, state)
{"#{group}#{item_name}", actual_state}
end
|> List.flatten()
end
def get_solution(queue, sensors, traffic_model, put_back, excluded, current_solution)
def get_solution(queue, sensors, traffic_model, put_back, [], current_solution)
when map_size(current_solution) == 0 do
if :queue.is_empty(queue) do
{%{}, queue}
else
{{:value, group}, queue} = :queue.out(queue)
if Map.fetch!(sensors, group) |> Map.values() |> Enum.any?(fn x -> x end) do
if not group_exception?(traffic_model, sensors, group) do
group_map = Map.fetch!(traffic_model, group)
items = group_map.items
duration = group_map.duration
associated =
if tuple_size(group_map.associated) > 0 do
expand_associated_groups(group_map.associated, traffic_model)
else
%{}
end
current_solution = %{
group => %{:items => items, :duration => duration, :associated => associated}
}
excluded = Tuple.to_list(group_map.excluded)
get_solution(queue, sensors, traffic_model, put_back, excluded, current_solution)
else
put_back = put_back ++ [group]
get_solution(queue, sensors, traffic_model, put_back, [], %{})
end
else
get_solution(queue, sensors, traffic_model, put_back, [], %{})
end
end
end
def get_solution(queue, sensors, traffic_model, put_back, excluded, current_solution)
when map_size(current_solution) > 0 do
if :queue.is_empty(queue) do
queue = :queue.from_list(put_back)
{current_solution, queue}
else
{{:value, group}, queue} = :queue.out(queue)
if Map.fetch!(sensors, group) |> Map.values() |> Enum.any?(fn x -> x end) do
if not group_exception?(traffic_model, sensors, group) and
not Enum.member?(excluded, group) do
group_map = Map.fetch!(traffic_model, group)
items = group_map.items
duration = group_map.duration
associated =
if tuple_size(group_map.associated) > 0 do
expand_associated_groups(group_map.associated, traffic_model)
else
%{}
end
current_solution =
Map.put(current_solution, group, %{
:items => items,
:duration => duration,
:associated => associated
})
excluded = excluded ++ Tuple.to_list(group_map.excluded)
get_solution(queue, sensors, traffic_model, put_back, excluded, current_solution)
else
put_back = put_back ++ [group]
get_solution(queue, sensors, traffic_model, put_back, excluded, current_solution)
end
else
get_solution(queue, sensors, traffic_model, put_back, excluded, current_solution)
end
end
end
end
|
lib/intersection_controller/traffic_model.ex
| 0.574514 | 0.454896 |
traffic_model.ex
|
starcoder
|
defmodule Cldr.Unit.Backend do
def define_unit_module(config) do
module = inspect(__MODULE__)
backend = config.backend
config = Macro.escape(config)
quote location: :keep, bind_quoted: [module: module, backend: backend, config: config] do
defmodule Unit do
@moduledoc false
if Cldr.Config.include_module_docs?(config.generate_docs) do
@moduledoc """
Supports the CLDR Units definitions which provide for the localization of many
unit types.
"""
end
@styles [:long, :short, :narrow]
alias Cldr.Math
defdelegate new(unit, value), to: Cldr.Unit
defdelegate new!(unit, value), to: Cldr.Unit
defdelegate compatible?(unit_1, unit_2), to: Cldr.Unit
defdelegate value(unit), to: Cldr.Unit
defdelegate zero(unit), to: Cldr.Unit
defdelegate zero?(unit), to: Cldr.Unit
defdelegate decompose(unit, list), to: Cldr.Unit
defdelegate localize(unit, usage, options), to: Cldr.Unit
defdelegate measurement_system_for(territory), to: Cldr.Unit
defdelegate measurement_system_for(territory, category), to: Cldr.Unit
defdelegate known_units, to: Cldr.Unit
defdelegate known_unit_categories, to: Cldr.Unit
defdelegate styles, to: Cldr.Unit
defdelegate default_style, to: Cldr.Unit
defdelegate validate_unit(unit), to: Cldr.Unit
defdelegate validate_style(unit), to: Cldr.Unit
defdelegate unit_category(unit), to: Cldr.Unit
defdelegate add(unit_1, unit_2), to: Cldr.Unit.Math
defdelegate sub(unit_1, unit_2), to: Cldr.Unit.Math
defdelegate mult(unit_1, unit_2), to: Cldr.Unit.Math
defdelegate div(unit_1, unit_2), to: Cldr.Unit.Math
defdelegate add!(unit_1, unit_2), to: Cldr.Unit.Math
defdelegate sub!(unit_1, unit_2), to: Cldr.Unit.Math
defdelegate mult!(unit_1, unit_2), to: Cldr.Unit.Math
defdelegate div!(unit_1, unit_2), to: Cldr.Unit.Math
defdelegate round(unit, places, mode), to: Cldr.Unit.Math
defdelegate round(unit, places), to: Cldr.Unit.Math
defdelegate round(unit), to: Cldr.Unit.Math
defdelegate convert(unit_1, to_unit), to: Cldr.Unit.Conversion
@doc """
Formats a number into a string according to a unit definition for a locale.
## Arguments
* `list_or_number` is any number (integer, float or Decimal) or a
`Cldr.Unit.t()` struct or a list of `Cldr.Unit.t()` structs
* `options` is a keyword list
## Options
* `:unit` is any unit returned by `Cldr.Unit.known_units/0`. Ignored if
the number to be formatted is a `Cldr.Unit.t()` struct
* `:locale` is any valid locale name returned by `Cldr.known_locale_names/0`
or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`
* `:style` is one of those returned by `Cldr.Unit.available_styles`.
The current styles are `:long`, `:short` and `:narrow`.
The default is `style: :long`
* `:per` allows compound units to be formatted. For example, assume
we want to format a string which represents "kilograms per second".
There is no such unit defined in CLDR (or perhaps anywhere!).
If however we define the unit `unit = Cldr.Unit.new!(:kilogram, 20)`
we can then execute `Cldr.Unit.to_string(unit, per: :second)`.
Each locale defines a specific way to format such a compount unit.
Usually it will return something like `20 kilograms/second`
* `:list_options` is a keyword list of options for formatting a list
which is passed through to `Cldr.List.to_string/3`. This is only
applicable when formatting a list of units.
* Any other options are passed to `Cldr.Number.to_string/2`
which is used to format the `number`
## Returns
* `{:ok, formatted_string}` or
* `{:error, {exception, message}}`
## Examples
iex> #{inspect(__MODULE__)}.to_string Cldr.Unit.new!(:gallon, 123)
{:ok, "123 gallons"}
iex> #{inspect(__MODULE__)}.to_string Cldr.Unit.new!(:gallon, 1)
{:ok, "1 gallon"}
iex> #{inspect(__MODULE__)}.to_string Cldr.Unit.new!(:gallon, 1), locale: "af"
{:ok, "1 gelling"}
iex> #{inspect(__MODULE__)}.to_string Cldr.Unit.new!(:gallon, 1), locale: "af-NA"
{:ok, "1 gelling"}
iex> #{inspect(__MODULE__)}.to_string Cldr.Unit.new!(:gallon, 1), locale: "bs"
{:ok, "1 galon"}
iex> #{inspect(__MODULE__)}.to_string Cldr.Unit.new!(:gallon, 1234), format: :long
{:ok, "1 thousand gallons"}
iex> #{inspect(__MODULE__)}.to_string Cldr.Unit.new!(:gallon, 1234), format: :short
{:ok, "1K gallons"}
iex> #{inspect(__MODULE__)}.to_string Cldr.Unit.new!(:megahertz, 1234)
{:ok, "1,234 megahertz"}
iex> #{inspect(__MODULE__)}.to_string Cldr.Unit.new!(:megahertz, 1234), style: :narrow
{:ok, "1,234MHz"}
iex> #{inspect(__MODULE__)}.to_string Cldr.Unit.new!(:megabyte, 1234), locale: "en", style: :unknown
{:error, {Cldr.UnknownFormatError, "The unit style :unknown is not known."}}
"""
@spec to_string(Cldr.Unit.t() | [Cldr.Unit.t(), ...], Keyword.t()) ::
{:ok, String.t()} | {:error, {atom, binary}}
def to_string(number, options \\ []) do
Cldr.Unit.to_string(number, unquote(backend), options)
end
@doc """
Formats a list using `to_string/3` but raises if there is
an error.
## Arguments
* `list_or_number` is any number (integer, float or Decimal) or a
`Cldr.Unit.t()` struct or a list of `Cldr.Unit.t()` structs
* `options` is a keyword list
## Options
* `:unit` is any unit returned by `Cldr.Unit.known_units/0`. Ignored if
the number to be formatted is a `Cldr.Unit.t()` struct
* `:locale` is any valid locale name returned by `Cldr.known_locale_names/0`
or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`
* `:style` is one of those returned by `Cldr.Unit.available_styles`.
The current styles are `:long`, `:short` and `:narrow`.
The default is `style: :long`
* `:list_options` is a keyword list of options for formatting a list
which is passed through to `Cldr.List.to_string/3`. This is only
applicable when formatting a list of units.
* Any other options are passed to `Cldr.Number.to_string/2`
which is used to format the `number`
## Returns
* `formatted_string` or
* raises an exception
## Examples
iex> #{inspect(__MODULE__)}.to_string! 123, unit: :gallon
"123 gallons"
iex> #{inspect(__MODULE__)}.to_string! 1, unit: :gallon
"1 gallon"
iex> #{inspect(__MODULE__)}.to_string! 1, unit: :gallon, locale: "af"
"1 gelling"
"""
@spec to_string!(Cldr.Unit.t()| [Cldr.Unit.t(), ...], Keyword.t()) ::
String.t() | no_return()
def to_string!(number, options \\ []) do
Cldr.Unit.to_string!(number, unquote(backend), options)
end
@doc """
Formats a number into an iolist according to a unit definition
for a locale.
## Arguments
* `list_or_number` is any number (integer, float or Decimal) or a
`Cldr.Unit.t()` struct or a list of `Cldr.Unit.t()` structs
* `options` is a keyword list
## Options
* `:unit` is any unit returned by `Cldr.Unit.known_units/0`. Ignored if
the number to be formatted is a `Cldr.Unit.t()` struct
* `:locale` is any valid locale name returned by `Cldr.known_locale_names/0`
or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`
* `:style` is one of those returned by `Cldr.Unit.available_styles`.
The current styles are `:long`, `:short` and `:narrow`.
The default is `style: :long`
* `:per` allows compound units to be formatted. For example, assume
we want to format a string which represents "kilograms per second".
There is no such unit defined in CLDR (or perhaps anywhere!).
If however we define the unit `unit = Cldr.Unit.new!(:kilogram, 20)`
we can then execute `Cldr.Unit.to_string(unit, per: :second)`.
Each locale defines a specific way to format such a compount unit.
Usually it will return something like `20 kilograms/second`
* `:list_options` is a keyword list of options for formatting a list
which is passed through to `Cldr.List.to_string/3`. This is only
applicable when formatting a list of units.
* Any other options are passed to `Cldr.Number.to_string/2`
which is used to format the `number`
## Returns
* `{:ok, io_list}` or
* `{:error, {exception, message}}`
## Examples
iex> #{inspect(__MODULE__)}.to_iolist Cldr.Unit.new!(:gallon, 123)
{:ok, ["123", " gallons"]}
iex> #{inspect(__MODULE__)}.to_iolist Cldr.Unit.new!(:megabyte, 1234), locale: "en", style: :unknown
{:error, {Cldr.UnknownFormatError, "The unit style :unknown is not known."}}
"""
@spec to_iolist(Cldr.Unit.t() | [Cldr.Unit.t(), ...], Keyword.t()) ::
{:ok, list()} | {:error, {atom, binary}}
def to_iolist(number, options \\ []) do
Cldr.Unit.to_iolist(number, unquote(backend), options)
end
@doc """
Formats a unit using `to_iolist/3` but raises if there is
an error.
## Arguments
* `list_or_number` is any number (integer, float or Decimal) or a
`Cldr.Unit.t()` struct or a list of `Cldr.Unit.t()` structs
* `options` is a keyword list
## Options
* `:unit` is any unit returned by `Cldr.Unit.known_units/0`. Ignored if
the number to be formatted is a `Cldr.Unit.t()` struct
* `:locale` is any valid locale name returned by `Cldr.known_locale_names/0`
or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`
* `:style` is one of those returned by `Cldr.Unit.available_styles`.
The current styles are `:long`, `:short` and `:narrow`.
The default is `style: :long`
* `:list_options` is a keyword list of options for formatting a list
which is passed through to `Cldr.List.to_string/3`. This is only
applicable when formatting a list of units.
* Any other options are passed to `Cldr.Number.to_string/2`
which is used to format the `number`
## Returns
* `io_list` or
* raises an exception
## Examples
iex> #{inspect(__MODULE__)}.to_iolist! 123, unit: :gallon
["123", " gallons"]
"""
@spec to_iolist!(Cldr.Unit.t()| [Cldr.Unit.t(), ...], Keyword.t()) ::
list() | no_return()
def to_iolist!(number, options \\ []) do
Cldr.Unit.to_iolist!(number, unquote(backend), options)
end
@doc """
Returns a list of the preferred units for a given
unit, locale, use case and scope.
The units used to represent length, volume and so on
depend on a given territory, measurement system and usage.
For example, in the US, people height is most commonly
referred to in `inches`, or informally as `feet and inches`.
In most of the rest of the world it is `centimeters`.
## Arguments
* `unit` is any unit returned by `Cldr.Unit.new/2`.
* `backend` is any Cldr backend module. That is, any module
that includes `use Cldr`. The default is `Cldr.default_backend/0`
* `options` is a keyword list of options or a
`Cldr.Unit.Conversion.Options` struct. The default
is `[]`.
## Options
* `:usage` is the unit usage. for example `;person` for a unit
type of length. The available usage for a given unit category can
be seen with `Cldr.Config.unit_preferences/3`. The default is `nil`
* `:locale` is any locale returned by `Cldr.validate_locale/2`
## Returns
* `{:ok, unit_list, formatting_options}` or
* `{:error, {exception, reason}}`
## Notes
`formatting_options` is a keyword list of options
that can be passed to `Cldr.Unit.to_string/3`. Its
primary intended usage is for localizing a unit that
decomposes into more than one unit (for example when
2 meters might become 6 feet 6 inches.) In such
cases, the last unit in the list (in this case the
inches) is formatted with the `formatting_options`.
## Examples
iex> meter = Cldr.Unit.new!(:meter, 1)
iex> #{inspect(__MODULE__)}.preferred_units meter, locale: "en-US", usage: :person_height
{:ok, [:foot, :inch], []}
iex> #{inspect(__MODULE__)}.preferred_units meter, locale: "en-US", usage: :person
{:ok, [:inch], []}
iex> #{inspect(__MODULE__)}.preferred_units meter, locale: "en-AU", usage: :person
{:ok, [:centimeter], []}
iex> #{inspect(__MODULE__)}.preferred_units meter, locale: "en-US", usage: :road
{:ok, [:foot], [round_nearest: 10]}
iex> #{inspect(__MODULE__)}.preferred_units meter, locale: "en-AU", usage: :road
{:ok, [:meter], [round_nearest: 10]}
"""
def preferred_units(unit, options \\ []) do
Cldr.Unit.Preference.preferred_units(unit, unquote(backend), options)
end
@doc """
Returns a list of the preferred units for a given
unit, locale, use case and scope.
The units used to represent length, volume and so on
depend on a given territory, measurement system and usage.
For example, in the US, people height is most commonly
referred to in `inches`, or informally as `feet and inches`.
In most of the rest of the world it is `centimeters`.
## Arguments
* `unit` is any unit returned by `Cldr.Unit.new/2`.
* `backend` is any Cldr backend module. That is, any module
that includes `use Cldr`. The default is `Cldr.default_backend/0`
* `options` is a keyword list of options or a
`Cldr.Unit.Conversion.Options` struct. The default
is `[]`.
## Options
* `:usage` is the unit usage. for example `;person` for a unit
type of length. The available usage for a given unit category can
be seen with `Cldr.Config.unit_preferences/3`. The default is `nil`.
* `:scope` is either `:small` or `nil`. In some usage, the units
used are different when the unit size is small. It is up to the
developer to determine when `scope: :small` is appropriate.
* `:alt` is either `:informal` or `nil`. Like `:scope`, the units
in use depend on whether they are being used in a formal or informal
context.
* `:locale` is any locale returned by `Cldr.validate_locale/2`
## Returns
* `unit_list` or
* raises an exception
## Examples
iex> meter = Cldr.Unit.new!(:meter, 2)
iex> #{inspect(__MODULE__)}.preferred_units! meter, locale: "en-US", usage: :person_height
[:foot, :inch]
iex> #{inspect(__MODULE__)}.preferred_units! meter, locale: "en-AU", usage: :person
[:centimeter]
iex> #{inspect(__MODULE__)}.preferred_units! meter, locale: "en-US", usage: :road
[:foot]
iex> #{inspect(__MODULE__)}.preferred_units! meter, locale: "en-AU", usage: :road
[:meter]
"""
def preferred_units!(unit, options \\ []) do
Cldr.Unit.Preference.preferred_units!(unit, unquote(backend), options)
end
# Generate the functions that encapsulate the unit data from CDLR
@doc false
def units_for(locale \\ unquote(backend).get_locale(), style \\ Cldr.Unit.default_style())
for locale_name <- Cldr.Config.known_locale_names(config) do
locale_data =
locale_name
|> Cldr.Config.get_locale(config)
|> Map.get(:units)
for style <- @styles do
units =
Map.get(locale_data, style)
|> Enum.map(&elem(&1, 1))
|> Cldr.Map.merge_map_list()
|> Enum.into(%{})
def units_for(unquote(locale_name), unquote(style)) do
unquote(Macro.escape(units))
end
end
end
def units_for(%LanguageTag{cldr_locale_name: cldr_locale_name}, style) do
units_for(cldr_locale_name, style)
end
end
end
end
end
|
lib/cldr/unit/backend.ex
| 0.867204 | 0.586345 |
backend.ex
|
starcoder
|
defmodule OrderedList do
@moduledoc ~S"""
Provides a set of algorithms for sorting and reordering the position number of maps in a list.
All of the functions expect a `List` where each element is a `Map` with a `:postion` key.
iex> original_list = [%{id: 1, position: 1},%{id: 2, position: 2}, %{id: 3, position: 3},%{id: 4, position: 4},%{id: 5, position: 5}]
iex> OrderedList.insert_at(original_list,%{id: 4, position: 4}, 2)
{
#Unchanged
[%{id: 1, position: 1}, %{id: 5, position: 5}],
#Changed
[
{%{id: 2, position: 2}, %{ position: 3 }},
{%{id: 3, position: 3}, %{ position: 4 }},
{%{id: 4, position: 4}, %{ position: 2 }}
]
}
The return value is a `Tuple` where the first element is a list of maps that haven't had
their position changed. The second element is a `List` of tuples where the first element is
the original `Map` and the second is params for the new position. The idea being that you would
be able to pass each `Map` in the second list to create changesets with `Ecto`.
post = MyRepo.get!(Post, 42)
posts = MyRepo.all(Post)
{ same_positions, new_positions } = OrderedList.insert_at(posts, post, 3)
changesets = Enum.map new_positions, fn ({orginal, params}) ->
Post.changeset(orginal, params)
end
Repo.transaction fn ->
Enum.each changesets, fn (post) ->
case MyRepo.update post do
{:ok, model} -> # Updated with success
{:error, changeset} -> # Something went wrong
end
end
end
"""
@doc ~S"""
Retuns a `Tuple` of two elements, the first being a `List` of maps that don't need there position updated.
The second is a `List` of tuples with the first element being the original `Map` and second being a `Map`
with new `:position`.
* `list` - A `List` where each element is a `Map` or `Struct` that contains a `:position` key.
* `original_element` - A `Map` or `Struct` that is contained within the `list` in the first argument
* `new_position` - An `Integer` of position that the `original_element` is moving to.
Example:
iex> original_list = [%{id: 1, position: 1},%{id: 2, position: 2}, %{id: 3, position: 3},%{id: 4, position: 4},%{id: 5, position: 5}]
iex> OrderedList.insert_at(original_list,%{id: 4, position: 4}, 2)
{
#Unchanged
[%{id: 1, position: 1}, %{id: 5, position: 5}],
#Changed
[
{%{id: 2, position: 2}, %{ position: 3 }},
{%{id: 3, position: 3}, %{ position: 4 }},
{%{id: 4, position: 4}, %{ position: 2 }}
]
}
"""
def insert_at(list, original_element, new_position) do
case valid_new_position?(list,original_element,new_position) do
true -> reorder_list(list, original_element, new_position)
false -> { list, [] }
end
end
@doc ~S"""
Moves the element one position down the list. Lower down the list means that the position
number will be higher.
* `list` - A `List` where each element is a `Map` or `Struct` that contains a `:position` key.
* `original_element` - A `Map` or `Struct` that is contained within the `list` in the first argument
Example:
iex> original_list = [%{id: 1, position: 1},%{id: 2, position: 2}, %{id: 3, position: 3},%{id: 4, position: 4},%{id: 5, position: 5}]
iex> OrderedList.move_lower(original_list, %{id: 1, position: 1})
{
#Unchanged
[%{id: 3, position: 3}, %{id: 4, position: 4}, %{id: 5, position: 5}],
#Changed
[
{%{id: 1, position: 1}, %{position: 2}},
{%{id: 2, position: 2}, %{position: 1}}
]
}
The position number will remain unchanged if it is already in the lowest position.
"""
def move_lower(list, original_element) do
insert_at(list,original_element, original_element.position + 1)
end
@doc ~S"""
Moves the `original_element` one position up the list. Higher up the list means that the position
number will be lower.
* `list` - A `List` where each element is a `Map` or `Struct` that contains a `:position` key.
* `original_element` - A `Map` or `Struct` that is contained within the `list` in the first argument
Example:
iex> original_list = [%{id: 1, position: 1},%{id: 2, position: 2}, %{id: 3, position: 3},%{id: 4, position: 4},%{id: 5, position: 5}]
iex> OrderedList.move_higher(original_list, %{id: 5, position: 5})
{
#Unchanged
[%{id: 1, position: 1}, %{id: 2, position: 2}, %{id: 3, position: 3}],
#Changed
[{%{id: 4, position: 4}, %{position: 5}}, {%{id: 5, position: 5}, %{position: 4}}]
}
The position number will remain unchanged if it is already in the highest position.
"""
def move_higher(list, original_element) do
insert_at(list,original_element, original_element.position - 1)
end
@doc ~S"""
Moves the `original_element` to the bottom of the list.
* `list` - A `List` where each element is a `Map` or `Struct` that contains a `:position` key.
* `original_element` - A `Map` or `Struct` that is contained within the `list` in the first argument
Example:
iex> original_list = [%{id: 1, position: 1},%{id: 2, position: 2}, %{id: 3, position: 3},%{id: 4, position: 4},%{id: 5, position: 5}]
iex> OrderedList.move_to_bottom(original_list, %{id: 1, position: 1})
{
#Unchanged
[],
#Changed
[
{%{id: 1, position: 1}, %{position: 5}},
{%{id: 2, position: 2}, %{position: 1}},
{%{id: 3, position: 3}, %{position: 2}},
{%{id: 4, position: 4}, %{position: 3}},
{%{id: 5, position: 5}, %{position: 4}}
]
}
The position number will remain unchanged if it is already in the lowest position.
"""
def move_to_bottom(list, original_element) do
max = Enum.max_by(list, &(&1.position))
insert_at(list, original_element, max.position)
end
@doc ~S"""
Moves the `original_element` to the top of the list.
* `list` - A `List` where each element is a `Map` or `Struct` that contains a `:position` key.
* `original_element` - A `Map` or `Struct` that is contained within the `list` in the first argument
Example:
iex> original_list = [%{id: 1, position: 1},%{id: 2, position: 2}, %{id: 3, position: 3},%{id: 4, position: 4},%{id: 5, position: 5}]
iex> OrderedList.move_to_top(original_list, %{id: 5, position: 5})
{
#Unchanged
[],
#Changed
[
{%{id: 1, position: 1}, %{position: 2}},
{%{id: 2, position: 2}, %{position: 3}},
{%{id: 3, position: 3}, %{position: 4}},
{%{id: 4, position: 4}, %{position: 5}},
{%{id: 5, position: 5}, %{position: 1}}
]
}
The position number will remain unchanged if it is already in the highest position.
"""
def move_to_top(list, original_element) do
min = Enum.min_by(list, &(&1.position))
insert_at(list, original_element, min.position)
end
@doc ~S"""
Returns a `Tuple` that contain two elements, the first being the item to be
removed and the second a `Tuple` containing the changes to positions that
have been effected by the removal of the element.
* `list` - A `List` where each element is a `Map` or `Struct` that contains a `:position` key.
* `original_element` - A `Map` or `Struct` that is contained within the `list` in the first argument
Example:
iex> original_list = [%{id: 1, position: 1},%{id: 2, position: 2}, %{id: 3, position: 3},%{id: 4, position: 4},%{id: 5, position: 5}]
iex> OrderedList.remove_from_list(original_list, %{id: 3, position: 3})
{
#Remove
%{id: 3, position: 3},
{
#Unchanged
[%{id: 1, position: 1}, %{id: 2, position: 2}],
#Changed
[
{%{id: 4, position: 4}, %{position: 3}},
{%{id: 5, position: 5}, %{position: 4}}
]
}
}
"""
def remove_from_list(list, original_element) do
{ delete, keep } = Enum.partition(list, &(&1.position == original_element.position))
{ reorder, keep} = Enum.partition(keep, &(&1.position > original_element.position))
reorder = decrement_positions(reorder)
{ List.first(delete), {keep,reorder} }
end
@doc ~S"""
Returns a `boolean` value if the element is in the first `:position` in the list.
* `list` - A `List` where each element is a `Map` or `Struct` that contains a `:position` key.
* `original_element` - A `Map` or `Struct` that is contained within the `list` in the first argument
Example:
iex> original_list = [%{id: 1, position: 1},%{id: 2, position: 2}, %{id: 3, position: 3},%{id: 4, position: 4},%{id: 5, position: 5}]
iex> OrderedList.first?(original_list, %{id: 1, position: 1})
true
iex> OrderedList.first?(original_list, %{id: 2, position: 2})
false
"""
def first?(_list, original_element) do
original_element.position == 1
end
@doc ~S"""
Returns a `boolean` value if the element is in the last `:position` in the list.
* `list` - A `List` where each element is a `Map` or `Struct` that contains a `:position` key.
* `original_element` - A `Map` or `Struct` that is contained within the `list` in the first argument
Example:
iex> original_list = [%{id: 1, position: 1},%{id: 2, position: 2}, %{id: 3, position: 3},%{id: 4, position: 4},%{id: 5, position: 5}]
iex> OrderedList.last?(original_list, %{id: 5, position: 5})
true
iex> OrderedList.last?(original_list, %{id: 4, position: 4})
false
"""
def last?(list, original_element) do
Enum.max_by(list, &(&1.position)).position == original_element.position
end
#private
defp reorder_list(list,element,new_position) do
{ reorder, ordered } = Enum.partition(list, &(&1.position in element.position..new_position))
reorder = Enum.filter(reorder, &(&1.position != element.position))
reorder =
case element.position > new_position do
true -> increment_positions(reorder)
false -> decrement_positions(reorder)
end
element = { element, %{ position: new_position } }
{ordered, Enum.sort_by(reorder ++ [element], &(elem(&1, 0).position))}
end
defp valid_new_position?(list, element, new_position) do
element.position != new_position &&
!(first?(list, element) && new_position < 1) &&
!(last?(list, element) && new_position > element.position)
end
defp increment_positions(list) do
Enum.map(list, fn(list_item) -> { list_item, %{ position: list_item.position + 1 } } end)
end
defp decrement_positions(list) do
Enum.map(list, fn(list_item) -> { list_item, %{ position: list_item.position - 1 } } end)
end
end
|
lib/ordered_list.ex
| 0.865736 | 0.834542 |
ordered_list.ex
|
starcoder
|
defmodule Andi.InputSchemas.DatasetInput do
@moduledoc """
Module for validating Ecto.Changesets on flattened dataset input.
"""
import Ecto.Changeset
alias Andi.DatasetCache
alias Andi.InputSchemas.DatasetSchemaValidator
alias Andi.InputSchemas.Options
@business_fields %{
benefitRating: :float,
contactEmail: :string,
contactName: :string,
dataTitle: :string,
description: :string,
homepage: :string,
issuedDate: :date,
keywords: {:array, :string},
language: :string,
license: :string,
modifiedDate: :date,
orgTitle: :string,
publishFrequency: :string,
riskRating: :float,
spatial: :string,
temporal: :string
}
@technical_fields %{
dataName: :string,
orgName: :string,
private: :boolean,
schema: {:array, :map},
sourceFormat: :string,
sourceType: :string,
sourceUrl: :string,
topLevelSelector: :string
}
@types %{id: :string}
|> Map.merge(@business_fields)
|> Map.merge(@technical_fields)
@required_fields [
:benefitRating,
:contactEmail,
:contactName,
:dataName,
:dataTitle,
:description,
:issuedDate,
:license,
:orgName,
:orgTitle,
:private,
:publishFrequency,
:riskRating,
:sourceFormat,
:sourceType,
:sourceUrl
]
@email_regex ~r/^[A-Za-z0-9._%+-+']+@[A-Za-z0-9.-]+\.[A-Za-z]+$/
@no_dashes_regex ~r/^[^\-]+$/
@ratings Map.keys(Options.ratings())
def business_keys(), do: Map.keys(@business_fields)
def technical_keys(), do: Map.keys(@technical_fields)
def all_keys(), do: Map.keys(@types)
def light_validation_changeset(changes), do: light_validation_changeset(%{}, changes)
def light_validation_changeset(schema, changes) do
{schema, @types}
|> cast(changes, Map.keys(@types), empty_values: [])
|> validate_required(@required_fields, message: "is required")
|> validate_format(:contactEmail, @email_regex)
|> validate_format(:orgName, @no_dashes_regex, message: "cannot contain dashes")
|> validate_format(:dataName, @no_dashes_regex, message: "cannot contain dashes")
|> validate_inclusion(:benefitRating, @ratings, message: "should be one of #{inspect(@ratings)}")
|> validate_inclusion(:riskRating, @ratings, message: "should be one of #{inspect(@ratings)}")
|> validate_top_level_selector()
|> validate_schema()
end
def full_validation_changeset(changes), do: full_validation_changeset(%{}, changes)
def full_validation_changeset(schema, changes) do
light_validation_changeset(schema, changes) |> validate_unique_system_name()
end
defp validate_unique_system_name(changeset) do
if has_unique_data_and_org_name?(changeset) do
changeset
else
add_error(changeset, :dataName, "existing dataset has the same orgName and dataName")
end
end
defp has_unique_data_and_org_name?(%{changes: changes}) do
DatasetCache.get_all()
|> Enum.filter(&Map.has_key?(&1, "dataset"))
|> Enum.map(& &1["dataset"])
|> Enum.all?(fn existing_dataset ->
changes[:orgName] != existing_dataset.technical.orgName ||
changes[:dataName] != existing_dataset.technical.dataName ||
changes[:id] == existing_dataset.id
end)
end
defp validate_top_level_selector(%{changes: %{sourceFormat: source_format}} = changeset)
when source_format in ["xml", "text/xml"] do
validate_required(changeset, [:topLevelSelector], message: "is required")
end
defp validate_top_level_selector(changeset), do: changeset
defp validate_schema(%{changes: %{sourceType: source_type}} = changeset)
when source_type in ["ingest", "stream"] do
case Map.get(changeset.changes, :schema) do
[] -> add_error(changeset, :schema, "cannot be empty")
nil -> add_error(changeset, :schema, "is required", validation: :required)
_ -> validate_schema_internals(changeset)
end
end
defp validate_schema(changeset), do: changeset
defp validate_schema_internals(%{changes: changes} = changeset) do
DatasetSchemaValidator.validate(changes[:schema], changes[:sourceFormat])
|> Enum.reduce(changeset, fn error, changeset_acc -> add_error(changeset_acc, :schema, error) end)
end
end
|
apps/andi/lib/andi/input_schemas/dataset_input.ex
| 0.676513 | 0.440349 |
dataset_input.ex
|
starcoder
|
defmodule Mix.Deps.Retriever do
@moduledoc false
@doc """
Gets all direct children of the current `Mix.Project`
as a `Mix.Dep` record. Umbrella project dependencies
are included as children.
"""
def children do
scms = Mix.SCM.available
from = Path.absname("mix.exs")
Enum.map(Mix.project[:deps] || [], &to_dep(&1, scms, from)) ++
Mix.Deps.Umbrella.unloaded
end
@doc """
Loads the given dependency information, including its
latest status and children.
"""
def load(dep) do
Mix.Dep[manager: manager, scm: scm, opts: opts] = dep
dep = dep.status(scm_status(scm, opts))
dest = opts[:dest]
{ dep, children } =
cond do
not ok?(dep.status) ->
{ dep, [] }
manager == :rebar ->
rebar_dep(dep)
mix?(dest) ->
mix_dep(dep.manager(:mix))
rebar?(dest) ->
rebar_dep(dep.manager(:rebar))
make?(dest) ->
{ dep.manager(:make), [] }
true ->
{ dep, [] }
end
{ validate_app(dep), children }
end
@doc """
Checks if a requirement from a dependency matches
the given version.
"""
def vsn_match?(nil, _actual), do: true
def vsn_match?(req, actual) when is_regex(req), do: actual =~ req
def vsn_match?(req, actual) when is_binary(req) do
Version.match?(actual, req)
end
## Helpers
defp to_dep(tuple, scms, from, manager // nil) do
dep = with_scm_and_app(tuple, scms).from(from).manager(manager)
if match?({ _, req, _ } when is_regex(req), tuple) and
not String.ends_with?(from, "rebar.config") do
invalid_dep_format(tuple)
end
dep
end
defp with_scm_and_app({ app, opts }, scms) when is_atom(app) and is_list(opts) do
with_scm_and_app({ app, nil, opts }, scms)
end
defp with_scm_and_app({ app, req, opts }, scms) when is_atom(app) and
(is_binary(req) or is_regex(req) or req == nil) and is_list(opts) do
dest = Path.join(Mix.Project.deps_path, app)
build = Path.join([Mix.Project.build_path, "lib", app])
opts = opts
|> Keyword.put(:dest, dest)
|> Keyword.put(:build, build)
{ scm, opts } = Enum.find_value scms, { nil, [] }, fn(scm) ->
(new = scm.accepts_options(app, opts)) && { scm, new }
end
if scm do
Mix.Dep[
scm: scm,
app: app,
requirement: req,
status: scm_status(scm, opts),
opts: opts
]
else
raise Mix.Error, message: "#{inspect Mix.Project.get} did not specify a supported scm " <>
"for app #{inspect app}, expected one of :git, :path or :in_umbrella"
end
end
defp with_scm_and_app(other, _scms) do
invalid_dep_format(other)
end
defp scm_status(scm, opts) do
if scm.checked_out? opts do
{ :ok, nil }
else
{ :unavailable, opts[:dest] }
end
end
defp ok?({ :ok, _ }), do: true
defp ok?(_), do: false
defp mix?(dest) do
File.regular?(Path.join(dest, "mix.exs"))
end
defp rebar?(dest) do
Enum.any?(["rebar.config", "rebar.config.script"], fn file ->
File.regular?(Path.join(dest, file))
end) or File.regular?(Path.join(dest, "rebar"))
end
defp make?(dest) do
File.regular? Path.join(dest, "Makefile")
end
defp invalid_dep_format(dep) do
raise Mix.Error, message: %s(Dependency specified in the wrong format: #{inspect dep}, ) <>
%s(expected { app :: atom, opts :: Keyword.t } | { app :: atom, requirement :: String.t, opts :: Keyword.t })
end
## Fetching
defp mix_dep(Mix.Dep[opts: opts] = dep) do
Mix.Deps.in_dependency(dep, fn _ ->
config = Mix.project
umbrella? = Mix.Project.umbrella?
if umbrella? do
opts = Keyword.put_new(opts, :app, false)
end
if req = old_elixir_req(config) do
dep = dep.status({ :elixirreq, req })
end
{ dep.manager(:mix).opts(opts).extra(umbrella: umbrella?), children }
end)
end
defp rebar_dep(Mix.Dep[] = dep) do
Mix.Deps.in_dependency(dep, fn _ ->
rebar = Mix.Rebar.load_config(".")
extra = Dict.take(rebar, [:sub_dirs])
{ dep.manager(:rebar).extra(extra), rebar_children(rebar) }
end)
end
defp rebar_children(root_config) do
scms = Mix.SCM.available
from = Path.absname("rebar.config")
Mix.Rebar.recur(root_config, fn config ->
Mix.Rebar.deps(config) |> Enum.map(&to_dep(&1, scms, from, :rebar))
end) |> Enum.concat
end
defp validate_app(Mix.Dep[opts: opts, requirement: req, app: app, status: status] = dep) do
opts_app = opts[:app]
if not ok?(status) or opts_app == false do
dep
else
path = if is_binary(opts_app), do: opts_app, else: "ebin/#{app}.app"
path = Path.expand(path, opts[:build])
dep.status app_status(path, app, req)
end
end
defp app_status(app_path, app, req) do
case :file.consult(app_path) do
{ :ok, [{ :application, ^app, config }] } ->
case List.keyfind(config, :vsn, 0) do
{ :vsn, actual } when is_list(actual) ->
actual = iolist_to_binary(actual)
if vsn_match?(req, actual) do
{ :ok, actual }
else
{ :nomatchvsn, actual }
end
{ :vsn, actual } ->
{ :invalidvsn, actual }
nil ->
{ :invalidvsn, nil }
end
{ :ok, _ } -> { :invalidapp, app_path }
{ :error, _ } -> { :noappfile, app_path }
end
end
defp old_elixir_req(config) do
req = config[:elixir]
if req && not Version.match?(System.version, req) do
req
end
end
end
|
lib/mix/lib/mix/deps/retriever.ex
| 0.731155 | 0.407274 |
retriever.ex
|
starcoder
|
defmodule ExUssd.Op do
@moduledoc false
alias ExUssd.{Display, Utils}
@allowed_fields [
:error,
:title,
:next,
:previous,
:should_close,
:split,
:delimiter,
:default_error,
:show_navigation,
:data,
:resolve,
:orientation,
:name,
:nav
]
@doc """
Add menu to ExUssd menu list.
"""
@spec add(ExUssd.t(), ExUssd.t() | [ExUssd.t()], keyword()) :: ExUssd.t()
def add(_, _, opts \\ [])
def add(%ExUssd{} = menu, %ExUssd{} = child, _opts) do
fun = fn
%ExUssd{data: data} = menu, %ExUssd{navigate: navigate} = child
when is_function(navigate, 2) ->
Map.get_and_update(menu, :menu_list, fn menu_list ->
{:ok, [%{child | data: data} | menu_list]}
end)
menu, child ->
Map.get_and_update(menu, :menu_list, fn menu_list -> {:ok, [child | menu_list]} end)
end
with {:ok, menu} <- apply(fun, [menu, child]), do: menu
end
def add(%ExUssd{} = menu, menus, opts) do
resolve = Keyword.get(opts, :resolve)
fun = fn
_menu, menus, _ when not is_list(menus) ->
{:error, "menus should be a list, found #{inspect(menus)}"}
_menu, menus, _ when menus == [] ->
{:error, "menus should not be empty, found #{inspect(menu)}"}
%ExUssd{orientation: :vertical}, _menus, nil ->
{:error, "resolve callback not found in opts keyword list"}
%ExUssd{} = menu, menus, resolve ->
if Enum.all?(menus, &is_struct(&1, ExUssd)) do
menu_list = Enum.map(menus, fn menu -> Map.put(menu, :resolve, resolve) end)
Map.put(menu, :menu_list, Enum.reverse(menu_list))
else
{:error, "menus should be a list of ExUssd menus, found #{inspect(menus)}"}
end
end
with {:error, message} <- apply(fun, [menu, menus, resolve]) do
raise %ArgumentError{message: message}
end
end
@doc """
Teminates session the gateway session id.
```elixir
iex> ExUssd.end_session(session_id: "sn1")
```
"""
@spec end_session(keyword()) :: no_return()
def end_session(session_id: session_id) do
ExUssd.Registry.stop(session_id)
end
@doc """
`ExUssd.goto/1` is called when the gateway provider calls the callback URL.
Returns
menu_string: to be used as gateway response string.
should_close: indicates if the gateway should close the session.
"""
@spec goto(map() | keyword()) :: {:ok, %{menu_string: String.t(), should_close: boolean()}}
def goto(opts)
def goto(fields) when is_list(fields),
do: goto(Enum.into(fields, %{}))
def goto(%{
payload: %{text: _, session_id: session, service_code: _} = payload,
menu: menu
}) do
payload
|> ExUssd.Route.get_route()
|> ExUssd.Navigation.navigate(menu, payload)
|> ExUssd.Display.to_string(ExUssd.Registry.fetch_state(session), Keyword.new(payload))
end
def goto(%{
payload: %{"text" => _, "session_id" => _, "service_code" => _} = payload,
menu: menu
}) do
goto(%{payload: Utils.format(payload), menu: menu})
end
def goto(%{payload: %{"session_id" => _, "service_code" => _} = payload, menu: _}) do
message = "'text' not found in payload #{inspect(payload)}"
raise %ArgumentError{message: message}
end
def goto(%{payload: %{"text" => _, "service_code" => _} = payload, menu: _}) do
message = "'session_id' not found in payload #{inspect(payload)}"
raise %ArgumentError{message: message}
end
def goto(%{payload: %{"text" => _, "session_id" => _} = payload, menu: _}) do
message = "'service_code' not found in payload #{inspect(payload)}"
raise %ArgumentError{message: message}
end
def goto(%{payload: payload, menu: _}) do
message = "'text', 'service_code', 'session_id', not found in payload #{inspect(payload)}"
raise %ArgumentError{message: message}
end
@doc """
Returns the ExUssd struct for the given keyword list opts.
"""
@spec new(String.t(), fun()) :: ExUssd.t()
def new(name, fun) when is_function(fun, 2) and is_bitstring(name) do
ExUssd.new(navigate: fun, name: name)
end
def new(name, fun) when is_function(fun, 2) do
raise ArgumentError, "`name` must be a string, #{inspect(name)}"
end
def new(_name, fun) do
raise ArgumentError, "expected a function with arity of 2, found #{inspect(fun)}"
end
@spec new(fun()) :: ExUssd.t()
def new(fun) when is_function(fun, 2) do
ExUssd.new(navigate: fun, name: "")
end
@spec new(keyword()) :: ExUssd.t()
def new(opts) do
fun = fn opts ->
if Keyword.keyword?(opts) do
{_, opts} =
Keyword.get_and_update(
opts,
:name,
&{&1, Utils.truncate(&1, length: 140, omission: "...")}
)
struct!(
ExUssd,
Keyword.take(opts, [:data, :resolve, :name, :orientation, :navigate, :is_zero_based])
)
end
end
with {:error, message} <- apply(fun, [opts]) |> validate_new(opts) do
raise %ArgumentError{message: message}
end
end
@doc """
Sets the allowed fields on ExUssd struct.
"""
@spec set(ExUssd.t(), keyword()) :: ExUssd.t()
def set(menu, opts)
def set(%ExUssd{} = menu, nav: %ExUssd.Nav{type: type} = nav)
when type in [:home, :next, :back] do
case Enum.find_index(menu.nav, fn nav -> nav.type == type end) do
nil ->
menu
index ->
Map.put(menu, :nav, List.update_at(menu.nav, index, fn _ -> nav end))
end
end
def set(%ExUssd{resolve: existing_resolve} = menu, resolve: resolve)
when not is_nil(existing_resolve) do
%{menu | navigate: resolve}
end
def set(%ExUssd{resolve: nil} = menu, resolve: resolve)
when is_function(resolve) or is_atom(resolve) do
%{menu | resolve: resolve}
end
def set(%ExUssd{resolve: nil}, resolve: resolve) do
raise %ArgumentError{
message: "resolve should be a function or a resolver module, found #{inspect(resolve)}"
}
end
def set(%ExUssd{}, nav: %ExUssd.Nav{type: type}) do
raise %ArgumentError{message: "nav has unknown type #{inspect(type)}"}
end
def set(%ExUssd{} = menu, nav: nav) when is_list(nav) do
if Enum.all?(nav, &is_struct(&1, ExUssd.Nav)) do
Map.put(menu, :nav, Enum.uniq_by(nav ++ menu.nav, fn n -> n.type end))
else
raise %ArgumentError{
message: "nav should be a list of ExUssd.Nav struct, found #{inspect(nav)}"
}
end
end
def set(%ExUssd{} = menu, opts) do
fun = fn menu, opts ->
if MapSet.subset?(MapSet.new(Keyword.keys(opts)), MapSet.new(@allowed_fields)) do
Map.merge(menu, Enum.into(opts, %{}))
end
end
with nil <- apply(fun, [menu, opts]) do
message =
"Expected field in allowable fields #{inspect(@allowed_fields)} found #{inspect(Keyword.keys(opts))}"
raise %ArgumentError{message: message}
end
end
@doc """
Returns Menu string for the given ExUssd struct.
"""
@spec to_string(ExUssd.t(), keyword()) ::
{:ok, %{:menu_string => binary(), :should_close => boolean()}} | {:error, String.t()}
def to_string(%ExUssd{} = menu, opts) do
case Utils.get_menu(menu, opts) do
%ExUssd{} = menu ->
Display.to_string(menu, ExUssd.Route.get_route(%{text: "*test#", service_code: "*test#"}))
_ ->
{:error, "Couldn't convert #{inspect(menu)} to_string"}
end
end
@spec to_string(ExUssd.t(), atom, keyword()) ::
{:ok, %{:menu_string => binary(), :should_close => boolean()}} | {:error, String.t()}
def to_string(%ExUssd{} = menu, atom, opts) do
if Keyword.get(opts, :simulate) do
raise %ArgumentError{message: "simulate is not supported, Use ExUssd.to_string/2"}
end
case Utils.get_menu(menu, atom, opts) do
%ExUssd{} = menu ->
Display.to_string(menu, ExUssd.Route.get_route(%{text: "*test#", service_code: "*test#"}))
_ ->
{:error, "Couldn't convert to_string for callback #{inspect(atom)}"}
end
end
@spec to_string!(ExUssd.t(), keyword()) :: String.t()
def to_string!(%ExUssd{} = menu, opts) do
case to_string(menu, opts) do
{:ok, %{menu_string: menu_string}} -> menu_string
{:error, error} -> raise ArgumentError, error
end
end
@spec to_string!(ExUssd.t(), atom, keyword()) :: String.t()
def to_string!(%ExUssd{} = menu, atom, opts) do
case to_string(menu, atom, opts) do
{:ok, %{menu_string: menu_string}} -> menu_string
{:error, error} -> raise ArgumentError, error
end
end
@spec validate_new(nil | ExUssd.t(), any()) :: ExUssd.t() | {:error, String.t()}
defp validate_new(menu, opts)
defp validate_new(nil, opts) do
{:error,
"Expected a keyword list opts or callback function with arity of 2, found #{inspect(opts)}"}
end
defp validate_new(%ExUssd{orientation: orientation} = menu, opts)
when orientation in [:vertical, :horizontal] do
fun = fn opts, key ->
if not Keyword.has_key?(opts, key) do
{:error, "Expected #{inspect(key)} in opts, found #{inspect(Keyword.keys(opts))}"}
end
end
Enum.reduce_while([:name], menu, fn key, _ ->
case apply(fun, [opts, key]) do
nil -> {:cont, menu}
error -> {:halt, error}
end
end)
end
defp validate_new(%ExUssd{orientation: orientation}, _opts) do
{:error, "Unknown orientation value, #{inspect(orientation)}"}
end
end
|
lib/ex_ussd/op.ex
| 0.671363 | 0.690331 |
op.ex
|
starcoder
|
defmodule Absinthe.Type.Field do
alias Absinthe.Type
@moduledoc """
Used to define a field.
Usually these are defined using `Absinthe.Schema.Notation.field/4`
See the `t` type below for details and examples of how to define a field.
"""
alias Absinthe.Type
alias Absinthe.Type.Deprecation
alias Absinthe.Schema
use Type.Fetch
@typedoc """
A resolver function.
See the `Absinthe.Type.Field.t` explanation of `:resolve` for more information.
"""
@type resolver_t :: (%{atom => any}, Absinthe.Resolution.t() -> result)
@typedoc """
The result of a resolver.
"""
@type result :: ok_result | error_result | middleware_result
@typedoc """
A complexity function.
See the `Absinthe.Type.Field/t` explanation of `:complexity` for more
information.
"""
@type complexity_t ::
(%{atom => any}, non_neg_integer -> non_neg_integer)
| (%{atom => any}, non_neg_integer, Absinthe.Complexity.t() -> non_neg_integer)
| {module, atom}
| non_neg_integer
@type ok_result :: {:ok, any}
@type error_result :: {:error, error_value}
@type middleware_result :: {:middleware, Absinthe.Middleware.spec(), term}
@typedoc """
An error message is a human-readable string describing the error that occurred.
"""
@type error_message :: String.t()
@typedoc """
Any serializable value.
"""
@type serializable :: any
@typedoc """
A custom error may be a `map` or a `Keyword.t`, but must contain a `:message` key.
Note that the values that make up a custom error must be serializable.
"""
@type custom_error ::
%{required(:message) => error_message, optional(atom) => serializable} | Keyword.t()
@typedoc """
An error value is a simple error message, a custom error, or a list of either/both of them.
"""
@type error_value ::
error_message | custom_error | [error_message | custom_error] | serializable
@typedoc """
The configuration for a field.
* `:name` - The name of the field, usually assigned automatically by
the `Absinthe.Schema.Notation.field/4`. Including this option will bypass the snake_case to camelCase conversion.
* `:description` - Description of a field, useful for introspection.
* `:deprecation` - Deprecation information for a field, usually
set-up using `Absinthe.Schema.Notation.deprecate/1`.
* `:type` - The type the value of the field should resolve to
* `:args` - The arguments of the field, usually created by using `Absinthe.Schema.Notation.arg/2`.
* `:resolve` - The resolution function. See below for more information.
* `:complexity` - The complexity function. See below for more information.
* `:default_value` - The default value of a field. Note this is not used during resolution; only fields that are part of an `Absinthe.Type.InputObject` should set this value.
## Resolution Functions
### Default
If no resolution function is given, the default resolution function is used,
which is roughly equivalent to this:
{:ok, Map.get(parent_object, field_name)}
This is commonly use when listing the available fields on a
`Absinthe.Type.Object` that models a data record. For instance:
```
object :person do
description "A person"
field :first_name, :string
field :last_name, :string
end
```
### Custom Resolution
When accepting arguments, however, you probably need to use them for
something. Here's an example of defining a field that looks up a list of
users for a given `location_id`:
```
query do
field :users, :person do
arg :location_id, non_null(:id)
resolve fn %{location_id: id}, _ ->
{:ok, MyApp.users_for_location_id(id)}
end
end
end
```
Custom resolution functions are passed two arguments:
1. A map of the arguments for the field, filled in with values from the
provided query document/variables.
2. An `Absinthe.Resolution` struct, containing the execution environment
for the field (and useful for complex resolutions using the resolved source
object, etc)
## Complexity function
### Default
If no complexity function is given, the default complexity function is used,
which is equivalent to:
fn(_, child_complexity) -> 1 + child_complexity end
### Custom Complexity
When accepting arguments, however, you probably need to use them for
something. Here's an example of defining a field that looks up at most
`limit` users:
```
query do
field :users, :person do
arg :limit, :integer
complexity fn %{limit: limit}, child_complexity ->
10 + limit * child_complexity
end
end
end
```
An optional third argument, `Absinthe.Complexity` struct, provides extra
information. Here's an example of changing the complexity using the context:
```
query do
field :users, :person do
arg :limit, :integer
complexity fn _, child_complexity, %{context: %{admin: admin?}} ->
if admin?, do: 0, else: 10 + limit * child_complexity
end
end
end
```
Custom complexity functions are passed two or three arguments:
1. A map of the arguments for the field, filled in with values from the
provided query document/variables.
2. A non negative integer, which is total complexity of the child fields.
3. An `Absinthe.Complexity` struct with information about the context of the
field. This argument is optional when using an anonymous function.
Alternatively complexity can be an integer greater than or equal to 0:
```
query do
field :users, :person do
complexity 10
end
end
```
"""
@type t :: %__MODULE__{
identifier: atom,
name: binary,
description: binary | nil,
type: Type.identifier_t(),
deprecation: Deprecation.t() | nil,
default_value: any,
args: %{(binary | atom) => Absinthe.Type.Argument.t()} | nil,
middleware: [],
complexity: complexity_t | nil,
__private__: Keyword.t(),
definition: module,
__reference__: Type.Reference.t()
}
defstruct identifier: nil,
name: nil,
description: nil,
type: nil,
deprecation: nil,
args: %{},
# used by subscription fields
config: nil,
# used by mutation fields
triggers: [],
middleware: [],
complexity: nil,
default_value: nil,
__private__: [],
definition: nil,
__reference__: nil
@doc false
defdelegate functions, to: Absinthe.Blueprint.Schema.FieldDefinition
defimpl Absinthe.Traversal.Node do
def children(node, traversal) do
found = Schema.lookup_type(traversal.context, node.type)
if found do
[found | node.args |> Map.values()]
else
type_names = traversal.context.types.by_identifier |> Map.keys() |> Enum.join(", ")
raise "Unknown Absinthe type for field `#{node.name}': (#{node.type |> Type.unwrap()} not in available types, #{
type_names
})"
end
end
end
end
|
lib/absinthe/type/field.ex
| 0.946745 | 0.896704 |
field.ex
|
starcoder
|
defmodule AWS.Budgets do
@moduledoc """
Budgets enable you to plan your service usage, service costs, and your RI
utilization. You can also track how close your plan is to your budgeted
amount or to the free tier limits. Budgets provide you with a quick way to
see your usage-to-date and current estimated charges from AWS and to see
how much your predicted usage accrues in charges by the end of the month.
Budgets also compare current estimates and charges to the amount that you
indicated you want to use or spend and lets you see how much of your budget
has been used. AWS updates your budget status several times a day. Budgets
track your unblended costs, subscriptions, and refunds. You can create the
following types of budgets:
<ul> <li> Cost budgets allow you to say how much you want to spend on a
service.
</li> <li> Usage budgets allow you to say how many hours you want to use
for one or more services.
</li> <li> RI utilization budgets allow you to define a utilization
threshold and receive alerts when RIs are tracking below that threshold.
</li> </ul> You can create up to 20,000 budgets per AWS master account.
Your first two budgets are free of charge. Each additional budget costs
$0.02 per day. You can set up optional notifications that warn you if you
exceed, or are forecasted to exceed, your budgeted amount. You can have
notifications sent to an Amazon SNS topic, to an email address, or to both.
For more information, see [Creating an Amazon SNS Topic for Budget
Notifications](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/budgets-sns-policy.html).
AWS Free Tier usage alerts via AWS Budgets are provided for you, and do not
count toward your budget limits.
Service Endpoint
The AWS Budgets API provides the following endpoint:
<ul> <li> https://budgets.us-east-1.amazonaws.com
</li> </ul>
"""
@doc """
Creates a budget and, if included, notifications and subscribers.
"""
def create_budget(client, input, options \\ []) do
request(client, "CreateBudget", input, options)
end
@doc """
Creates a notification. You must create the budget before you create the
associated notification.
"""
def create_notification(client, input, options \\ []) do
request(client, "CreateNotification", input, options)
end
@doc """
Creates a subscriber. You must create the associated budget and
notification before you create the subscriber.
"""
def create_subscriber(client, input, options \\ []) do
request(client, "CreateSubscriber", input, options)
end
@doc """
Deletes a budget. You can delete your budget at any time.
**Deleting a budget also deletes the notifications and subscribers
associated with that budget.**
"""
def delete_budget(client, input, options \\ []) do
request(client, "DeleteBudget", input, options)
end
@doc """
Deletes a notification.
**Deleting a notification also deletes the subscribers associated with the
notification.**
"""
def delete_notification(client, input, options \\ []) do
request(client, "DeleteNotification", input, options)
end
@doc """
Deletes a subscriber.
**Deleting the last subscriber to a notification also deletes the
notification.**
"""
def delete_subscriber(client, input, options \\ []) do
request(client, "DeleteSubscriber", input, options)
end
@doc """
Describes a budget.
"""
def describe_budget(client, input, options \\ []) do
request(client, "DescribeBudget", input, options)
end
@doc """
Lists the budgets associated with an account.
"""
def describe_budgets(client, input, options \\ []) do
request(client, "DescribeBudgets", input, options)
end
@doc """
Lists the notifications associated with a budget.
"""
def describe_notifications_for_budget(client, input, options \\ []) do
request(client, "DescribeNotificationsForBudget", input, options)
end
@doc """
Lists the subscribers associated with a notification.
"""
def describe_subscribers_for_notification(client, input, options \\ []) do
request(client, "DescribeSubscribersForNotification", input, options)
end
@doc """
Updates a budget. You can change every part of a budget except for the
`budgetName` and the `calculatedSpend`. When a budget is modified, the
`calculatedSpend` drops to zero until AWS has new usage data to use for
forecasting.
"""
def update_budget(client, input, options \\ []) do
request(client, "UpdateBudget", input, options)
end
@doc """
Updates a notification.
"""
def update_notification(client, input, options \\ []) do
request(client, "UpdateNotification", input, options)
end
@doc """
Updates a subscriber.
"""
def update_subscriber(client, input, options \\ []) do
request(client, "UpdateSubscriber", input, options)
end
@spec request(map(), binary(), map(), list()) ::
{:ok, Poison.Parser.t | nil, Poison.Response.t} |
{:error, Poison.Parser.t} |
{:error, HTTPoison.Error.t}
defp request(client, action, input, options) do
client = %{client | service: "budgets"}
host = get_host("budgets", client)
url = get_url(host, client)
headers = [{"Host", host},
{"Content-Type", "application/x-amz-json-1.1"},
{"X-Amz-Target", "AWSBudgetServiceGateway.#{action}"}]
payload = Poison.Encoder.encode(input, [])
headers = AWS.Request.sign_v4(client, "POST", url, headers, payload)
case HTTPoison.post(url, payload, headers, options) do
{:ok, response=%HTTPoison.Response{status_code: 200, body: ""}} ->
{:ok, nil, response}
{:ok, response=%HTTPoison.Response{status_code: 200, body: body}} ->
{:ok, Poison.Parser.parse!(body), response}
{:ok, _response=%HTTPoison.Response{body: body}} ->
error = Poison.Parser.parse!(body)
exception = error["__type"]
message = error["message"]
{:error, {exception, message}}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, %HTTPoison.Error{reason: reason}}
end
end
defp get_host(endpoint_prefix, client) do
if client.region == "local" do
"localhost"
else
"#{endpoint_prefix}.#{client.region}.#{client.endpoint}"
end
end
defp get_url(host, %{:proto => proto, :port => port}) do
"#{proto}://#{host}:#{port}/"
end
end
|
lib/aws/budgets.ex
| 0.752104 | 0.557123 |
budgets.ex
|
starcoder
|
defmodule Cldr.DateTime.Interval do
@moduledoc """
Interval formats allow for software to format intervals like "Jan 10-12, 2008" as a
shorter and more natural format than "Jan 10, 2008 - Jan 12, 2008". They are designed
to take a start and end date, time or datetime plus a formatting pattern
and use that information to produce a localized format.
See `Cldr.Interval.to_string/3` and `Cldr.DateTime.Interval.to_string/3`
"""
import Cldr.Date.Interval,
only: [
greatest_difference: 2
]
import Cldr.Calendar,
only: [
naivedatetime: 0
]
@default_format :medium
@formats [:short, :medium, :long]
if Cldr.Code.ensure_compiled?(CalendarInterval) do
@doc false
def to_string(%CalendarInterval{} = interval) do
{locale, backend} = Cldr.locale_and_backend_from(nil, nil)
to_string(interval, backend, locale: locale)
end
end
if Cldr.Code.ensure_compiled?(CalendarInterval) do
@doc false
def to_string(%CalendarInterval{} = interval, backend) when is_atom(backend) do
{locale, backend} = Cldr.locale_and_backend_from(nil, backend)
to_string(interval, backend, locale: locale)
end
@doc false
def to_string(%CalendarInterval{} = interval, options) when is_list(options) do
{locale, backend} = Cldr.locale_and_backend_from(options)
to_string(interval, backend, locale: locale)
end
@doc """
Returns a localised string representing the formatted
`CalendarInterval`.
## Arguments
* `range` is a `CalendarInterval.t`
* `backend` is any module that includes `use Cldr` and
is therefore a `Cldr` backend module
* `options` is a keyword list of options. The default is `[]`.
## Options
* `:format` is one of `:short`, `:medium` or `:long` or a
specific format type or a string representing of an interval
format. The default is `:medium`.
* `locale` is any valid locale name returned by `Cldr.known_locale_names/0`
or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`
* `number_system:` a number system into which the formatted date digits should
be transliterated
## Returns
* `{:ok, string}` or
* `{:error, {exception, reason}}`
## Notes
* `CalendarInterval` support requires adding the
dependency [calendar_interval](https://hex.pm/packages/calendar_interval)
to the `deps` configuration in `mix.exs`.
* For more information on interval format string
see the `Cldr.Interval`.
* The available predefined formats that can be applied are the
keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)`
where `"en"` can be replaced by any configuration locale name and `:gregorian`
is the underlying `CLDR` calendar type.
* In the case where `from` and `to` are equal, a single
datetime is formatted instead of an interval
## Examples
iex> Cldr.DateTime.Interval.to_string ~I"2020-01-01 10:00/12:00", MyApp.Cldr
{:ok, "Jan 1, 2020, 10:00:00 AM – 12:00:00 PM"}
"""
@spec to_string(CalendarInterval.t, Cldr.backend(), Keyword.t) ::
{:ok, String.t} | {:error, {module, String.t}}
def to_string(%CalendarInterval{first: from, last: to, precision: precision}, backend, options)
when precision in [:year, :month, :day] do
Cldr.Date.Interval.to_string(from, to, backend, options)
end
def to_string(%CalendarInterval{first: from, last: to, precision: precision}, backend, options)
when precision in [:hour, :minute] do
from = %{from | second: 0, microsecond: {0, 6}}
to = %{to | second: 0, microsecond: {0, 6}}
to_string(from, to, backend, options)
end
def to_string(%CalendarInterval{first: from, last: to, precision: precision}, backend, options)
when precision in [:hour, :minute] do
from = %{from | microsecond: {0, 6}}
to = %{to | microsecond: {0, 6}}
to_string(from, to, backend, options)
end
end
@doc false
def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to) do
{locale, backend} = Cldr.locale_and_backend_from(nil, nil)
to_string(from, to, backend, locale: locale)
end
@doc false
def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to, backend)
when is_atom(backend) do
{locale, backend} = Cldr.locale_and_backend_from(nil, backend)
to_string(from, to, backend, locale: locale)
end
@doc false
def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to, options)
when is_list(options) do
{locale, backend} = Cldr.locale_and_backend_from(options)
to_string(from, to, backend, locale: locale)
end
@doc """
Returns a localised string representing the formatted
interval formed by two dates.
## Arguments
* `from` is any map that conforms to the
`Calendar.datetime` type.
* `to` is any map that conforms to the
`Calendar.datetime` type. `to` must occur
on or after `from`.
* `backend` is any module that includes `use Cldr` and
is therefore a `Cldr` backend module
* `options` is a keyword list of options. The default is `[]`.
## Options
* `:format` is one of `:short`, `:medium` or `:long` or a
specific format type or a string representing of an interval
format. The default is `:medium`.
* `locale` is any valid locale name returned by `Cldr.known_locale_names/0`
or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`
* `number_system:` a number system into which the formatted date digits should
be transliterated
## Returns
* `{:ok, string}` or
* `{:error, {exception, reason}}`
## Notes
* For more information on interval format string
see the `Cldr.Interval`.
* The available predefined formats that can be applied are the
keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)`
where `"en"` can be replaced by any configuration locale name and `:gregorian`
is the underlying `CLDR` calendar type.
* In the case where `from` and `to` are equal, a single
date is formatted instead of an interval
## Examples
iex> Cldr.DateTime.Interval.to_string ~U[2020-01-01 00:00:00.0Z],
...> ~U[2020-12-31 10:00:00.0Z], MyApp.Cldr
{:ok, "Jan 1, 2020, 12:00:00 AM – Dec 31, 2020, 10:00:00 AM"}
"""
@spec to_string(Calendar.datetime, Calendar.datetime, Cldr.backend(), Keyword.t) ::
{:ok, String.t} | {:error, {module, String.t}}
def to_string(from, to, backend, options \\ [])
def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to, backend, options)
when calendar == Calendar.ISO do
from = %{from | calendar: Cldr.Calendar.Gregorian}
to = %{to | calendar: Cldr.Calendar.Gregorian}
to_string(from, to, backend, options)
end
def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to, options, [])
when is_list(options) do
{locale, backend} = Cldr.locale_and_backend_from(options)
to_string(from, to, backend, Keyword.put_new(options, :locale, locale))
end
def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to, backend, options) do
{locale, backend} = Cldr.locale_and_backend_from(options[:locale], backend)
format = Keyword.get(options, :format, @default_format)
locale_number_system = Cldr.Number.System.number_system_from_locale(locale, backend)
number_system = Keyword.get(options, :number_system, locale_number_system)
options =
options
|> Keyword.put(:locale, locale)
|> Keyword.put(:nunber_system, number_system)
with {:ok, _} <- from_less_than_or_equal_to(from, to),
{:ok, backend} <- Cldr.validate_backend(backend),
{:ok, locale} <- Cldr.validate_locale(locale, backend),
{:ok, _} <- Cldr.Number.validate_number_system(locale, number_system, backend),
{:ok, format} <- validate_format(format),
{:ok, calendar} <- Cldr.Calendar.validate_calendar(from.calendar),
{:ok, greatest_difference} <- greatest_difference(from, to) do
options = adjust_options(options, locale, format)
format_date_time(from, to, locale, backend, calendar, greatest_difference, options)
else
{:error, :no_practical_difference} ->
options = adjust_options(options, locale, format)
Cldr.DateTime.to_string(from, backend, options)
other ->
other
end
end
if Cldr.Code.ensure_compiled?(CalendarInterval) do
@doc false
def to_string!(%CalendarInterval{} = range, backend) when is_atom(backend) do
{locale, backend} = Cldr.locale_and_backend_from(nil, backend)
to_string!(range, backend, locale: locale)
end
@doc false
def to_string!(%CalendarInterval{} = range, options) when is_list(options) do
{locale, backend} = Cldr.locale_and_backend_from(options[:locale], nil)
options = Keyword.put_new(options, :locale, locale)
to_string!(range, backend, options)
end
end
if Cldr.Code.ensure_compiled?(CalendarInterval) do
@doc """
Returns a localised string representing the formatted
interval formed by two dates or raises an
exception.
## Arguments
* `from` is any map that conforms to the
`Calendar.datetime` type.
* `to` is any map that conforms to the
`Calendar.datetime` type. `to` must occur
on or after `from`.
* `backend` is any module that includes `use Cldr` and
is therefore a `Cldr` backend module.
* `options` is a keyword list of options. The default is `[]`.
## Options
* `:format` is one of `:short`, `:medium` or `:long` or a
specific format type or a string representing of an interval
format. The default is `:medium`.
* `locale` is any valid locale name returned by `Cldr.known_locale_names/0`
or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`.
* `number_system:` a number system into which the formatted date digits should
be transliterated.
## Returns
* `string` or
* raises an exception
## Notes
* For more information on interval format string
see the `Cldr.Interval`.
* The available predefined formats that can be applied are the
keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)`
where `"en"` can be replaced by any configuration locale name and `:gregorian`
is the underlying `CLDR` calendar type.
* In the case where `from` and `to` are equal, a single
date is formatted instead of an interval
## Examples
iex> use CalendarInterval
iex> Cldr.DateTime.Interval.to_string! ~I"2020-01-01 00:00/10:00", MyApp.Cldr
"Jan 1, 2020, 12:00:00 AM – 10:00:59 AM"
"""
@spec to_string!(CalendarInterval.t, Cldr.backend(), Keyword.t) ::
String.t | no_return
def to_string!(%CalendarInterval{first: from, last: to, precision: precision}, backend, options)
when precision in [:year, :month, :day] do
Cldr.Date.Interval.to_string!(from, to, backend, options)
end
def to_string!(%CalendarInterval{first: from, last: to, precision: precision}, backend, options)
when precision in [:hour, :minute, :second] do
to_string!(from, to, backend, options)
end
end
@doc """
Returns a localised string representing the formatted
interval formed by two dates or raises an
exception.
## Arguments
* `from` is any map that conforms to the
`Calendar.datetime` type.
* `to` is any map that conforms to the
`Calendar.datetime` type. `to` must occur
on or after `from`.
* `backend` is any module that includes `use Cldr` and
is therefore a `Cldr` backend module.
* `options` is a keyword list of options. The default is `[]`.
## Options
* `:format` is one of `:short`, `:medium` or `:long` or a
specific format type or a string representing of an interval
format. The default is `:medium`.
* `locale` is any valid locale name returned by `Cldr.known_locale_names/0`
or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`.
* `number_system:` a number system into which the formatted date digits should
be transliterated.
## Returns
* `string` or
* raises an exception
## Notes
* For more information on interval format string
see the `Cldr.Interval`.
* The available predefined formats that can be applied are the
keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)`
where `"en"` can be replaced by any configuration locale name and `:gregorian`
is the underlying `CLDR` calendar type.
* In the case where `from` and `to` are equal, a single
date is formatted instead of an interval
## Examples
iex> Cldr.DateTime.Interval.to_string! ~U[2020-01-01 00:00:00.0Z],
...> ~U[2020-12-31 10:00:00.0Z], MyApp.Cldr
"Jan 1, 2020, 12:00:00 AM – Dec 31, 2020, 10:00:00 AM"
"""
def to_string!(from, to, backend, options \\ []) do
case to_string(from, to, backend, options) do
{:ok, string} -> string
{:error, {exception, reason}} -> raise exception, reason
end
end
defp from_less_than_or_equal_to(%{time_zone: zone} = from, %{time_zone: zone} = to) do
case DateTime.compare(from, to) do
comp when comp in [:eq, :lt] -> {:ok, comp}
_other -> {:error, Cldr.Date.Interval.datetime_order_error(from, to)}
end
end
defp from_less_than_or_equal_to(%{time_zone: _zone1} = from, %{time_zone: _zone2} = to) do
{:error, Cldr.Date.Interval.datetime_incompatible_timezone_error(from, to)}
end
defp from_less_than_or_equal_to(from, to) do
case NaiveDateTime.compare(from, to) do
comp when comp in [:eq, :lt] -> {:ok, comp}
_other -> {:error, Cldr.Date.Interval.datetime_order_error(from, to)}
end
end
@doc false
def adjust_options(options, locale, format) do
options
|> Keyword.put(:locale, locale)
|> Keyword.put(:format, format)
|> Keyword.delete(:style)
end
defp format_date_time(from, to, locale, backend, calendar, difference, options) do
backend_format = Module.concat(backend, DateTime.Format)
{:ok, calendar} = Cldr.DateTime.type_from_calendar(calendar)
fallback = backend_format.date_time_interval_fallback(locale, calendar)
format = Keyword.fetch!(options, :format)
[from_format, to_format] = extract_format(format)
from_options = Keyword.put(options, :format, from_format)
to_options = Keyword.put(options, :format, to_format)
do_format_date_time(from, to, backend, format, difference, from_options, to_options, fallback)
end
# The difference is only in the time part
defp do_format_date_time(from, to, backend, format, difference, from_opts, to_opts, fallback)
when difference in [:H, :m] do
with {:ok, from_string} <- Cldr.DateTime.to_string(from, backend, from_opts),
{:ok, to_string} <- Cldr.Time.to_string(to, backend, to_opts) do
{:ok, combine_result(from_string, to_string, format, fallback)}
end
end
# The difference is in the date part
# Format each datetime separately and join with
# the interval fallback format
defp do_format_date_time(from, to, backend, format, difference, from_opts, to_opts, fallback)
when difference in [:y, :M, :d] do
with {:ok, from_string} <- Cldr.DateTime.to_string(from, backend, from_opts),
{:ok, to_string} <- Cldr.DateTime.to_string(to, backend, to_opts) do
{:ok, combine_result(from_string, to_string, format, fallback)}
end
end
defp combine_result(left, right, format, _fallback) when is_list(format) do
left <> right
end
defp combine_result(left, right, format, fallback) when is_atom(format) do
[left, right]
|> Cldr.Substitution.substitute(fallback)
|> Enum.join()
end
defp extract_format(format) when is_atom(format) do
[format, format]
end
defp extract_format([from_format, to_format]) do
[from_format, to_format]
end
# Using standard format terms like :short, :medium, :long
defp validate_format(format) when format in @formats do
{:ok, format}
end
# Direct specification of a format as a string
@doc false
defp validate_format(format) when is_binary(format) do
Cldr.DateTime.Format.split_interval(format)
end
@doc false
def format_error(format) do
{
Cldr.DateTime.UnresolvedFormat,
"The interval format #{inspect(format)} is invalid. " <>
"Valid formats are #{inspect(@formats)} or an interval format string.}"
}
end
end
|
lib/cldr/interval/date_time.ex
| 0.939109 | 0.60013 |
date_time.ex
|
starcoder
|
defmodule HubStops do
@moduledoc """
Represents a list of Hub Stops
"""
alias Routes.Route
@commuter_hubs [
{"place-sstat", "/images/stops/south_station",
"Entrances to Red Line and Commuter Rail outside South Station"},
{"place-north", "/images/stops/north_station_commuter",
"People walking by train departure board inside North Station"},
{"place-bbsta", "/images/stops/back_bay", "Lobby inside Back Bay station"}
]
@red_line_hubs [
{"place-sstat", "/images/stops/south_station",
"Entrances to Red Line and Commuter Rail outside South Station"},
{"place-pktrm", "/images/stops/park_street",
"Entrance to Green and Red Lines outside Park Street"},
{"place-dwnxg", "/images/stops/downtown_crossing",
"Entrance to Orange and Red Lines outside Downtown Crossing"}
]
@green_line_hubs [
{"place-north", "/images/stops/north_station_green",
"People walking towards Green Line train inside North Station"},
{"place-pktrm", "/images/stops/park_street",
"Entrance to Green and Red Lines outside Park Street"},
{"place-gover", "/images/stops/government_center",
"Entrance to Blue and Green Lines outside Government Center"}
]
@orange_line_hubs [
{"place-north", "/images/stops/north_station",
"People waiting as orange line train arrives inside North Station"},
{"place-bbsta", "/images/stops/back_bay", "Lobby inside Back Bay station"},
{"place-rugg", "/images/stops/ruggles", "Entrance to Ruggles station"}
]
@blue_line_hubs [
{"place-state", "/images/stops/state_street",
"Blue Line subway platform inside State Street"},
{"place-wondl", "/images/stops/wonderland", "Exterior of Wonderland station"},
{"place-aport", "/images/stops/airport", "Blue Line train departing Airport station"}
]
@hub_map %{
"Red" => @red_line_hubs,
"Blue" => @blue_line_hubs,
"Green" => @green_line_hubs,
"Orange" => @orange_line_hubs
}
@doc """
Returns a list of HubStops for the given mode that are
found in the given list of DetailedStopGroup's
"""
@spec mode_hubs(atom, [DetailedStopGroup.t()]) :: [HubStop.t()]
def mode_hubs(:commuter_rail, route_stop_pairs) do
all_mode_stops = Enum.flat_map(route_stop_pairs, fn {_route, stops} -> stops end)
@commuter_hubs
|> Enum.map(&build_hub_stop(&1, all_mode_stops))
end
def mode_hubs(_mode, _route_stop_pairs) do
[]
end
@doc """
Returns a map of %{route_id -> HubStopList} which represents all
the hubstops for all routes found in the given list of DetailedStopGroup
"""
@spec route_hubs([DetailedStopGroup.t()]) :: %{String.t() => [HubStop.t()]}
def route_hubs(route_stop_pairs) do
Map.new(route_stop_pairs, &do_from_stop_info/1)
end
@spec do_from_stop_info(DetailedStopGroup.t()) :: {String.t(), [HubStop.t()]}
defp do_from_stop_info({%Route{id: route_id}, detailed_stops})
when route_id in ["Red", "Blue", "Green", "Orange"] do
hub_stops =
@hub_map
|> Map.get(route_id)
|> Task.async_stream(&build_hub_stop(&1, detailed_stops))
|> Enum.map(fn {:ok, hub_stop} -> hub_stop end)
{route_id, hub_stops}
end
defp do_from_stop_info({%Route{id: route_id}, _}), do: {route_id, []}
@spec build_hub_stop({String.t(), String.t(), String.t()}, [DetailedStop.t()]) :: HubStop.t()
defp build_hub_stop({stop_id, path, alt_text}, detailed_stops) do
%HubStop{
detailed_stop: Enum.find(detailed_stops, &(&1.stop.id == stop_id)),
image: path,
alt_text: alt_text
}
end
end
|
apps/site/lib/hub_stops.ex
| 0.716417 | 0.462291 |
hub_stops.ex
|
starcoder
|
defmodule Romeo.Stanza do
@moduledoc """
Provides convenience functions for building XMPP stanzas.
"""
use Romeo.XML
@doc """
Converts an `xml` record to an XML binary string.
"""
def to_xml(record) when Record.is_record(record) do
Romeo.XML.encode!(record)
end
def to_xml(record) when Record.is_record(record) do
Romeo.XML.encode!(record)
end
def to_xml(%IQ{} = stanza) do
xmlel(
name: "iq",
attrs: [
{"to", to_string(stanza.to)},
{"type", stanza.type},
{"id", stanza.id}
]
)
|> to_xml
end
def to_xml(%Presence{} = stanza) do
xmlel(
name: "presence",
attrs: [
{"to", to_string(stanza.to)},
{"type", stanza.type}
]
)
|> to_xml
end
def to_xml(%Message{to: to, type: type, body: body}) do
message(to_string(to), type, body) |> to_xml
end
@doc """
Starts an XML stream.
## Example
iex> stanza = Romeo.Stanza.start_stream("im.capulet.lit")
{:xmlstreamstart, "stream:stream",
[{"to", "im.capulet.lit"}, {"version", "1.0"}, {"xml:lang", "en"},
{"xmlns", "jabber:client"},
{"xmlns:stream", "http://etherx.jabber.org/streams"}]}
iex> Romeo.Stanza.to_xml(stanza)
"<stream:stream to='im.capulet.lit' version='1.0' xml:lang='en' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>"
"""
def start_stream(server, xmlns \\ ns_jabber_client()) do
xmlstreamstart(
name: "stream:stream",
attrs: [
{"to", server},
{"version", "1.0"},
{"xml:lang", "en"},
{"xmlns", xmlns},
{"xmlns:stream", ns_xmpp()}
]
)
end
@doc """
Ends the XML stream
## Example
iex> stanza = Romeo.Stanza.end_stream
{:xmlstreamend, "stream:stream"}
iex> Romeo.Stanza.to_xml(stanza)
"</stream:stream>"
"""
def end_stream, do: xmlstreamend(name: "stream:stream")
@doc """
Generates the XML to start TLS.
## Example
iex> stanza = Romeo.Stanza.start_tls
{:xmlel, "starttls", [{"xmlns", "urn:ietf:params:xml:ns:xmpp-tls"}], []}
iex> Romeo.Stanza.to_xml(stanza)
"<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>"
"""
def start_tls do
xmlel(
name: "starttls",
attrs: [
{"xmlns", ns_tls()}
]
)
end
def compress(method) do
xmlel(
name: "compress",
attrs: [
{"xmlns", ns_compress()}
],
children: [
xmlel(name: "method", children: [cdata(method)])
]
)
end
def handshake(hash) do
cdata = xmlcdata(content: hash)
xmlel(name: "handshake", children: [cdata])
end
def auth(mechanism), do: auth(mechanism, [])
def auth(mechanism, body, additional_attrs \\ []) do
xmlel(
name: "auth",
attrs: [
{"xmlns", ns_sasl()},
{"mechanism", mechanism}
| additional_attrs
],
children: [body]
)
end
def bind(resource) do
body =
xmlel(
name: "bind",
attrs: [{"xmlns", ns_bind()}],
children: [
xmlel(
name: "resource",
children: [cdata(resource)]
)
]
)
iq("set", body)
end
def session do
iq("set", xmlel(name: "session", attrs: [{"xmlns", ns_session()}]))
end
def presence do
xmlel(name: "presence")
end
def presence(type) do
xmlel(name: "presence", attrs: [{"type", type}])
end
@doc """
Returns a presence stanza to a given jid, of a given type.
"""
def presence(to, type) do
xmlel(name: "presence", attrs: [{"type", type}, {"to", to}])
end
def iq(type, body) do
xmlel(name: "iq", attrs: [{"type", type}, {"id", id()}], children: [body])
end
def iq(to, type, body) do
iq = iq(type, body)
xmlel(iq, attrs: [{"to", to} | xmlel(iq, :attrs)])
end
def get_roster do
iq("get", xmlel(name: "query", attrs: [{"xmlns", ns_roster()}]))
end
def set_roster_item(jid, subscription \\ "both", name \\ "", group \\ "") do
name_to_set =
case name do
"" -> Romeo.JID.parse(jid).user
_ -> name
end
group_xmlel =
case group do
"" -> []
_ -> [xmlel(name: "group", children: [cdata(group)])]
end
iq(
"set",
xmlel(
name: "query",
attrs: [{"xmlns", ns_roster()}],
children: [
xmlel(
name: "item",
attrs: [
{"jid", jid},
{"subscription", subscription},
{"name", name_to_set}
],
children: group_xmlel
)
]
)
)
end
def get_inband_register do
iq("get", xmlel(name: "query", attrs: [{"xmlns", ns_inband_register()}]))
end
def set_inband_register(username, password) do
iq(
"set",
xmlel(
name: "query",
attrs: [{"xmlns", ns_inband_register()}],
children: [
xmlel(name: "username", children: [cdata(username)]),
xmlel(name: "password", children: [cdata(password)])
]
)
)
end
def get_vcard(to) do
iq(to, "get", xmlel(name: "vCard", attrs: [{"xmlns", ns_vcard()}]))
end
def disco_info(to) do
iq(to, "get", xmlel(name: "query", attrs: [{"xmlns", ns_disco_info()}]))
end
def disco_items(to) do
iq(to, "get", xmlel(name: "query", attrs: [{"xmlns", ns_disco_items()}]))
end
@doc """
Generates a stanza to join a pubsub node. (XEP-0060)
"""
def subscribe(to, node, jid) do
iq(
to,
"set",
xmlel(
name: "pubsub",
attrs: [{"xmlns", ns_pubsub()}],
children: [
xmlel(name: "subscribe", attrs: [{"node", node}, {"jid", jid}])
]
)
)
end
@doc """
Generates a presence stanza to join a MUC room.
## Options
* `password` - the password for a MUC room - if required.
* `history` - used for specifying the amount of old messages to receive once
joined. The value of the `:history` option should be a keyword list of one
of the following:
* `maxchars` - limit the total number of characters in the history.
* `maxstanzas` - limit the total number of messages in the history.
* `seconds` - send only the messages received in the last `n` seconds.
* `since` - send only the messages received since the UTC datetime specified.
See http://xmpp.org/extensions/xep-0045.html#enter-managehistory
for details.
## Examples
iex> Romeo.Stanza.join("lobby<EMAIL>", "hedwigbot")
{:xmlel, "presence", [{"to", "<EMAIL>/hedwigbot"}],
[{:xmlel, "x", [{"xmlns", "http://jabber.org/protocol/muc"}],
[{:xmlel, "history", [{"maxstanzas", "0"}], []}]}]}
"""
def join(room, nickname, opts \\ []) do
history = Keyword.get(opts, :history)
password = Keyword.get(opts, :password)
password = if password, do: [muc_password(password)], else: []
history = if history, do: [history(history)], else: [history(maxstanzas: 0)]
children = history ++ password
xmlel(
name: "presence",
attrs: [
{"to", "#{room}/#{nickname}"}
],
children: [
xmlel(
name: "x",
attrs: [{"xmlns", ns_muc()}],
children: children
)
]
)
end
defp history([{key, value}]) do
xmlel(name: "history", attrs: [{to_string(key), to_string(value)}])
end
defp muc_password(password) do
xmlel(name: "password", children: [xmlcdata(content: password)])
end
def chat(to, body), do: message(to, "chat", body)
def normal(to, body), do: message(to, "normal", body)
def groupchat(to, body), do: message(to, "groupchat", body)
def message(msg) when is_map(msg) do
message(msg["to"], msg["type"], msg["body"])
end
def message(to, type, message) do
xmlel(
name: "message",
attrs: [
{"to", to},
{"type", type},
{"id", id()},
{"xml:lang", "en"}
],
children: generate_body(message)
)
end
def generate_body(data) do
cond do
is_list(data) ->
data
is_tuple(data) ->
[data]
true ->
[body(data)]
end
end
def body(data) do
xmlel(
name: "body",
children: [
cdata(data)
]
)
end
def xhtml_im(data) when is_binary(data) do
data
|> :fxml_stream.parse_element()
|> xhtml_im
end
def xhtml_im(data) do
xmlel(
name: "html",
attrs: [
{"xmlns", ns_xhtml_im()}
],
children: [
xmlel(
name: "body",
attrs: [
{"xmlns", ns_xhtml()}
],
children: [
data
]
)
]
)
end
def cdata(payload) do
xmlcdata(content: payload)
end
def base64_cdata(payload) do
xmlcdata(content: Base.encode64(payload))
end
@doc """
Generates a random hex string for use as an id for a stanza.
"""
def id do
:crypto.strong_rand_bytes(2) |> Base.encode16(case: :lower)
end
end
|
lib/romeo/stanza.ex
| 0.816772 | 0.42674 |
stanza.ex
|
starcoder
|
defmodule Faker.Address do
defdelegate postcode, to: Faker.Address, as: :zip_code
defdelegate zip, to: Faker.Address, as: :zip_code
data_path = Path.expand(Path.join(__DIR__, "../../priv/address.json"))
json = File.read!(data_path) |> Poison.Parser.parse!
Enum.each json, fn(el) ->
{lang, data} = el
Enum.each data, fn
{"values", values} ->
Enum.each values, fn({fun, list}) ->
def unquote(String.to_atom(fun))() do
unquote(String.to_atom("get_#{fun}"))(Faker.locale, :crypto.rand_uniform(0, unquote(String.to_atom("#{fun}_count"))(Faker.locale)))
end
defp unquote(String.to_atom("#{fun}_count"))(unquote(String.to_atom(lang))) do
unquote(Enum.count(list))
end
Enum.with_index(list) |> Enum.each fn({el, index}) ->
defp unquote(String.to_atom("get_#{fun}"))(unquote(String.to_atom(lang)), unquote(index)) do
unquote(el)
end
end
end
{"formats", values} ->
Enum.each values, fn({fun, list}) ->
def unquote(String.to_atom(fun))() do
unquote(String.to_atom("format_#{fun}"))(Faker.locale, :crypto.rand_uniform(0, unquote(String.to_atom("#{fun}_count"))(Faker.locale)))
end
Enum.with_index(list) |> Enum.each fn({el, index}) ->
defp unquote(String.to_atom("format_#{fun}"))(unquote(String.to_atom(lang)), unquote(index)) do
Faker.format(unquote(el))
end
end
defp unquote(String.to_atom("#{fun}_count"))(unquote(String.to_atom(lang))) do
unquote(Enum.count(list))
end
end
{"functions", values} ->
Enum.each values, fn({fun, list}) ->
def unquote(String.to_atom(fun))() do
unquote(String.to_atom(fun))(Faker.locale, :crypto.rand_uniform(0, unquote(String.to_atom("#{fun}_count"))(Faker.locale)))
end
Enum.with_index(list) |> Enum.each fn({el, index}) ->
defp unquote(String.to_atom(fun))(unquote(String.to_atom(lang)), unquote(index)) do
unquote(Code.string_to_quoted!('"#{el}"'))
end
end
defp unquote(String.to_atom("#{fun}_count"))(unquote(String.to_atom(lang))) do
unquote(Enum.count(list))
end
end
end
end
def latitude do
:random.seed(:os.timestamp)
((:random.uniform * 180) - 90)
end
def longitude do
:random.seed(:os.timestamp)
((:random.uniform * 360) - 180)
end
def street_address(true), do: street_address <> " " <> secondary_address
def street_address(_), do: street_address
end
|
lib/faker/address.ex
| 0.527803 | 0.418489 |
address.ex
|
starcoder
|
defmodule Livebook.Utils.ANSI.Modifier do
@moduledoc false
defmacro defmodifier(modifier, code, terminator \\ "m") do
quote bind_quoted: [modifier: modifier, code: code, terminator: terminator] do
defp ansi_prefix_to_modifier(unquote("[#{code}#{terminator}") <> rest) do
{:ok, unquote(modifier), rest}
end
end
end
end
defmodule Livebook.Utils.ANSI do
@moduledoc false
import Livebook.Utils.ANSI.Modifier
@type modifier ::
{:font_weight, :bold | :light}
| {:font_style, :italic}
| {:text_decoration, :underline | :line_through | :overline}
| {:foreground_color, color()}
| {:background_color, color()}
@type color :: basic_color() | {:grayscale24, 0..23} | {:rgb6, 0..5, 0..5, 0..5}
@type basic_color ::
:black
| :red
| :green
| :yellow
| :blue
| :magenta
| :cyan
| :white
| :light_black
| :light_red
| :light_green
| :light_yellow
| :light_blue
| :light_magenta
| :light_cyan
| :light_white
@doc """
Takes a string with ANSI escape codes and parses it
into a list of `{modifiers, string}` parts.
"""
@spec parse_ansi_string(String.t()) :: list({list(modifier()), String.t()})
def parse_ansi_string(string) do
[head | ansi_prefixed_strings] = String.split(string, "\e")
# Each part has the form of {modifiers, string}
{tail_parts, _} =
Enum.map_reduce(ansi_prefixed_strings, %{}, fn string, modifiers ->
{modifiers, rest} =
case ansi_prefix_to_modifier(string) do
{:ok, modifier, rest} ->
modifiers = add_modifier(modifiers, modifier)
{modifiers, rest}
{:error, _rest} ->
{modifiers, "\e" <> string}
end
{{Map.to_list(modifiers), rest}, modifiers}
end)
parts = [{[], head} | tail_parts]
parts
|> Enum.reject(fn {_modifiers, string} -> string == "" end)
|> merge_adjacent_parts([])
end
defp merge_adjacent_parts([], acc), do: Enum.reverse(acc)
defp merge_adjacent_parts([{modifiers, string1}, {modifiers, string2} | parts], acc) do
merge_adjacent_parts([{modifiers, string1 <> string2} | parts], acc)
end
defp merge_adjacent_parts([part | parts], acc) do
merge_adjacent_parts(parts, [part | acc])
end
# Below goes a number of `ansi_prefix_to_modifier` function definitions,
# that take a string like "[32msomething" (starting with ANSI code without the leading "\e")
# and parse the prefix into the corresponding modifier.
# The function returns either {:ok, modifier, rest} or {:error, rest}
defmodifier(:reset, 0)
# When the code is missing (i.e., "\e[m"), it is 0 for reset.
defmodifier(:reset, "")
@colors [:black, :red, :green, :yellow, :blue, :magenta, :cyan, :white]
for {color, index} <- Enum.with_index(@colors) do
defmodifier({:foreground_color, color}, 30 + index)
defmodifier({:background_color, color}, 40 + index)
defmodifier({:foreground_color, :"light_#{color}"}, 90 + index)
defmodifier({:background_color, :"light_#{color}"}, 100 + index)
end
defmodifier({:foreground_color, :reset}, 39)
defmodifier({:background_color, :reset}, 49)
defmodifier({:font_weight, :bold}, 1)
defmodifier({:font_weight, :light}, 2)
defmodifier({:font_style, :italic}, 3)
defmodifier({:text_decoration, :underline}, 4)
defmodifier({:text_decoration, :line_through}, 9)
defmodifier({:font_weight, :reset}, 22)
defmodifier({:font_style, :reset}, 23)
defmodifier({:text_decoration, :reset}, 24)
defmodifier({:text_decoration, :overline}, 53)
defmodifier({:text_decoration, :reset}, 55)
defp ansi_prefix_to_modifier("[38;5;" <> string) do
with {:ok, color, rest} <- bit8_prefix_to_color(string) do
{:ok, {:foreground_color, color}, rest}
end
end
defp ansi_prefix_to_modifier("[48;5;" <> string) do
with {:ok, color, rest} <- bit8_prefix_to_color(string) do
{:ok, {:background_color, color}, rest}
end
end
# "\e(B" is RFC1468's switch to ASCII character set and can be ignored. This
# can appear even when JIS character sets aren't in use.
defp ansi_prefix_to_modifier("(B" <> rest) do
{:ok, :ignored, rest}
end
defp bit8_prefix_to_color(string) do
case Integer.parse(string) do
{n, "m" <> rest} when n in 0..255 ->
color = color_from_code(n)
{:ok, color, rest}
_ ->
{:error, string}
end
end
ignored_codes = [5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 25, 27, 51, 52, 54]
for code <- ignored_codes do
defmodifier(:ignored, code)
end
defmodifier(:ignored, 1, "A")
defmodifier(:ignored, 1, "B")
defmodifier(:ignored, 1, "C")
defmodifier(:ignored, 1, "D")
defmodifier(:ignored, 2, "J")
defmodifier(:ignored, 2, "K")
defmodifier(:ignored, "", "H")
defp ansi_prefix_to_modifier(string), do: {:error, string}
defp color_from_code(code) when code in 0..7 do
Enum.at(@colors, code)
end
defp color_from_code(code) when code in 8..15 do
color = Enum.at(@colors, code - 8)
:"light_#{color}"
end
defp color_from_code(code) when code in 16..231 do
rgb_code = code - 16
b = rgb_code |> rem(6)
g = rgb_code |> div(6) |> rem(6)
r = rgb_code |> div(36)
{:rgb6, r, g, b}
end
defp color_from_code(code) when code in 232..255 do
level = code - 232
{:grayscale24, level}
end
defp add_modifier(modifiers, :ignored), do: modifiers
defp add_modifier(_modifiers, :reset), do: %{}
defp add_modifier(modifiers, {key, :reset}), do: Map.delete(modifiers, key)
defp add_modifier(modifiers, {key, value}), do: Map.put(modifiers, key, value)
end
|
lib/livebook/utils/ansi.ex
| 0.786336 | 0.455259 |
ansi.ex
|
starcoder
|
defmodule Familiar do
@moduledoc """
Helper functions for creating database views and functions - your database's
familiars.
View and function definitions are stored as SQL files in `priv/repo/views` and
`priv/repo/functions` respectively.
Each definition file has the following file name format:
NAME_vNUMBER.sql
The NAME will be the name of the created database object and will be what is
used to refer to it in the functions defined in this module. The NUMBER is the
version number and should be incremented whenever a view or function is
revised. Old versions should be kept and shouldn't be modified once deployed.
A view definition file can be generated using the following mix task:
$ mix familiar.gen.view my_view
## Example
Given the following view definition in `priv/repo/views/active_users_v1.sql`:
SELECT * FROM users
WHERE users.active = TRUE;
The view can be created like so:
defmodule MyRepo.Migrations.CreateActiveUsers do
use Ecto.Migration
use Familiar
def change do
create_view :active_users
end
end
### Updating the view
If we want to update the `active_users` view created above, we can first generate a new version of the view by running:
$ mix familiar.gen.view active_users
And then editing the generated `active_users_v2.sql` as needed. Then the view can be updated in a migration:
defmodule MyRepo.Migrations.UpdateActiveUsers do
use Ecto.Migration
use Familiar
def change do
update_view :active_users, revert: 1
end
end
The `:revert` option is optional however if it is omitted the migration will not be reversible.
The new version number can be specified explicitly if desired:
$ mix familiar.gen.view my_view --version 3
### Non default schema
Definition to be created in the non default schema can be placed in
a subdirectory with the name of the schema. For example
`priv/repo/views/bi/analytics_v1.sql` will create a the `analytics`
view in the `bi` schema.
The `:schema` option then needs to be added to each function call.
The `--schema` option can be also be passed to `familiar.gen.view`.
"""
defmacro __using__(_opts) do
quote do
import Familiar
end
end
@doc """
Creates a new database view from a view definition file.
## Options:
* `:version` - the version of the view to create
* `:materialized` - whether the view is materialized or not. Defaults to `false`.
* `:schema` - the schema to create the view in. Creates in default schema if not specified
"""
def create_view(view_name, opts) do
view_name = normalise_name(view_name)
version = Keyword.fetch!(opts, :version)
materialized = Keyword.get(opts, :materialized, false)
schema = Keyword.get(opts, :schema)
new_sql = read_file(:views, view_name, version, schema)
execute(
create_view_sql(view_name, new_sql, materialized, schema),
drop_view_sql(view_name, materialized, schema)
)
end
@doc """
Updates a database view from a view definition file.
This function will drop the existing view and then create the new version of
the view so dependant views, functions, triggers etc will need to be dropped
first.
## Options:
* `:version` - the version of the updated view
* `:materialized` - whether the view is materialized or not. Defaults to `false`.
* `:revert` - the version to revert to if the migration is rolled back
* `:schema` - the schema the view lives in. Uses default schema if not specified
"""
def update_view(view_name, opts) do
view_name = normalise_name(view_name)
version = Keyword.fetch!(opts, :version)
materialized = Keyword.get(opts, :materialized, false)
schema = Keyword.get(opts, :schema)
revert = Keyword.get(opts, :revert)
new_sql = read_file(:views, view_name, version, schema)
if revert do
old_sql = read_file(:views, view_name, revert, schema)
execute(
drop_and_create_view(view_name, new_sql, materialized, schema),
drop_and_create_view(view_name, old_sql, materialized, schema)
)
else
execute(drop_and_create_view(view_name, new_sql, materialized, schema))
end
end
@doc """
Replaces a database view from a view definition file.
This function will use `CREATE OR REPLACE VIEW` so can only be used if the new
version has the same columns as the old version.
## Options:
* `:version` - the version of the updated view
* `:materialized` - whether the view is materialized or not. Defaults to `false`.
* `:revert` - the version to revert to if the migration is rolled back
* `:schema` - the schema the view lives in. Uses default schema if not specified
"""
def replace_view(view_name, opts) do
view_name = normalise_name(view_name)
version = Keyword.fetch!(opts, :version)
schema = Keyword.get(opts, :schema)
revert = Keyword.get(opts, :revert)
new_sql = read_file(:views, view_name, version, schema)
if revert do
old_sql = read_file(:views, view_name, revert, schema)
execute(
replace_view_sql(view_name, new_sql, schema),
replace_view_sql(view_name, old_sql, schema)
)
else
execute(replace_view_sql(view_name, new_sql, schema))
end
end
@doc """
Drops a database view.
## Options:
* `:materialized` - whether the view is materialized or not. Defaults to `false`.
* `:revert` - the version to create if the migration is rolled back
* `:schema` - the schema the view lives in. Uses default schema if not specified
"""
def drop_view(view_name, opts \\ []) do
revert = Keyword.get(opts, :revert)
view_name = normalise_name(view_name)
schema = Keyword.get(opts, :schema)
materialized = Keyword.get(opts, :materialized, false)
if revert do
sql = read_file(:views, view_name, revert, schema)
execute(
drop_view_sql(view_name, materialized, schema),
create_view_sql(view_name, sql, materialized, schema)
)
else
execute(drop_view_sql(view_name, materialized, schema))
end
end
@doc """
Creates a new database function from a function definition file.
## Options:
* `:version` - the version of the function to create
* `:schema` - the schema to create the function in. Uses default schema if not specified
"""
def create_function(function_name, opts) do
function_name = normalise_name(function_name)
version = Keyword.fetch!(opts, :version)
schema = Keyword.get(opts, :schema)
new_sql = read_file(:functions, function_name, version, schema)
execute(
create_function_sql(function_name, new_sql, schema),
drop_function_sql(function_name, schema)
)
end
@doc """
Updates a new database function from a function definition file.
This function will drop the existing function before creating a new function
so dependant views, functions, triggers etc will need to be dropped first.
## Options:
* `:version` - the version of the updated function
* `:revert` - the version to revert to if the migration is rolled back
* `:schema` - the schema the function lives in. Uses default schema if not specified
"""
def update_function(function_name, opts) do
function_name = normalise_name(function_name)
version = Keyword.fetch!(opts, :version)
schema = Keyword.get(opts, :schema)
revert = Keyword.get(opts, :revert)
new_sql = read_file(:functions, function_name, version, schema)
if revert do
old_sql = read_file(:functions, function_name, revert, schema)
execute(
drop_and_create_function(function_name, new_sql, schema),
drop_and_create_function(function_name, old_sql, schema)
)
else
execute(drop_and_create_function(function_name, new_sql, schema))
end
end
@doc """
Replaces a new database function from a function definition file.
This function will use `CREATE OR REPLACE FUNCTION` so can only be used if the new
version has the same arguments and return type as the old version.
## Options:
* `:version` - the version of the updated function
* `:revert` - the version to revert to if the migration is rolled back
* `:schema` - the schema the function lives in. Uses default schema if not specified
"""
def replace_function(function_name, opts) do
function_name = normalise_name(function_name)
version = Keyword.fetch!(opts, :version)
schema = Keyword.get(opts, :schema)
revert = Keyword.get(opts, :revert)
new_sql = read_file(:functions, function_name, version, schema)
if revert do
old_sql = read_file(:functions, function_name, revert, schema)
execute(
replace_function_sql(function_name, new_sql, schema),
replace_function_sql(function_name, old_sql, schema)
)
else
execute(replace_function_sql(function_name, new_sql, schema))
end
end
@doc """
Drops a database function.
## Options:
* `:revert` - the version to create if the migration is rolled back
* `:schema` - the schema the function lives in. Uses default schema if not specified
"""
def drop_function(function_name, opts \\ []) do
function_name = normalise_name(function_name)
schema = Keyword.get(opts, :schema)
revert = Keyword.get(opts, :revert)
if revert do
old_sql = read_file(:functions, function_name, revert, schema)
execute(
drop_function_sql(function_name, schema),
create_function_sql(function_name, old_sql, schema)
)
else
execute(drop_function_sql(function_name, schema))
end
end
defp normalise_name(view_name) do
"#{view_name}"
end
defp execute(sql) do
Ecto.Migration.execute(wrap(sql))
end
defp execute(up, down) do
Ecto.Migration.execute(wrap(up), wrap(down))
end
defp wrap(statements) when is_list(statements) do
fn ->
for sql <- statements do
Ecto.Migration.repo().query!(sql)
end
end
end
defp wrap(sql) do
fn -> Ecto.Migration.repo().query!(sql) end
end
defp create_view_sql(view_name, sql, materialized, schema) do
m = if materialized, do: "MATERIALIZED", else: ""
"CREATE #{m} VIEW #{wrap_name(view_name, schema)} AS #{sql};"
end
defp replace_view_sql(view_name, sql, schema) do
"CREATE OR REPLACE VIEW #{wrap_name(view_name, schema)} AS #{sql};"
end
defp drop_view_sql(view_name, materialized, schema) do
m = if materialized, do: "MATERIALIZED", else: ""
"DROP #{m} VIEW #{wrap_name(view_name, schema)};"
end
defp drop_and_create_view(view_name, sql, materialized, schema) do
[
drop_view_sql(view_name, materialized, schema),
create_view_sql(view_name, sql, materialized, schema)
]
end
defp create_function_sql(function_name, sql, schema) do
"CREATE FUNCTION #{wrap_name(function_name, schema)} #{sql};"
end
defp replace_function_sql(function_name, sql, schema) do
"CREATE OR REPLACE FUNCTION #{wrap_name(function_name, schema)} #{sql};"
end
defp drop_function_sql(function_name, schema) do
"DROP FUNCTION #{wrap_name(function_name, schema)}"
end
defp wrap_name(name, schema) when not is_nil(schema) do
~s|"#{schema}"."#{name}"|
end
defp wrap_name(name, nil) do
~s|"#{name}"|
end
defp drop_and_create_function(function_name, sql, schema) do
[drop_function_sql(function_name, schema), create_function_sql(function_name, sql, schema)]
end
defp read_file(type, view_name, version, schema) do
schema_str = if schema, do: "#{schema}/", else: ""
File.read!(make_dir(type) <> "/#{schema_str}#{view_name}_v#{version}.sql")
end
defp make_dir(type) do
otp_app = Ecto.Migration.repo().config()[:otp_app]
Application.app_dir(otp_app, "priv/repo/#{type}/")
end
end
|
lib/familiar.ex
| 0.884782 | 0.63409 |
familiar.ex
|
starcoder
|
defmodule SymmetricEncryption do
@moduledoc """
Symmetric Encryption.
Supports AES symmetric encryption using the CBC block cipher.
"""
@doc """
Encrypt String data.
## Examples
iex> SymmetricEncryption.encrypt("Hello World")
"QEVuQwIAPiplaSyln4bywEKXYKDOqQ=="
"""
defdelegate encrypt(data), to: SymmetricEncryption.Encryptor
@doc """
Always return the same encrypted value for the same input data.
The same global IV is used to generate the encrypted data, which is considered insecure since
too much encrypted data using the same key and IV will allow hackers to reverse the key.
The same encrypted value is returned every time the same data is encrypted, which is useful
when the encrypted value is used with database lookups etc.
## Examples
iex> SymmetricEncryption.fixed_encrypt("Hello World")
"QEVuQwIAPiplaSyln4bywEKXYKDOqQ=="
iex> SymmetricEncryption.fixed_encrypt("Hello World")
"QEVuQwIAPiplaSyln4bywEKXYKDOqQ=="
"""
defdelegate fixed_encrypt(data), to: SymmetricEncryption.Encryptor
@doc """
Decrypt String data.
## Examples
iex> encrypted = SymmetricEncryption.encrypt("Hello World")
"QEVuQwIAPiplaSyln4bywEKXYKDOqQ=="
iex> SymmetricEncryption.decrypt(encrypted)
"Hello World"
"""
defdelegate decrypt(encrypted), to: SymmetricEncryption.Decryptor
@doc """
Is the string encrypted?
## Examples
iex> encrypted = SymmetricEncryption.encrypt("Hello World")
"QEVuQwIAPiplaSyln4bywEKXYKDOqQ=="
iex> SymmetricEncryption.encrypted?(encrypted)
true
iex> SymmetricEncryption.encrypted?("Hello World")
false
"""
defdelegate encrypted?(encrypted), to: SymmetricEncryption.Decryptor
@doc """
Return the header for an encrypted string.
## Examples
iex> encrypted = SymmetricEncryption.encrypt("Hello World")
"QEVuQwJAEAAPX3a7EGJ7STMqIO8g38VeB7mFO/DC6DhdYljT4AmdFw=="
iex> SymmetricEncryption.header(encrypted)
%SymmetricEncryption.Header{
auth_tag: nil,
cipher_name: nil,
compress: false,
encrypted_key: nil,
iv: <<15, 95, 118, 187, 16, 98, 123, 73, 51, 42, 32, 239, 32, 223, 197, 94>>,
version: 2
}
"""
def header(encrypted) do
{_, header} = SymmetricEncryption.Decryptor.parse_header(encrypted)
header
end
@doc """
Adds a Cipher struct into memory
## Examples
iex> SymmetricEncryption.add_cipher(%Cipher{iv: "fake_iv", key: "fake_key" , version: 1})
%SymmetricEncryption.Cipher{
iv: "fake_iv",
key: "fake_key",
version: 1
}
"""
defdelegate add_cipher(cipher), to: SymmetricEncryption.Config
end
|
lib/symmetric_encryption.ex
| 0.879257 | 0.455804 |
symmetric_encryption.ex
|
starcoder
|
defmodule URI do
@moduledoc """
Utilities for working with and creating URIs.
"""
defrecord Info, [scheme: nil, path: nil, query: nil,
fragment: nil, authority: nil,
userinfo: nil, host: nil, port: nil]
import Bitwise
@ports [
{ "ftp", 21 },
{ "http", 80 },
{ "https", 443 },
{ "ldap", 389 },
{ "sftp", 22 },
{ "tftp", 69 },
]
Enum.each @ports, fn { scheme, port } ->
def normalize_scheme(unquote(scheme)), do: unquote(scheme)
def default_port(unquote(scheme)), do: unquote(port)
end
@doc """
Normalizes the scheme according to the spec by downcasing it.
"""
def normalize_scheme(nil), do: nil
def normalize_scheme(scheme), do: String.downcase(scheme)
@doc """
Returns the default port for a given scheme.
If the scheme is unknown to URI, returns `nil`.
Any scheme may be registered via `default_port/2`.
## Examples
iex> URI.default_port("ftp")
21
iex> URI.default_port("ponzi")
nil
"""
def default_port(scheme) when is_binary(scheme) do
{ :ok, dict } = :application.get_env(:elixir, :uri)
Dict.get(dict, scheme)
end
@doc """
Registers a scheme with a default port.
"""
def default_port(scheme, port) when is_binary(scheme) and port > 0 do
{ :ok, dict } = :application.get_env(:elixir, :uri)
:application.set_env(:elixir, :uri, Dict.put(dict, scheme, port))
end
@doc """
Encodes an enumerable into a query string.
Takes an enumerable (containing a sequence of two-item tuples)
and returns a string of the form "key1=value1&key2=value2..." where
keys and values are URL encoded as per `encode/1`. Keys and values can
be any term that implements the `String.Chars` protocol (i.e. can be converted
to a binary).
## Examples
iex> hd = HashDict.new([{"foo", 1}, {"bar", "2"}])
iex> URI.encode_query(hd)
"bar=2&foo=1"
"""
def encode_query(l), do: Enum.map_join(l, "&", &pair/1)
@doc """
Decodes a query string into a `HashDict`.
Given a query string of the form "key1=value1&key2=value2...", produces a
`HashDict` with one entry for each key-value pair. Each key and value will be a
binary. Keys and values will be percent-unescaped.
Use `query_decoder/1` if you want to iterate over each value manually.
## Examples
iex> URI.decode_query("foo=1&bar=2") |> Dict.to_list
[{"bar", "2"}, {"foo", "1"}]
iex> hd = HashDict.new()
iex> URI.decode_query("foo=1&bar=2", hd) |> HashDict.keys
["bar", "foo"]
iex> URI.decode_query("foo=1&bar=2", hd) |> HashDict.values
["2", "1"]
"""
def decode_query(q, dict // HashDict.new) when is_binary(q) do
Enum.reduce query_decoder(q), dict, fn({ k, v }, acc) -> Dict.put(acc, k, v) end
end
@doc """
Returns an iterator function over the query string that decodes
the query string in steps.
## Examples
iex> URI.query_decoder("foo=1&bar=2") |> Enum.map &(&1)
[{"foo", "1"}, {"bar", "2"}]
"""
def query_decoder(q) when is_binary(q) do
Stream.unfold(q, &do_decoder/1)
end
defp do_decoder("") do
nil
end
defp do_decoder(q) do
{ first, next } =
case :binary.split(q, "&") do
[first, rest] -> { first, rest }
[first] -> { first, "" }
end
current =
case :binary.split(first, "=") do
[ key, value ] -> { decode(key), decode(value) }
[ key ] -> { decode(key), nil }
end
{ current, next }
end
defp pair({k, v}) do
encode(to_string(k)) <> "=" <> encode(to_string(v))
end
@doc """
Percent-escape a URI.
## Example
iex> URI.encode("http://elixir-lang.com/getting_started/2.html")
"http%3A%2F%2Felixir-lang.com%2Fgetting_started%2F2.html"
"""
def encode(s), do: bc(<<c>> inbits s, do: <<percent(c) :: binary>>)
defp percent(32), do: <<?+>>
defp percent(?-), do: <<?->>
defp percent(?_), do: <<?_>>
defp percent(?.), do: <<?.>>
defp percent(c)
when c >= ?0 and c <= ?9
when c >= ?a and c <= ?z
when c >= ?A and c <= ?Z do
<<c>>
end
defp percent(c), do: "%" <> hex(bsr(c, 4)) <> hex(band(c, 15))
defp hex(n) when n <= 9, do: <<n + ?0>>
defp hex(n), do: <<n + ?A - 10>>
@doc """
Percent-unescape a URI.
## Examples
iex> URI.decode("http%3A%2F%2Felixir-lang.com")
"http://elixir-lang.com"
"""
def decode(<<?%, hex1, hex2, tail :: binary >>) do
<< bsl(hex2dec(hex1), 4) + hex2dec(hex2) >> <> decode(tail)
end
def decode(<<head, tail :: binary >>) do
<<check_plus(head)>> <> decode(tail)
end
def decode(<<>>), do: <<>>
defp hex2dec(n) when n in ?A..?F, do: n - ?A + 10
defp hex2dec(n) when n in ?a..?f, do: n - ?a + 10
defp hex2dec(n) when n in ?0..?9, do: n - ?0
defp check_plus(?+), do: 32
defp check_plus(c), do: c
@doc """
Parses a URI into components.
URIs have portions that are handled specially for the particular
scheme of the URI. For example, http and https have different
default ports. Such values can be accessed and registered via
`URI.default_port/1` and `URI.default_port/2`.
## Examples
iex> URI.parse("http://elixir-lang.org/")
URI.Info[scheme: "http", path: "/", query: nil, fragment: nil,
authority: "elixir-lang.org", userinfo: nil,
host: "elixir-lang.org", port: 80]
"""
def parse(s) when is_binary(s) do
# From http://tools.ietf.org/html/rfc3986#appendix-B
regex = %r/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/
parts = nillify(Regex.run(regex, s))
destructure [_, _, scheme, _, authority, path, _, query, _, fragment], parts
{ userinfo, host, port } = split_authority(authority)
if authority do
authority = ""
if userinfo, do: authority = authority <> userinfo <> "@"
if host, do: authority = authority <> host
if port, do: authority = authority <> ":" <> integer_to_binary(port)
end
scheme = normalize_scheme(scheme)
if nil?(port) and not nil?(scheme) do
port = default_port(scheme)
end
URI.Info[
scheme: scheme, path: path, query: query,
fragment: fragment, authority: authority,
userinfo: userinfo, host: host, port: port
]
end
# Split an authority into its userinfo, host and port parts.
defp split_authority(s) do
s = s || ""
components = Regex.run %r/(^(.*)@)?(\[[a-zA-Z0-9:.]*\]|[^:]*)(:(\d*))?/, s
destructure [_, _, userinfo, host, _, port], nillify(components)
port = if port, do: binary_to_integer(port)
host = if host, do: host |> String.lstrip(?[) |> String.rstrip(?])
{ userinfo, host, port }
end
# Regex.run returns empty strings sometimes. We want
# to replace those with nil for consistency.
defp nillify(l) do
lc s inlist l do
if size(s) > 0, do: s, else: nil
end
end
end
defimpl String.Chars, for: URI.Info do
def to_string(URI.Info[] = uri) do
scheme = uri.scheme
if scheme && (port = URI.default_port(scheme)) do
if uri.port == port, do: uri = uri.port(nil)
end
result = ""
if uri.scheme, do: result = result <> uri.scheme <> "://"
if uri.userinfo, do: result = result <> uri.userinfo <> "@"
if uri.host, do: result = result <> uri.host
if uri.port, do: result = result <> ":" <> integer_to_binary(uri.port)
if uri.path, do: result = result <> uri.path
if uri.query, do: result = result <> "?" <> uri.query
if uri.fragment, do: result = result <> "#" <> uri.fragment
result
end
end
|
lib/elixir/lib/uri.ex
| 0.847653 | 0.534187 |
uri.ex
|
starcoder
|
defmodule Mimic.Cover do
@moduledoc """
Abuse cover private functions to move stuff around.
Completely based on meck's solution:
https://github.com/eproxus/meck/blob/2c7ba603416e95401500d7e116c5a829cb558665/src/meck_cover.erl#L67-L91
"""
@doc false
def export_private_functions do
{_, binary, _} = :code.get_object_code(:cover)
{:ok, {_, [{_, {_, abstract_code}}]}} = :beam_lib.chunks(binary, [:abstract_code])
{:ok, module, binary} = :compile.forms(abstract_code, [:export_all])
:code.load_binary(module, '', binary)
end
@doc false
def replace_coverdata!(module, original_beam, original_coverdata) do
original_module = Mimic.Module.original(module)
path = export_coverdata!(original_module)
rewrite_coverdata!(path, module)
Mimic.Module.clear!(module)
:cover.compile_beam(original_beam)
:ok = :cover.import(path)
:ok = :cover.import(original_coverdata)
File.rm(path)
File.rm(original_coverdata)
end
@doc false
def export_coverdata!(module) do
path = Path.expand("#{module}-#{:os.getpid()}.coverdata", ".")
:ok = :cover.export(path, module)
path
end
defp rewrite_coverdata!(path, module) do
terms = get_terms(path)
terms = replace_module_name(terms, module)
write_coverdata!(path, terms)
end
defp replace_module_name(terms, module) do
Enum.map(terms, fn term -> do_replace_module_name(term, module) end)
end
defp do_replace_module_name({:file, old, file}, module) do
{:file, module, String.replace(file, to_string(old), to_string(module))}
end
defp do_replace_module_name({bump = {:bump, _mod, _, _, _, _}, value}, module) do
{put_elem(bump, 1, module), value}
end
defp do_replace_module_name({_mod, clauses}, module) do
{module, replace_module_name(clauses, module)}
end
defp do_replace_module_name(clause = {_mod, _, _, _, _}, module) do
put_elem(clause, 0, module)
end
defp get_terms(path) do
{:ok, resource} = File.open(path, [:binary, :read, :raw])
terms = get_terms(resource, [])
File.close(resource)
terms
end
defp get_terms(resource, terms) do
case apply(:cover, :get_term, [resource]) do
:eof -> terms
term -> get_terms(resource, [term | terms])
end
end
defp write_coverdata!(path, terms) do
{:ok, resource} = File.open(path, [:write, :binary, :raw])
Enum.each(terms, fn term -> apply(:cover, :write, [term, resource]) end)
File.close(resource)
end
end
|
lib/mimic/cover.ex
| 0.639849 | 0.464355 |
cover.ex
|
starcoder
|
defmodule Mix.Tasks.Espec do
alias Mix.Utils.Stale
defmodule Cover do
@moduledoc false
def start(compile_path, opts) do
Mix.shell().info("Cover compiling modules ... ")
_ = :cover.start()
case :cover.compile_beam_directory(compile_path |> to_charlist) do
results when is_list(results) ->
:ok
{:error, _} ->
Mix.raise("Failed to cover compile directory: " <> compile_path)
end
output = opts[:output]
fn ->
Mix.shell().info("\nGenerating cover results ... ")
File.mkdir_p!(output)
Enum.each(:cover.modules(), fn mod -> cover_function(mod, output) end)
end
end
defp cover_function(mod, output) do
case :cover.analyse_to_file(mod, '#{output}/#{mod}.html', [:html]) do
{:ok, _} -> nil
{:error, error} -> Mix.shell().info("#{error} while generating cover results for #{mod}")
end
end
end
use Mix.Task
@shortdoc "Runs specs"
@preferred_cli_env :test
alias ESpec.Configuration
@moduledoc """
Runs the specs.
This task starts the current application, loads up
`spec/spec_helper.exs` and then requires all files matching the
`spec/**/_spec.exs` pattern in parallel.
A list of files can be given after the task name in order to select
the files to compile:
mix espec spec/some/particular/file_spec.exs
In case a single file is being tested, it is possible pass a specific
line number:
mix espec spec/some/particular/file_spec.exs:42
## Command line options
* `--focus` - run examples with `focus` only
* `--silent` - no output
* `--order` - run examples in the order in which they are declared
* `--sync` - run all specs synchronously ignoring 'async' tag
* `--trace` - detailed output
* `--cover` - enable code coverage
* `--only` - run only tests that match the filter `--only some:tag`
* `--exclude` - exclude tests that match the filter `--exclude some:tag`
* `--string` - run only examples whose full nested descriptions contain string `--string 'only this'`
* `--seed` - seeds the random number generator used to randomize tests order
* `--stale` - The --stale command line option attempts to run only those test files which reference modules that have changed since the last time you ran this task with --stale
## Configuration
* `:spec_paths` - list of paths containing spec files, defaults to `["spec"]`.
It is expected all spec paths to contain a `spec_helper.exs` file.
* `:spec_pattern` - a pattern to load spec files, defaults to `*_spec.exs`.
* `:test_coverage` - a set of options to be passed down to the coverage mechanism.
## Coverage
The `:test_coverage` configuration accepts the following options:
* `:output` - the output for cover results, defaults to `"cover"`
* `:tool` - the coverage tool
By default, a very simple wrapper around OTP's `cover` is used as a tool,
but it can be overridden as follows:
test_coverage: [tool: CoverModule]
`CoverModule` can be any module that exports `start/2`, receiving the
compilation path and the `test_coverage` options as arguments. It must
return an anonymous function of zero arity that will be run after the
test suite is done or `nil`.
"""
@cover [output: "cover", tool: Cover]
@recursive true
@switches [
focus: :boolean,
silent: :boolean,
order: :boolean,
sync: :boolean,
trace: :boolean,
cover: :boolean,
only: :string,
exclude: :string,
string: :string,
seed: :integer,
stale: :boolean
]
def run(args) do
{opts, files, mix_opts} = OptionParser.parse(args, strict: @switches)
check_env!()
Mix.Task.run("loadpaths", args)
if Keyword.get(mix_opts, :compile, true), do: Mix.Task.run("compile", args)
project = Mix.Project.config()
cover = Keyword.merge(@cover, project[:test_coverage] || [])
# Start cover after we load deps but before we start the app.
cover =
if opts[:cover] do
cover[:tool].start(Mix.Project.compile_path(project), cover)
end
Mix.shell().print_app
Mix.Task.run("app.start", args)
ensure_espec_loaded!()
set_configuration(opts)
success = run_espec(project, files, cover)
System.at_exit(fn _ -> unless success, do: exit({:shutdown, 1}) end)
end
def parse_files(files), do: files |> Enum.map(&parse_file(&1))
def parse_file(file) do
case Regex.run(~r/^(.+):(\d+)$/, file, capture: :all_but_first) do
[file, line_number] ->
{Path.absname(file), [line: String.to_integer(line_number)]}
nil ->
{Path.absname(file), []}
end
end
defp run_espec(project, files, cover) do
ESpec.start()
if parse_spec_files(project, files) do
success = ESpec.run()
if cover, do: cover.()
ESpec.stop()
success
else
false
end
end
defp require_spec_helper(dir) do
file = Path.join(dir, "spec_helper.exs")
if File.exists?(file) do
Code.require_file(file)
true
else
IO.puts("Cannot run tests because spec helper file `#{file}` does not exist.")
false
end
end
defp check_env! do
if elixir_version() < "1.3.0" do
unless System.get_env("MIX_ENV") || Mix.env() == :test do
Mix.raise(
"espec is running on environment #{Mix.env()}.\n" <>
"It is recommended to run espec in test environment.\n" <>
"Please add `preferred_cli_env: [espec: :test]` to project configurations in mix.exs file.\n" <>
"Or set MIX_ENV explicitly (MIX_ENV=test mix espec)"
)
end
end
end
defp elixir_version do
System.version() |> String.split("-") |> hd
end
defp ensure_espec_loaded! do
case Application.load(:espec) do
:ok -> :ok
{:error, {:already_loaded, :espec}} -> :ok
end
end
defp set_configuration(opts) do
Configuration.add(start_loading_time: :os.timestamp())
Configuration.add(opts)
end
defp parse_spec_files(project, files) do
spec_paths = get_spec_paths(project)
spec_pattern = get_spec_pattern(project)
if Enum.all?(spec_paths, &require_spec_helper(&1)) do
files_with_opts = if Enum.any?(files), do: parse_files(files), else: []
shared_spec_files = extract_shared_specs(project)
compile_result =
files_with_opts
|> Enum.map(&elem(&1, 0))
|> if_empty_use(spec_paths)
|> extract_files(spec_pattern)
|> filter_stale_files()
|> compile(include_shared: shared_spec_files)
case compile_result do
{:error, _, _} ->
false
_ ->
Configuration.add(file_opts: files_with_opts)
Configuration.add(shared_specs: shared_spec_files)
Configuration.add(finish_loading_time: :os.timestamp())
end
else
false
end
end
defp filter_stale_files(test_files) do
case Configuration.get(:stale) do
true ->
test_files
|> Stale.set_up_stale_sources()
_ ->
{test_files, []}
end
end
defp if_empty_use([], default), do: default
defp if_empty_use(value, _default), do: value
defp get_spec_paths(project) do
project[:spec_paths] || ["spec"]
end
defp get_spec_pattern(project) do
project[:spec_pattern] || "*_spec.exs"
end
defp extract_files(paths, pattern) do
already_loaded = MapSet.new(Code.required_files())
paths
|> Mix.Utils.extract_files(pattern)
|> Enum.map(&Path.absname/1)
|> Enum.reject(fn path ->
full_path = Path.expand(path)
MapSet.member?(already_loaded, full_path)
end)
end
defp extract_shared_specs(project) do
shared_spec_paths = get_shared_spec_paths(project)
shared_spec_pattern = get_shared_spec_pattern(project)
extract_files(shared_spec_paths, shared_spec_pattern)
end
defp get_shared_spec_paths(project) do
project[:shared_spec_paths] || default_shared_spec_paths(project)
end
defp default_shared_spec_paths(project) do
project
|> get_spec_paths()
|> Enum.map(&Path.join(&1, "shared"))
end
defp get_shared_spec_pattern(project) do
project[:shared_spec_pattern] || get_spec_pattern(project)
end
defp compile({spec_files, parallel_require_callbacks}, include_shared: shared_spec_files) do
shared_spec_files = shared_spec_files || []
shared_spec_files
|> Enum.each(&Code.require_file/1)
Kernel.ParallelCompiler.compile(spec_files -- shared_spec_files, parallel_require_callbacks)
end
end
|
lib/mix/tasks/espec.ex
| 0.705988 | 0.54462 |
espec.ex
|
starcoder
|
defmodule Parser do
use Platform.Parsing.Behaviour
## test payloads
# 02035a0003800a8000800080008009812b8014810880b4a57c820c810980027fe88056800880040bf5
# 02035a00020bf5
def fields do
[
%{field: "solar_radiation", display: "Solar radiation", unit: "W⋅m⁻²"},
%{field: "precipitation", display: "Precipitation", unit: "mm"},
%{field: "lightning_strike_count", display: "Lightning strike count", unit: ""},
%{field: "lightning_average_distance", display: "Lightning average distance", unit: "km"},
%{field: "wind_speed", display: "Wind speed", unit: "m⋅s⁻¹"},
%{field: "wind_direction", display: "Wind direction", unit: "°"},
%{field: "maximum_wind_speed", display: "Maximum wind speed", unit: "m⋅s⁻¹"},
%{field: "air_temperature", display: "Air temperature", unit: "°C"},
%{field: "vapor_pressure", display: "Vapor pressure", unit: "kPa"},
%{field: "atmospheric_pressure", display: "Atmospheric pressure", unit: "kPa"},
%{field: "relative_humidity", display: "Relative humidity", unit: "%"},
%{field: "sensor_temperature_internal", display: "Sensor temperature (internal)", unit: "°C"},
%{field: "x_orientation_angle", display: "X orientation angle", unit: "°"},
%{field: "y_orientation_angle", display: "Y orientation angle", unit: "°"},
%{field: "compass_heading", display: "Compass heading", unit: "°"},
%{field: "north_wind_speed", display: "North wind speed", unit: "m⋅s⁻¹"},
%{field: "east_wind_speed", display: "East wind speed", unit: "m⋅s⁻¹"},
%{field: "battery_voltage", display: "Battery voltage", unit: "V"}
]
end
def parse(<<2, device_id::size(16), flags::binary-size(2), words::binary>>, _meta) do
{_remaining, result} =
{words, %{:device_id => device_id, :protocol_version => 2}}
|> sensor0(flags)
|> sensor1(flags)
result
end
defp sensor0({<<x0::size(16), x1::size(16), x2::size(16), x3::size(16), x4::size(16), x5::size(16), x6::size(16), x7::size(16), x8::size(16), x9::size(16), x10::size(16), x11::size(16), x12::size(16), x13::size(16), x14::size(16), x15::size(16), x16::size(16), remaining::binary>>, result},
<<_::size(15), 1::size(1), _::size(0)>>) do
{remaining,
Map.merge(result,
%{
:solar_radiation => x0 - 32768,
:precipitation => (x1 - 32768) / 1000,
:lightning_strike_count => x2 - 32768,
:lightning_average_distance => x3 - 32768,
:wind_speed => (x4 - 32768) / 100,
:wind_direction => (x5 - 32768) / 10,
:maximum_wind_speed => (x6 - 32768) / 100,
:air_temperature => (x7 - 32768) / 10,
:vapor_pressure => (x8 - 32768) / 100,
:atmospheric_pressure => (x9 - 32768) / 100,
:relative_humidity => (x10 - 32768) / 10,
:sensor_temperature_internal => (x11 - 32768) / 10,
:x_orientation_angle => (x12 - 32768) / 10,
:y_orientation_angle => (x13 - 32768) / 10,
:compass_heading => x14 - 32768,
:north_wind_speed => (x15 - 32768) / 100,
:east_wind_speed => (x16 - 32768) / 100
})}
end
defp sensor0(result, _flags), do: result
defp sensor1({<<x0::size(16), remaining::binary>>, result},
<<_::size(14), 1::size(1), _::size(1)>>) do
{remaining,
Map.merge(result,
%{
:battery_voltage => x0 / 1000
})}
end
defp sensor1(result, _flags), do: result
end
|
DL-ATM41/DL-ATM41.ELEMENT-IoT.ex
| 0.51879 | 0.522385 |
DL-ATM41.ELEMENT-IoT.ex
|
starcoder
|
defmodule ICouch.Document do
@moduledoc """
Module which handles CouchDB documents.
The struct's main use is to to conveniently handle attachments. You can
access the fields transparently with `doc["fieldname"]` since this struct
implements the Elixir Access behaviour. You can also retrieve or pattern match
the internal document with the `fields` attribute.
Note that you should not manipulate the fields directly, especially the
attachments. This is because of the efficient multipart transmission which
requires the attachments to be in the same order within the JSON as in the
multipart body. The accessor functions provided in this module handle this.
"""
@behaviour Access
defstruct [id: nil, rev: nil, fields: %{}, attachment_order: [], attachment_data: %{}]
@type key :: String.t
@type value :: any
@type t :: %__MODULE__{
id: String.t | nil,
rev: String.t | nil,
fields: %{optional(key) => value},
attachment_order: [String.t],
attachment_data: %{optional(key) => binary}
}
@doc """
Creates a new document struct.
You can create an empty document or give it an ID and revision number or
create a document struct from a map.
"""
@spec new(id_or_fields :: String.t | nil | map, rev :: String.t | nil) :: t
def new(id_or_fields \\ nil, rev \\ nil)
def new(fields, _) when is_map(fields),
do: from_api!(fields)
def new(nil, nil),
do: %__MODULE__{}
def new(id, nil),
do: %__MODULE__{id: id, fields: %{"_id" => id}}
def new(id, rev),
do: %__MODULE__{id: id, rev: rev, fields: %{"_id" => id, "_rev" => rev}}
@doc """
Deserializes a document from a map or binary.
If attachments with data exist, they will be decoded and stored in the struct
separately.
"""
@spec from_api(fields :: map | binary) :: {:ok, t} | :error
def from_api(doc) when is_binary(doc) do
case Poison.decode(doc) do
{:ok, fields} -> from_api(fields)
other -> other
end
end
def from_api(%{"_attachments" => doc_atts} = fields) when (is_map(doc_atts) and map_size(doc_atts) > 0) or doc_atts != [] do
{doc_atts, order, data} = Enum.reduce(doc_atts, {%{}, [], %{}}, &decode_att/2)
{:ok, %__MODULE__{id: Map.get(fields, "_id"), rev: Map.get(fields, "_rev"), fields: %{fields | "_attachments" => doc_atts}, attachment_order: Enum.reverse(order), attachment_data: data}}
end
def from_api(%{} = fields),
do: {:ok, %__MODULE__{id: Map.get(fields, "_id"), rev: Map.get(fields, "_rev"), fields: fields}}
@doc """
Like `from_api/1` but raises an error on decoding failures.
"""
@spec from_api!(fields :: map | binary) :: t
def from_api!(doc) when is_binary(doc),
do: from_api!(Poison.decode!(doc))
def from_api!(fields) when is_map(fields) do
{:ok, doc} = from_api(fields)
doc
end
@doc """
Deserializes a document including its attachment data from a list of multipart
segments as returned by `ICouch.Multipart.split/2`.
"""
@spec from_multipart(parts :: [{map, binary}]) :: {:ok, t} | {:error, term}
def from_multipart([{doc_headers, doc_body} | atts]) do
doc_body = if ICouch.Server.has_gzip_encoding?(doc_headers) do
try do
:zlib.gunzip(doc_body)
rescue _ ->
doc_body
end
else
doc_body
end
case from_api(doc_body) do
{:ok, doc} ->
{:ok, Enum.reduce(atts, doc, fn {att_headers, att_body}, acc ->
case Regex.run(~r/attachment; *filename="([^"]*)"/, Map.get(att_headers, "content-disposition", "")) do
[_, filename] ->
case Map.get(att_headers, "content-encoding") do
"gzip" ->
try do
:zlib.gunzip(att_body)
rescue _ ->
nil
end
_ ->
att_body
end
|>
case do
nil -> acc
att_body -> ICouch.Document.put_attachment_data(acc, filename, att_body)
end
_ ->
acc
end
end)}
other ->
other
end
end
@doc """
Serializes the given document to a binary.
This will encode the attachments unless `multipart: true` is given as option
at which point the attachments that have data are marked with
`"follows": true`. The attachment order is maintained.
"""
@spec to_api(doc :: t, options :: [any]) :: {:ok, binary} | {:error, term}
def to_api(doc, options \\ []),
do: Poison.encode(doc, options)
@doc """
Like `to_api/1` but raises an error on encoding failures.
"""
@spec to_api!(doc :: t, options :: [any]) :: binary
def to_api!(doc, options \\ []),
do: Poison.encode!(doc, options)
@doc """
Serializes the given document including its attachment data to a list of
multipart segments as consumed by `ICouch.Multipart.join/2`.
"""
@spec to_multipart(doc :: t) :: {:ok, [{map, binary}]} | :error
def to_multipart(doc) do
case to_api(doc, multipart: true) do
{:ok, doc_body} ->
{:ok, [
{%{"Content-Type" => "application/json"}, doc_body} |
(for {filename, data} <- get_attachment_data(doc), data != nil, do: {%{"Content-Disposition" => "attachment; filename=\"#{filename}\""}, data})
]}
other ->
other
end
end
@doc """
Tests two documents for equality.
Includes `_id`, `_rev` and `_revisions`/`_revs_info`.
Attachments are compared using `equal_attachments?/2`.
"""
@spec equal?(t | map, t | map) :: boolean
def equal?(%__MODULE__{id: id, rev: rev} = doc1, %__MODULE__{id: id, rev: rev} = doc2) do
if revisions(doc1) == revisions(doc2),
do: equal_content?(doc1, doc2),
else: false
end
def equal?(%__MODULE__{}, %__MODULE__{}),
do: false
def equal?(doc1, %__MODULE__{} = doc2) when is_map(doc1),
do: equal?(from_api!(doc1), doc2)
def equal?(%__MODULE__{} = doc1, doc2) when is_map(doc2),
do: equal?(doc1, from_api!(doc2))
def equal?(doc1, doc2) when is_map(doc1) and is_map(doc2),
do: equal?(from_api!(doc1), from_api!(doc2))
@doc """
Tests two documents for field equality.
Ignores `_id`, `_rev` and `_revisions`.
Attachments are compared using `equal_attachments?/2`.
"""
@spec equal_content?(t | map, t | map) :: boolean
def equal_content?(%__MODULE__{fields: fields1} = doc1, %__MODULE__{fields: fields2} = doc2) do
dropped = ["_id", "_rev", "_revisions", "_attachments"]
if Map.drop(fields1, dropped) == Map.drop(fields2, dropped),
do: equal_attachments?(doc1, doc2),
else: false
end
def equal_content?(doc1, %__MODULE__{} = doc2) when is_map(doc1),
do: equal_content?(from_api!(doc1), doc2)
def equal_content?(%__MODULE__{} = doc1, doc2) when is_map(doc2),
do: equal_content?(doc1, from_api!(doc2))
def equal_content?(doc1, doc2) when is_map(doc1) and is_map(doc2),
do: equal_content?(from_api!(doc1), from_api!(doc2))
@doc """
Tests the attachments of two documents for equality.
An attachment is considered equal if the name, content_type, length and digest
are equal. If digests are absent, the data will be checked for equality; if
both documents do not hold attachment data, this is considered equal as well.
"""
@spec equal_attachments?(t | map, t | map) :: boolean
def equal_attachments?(%__MODULE__{fields: %{"_attachments" => atts1}, attachment_data: data1}, %__MODULE__{fields: %{"_attachments" => atts2}, attachment_data: data2})
when map_size(atts1) == map_size(atts2) do
Enum.all?(atts1, fn {name, meta1} ->
case Map.fetch(atts2, name) do
{:ok, meta2} ->
dig1 = meta1["digest"]
dig2 = meta2["digest"]
meta1["content_type"] == meta2["content_type"] and (
(dig1 != nil and dig2 != nil and dig1 == dig2 and meta1["length"] == meta2["length"])
or
(dig1 == nil and dig2 == nil and data1[name] == data2[name])
)
_ ->
false
end
end)
end
def equal_attachments?(%__MODULE__{fields: fields1}, %__MODULE__{fields: fields2}),
do: not Map.has_key?(fields1, "_attachments") and not Map.has_key?(fields2, "_attachments")
def equal_attachments?(doc1, %__MODULE__{} = doc2) when is_map(doc1),
do: equal_attachments?(from_api!(doc1), doc2)
def equal_attachments?(%__MODULE__{} = doc1, doc2) when is_map(doc2),
do: equal_attachments?(doc1, from_api!(doc2))
def equal_attachments?(doc1, doc2) when is_map(doc1) and is_map(doc2),
do: equal_attachments?(from_api!(doc1), from_api!(doc2))
@doc """
Returns whether the document is marked as deleted.
"""
@spec deleted?(doc :: t) :: boolean
def deleted?(%__MODULE__{fields: %{"_deleted" => true}}),
do: true
def deleted?(%__MODULE__{}),
do: false
@doc """
Marks the document as deleted.
This removes all fields except `_id` and `_rev` and deletes all attachments
unless `keep_fields` is set to `true`.
"""
@spec set_deleted(doc :: t, keep_fields :: boolean) :: t
def set_deleted(doc, keep_fields \\ false)
def set_deleted(doc, true),
do: put(doc, "_deleted", true)
def set_deleted(%__MODULE__{id: nil, rev: nil} = doc, _),
do: %{doc | fields: %{"_deleted" => true}, attachment_order: [], attachment_data: %{}}
def set_deleted(%__MODULE__{id: nil, rev: rev} = doc, _),
do: %{doc | fields: %{"_rev" => rev, "_deleted" => true}, attachment_order: [], attachment_data: %{}}
def set_deleted(%__MODULE__{id: id, rev: nil} = doc, _),
do: %{doc | fields: %{"_id" => id, "_deleted" => true}, attachment_order: [], attachment_data: %{}}
def set_deleted(%__MODULE__{id: id, rev: rev, fields: %{"_revisions" => revisions}} = doc, _),
do: %{doc | fields: %{"_id" => id, "_rev" => rev, "_revisions" => revisions, "_deleted" => true}, attachment_order: [], attachment_data: %{}}
def set_deleted(%__MODULE__{id: id, rev: rev} = doc, _),
do: %{doc | fields: %{"_id" => id, "_rev" => rev, "_deleted" => true}, attachment_order: [], attachment_data: %{}}
@doc """
Returns the approximate size of this document if it was encoded in JSON.
Does not include the attachment data.
"""
def json_byte_size(%__MODULE__{fields: fields}),
do: ICouch.json_byte_size(fields)
@doc """
Returns the approximate size of this document if it was encoded entirely in
JSON, including the attachments being represented as as Base64.
"""
def full_json_byte_size(doc) do
atds = attachment_data_size(doc)
json_byte_size(doc) + div(atds + rem(3 - rem(atds, 3), 3), 3) * 4
end
@doc """
Set the document ID for `doc`.
Attempts to set it to `nil` will actually remove the ID from the document.
"""
@spec set_id(doc :: t, id :: String.t | nil) :: t
def set_id(%__MODULE__{fields: fields} = doc, nil),
do: %{doc | id: nil, fields: Map.delete(fields, "_id")}
def set_id(%__MODULE__{fields: fields} = doc, id),
do: %{doc | id: id, fields: Map.put(fields, "_id", id)}
@doc """
Set the revision number for `doc`.
Attempts to set it to `nil` will actually remove the revision number from the
document.
"""
@spec set_rev(doc :: t, rev :: String.t | nil) :: t
def set_rev(%__MODULE__{fields: fields} = doc, nil),
do: %{doc | rev: nil, fields: Map.delete(fields, "_rev")}
def set_rev(%__MODULE__{fields: fields} = doc, rev),
do: %{doc | rev: rev, fields: Map.put(fields, "_rev", rev)}
@doc """
Fetches the field value for a specific `key` in the given `doc`.
If `doc` contains the given `key` with value `value`, then `{:ok, value}` is
returned. If `doc` doesn't contain `key`, `:error` is returned.
Part of the Access behavior.
"""
@spec fetch(doc :: t, key) :: {:ok, value} | :error
def fetch(%__MODULE__{id: id}, "_id"),
do: if id != nil, do: {:ok, id}, else: :error
def fetch(%__MODULE__{rev: rev}, "_rev"),
do: if rev != nil, do: {:ok, rev}, else: :error
def fetch(%__MODULE__{fields: fields}, key),
do: Map.fetch(fields, key)
@doc """
Gets the field value for a specific `key` in `doc`.
If `key` is present in `doc` with value `value`, then `value` is
returned. Otherwise, `default` is returned (which is `nil` unless
specified otherwise).
Part of the Access behavior.
"""
@spec get(doc :: t, key, default :: value) :: value
def get(doc, key, default \\ nil) do
case fetch(doc, key) do
{:ok, value} -> value
:error -> default
end
end
@doc """
Gets the field value from `key` and updates it, all in one pass.
`fun` is called with the current value under `key` in `doc` (or `nil` if `key`
is not present in `doc`) and must return a two-element tuple: the "get" value
(the retrieved value, which can be operated on before being returned) and the
new value to be stored under `key` in the resulting new document. `fun` may
also return `:pop`, which means the current value shall be removed from `doc`
and returned (making this function behave like `Document.pop(doc, key)`.
The returned value is a tuple with the "get" value returned by
`fun` and a new document with the updated value under `key`.
Part of the Access behavior.
"""
@spec get_and_update(doc :: t, key, (value -> {get, value} | :pop)) :: {get, t} when get: term
def get_and_update(doc, key, fun) when is_function(fun, 1) do
current = get(doc, key)
case fun.(current) do
{get, update} ->
{get, put(doc, key, update)}
:pop ->
{current, delete(doc, key)}
other ->
raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}"
end
end
@doc """
Returns and removes the field value associated with `key` in `doc`.
If `key` is present in `doc` with value `value`, `{value, new_doc}` is
returned where `new_doc` is the result of removing `key` from `doc`. If `key`
is not present in `doc`, `{default, doc}` is returned.
"""
@spec pop(doc :: t, key, default :: value) :: {value, t}
def pop(doc, key, default \\ nil)
def pop(%__MODULE__{id: id} = doc, "_id", default),
do: {id || default, set_id(doc, nil)}
def pop(%__MODULE__{rev: rev} = doc, "_rev", default),
do: {rev || default, set_rev(doc, nil)}
def pop(%__MODULE__{fields: fields} = doc, "_attachments", default),
do: {Map.get(fields, "_attachments", default), delete_attachments(doc)}
def pop(%__MODULE__{fields: fields} = doc, key, default) do
{value, fields} = Map.pop(fields, key, default)
{value, %{doc | fields: fields}}
end
@doc """
Puts the given field `value` under `key` in `doc`.
The `_attachments` field is treated specially:
- Any given `data` is decoded internally and the `length` attribute is set
- The `follows` attribute is removed and the `stub` attribute is set
- If the attachments are given as list of tuples, their order is preserved
If the document already had attachments:
- If `data` is set for any given attachment, it will override existing data;
if not, existing data is kept
- If the attachments are given as map, the existing order is preserved;
if not, the order is taken from the list
"""
@spec put(doc :: t, key, value) :: t
def put(doc, "_id", value),
do: set_id(doc, value)
def put(doc, "_rev", value),
do: set_rev(doc, value)
def put(%__MODULE__{fields: fields} = doc, "_attachments", doc_atts) when (is_map(doc_atts) and map_size(doc_atts) == 0) or doc_atts == [],
do: %{doc | fields: Map.put(fields, "_attachments", %{}), attachment_order: [], attachment_data: %{}}
def put(%__MODULE__{fields: fields, attachment_order: orig_order, attachment_data: orig_data} = doc, "_attachments", doc_atts) do
data = Enum.reduce(Map.keys(orig_data), orig_data, fn name, acc -> if Map.has_key?(doc_atts, name), do: acc, else: Map.delete(acc, name) end)
{clean_doc_atts, order, data} = Enum.reduce(doc_atts, {%{}, [], data}, &decode_att/2)
order = if is_map(doc_atts) do
Enum.reduce(
order,
Enum.reduce(orig_order, {[], %{}}, fn
name, {o, s} = acc -> if Map.has_key?(doc_atts, name), do: {[name | o], Map.put(s, name, true)}, else: acc
end),
fn name, {o, s} = acc -> if Map.has_key?(s, name), do: acc, else: {[name | o], s} end
) |> elem(0)
else
order
end
%{doc | fields: Map.put(fields, "_attachments", clean_doc_atts), attachment_order: Enum.reverse(order), attachment_data: data}
end
def put(%__MODULE__{fields: fields} = doc, key, value),
do: %{doc | fields: Map.put(fields, key, value)}
defp decode_att({name, att}, {doc_atts, order, data}) do
case Map.pop(att, "data") do
{nil, %{"stub" => true} = att} ->
{Map.put(doc_atts, name, att), [name | order], data}
{nil, att_wod} ->
att = att_wod
|> Map.delete("follows")
|> Map.put("stub", true)
{Map.put(doc_atts, name, att), [name | order], data}
{b64_data, att_wod} ->
case Base.decode64(b64_data) do
{:ok, dec_data} ->
att = att_wod
|> Map.put("stub", true)
|> Map.put("length", byte_size(dec_data))
{Map.put(doc_atts, name, att), [name | order], Map.put(data, name, dec_data)}
_ ->
{Map.put(doc_atts, name, att), [name | order], data}
end
end
end
@doc """
Deletes the entry in `doc` for a specific `key`.
If the `key` does not exist, returns `doc` unchanged.
"""
@spec delete(doc :: t, key) :: t
def delete(doc, "_id"),
do: set_id(doc, nil)
def delete(doc, "_rev"),
do: set_rev(doc, nil)
def delete(doc, "_attachments"),
do: delete_attachments(doc)
def delete(%__MODULE__{fields: fields} = doc, key),
do: %{doc | fields: :maps.remove(key, fields)}
@doc """
Returns the attachment info (stub) for a specific `filename` or `nil` if not
found.
"""
@spec get_attachment_info(doc :: t, filename :: key) :: map | nil
def get_attachment_info(%__MODULE__{fields: fields}, filename),
do: Map.get(fields, "_attachments", %{}) |> Map.get(filename)
@doc """
Returns whether an attachment with the given `filename` exists.
"""
@spec has_attachment?(doc :: t, filename :: key) :: boolean
def has_attachment?(%__MODULE__{fields: %{"_attachments" => doc_atts}}, filename),
do: Map.has_key?(doc_atts, filename)
def has_attachment?(%__MODULE__{}, _),
do: false
@doc """
Returns the data of the attachment specified by `filename` if present or
`nil`.
"""
@spec get_attachment_data(doc :: t, filename :: key) :: binary | nil
def get_attachment_data(%__MODULE__{attachment_data: data}, filename),
do: Map.get(data, filename)
@doc """
Returns whether the attachment specified by `filename` is present and has
data associated with it.
"""
@spec has_attachment_data?(doc :: t, filename :: key) :: boolean
def has_attachment_data?(%__MODULE__{attachment_data: data}, filename),
do: Map.has_key?(data, filename)
@doc """
Returns a list of tuples with attachment names and data, in the order in which
they will appear in the serialized JSON.
Note that the list will also contain attachments that have no associated data.
"""
@spec get_attachment_data(doc :: t) :: [{String.t, binary | nil}]
def get_attachment_data(%__MODULE__{attachment_order: order, attachment_data: data}),
do: for filename <- order, do: {filename, Map.get(data, filename)}
@doc """
Returns both the info and data of the attachment specified by `filename` if
present or `nil`. The data itself can be missing.
"""
@spec get_attachment(doc :: t, filename :: key) :: {map, binary | nil} | nil
def get_attachment(%__MODULE__{fields: fields, attachment_data: data}, filename) do
case Map.get(fields, "_attachments", %{}) |> Map.get(filename) do
nil ->
nil
attachment_info ->
{attachment_info, Map.get(data, filename)}
end
end
@doc """
Inserts or updates the attachment info (stub) in `doc` for the attachment
specified by `filename`.
"""
@spec put_attachment_info(doc :: t, filename :: key, info :: map) :: t
def put_attachment_info(%__MODULE__{fields: fields, attachment_order: order} = doc, filename, info) do
case Map.get(fields, "_attachments", %{}) do
%{^filename => _} = doc_atts ->
%{doc | fields: Map.put(fields, "_attachments", %{doc_atts | filename => info})}
doc_atts ->
%{doc | fields: Map.put(fields, "_attachments", Map.put(doc_atts, filename, info)), attachment_order: order ++ [filename]}
end
end
@doc """
Inserts or updates the attachment data in `doc` for the attachment specified
by `filename`. The attachment info (stub) has to exist or an error is raised.
"""
@spec put_attachment_data(doc :: t, filename :: key, data :: binary) :: t
def put_attachment_data(%__MODULE__{fields: %{"_attachments" => doc_atts}, attachment_data: attachment_data} = doc, filename, data) do
if not Map.has_key?(doc_atts, filename), do: raise KeyError, key: filename, term: "_attachments"
%{doc | attachment_data: Map.put(attachment_data, filename, data)}
end
def put_attachment_data(%__MODULE__{}, filename, _),
do: raise KeyError, key: filename, term: "_attachments"
@doc """
Deletes the attachment data of all attachments in `doc`.
This does not delete the respective attachment info (stub).
"""
@spec delete_attachment_data(doc :: t) :: t
def delete_attachment_data(%__MODULE__{} = doc),
do: %{doc | attachment_data: %{}}
@doc """
Deletes the attachment data specified by `filename` from `doc`.
"""
@spec delete_attachment_data(doc :: t, filename :: key) :: t
def delete_attachment_data(%__MODULE__{attachment_data: attachment_data} = doc, filename),
do: %{doc | attachment_data: Map.delete(attachment_data, filename)}
@doc """
"""
@spec put_attachment(doc :: t, filename :: key, data :: binary | {map, binary}, content_type :: String.t, digest :: String.t | nil) :: t
def put_attachment(doc, filename, data, content_type \\ "application/octet-stream", digest \\ nil)
def put_attachment(doc, filename, data, content_type, nil) when is_binary(data),
do: put_attachment(doc, filename, {%{"content_type" => content_type, "length" => byte_size(data), "stub" => true}, data}, "", nil)
def put_attachment(doc, filename, data, content_type, digest) when is_binary(data),
do: put_attachment(doc, filename, {%{"content_type" => content_type, "digest" => digest, "length" => byte_size(data), "stub" => true}, data}, "", nil)
def put_attachment(%__MODULE__{fields: fields, attachment_order: order, attachment_data: attachment_data} = doc, filename, {stub, data}, _, _) do
{doc_atts, order} = case Map.get(fields, "_attachments", %{}) do
%{^filename => _} = doc_atts ->
{Map.put(doc_atts, filename, stub), order}
doc_atts ->
{Map.put(doc_atts, filename, stub), order ++ [filename]}
end
%{doc | fields: Map.put(fields, "_attachments", doc_atts), attachment_order: order, attachment_data: Map.put(attachment_data, filename, data)}
end
@doc """
Deletes the attachment specified by `filename` from `doc`.
Returns the document unchanged, if the attachment didn't exist.
"""
@spec delete_attachment(doc :: t, filename :: key) :: t
def delete_attachment(%__MODULE__{fields: %{"_attachments" => doc_atts} = fields, attachment_order: order, attachment_data: data} = doc, filename),
do: %{doc | fields: %{fields | "_attachments" => Map.delete(doc_atts, filename)}, attachment_order: List.delete(order, filename), attachment_data: Map.delete(data, filename)}
def delete_attachment(%__MODULE__{} = doc, _),
do: doc
@doc """
Deletes all attachments and attachment data from `doc`.
"""
@spec delete_attachments(doc :: t) :: t
def delete_attachments(%__MODULE__{fields: fields} = doc),
do: %{doc | fields: Map.delete(fields, "_attachments"), attachment_order: [], attachment_data: %{}}
@doc """
Returns the size of the attachment data specified by `filename` in `doc`.
Note that this will return 0 if the attachment data is missing and/or the
attachment does not exist.
"""
@spec attachment_data_size(doc :: t, filename :: key) :: integer
def attachment_data_size(%__MODULE__{attachment_data: data}, filename),
do: byte_size(Map.get(data, filename, ""))
@doc """
Returns the sum of all attachment data sizes in `doc`.
The calculation is done for data that actually is present in this document,
not neccessarily all attachments that are referenced in `_attachments`.
"""
@spec attachment_data_size(doc :: t) :: integer
def attachment_data_size(%__MODULE__{attachment_data: data}),
do: Enum.reduce(data, 0, fn {_, d}, acc -> acc + byte_size(d) end)
@doc """
Returns a list of full revision numbers given through the document's
`_revisions` or `_revs_info` field, or `nil` if the both fields are missing
or invalid. The revisions are sorted from newest to oldest.
"""
@spec revisions(doc :: t) :: [String.t] | nil
def revisions(%__MODULE__{fields: %{"_revisions" => %{"ids" => ids, "start" => start}}}) do
l = length(ids)
s = start - l + 1
Enum.reverse(ids)
|> Enum.reduce({[], s}, fn e, {acc, ss} -> {["#{ss}-#{e}" | acc], ss + 1} end)
|> elem(0)
end
def revisions(%__MODULE__{fields: %{"_revs_info" => ri}}),
do: (for %{"rev" => r} <- ri, do: r)
def revisions(%__MODULE__{}),
do: nil
end
defimpl Enumerable, for: ICouch.Document do
def count(%ICouch.Document{fields: fields}),
do: {:ok, map_size(fields)}
def member?(%ICouch.Document{fields: fields}, {key, value}),
do: {:ok, match?({:ok, ^value}, :maps.find(key, fields))}
def member?(_doc, _other),
do: {:ok, false}
def slice(%ICouch.Document{fields: fields}),
do: Enumerable.Map.slice(fields)
def reduce(%ICouch.Document{fields: fields}, acc, fun),
do: Enumerable.Map.reduce(fields, acc, fun)
end
defimpl Collectable, for: ICouch.Document do
def into(%ICouch.Document{fields: original, attachment_order: attachment_order, attachment_data: attachment_data}) do
{original, fn
fields, {:cont, {k, v}} ->
Map.put(fields, k, v)
%{"_attachments" => doc_atts} = fields, :done when map_size(doc_atts) > 0 ->
%ICouch.Document{id: Map.get(fields, "_id"), rev: Map.get(fields, "_rev"), fields: fields, attachment_order: attachment_order, attachment_data: attachment_data}
|> ICouch.Document.put("_attachments", doc_atts)
fields, :done ->
%ICouch.Document{id: Map.get(fields, "_id"), rev: Map.get(fields, "_rev"), fields: fields}
_, :halt ->
:ok
end}
end
end
defimpl Poison.Encoder, for: ICouch.Document do
@compile :inline_list_funcs
alias Poison.Encoder
use Poison.{Encode, Pretty}
def encode(%ICouch.Document{fields: %{"_attachments" => doc_atts}, attachment_order: []}, _) when map_size(doc_atts) > 0,
do: raise ArgumentError, message: "document attachments inconsistent"
def encode(%ICouch.Document{fields: %{"_attachments" => doc_atts} = fields, attachment_order: [_|_] = order, attachment_data: data}, options) do
if length(order) != map_size(doc_atts),
do: raise ArgumentError, message: "document attachments inconsistent"
shiny = pretty(options)
if shiny do
indent = indent(options)
offset = offset(options) + indent
options = offset(options, offset)
fun = &[",\n", spaces(offset), Encoder.BitString.encode(encode_name(&1), options), ": ",
encode_field_value(&1, :maps.get(&1, fields), order, data, shiny, options) | &2]
["{\n", tl(:lists.foldl(fun, [], :maps.keys(fields))), ?\n, spaces(offset - indent), ?}]
else
fun = &[?,, Encoder.BitString.encode(encode_name(&1), options), ?:,
encode_field_value(&1, :maps.get(&1, fields), order, data, shiny, options) | &2]
[?{, tl(:lists.foldl(fun, [], :maps.keys(fields))), ?}]
end
end
def encode(%ICouch.Document{fields: fields}, options),
do: Poison.Encoder.Map.encode(fields, options)
defp encode_field_value("_attachments", doc_atts, order, data, true, options) do
multipart = Keyword.get(options, :multipart, false)
indent = indent(options)
offset = offset(options) + indent
options = offset(options, offset)
fun = &[",\n", spaces(offset), Encoder.BitString.encode(encode_name(&1), options), ": ",
encode_attachment(:maps.get(&1, doc_atts), :maps.find(&1, data), multipart, options) | &2]
["{\n", tl(:lists.foldr(fun, [], order)), ?\n, spaces(offset - indent), ?}]
end
defp encode_field_value("_attachments", doc_atts, order, data, _, options) do
multipart = Keyword.get(options, :multipart, false)
fun = &[?,, Encoder.BitString.encode(encode_name(&1), options), ?:,
encode_attachment(:maps.get(&1, doc_atts), :maps.find(&1, data), multipart, options) | &2]
[?{, tl(:lists.foldr(fun, [], order)), ?}]
end
defp encode_field_value(_, value, _, _, _, options),
do: Encoder.encode(value, options)
defp encode_attachment(att, {:ok, _}, true, options),
do: Encoder.Map.encode(att |> Map.delete("stub") |> Map.put("follows", true), options)
defp encode_attachment(att, {:ok, data}, _, options),
do: Encoder.Map.encode(att |> Map.delete("stub") |> Map.delete("length") |> Map.put("data", Base.encode64(data)), options)
defp encode_attachment(att, _, _, options),
do: Encoder.Map.encode(att, options)
end
|
lib/icouch/document.ex
| 0.857813 | 0.495545 |
document.ex
|
starcoder
|
defmodule Aja.Enum do
@moduledoc """
Drop-in replacement for the `Enum` module, optimized to work with Aja's data structures such as `Aja.Vector`.
It currently only covers a subset of `Enum`, but `Aja.Enum` aims to completely mirror the API of `Enum`,
and should behave exactly the same for any type of `Enumerable`.
The only expected difference should be a significant increase in performance for Aja structures.
## Rationale
Structures such as `Aja.Vector` or `Aja.OrdMap` are implementing the `Enumerable` protocol, which means they can be
used directly with the `Enum` module. The `Enumerable` protocol however comes with its overhead and is strongly
limited in terms of performance.
On the other hand, `Aja.Enum` provides hand-crafted highly-optimized functions that fully take advantage of
immutable vectors. The speedup can easily reach more than a factor 10 compared to `Enum` used on non-list
structures, and sometimes even be noticeably faster than `Enum` used over lists.
One of the main reasons to adopt a specific data structure is the performance.
Using vectors with `Enum` would defeat the purpose, hence the introduction of `Aja.Enum`.
iex> vector = Aja.Vector.new(1..10000)
iex> Enum.sum(vector) # slow
50005000
iex> Aja.Enum.sum(vector) # same result, much faster
50005000
"""
require Aja.Vector.Raw, as: RawVector
alias Aja.EnumHelper, as: H
@compile :inline_list_funcs
@dialyzer :no_opaque
@type index :: integer
@type value :: any
@type t(value) :: Aja.Vector.t(value) | [value] | Enumerable.t()
@empty_vector RawVector.empty()
# TODO optimize ranges (sum, random...)
@doc """
Converts `enumerable` to a list.
Mirrors `Enum.to_list/1` with higher performance for Aja structures.
"""
@spec to_list(t(val)) :: [val] when val: value
defdelegate to_list(enumerable), to: H
@doc """
Returns the size of the `enumerable`.
Mirrors `Enum.count/1` with higher performance for Aja structures.
"""
@spec count(t(any)) :: non_neg_integer
def count(enumerable) do
case enumerable do
list when is_list(list) -> length(list)
%Aja.Vector{__vector__: vector} -> RawVector.size(vector)
%Aja.OrdMap{__ord_map__: map} -> map_size(map)
%MapSet{} -> MapSet.size(enumerable)
start..stop -> abs(start - stop) + 1
_ -> Enum.count(enumerable)
end
end
@doc """
Returns the count of elements in the `enumerable` for which `fun` returns
a truthy value.
Mirrors `Enum.count/2` with higher performance for Aja structures.
"""
@spec count(t(val), (val -> as_boolean(term))) :: non_neg_integer when val: value
def count(enumerable, fun) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.count(enumerable, fun)
list when is_list(list) ->
count_list(list, fun, 0)
vector ->
RawVector.count(vector, fun)
end
end
defp count_list([], _fun, acc), do: acc
defp count_list([head | tail], fun, acc) do
new_acc =
if fun.(head) do
acc + 1
else
acc
end
count_list(tail, fun, new_acc)
end
@doc """
Returns `true` if `enumerable` is empty, otherwise `false`.
Mirrors `Enum.empty?/1` with higher performance for Aja structures.
"""
@spec empty?(t(any)) :: boolean
def empty?(enumerable) do
case enumerable do
list when is_list(list) -> list == []
%Aja.Vector{__vector__: vector} -> vector === @empty_vector
%Aja.OrdMap{__ord_map__: map} -> map == %{}
%MapSet{} -> MapSet.size(enumerable) == 0
%Range{} -> false
_ -> Enum.empty?(enumerable)
end
end
# Note: Could not optimize it noticeably for vectors
@doc """
Checks if `element` exists within the `enumerable`.
Just an alias for `Enum.member?/2`, does not improve performance.
"""
@spec member?(t(val), val) :: boolean when val: value
defdelegate member?(enumerable, value), to: Enum
# TODO optimize for vector
@doc """
Returns a subset list of the given `enumerable` by `index_range`.
Mirrors `Enum.slice/2` with higher performance for Aja structures.
"""
@spec slice(t(val), Range.t()) :: [val] when val: value
defdelegate slice(enumerable, index_range), to: Enum
@doc """
Returns a subset list of the given `enumerable`, from `start_index` (zero-based)
with `amount` number of elements if available.
Mirrors `Enum.slice/3`.
"""
@spec slice(t(val), index, non_neg_integer) :: [val] when val: value
defdelegate slice(enumerable, start_index, amount), to: Enum
@doc """
Inserts the given `enumerable` into a `collectable`.
Mirrors `Enum.into/2` with higher performance for Aja structures.
"""
@spec into(t(val), Collectable.t()) :: Collectable.t() when val: value
def into(enumerable, collectable)
def into(enumerable, %Aja.Vector{} = vector) do
# TODO improve when this is the empty vector/ord_map
Aja.Vector.concat(vector, enumerable)
end
def into(enumerable, %Aja.OrdMap{} = ord_map) do
Aja.OrdMap.merge_list(ord_map, H.to_list(enumerable))
end
def into(enumerable, collectable) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> enumerable
list when is_list(list) -> list
vector -> RawVector.to_list(vector)
end
|> Enum.into(collectable)
end
@doc """
Inserts the given `enumerable` into a `collectable` according to the `transform` function.
Mirrors `Enum.into/3` with higher performance for Aja structures.
"""
def into(enumerable, collectable, transform)
def into(enumerable, %Aja.Vector{} = vector, transform) do
# TODO we can probably improve this with the builder
Aja.Vector.concat(vector, H.map(enumerable, transform))
end
def into(enumerable, %Aja.OrdMap{} = ord_map, transform) do
Aja.OrdMap.merge_list(ord_map, H.map(enumerable, transform))
end
def into(enumerable, collectable, transform) when is_function(transform, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> enumerable
list when is_list(list) -> list
vector -> RawVector.to_list(vector)
end
|> Enum.into(collectable, transform)
end
@doc """
Given an enumerable of enumerables, concatenates the `enumerables` into
a single list.
Mirrors `Enum.concat/1` with higher performance for Aja structures.
"""
@spec concat(t(t(val))) :: t(val) when val: value
def concat(enumerables) do
case H.try_get_raw_vec_or_list(enumerables) do
nil -> Enum.reverse(enumerables) |> concat_wrap([])
list when is_list(list) -> :lists.reverse(list) |> concat_wrap([])
vector -> RawVector.foldr(vector, [], &concat/2)
end
end
defp concat_wrap(_reversed = [], acc), do: acc
defp concat_wrap([head | tail], acc) do
concat_wrap(tail, concat(head, acc))
end
@doc """
Concatenates the enumerable on the `right` with the enumerable on the `left`.
Mirrors `Enum.concat/2` with higher performance for Aja structures.
"""
@spec concat(t(val), t(val)) :: t(val) when val: value
def concat(left, right)
def concat(left, right) when is_list(left) and is_list(right) do
left ++ right
end
def concat(left, right) do
case H.try_get_raw_vec_or_list(left) do
nil -> Enum.concat(left, right)
list when is_list(list) -> list ++ to_list(right)
vector -> RawVector.to_list(vector, to_list(right))
end
end
@doc """
Finds the element at the given `index` (zero-based).
Mirrors `Enum.at/3` with higher performance for Aja structures.
"""
@spec at(t(val), integer, default) :: val | default when val: value, default: any
def at(enumerable, index, default \\ nil) when is_integer(index) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.at(enumerable, index, default)
list when is_list(list) ->
Enum.at(list, index, default)
vector ->
size = RawVector.size(vector)
case RawVector.actual_index(index, size) do
nil -> default
actual_index -> RawVector.fetch_positive!(vector, actual_index)
end
end
end
@doc """
Finds the element at the given `index` (zero-based).
Mirrors `Enum.fetch/2` with higher performance for Aja structures.
"""
@spec fetch(t(val), integer) :: {:ok, val} | :error when val: value
def fetch(enumerable, index) when is_integer(index) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.fetch(enumerable, index)
list when is_list(list) ->
Enum.fetch(list, index)
vector ->
size = RawVector.size(vector)
case RawVector.actual_index(index, size) do
nil -> :error
actual_index -> {:ok, RawVector.fetch_positive!(vector, actual_index)}
end
end
end
@doc """
Finds the element at the given `index` (zero-based).
Mirrors `Enum.fetch!/2` with higher performance for Aja structures.
"""
@spec fetch!(t(val), integer) :: val when val: value
def fetch!(enumerable, index) when is_integer(index) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.fetch!(enumerable, index)
list when is_list(list) ->
Enum.fetch!(list, index)
vector ->
size = RawVector.size(vector)
case RawVector.actual_index(index, size) do
nil -> raise Enum.OutOfBoundsError
actual_index -> RawVector.fetch_positive!(vector, actual_index)
end
end
end
@doc """
Returns a list of elements in `enumerable` in reverse order.
Mirrors `Enum.reverse/1` with higher performance for Aja structures.
"""
@spec reverse(t(val)) :: [val] when val: value
def reverse(enumerable) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.reverse(enumerable)
list when is_list(list) -> :lists.reverse(list)
vector -> RawVector.reverse_to_list(vector, [])
end
end
@doc """
Reverses the elements in `enumerable`, concatenates the `tail`,
and returns it as a list.
Mirrors `Enum.reverse/2` with higher performance for Aja structures.
"""
@spec reverse(t(val), t(val)) :: [val] when val: value
def reverse(enumerable, tail) do
tail = H.to_list(tail)
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.reverse(enumerable, tail)
list when is_list(list) -> :lists.reverse(list, tail)
vector -> RawVector.reverse_to_list(vector, tail)
end
end
@doc """
Returns a list where each element is the result of invoking
`fun` on each corresponding element of `enumerable`.
Mirrors `Enum.map/2` with higher performance for Aja structures.
"""
@spec map(t(v1), (v1 -> v2)) :: [v2] when v1: value, v2: value
defdelegate map(enumerable, fun), to: H
@doc """
Filters the `enumerable`, i.e. returns only those elements
for which `fun` returns a truthy value.
Mirrors `Enum.filter/2` with higher performance for Aja structures.
"""
@spec filter(t(val), (val -> as_boolean(term))) :: [val] when val: value
def filter(enumerable, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.filter(enumerable, fun)
list when is_list(list) -> filter_list(list, fun, [])
vector -> RawVector.filter_to_list(vector, fun)
end
end
defp filter_list([], _fun, acc), do: :lists.reverse(acc)
defp filter_list([head | tail], fun, acc) do
acc =
if fun.(head) do
[head | acc]
else
acc
end
filter_list(tail, fun, acc)
end
@doc """
Returns a list of elements in `enumerable` excluding those for which the function `fun` returns
a truthy value.
Mirrors `Enum.reject/2` with higher performance for Aja structures.
"""
@spec reject(t(val), (val -> as_boolean(term))) :: [val] when val: value
def reject(enumerable, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.reject(enumerable, fun)
list when is_list(list) -> Enum.reject(list, fun)
vector -> RawVector.reject_to_list(vector, fun)
end
end
@doc """
Splits the `enumerable` in two lists according to the given function `fun`.
Mirrors `Enum.split_with/2` with higher performance for Aja structures.
"""
@spec split_with(t(val), (val -> as_boolean(term))) :: {[val], [val]} when val: value
def split_with(enumerable, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.split_with(enumerable, fun)
list when is_list(list) -> Enum.split_with(list, fun)
vector -> vector |> RawVector.to_list() |> Enum.split_with(fun)
end
end
@doc """
Invokes `fun` for each element in the `enumerable` with the
accumulator.
Mirrors `Enum.reduce/2` with higher performance for Aja structures.
"""
@spec reduce(t(val), (val, val -> val)) :: val when val: value
def reduce(enumerable, fun) when is_function(fun, 2) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.reduce(enumerable, fun)
list when is_list(list) -> Enum.reduce(list, fun)
vector -> RawVector.reduce(vector, fun)
end
end
@doc """
Invokes `fun` for each element in the `enumerable` with the accumulator.
Mirrors `Enum.reduce/3` with higher performance for Aja structures.
"""
@spec reduce(t(val), acc, (val, acc -> acc)) :: acc when val: value, acc: term
def reduce(enumerable, acc, fun) when is_function(fun, 2) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.reduce(enumerable, acc, fun)
list when is_list(list) -> :lists.foldl(fun, acc, list)
vector -> RawVector.foldl(vector, acc, fun)
end
end
# FINDS
@doc """
Returns `true` if at least one element in `enumerable` is truthy.
When an element has a truthy value (neither `false` nor `nil`) iteration stops
immediately and `true` is returned. In all other cases `false` is returned.
## Examples
iex> Aja.Enum.any?([false, false, false])
false
iex> Aja.Enum.any?([false, true, false])
true
iex> Aja.Enum.any?([])
false
"""
@spec any?(t(as_boolean(val))) :: boolean when val: value
def any?(enumerable) do
case enumerable do
%Aja.Vector{__vector__: vector} -> RawVector.any?(vector)
_ -> Enum.any?(enumerable)
end
end
@doc """
Returns `true` if `fun.(element)` is truthy for at least one element in `enumerable`.
Iterates over the `enumerable` and invokes `fun` on each element. When an invocation
of `fun` returns a truthy value (neither `false` nor `nil`) iteration stops
immediately and `true` is returned. In all other cases `false` is returned.
## Examples
iex> Aja.Enum.any?([2, 4, 6], fn x -> rem(x, 2) == 1 end)
false
iex> Aja.Enum.any?([2, 3, 4], fn x -> rem(x, 2) == 1 end)
true
iex> Aja.Enum.any?([], fn x -> x > 0 end)
false
"""
# TODO When only support Elixir 1.12
# @doc copy_doc_for.(:any?, 2)
@spec any?(t(val), (val -> as_boolean(term))) :: boolean when val: value
def any?(enumerable, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.any?(enumerable, fun)
list when is_list(list) -> Enum.any?(list, fun)
vector -> RawVector.any?(vector, fun)
end
end
@doc """
Returns `true` if all elements in `enumerable` are truthy.
When an element has a falsy value (`false` or `nil`) iteration stops immediately
and `false` is returned. In all other cases `true` is returned.
## Examples
iex> Aja.Enum.all?([1, 2, 3])
true
iex> Aja.Enum.all?([1, nil, 3])
false
iex> Aja.Enum.all?([])
true
"""
@spec all?(t(as_boolean(val))) :: boolean when val: value
def all?(enumerable) do
case enumerable do
%Aja.Vector{__vector__: vector} -> RawVector.all?(vector)
_ -> Enum.all?(enumerable)
end
end
@doc """
Returns `true` if `fun.(element)` is truthy for all elements in `enumerable`.
Iterates over `enumerable` and invokes `fun` on each element. If `fun` ever
returns a falsy value (`false` or `nil`), iteration stops immediately and
`false` is returned. Otherwise, `true` is returned.
## Examples
iex> Aja.Enum.all?([2, 4, 6], fn x -> rem(x, 2) == 0 end)
true
iex> Aja.Enum.all?([2, 3, 4], fn x -> rem(x, 2) == 0 end)
false
iex> Aja.Enum.all?([], fn _ -> nil end)
true
"""
# TODO When only support Elixir 1.12
# @doc copy_doc_for.(:all?, 2)
@spec all?(t(val), (val -> as_boolean(term))) :: boolean when val: value
def all?(enumerable, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.all?(enumerable, fun)
list when is_list(list) -> Enum.all?(list, fun)
vector -> RawVector.all?(vector, fun)
end
end
@doc """
Returns the first element for which `fun` returns a truthy value.
If no such element is found, returns `default`.
Mirrors `Enum.find/3` with higher performance for Aja structures.
"""
@spec find(t(val), default, (val -> as_boolean(term))) :: val | default
when val: value, default: value
def find(enumerable, default \\ nil, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.find(enumerable, default, fun)
list when is_list(list) -> Enum.find(list, default, fun)
vector -> RawVector.find(vector, default, fun)
end
end
@doc """
Similar to `find/3`, but returns the value of the function
invocation instead of the element itself.
Mirrors `Enum.find_value/3` with higher performance for Aja structures.
"""
@spec find_value(t(val), default, (val -> new_val)) :: new_val | default
when val: value, new_val: value, default: value
def find_value(enumerable, default \\ nil, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.find_value(enumerable, default, fun)
list when is_list(list) -> Enum.find_value(list, default, fun)
vector -> RawVector.find_value(vector, fun) || default
end
end
@doc """
Similar to `find/3`, but returns the index (zero-based)
of the element instead of the element itself.
Mirrors `Enum.find_index/2` with higher performance for Aja structures.
"""
@spec find_index(t(val), (val -> as_boolean(term))) :: non_neg_integer | nil when val: value
def find_index(enumerable, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.find_index(enumerable, fun)
list when is_list(list) -> Enum.find_index(list, fun)
vector -> RawVector.find_index(vector, fun)
end
end
## FOLDS
@doc """
Returns the sum of all elements.
Mirrors `Enum.sum/1` with higher performance for Aja structures.
"""
@spec sum(t(num)) :: num when num: number
def sum(enumerable) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.sum(enumerable)
list when is_list(list) ->
:lists.sum(list)
vector ->
RawVector.sum(vector)
end
end
@doc """
Returns the product of all elements in the `enumerable`.
Mirrors Enum.product/1 from Elixir 1.12.
Raises `ArithmeticError` if `enumerable` contains a non-numeric value.
## Examples
iex> 1..5 |> Aja.Enum.product()
120
iex> [] |> Aja.Enum.product()
1
"""
@spec product(t(num)) :: num when num: number
def product(enumerable) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
# TODO use Enum.product/1 for Elixir 1.11
reduce(enumerable, 1, &*/2)
list when is_list(list) ->
product_list(list, 1)
vector ->
RawVector.product(vector)
end
end
defp product_list([], acc), do: acc
defp product_list([head | rest], acc) do
product_list(rest, head * acc)
end
@doc """
Joins the given `enumerable` into a string using `joiner` as a
separator.
Mirrors `Enum.join/2` with higher performance for Aja structures.
"""
@spec join(t(val), String.t()) :: String.t() when val: String.Chars.t()
def join(enumerable, joiner \\ "") when is_binary(joiner) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.join(enumerable, joiner)
list when is_list(list) ->
Enum.join(list, joiner)
vector ->
# TODO add join_as_iodata
RawVector.join_as_iodata(vector, joiner) |> IO.iodata_to_binary()
end
end
@doc """
Maps and joins the given `enumerable` in one pass.
Mirrors `Enum.map_join/3` with higher performance for Aja structures.
"""
@spec map_join(t(val), String.t(), (val -> String.Chars.t())) :: String.t()
when val: value
def map_join(enumerable, joiner \\ "", mapper)
when is_binary(joiner) and is_function(mapper, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.map_join(enumerable, joiner, mapper)
list when is_list(list) ->
Enum.map_join(list, joiner, mapper)
# TODO do this in one pass
vector ->
vector
|> RawVector.map(mapper)
|> RawVector.join_as_iodata(joiner)
|> IO.iodata_to_binary()
end
end
@doc """
Intersperses `separator` between each element of the given `enumerable`.
Mirrors `Enum.intersperse/2` with higher performance for Aja structures.
"""
@spec intersperse(t(val), separator) :: [val | separator] when val: value, separator: value
def intersperse(enumerable, separator) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.intersperse(enumerable, separator)
list when is_list(list) -> Enum.intersperse(list, separator)
vector -> RawVector.intersperse_to_list(vector, separator)
end
end
@doc """
Maps and intersperses the given `enumerable` in one pass.
Mirrors `Enum.map_intersperse/3` with higher performance for Aja structures.
"""
@spec map_intersperse(t(val), separator, (val -> mapped_val)) :: [mapped_val | separator]
when val: value, separator: value, mapped_val: value
def map_intersperse(enumerable, separator, mapper)
when is_function(mapper, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.map_intersperse(enumerable, separator, mapper)
list when is_list(list) -> Enum.map_intersperse(list, separator, mapper)
vector -> RawVector.map_intersperse_to_list(vector, separator, mapper)
end
end
@doc """
Maps the given `fun` over `enumerable` and flattens the result.
Mirrors `Enum.flat_map/2` with higher performance for Aja structures.
"""
@spec flat_map(t(val), (val -> t(mapped_val))) :: [mapped_val]
when val: value, mapped_val: value
defdelegate flat_map(enumerable, fun), to: H
@doc """
Returns a map with keys as unique elements of `enumerable` and values
as the count of every element.
Mirrors `Enum.frequencies/1` with higher performance for Aja structures.
"""
@spec frequencies(t(val)) :: %{optional(val) => non_neg_integer} when val: value
def frequencies(enumerable) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.frequencies(enumerable)
list when is_list(list) -> Enum.frequencies(list)
vector -> RawVector.frequencies(vector)
end
end
@doc """
Returns a map with keys as unique elements given by `key_fun` and values
as the count of every element.
Mirrors `Enum.frequencies_by/2` with higher performance for Aja structures.
"""
@spec frequencies_by(t(val), (val -> key)) :: %{optional(key) => non_neg_integer}
when val: value, key: any
def frequencies_by(enumerable, key_fun) when is_function(key_fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.frequencies_by(enumerable, key_fun)
list when is_list(list) -> Enum.frequencies_by(list, key_fun)
vector -> RawVector.frequencies_by(vector, key_fun)
end
end
@doc """
Splits the `enumerable` into groups based on `key_fun`.
Mirrors `Enum.group_by/3` with higher performance for Aja structures.
"""
@spec group_by(t(val), (val -> key), (val -> mapped_val)) :: %{optional(key) => [mapped_val]}
when val: value, key: any, mapped_val: any
def group_by(enumerable, key_fun, value_fun \\ fn x -> x end)
when is_function(key_fun, 1) and is_function(value_fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.group_by(enumerable, key_fun, value_fun)
list when is_list(list) -> Enum.group_by(list, key_fun, value_fun)
vector -> RawVector.group_by(vector, key_fun, value_fun)
end
end
@doc """
Invokes the given `fun` for each element in the `enumerable`.
Mirrors `Enum.each/2` with higher performance for Aja structures.
"""
@spec each(t(val), (val -> term)) :: :ok when val: value
def each(enumerable, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.each(enumerable, fun)
list when is_list(list) -> :lists.foreach(fun, list)
vector -> RawVector.each(vector, fun)
end
end
## RANDOM
@doc """
Returns a random element of an `enumerable`.
Mirrors `Enum.random/1` with higher performance for Aja structures.
"""
@spec random(t(val)) :: val when val: value
def random(enumerable) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.random(enumerable)
list when is_list(list) -> Enum.random(list)
vector -> RawVector.random(vector)
end
end
@doc """
Takes `count` random elements from `enumerable`.
Mirrors `Enum.take_random/2` with higher performance for Aja structures.
"""
@spec take_random(t(val), non_neg_integer) :: [val] when val: value
def take_random(enumerable, count)
def take_random(_enumerable, 0), do: []
# TODO: optimize 1 for non-empty vectors
def take_random(enumerable, count) do
enumerable
|> H.to_list()
|> Enum.take_random(count)
end
@doc """
Returns a list with the elements of `enumerable` shuffled.
Mirrors `Enum.shuffle/1` with higher performance for Aja structures.
"""
@spec shuffle(t(val)) :: [val] when val: value
def shuffle(enumerable) do
enumerable
|> H.to_list()
|> Enum.shuffle()
end
# UNIQ
@doc """
Enumerates the `enumerable`, returning a list where all consecutive
duplicated elements are collapsed to a single element.
Mirrors `Enum.dedup/1` with higher performance for Aja structures.
"""
@spec dedup(t(val)) :: [val] when val: value
def dedup(enumerable)
def dedup(%MapSet{} = set) do
MapSet.to_list(set)
end
def dedup(enumerable) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.dedup(enumerable)
list when is_list(list) -> dedup_list(list)
vector -> RawVector.dedup_list(vector)
end
end
@doc """
Enumerates the `enumerable`, returning a list where all consecutive
duplicated elements are collapsed to a single element.
Mirrors `Enum.dedup_by/2` with higher performance for Aja structures.
"""
@spec dedup_by(t(val), (val -> term)) :: [val] when val: value
def dedup_by(enumerable, fun) when is_function(fun, 1) do
enumerable
|> H.to_list()
|> Enum.dedup_by(fun)
end
@doc """
Enumerates the `enumerable`, removing all duplicated elements.
Mirrors `Enum.uniq/1` with higher performance for Aja structures.
"""
@spec uniq(t(val)) :: [val] when val: value
def uniq(enumerable)
def uniq(%MapSet{} = set) do
MapSet.to_list(set)
end
def uniq(enumerable) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.uniq(enumerable)
list when is_list(list) -> Enum.uniq(list)
vector -> RawVector.uniq_list(vector)
end
end
@doc """
Enumerates the `enumerable`, by removing the elements for which
function `fun` returned duplicate elements.
Mirrors `Enum.uniq_by/2` with higher performance for Aja structures.
"""
@spec uniq_by(t(val), (val -> term)) :: [val] when val: value
def uniq_by(enumerable, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.uniq_by(enumerable, fun)
list when is_list(list) -> Enum.uniq_by(list, fun)
vector -> RawVector.uniq_by_list(vector, fun)
end
end
# ## MIN-MAX
defguardp is_list_or_struct(enumerable)
when is_list(enumerable) or :erlang.map_get(:__struct__, enumerable) |> is_atom()
defguardp is_empty_list_or_vec(list_or_vec)
when list_or_vec === [] or list_or_vec === @empty_vector
@doc false
def min(enumerable) when is_list_or_struct(enumerable) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.min(enumerable)
empty when is_empty_list_or_vec(empty) -> raise Enum.EmptyError
list when is_list(list) -> :lists.min(list)
vector -> RawVector.min(vector)
end
end
@doc false
@spec min(t(val), (() -> empty_result)) :: val | empty_result when val: value, empty_result: any
def min(enumerable, empty_fallback) when is_function(empty_fallback, 0) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.min(enumerable, empty_fallback)
empty when is_empty_list_or_vec(empty) -> empty_fallback.()
list when is_list(list) -> :lists.min(list)
vector -> RawVector.min(vector)
end
end
@doc """
Returns the minimal element in the `enumerable` according
to Erlang's term ordering.
Mirrors `Enum.min/3` with higher performance for Aja structures.
"""
@spec min(t(val), (val, val -> boolean) | module, (() -> empty_result)) :: val | empty_result
when val: value, empty_result: any
def min(enumerable, sorter \\ &<=/2, empty_fallback \\ fn -> raise Enum.EmptyError end)
when is_function(empty_fallback, 0) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.min(enumerable, sorter, empty_fallback)
@empty_vector -> empty_fallback.()
list when is_list(list) -> Enum.min(list, sorter, empty_fallback)
vector -> RawVector.custom_min_max(vector, min_sort_fun(sorter))
end
end
@doc false
def max(enumerable) when is_list_or_struct(enumerable) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.max(enumerable)
empty when is_empty_list_or_vec(empty) -> raise Enum.EmptyError
list when is_list(list) -> :lists.max(list)
vector -> RawVector.max(vector)
end
end
@doc false
@spec max(t(val), (() -> empty_result)) :: val | empty_result when val: value, empty_result: any
def max(enumerable, empty_fallback) when is_function(empty_fallback, 0) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.max(enumerable, empty_fallback)
empty when is_empty_list_or_vec(empty) -> empty_fallback.()
list when is_list(list) -> :lists.max(list)
vector -> RawVector.max(vector)
end
end
@doc """
Returns the maximal element in the `enumerable` according
to Erlang's term ordering.
Mirrors `Enum.max/3` with higher performance for Aja structures.
"""
@spec max(t(val), (val, val -> boolean) | module, (() -> empty_result)) :: val | empty_result
when val: value, empty_result: any
def max(enumerable, sorter \\ &>=/2, empty_fallback \\ fn -> raise Enum.EmptyError end)
when is_function(empty_fallback, 0) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.max(enumerable, sorter, empty_fallback)
@empty_vector -> empty_fallback.()
list when is_list(list) -> Enum.max(list, sorter, empty_fallback)
vector -> RawVector.custom_min_max(vector, max_sort_fun(sorter))
end
end
@doc false
def min_by(enumerable, fun, empty_fallback)
when is_function(fun, 1) and is_function(empty_fallback, 0) do
min_by(enumerable, fun, &<=/2, empty_fallback)
end
@doc """
Returns the minimal element in the `enumerable` as calculated
by the given `fun`.
Mirrors `Enum.min_by/4` with higher performance for Aja structures.
"""
@spec min_by(t(val), (val -> key), (key, key -> boolean) | module, (() -> empty_result)) ::
val | empty_result
when val: value, key: term, empty_result: any
def min_by(enumerable, fun, sorter \\ &<=/2, empty_fallback \\ fn -> raise Enum.EmptyError end)
when is_function(fun, 1) and is_function(empty_fallback, 0) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.min_by(enumerable, fun, sorter, empty_fallback)
list when is_list(list) -> Enum.min_by(list, fun, sorter, empty_fallback)
@empty_vector -> empty_fallback.()
vector -> RawVector.custom_min_max_by(vector, fun, min_sort_fun(sorter))
end
end
@doc false
def max_by(enumerable, fun, empty_fallback)
when is_function(fun, 1) and is_function(empty_fallback, 0) do
max_by(enumerable, fun, &>=/2, empty_fallback)
end
@doc """
Returns the maximal element in the `enumerable` as calculated
by the given `fun`.
Mirrors `Enum.max_by/4` with higher performance for Aja structures.
"""
@spec max_by(t(val), (val -> key), (key, key -> boolean) | module, (() -> empty_result)) ::
val | empty_result
when val: value, key: term, empty_result: any
def max_by(enumerable, fun, sorter \\ &>=/2, empty_fallback \\ fn -> raise Enum.EmptyError end)
when is_function(fun, 1) and is_function(empty_fallback, 0) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.max_by(enumerable, fun, sorter, empty_fallback)
list when is_list(list) -> Enum.max_by(list, fun, sorter, empty_fallback)
@empty_vector -> empty_fallback.()
vector -> RawVector.custom_min_max_by(vector, fun, max_sort_fun(sorter))
end
end
defp max_sort_fun(sorter) when is_function(sorter, 2), do: sorter
defp max_sort_fun(module) when is_atom(module), do: &(module.compare(&1, &2) != :lt)
defp min_sort_fun(sorter) when is_function(sorter, 2), do: sorter
defp min_sort_fun(module) when is_atom(module), do: &(module.compare(&1, &2) != :gt)
## MAP-REDUCE
@doc ~S"""
Returns a list with with each element of `enumerable` wrapped in a tuple alongside its index.
Mirrors `Enum.with_index/2` (Elixir 1.12 version): may receive a function or an integer offset.
If an integer `offset` is given, it will index from the given `offset` instead of from zero.
If a `function` is given, it will index by invoking the function for each
element and index (zero-based) of the `enumerable`.
## Examples
iex> Aja.Enum.with_index([:a, :b, :c])
[a: 0, b: 1, c: 2]
iex> Aja.Enum.with_index([:a, :b, :c], 3)
[a: 3, b: 4, c: 5]
iex> Aja.Enum.with_index([:a, :b, :c], fn element, index -> {index, element} end)
[{0, :a}, {1, :b}, {2, :c}]
"""
@spec with_index(t(val), index) :: [{val, index}] when val: value
@spec with_index(t(val), (val, index -> mapped_val)) :: [mapped_val]
when val: value, mapped_val: value
def with_index(enumerable, offset_or_fun \\ 0)
def with_index(enumerable, offset) when is_integer(offset) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.with_index(enumerable, offset)
list when is_list(list) -> with_index_list_offset(list, offset, [])
vector -> RawVector.with_index(vector, offset) |> RawVector.to_list()
end
end
def with_index(enumerable, fun) when is_function(fun, 2) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
enumerable
|> Enum.map_reduce(0, fn x, i -> {fun.(x, i), i + 1} end)
|> elem(0)
list when is_list(list) ->
with_index_list_fun(list, 0, fun, [])
vector ->
RawVector.with_index(vector, 0, fun) |> RawVector.to_list()
end
end
defp with_index_list_offset([], _offset, acc), do: :lists.reverse(acc)
defp with_index_list_offset([head | tail], offset, acc) do
with_index_list_offset(tail, offset + 1, [{head, offset} | acc])
end
defp with_index_list_fun([], _offset, _fun, acc), do: :lists.reverse(acc)
defp with_index_list_fun([head | tail], offset, fun, acc) do
with_index_list_fun(tail, offset + 1, fun, [fun.(head, offset) | acc])
end
@doc """
Invokes the given function to each element in the `enumerable` to reduce
it to a single element, while keeping an accumulator.
Mirrors `Enum.map_reduce/3` with higher performance for Aja structures.
"""
@spec map_reduce(t(val), acc, (val, acc -> {mapped_val, acc})) :: {t(mapped_val), acc}
when val: value, mapped_val: value, acc: any
def map_reduce(enumerable, acc, fun) when is_function(fun, 2) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.map_reduce(enumerable, acc, fun)
list when is_list(list) ->
:lists.mapfoldl(fun, acc, list)
vector ->
{new_vector, new_acc} = RawVector.map_reduce(vector, acc, fun)
{RawVector.to_list(new_vector), new_acc}
end
end
@doc """
Applies the given function to each element in the `enumerable`,
storing the result in a list and passing it as the accumulator
for the next computation. Uses the first element in the `enumerable`
as the starting value.
Mirrors `Enum.scan/2` with higher performance for Aja structures.
"""
@spec scan(t(val), (val, val -> val)) :: val when val: value
def scan(enumerable, fun) when is_function(fun, 2) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.scan(enumerable, fun)
list when is_list(list) -> Enum.scan(list, fun)
vector -> RawVector.scan(vector, fun) |> RawVector.to_list()
end
end
@doc """
Applies the given function to each element in the `enumerable`,
storing the result in a list and passing it as the accumulator
for the next computation. Uses the given `acc` as the starting value.
Mirrors `Enum.scan/3` with higher performance for Aja structures.
"""
@spec scan(t(val), acc, (val, acc -> acc)) :: acc when val: value, acc: term
def scan(enumerable, acc, fun) when is_function(fun, 2) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.scan(enumerable, acc, fun)
list when is_list(list) -> Enum.scan(list, acc, fun)
vector -> RawVector.scan(vector, acc, fun) |> RawVector.to_list()
end
end
## SLICING
@doc """
Takes an `amount` of elements from the beginning or the end of the `enumerable`.
Mirrors `Enum.take/2` with higher performance for Aja structures.
"""
@spec take(t(val), integer) :: [val] when val: value
def take(enumerable, amount) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.take(enumerable, amount)
list when is_list(list) -> Enum.take(list, amount)
vector -> do_take_vector(vector, amount)
end
end
defp do_take_vector(_vector, 0), do: []
defp do_take_vector(vector, amount) when amount > 0 do
size = RawVector.size(vector)
if amount < size do
RawVector.slice(vector, 0, amount - 1)
else
RawVector.to_list(vector)
end
end
defp do_take_vector(vector, amount) do
size = RawVector.size(vector)
start = amount + size
if start > 0 do
RawVector.slice(vector, start, size - 1)
else
RawVector.to_list(vector)
end
end
@doc """
Drops the `amount` of elements from the `enumerable`.
Mirrors `Enum.drop/2` with higher performance for Aja structures.
"""
@spec drop(t(val), integer) :: [val] when val: value
def drop(enumerable, amount) do
case H.try_get_raw_vec_or_list(enumerable) do
nil -> Enum.drop(enumerable, amount)
list when is_list(list) -> Enum.drop(list, amount)
vector -> do_drop_vector(vector, amount)
end
end
defp do_drop_vector(vector, 0), do: RawVector.to_list(vector)
defp do_drop_vector(vector, amount) when amount > 0 do
size = RawVector.size(vector)
if amount < size do
RawVector.slice(vector, amount, size - 1)
else
[]
end
end
defp do_drop_vector(vector, amount) do
size = RawVector.size(vector)
last = amount + size
if last > 0 do
RawVector.slice(vector, 0, last - 1)
else
[]
end
end
@doc """
Splits the `enumerable` into two enumerables, leaving `count` elements in the first one.
Mirrors `Enum.split/2` with higher performance for Aja structures.
"""
@spec split(t(val), integer) :: {[val], [val]} when val: value
def split(enumerable, amount) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.split(enumerable, amount)
list when is_list(list) ->
Enum.split(list, amount)
vector ->
if amount >= 0 do
{do_take_vector(vector, amount), do_drop_vector(vector, amount)}
else
{do_drop_vector(vector, amount), do_take_vector(vector, amount)}
end
end
end
@doc """
Takes the elements from the beginning of the `enumerable` while `fun` returns a truthy value.
Mirrors `Enum.take_while/2` with higher performance for Aja structures.
"""
@spec take_while(t(val), (val -> as_boolean(term()))) :: [val] when val: value
def take_while(enumerable, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.take_while(enumerable, fun)
list when is_list(list) ->
Enum.take_while(list, fun)
vector ->
case RawVector.find_falsy_index(vector, fun) do
nil -> RawVector.to_list(vector)
index -> do_take_vector(vector, index)
end
end
end
@doc """
Drops elements at the beginning of the `enumerable` while `fun` returns a truthy value.
Mirrors `Enum.drop_while/2` with higher performance for Aja structures.
"""
@spec drop_while(t(val), (val -> as_boolean(term()))) :: [val] when val: value
def drop_while(enumerable, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.drop_while(enumerable, fun)
list when is_list(list) ->
Enum.drop_while(list, fun)
vector ->
case RawVector.find_falsy_index(vector, fun) do
nil -> []
index -> do_drop_vector(vector, index)
end
end
end
@doc """
Splits `enumerable` in two at the position of the element for which `fun` returns a falsy value
(`false` or `nil`) for the first time.
Mirrors `Enum.split_while/2` with higher performance for Aja structures.
"""
@spec split_while(t(val), (val -> as_boolean(term()))) :: {[val], [val]} when val: value
def split_while(enumerable, fun) when is_function(fun, 1) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.split_while(enumerable, fun)
list when is_list(list) ->
Enum.split_while(list, fun)
vector ->
case RawVector.find_falsy_index(vector, fun) do
nil -> {RawVector.to_list(vector), []}
index -> {do_take_vector(vector, index), do_drop_vector(vector, index)}
end
end
end
## SORT
@doc """
Sorts the `enumerable` according to Erlang's term ordering.
Mirrors `Enum.sort/1` with higher performance for Aja structures.
"""
@spec sort(t(val)) :: [val] when val: value
def sort(enumerable) do
enumerable
|> H.to_list()
|> Enum.sort()
end
@doc """
Sorts the `enumerable` by the given function.
Mirrors `Enum.sort/2` with higher performance for Aja structures.
"""
@spec sort(
t(val),
(val, val -> boolean)
| :asc
| :desc
| module
| {:asc | :desc, module}
) :: [val]
when val: value
def sort(enumerable, fun) do
enumerable
|> H.to_list()
|> Enum.sort(fun)
end
@doc """
Sorts the mapped results of the `enumerable` according to the provided `sorter`
function.
Mirrors `Enum.sort_by/3` with higher performance for Aja structures.
"""
@spec sort_by(
t(val),
(val -> mapped_val),
(val, val -> boolean)
| :asc
| :desc
| module
| {:asc | :desc, module}
) :: [val]
when val: value, mapped_val: value
def sort_by(enumerable, mapper, sorter \\ &<=/2) do
enumerable
|> H.to_list()
|> Enum.sort_by(mapper, sorter)
end
@doc """
Zips corresponding elements from two enumerables into one list of tuples.
Mirrors `Enum.zip/2` with higher performance for Aja structures.
"""
@spec zip(t(val1), t(val2)) :: list({val1, val2}) when val1: value, val2: value
def zip(enumerable1, enumerable2) do
case {H.try_get_raw_vec_or_list(enumerable1), H.try_get_raw_vec_or_list(enumerable2)} do
{vector1, vector2} when is_tuple(vector1) and is_tuple(vector2) ->
RawVector.zip(vector1, vector2) |> RawVector.to_list()
{list1, list2} when is_list(list1) and is_list(list2) ->
zip_lists(list1, list2, [])
{result1, result2} ->
list_or_enum1 = zip_try_get_list(result1, enumerable1)
list_or_enum2 = zip_try_get_list(result2, enumerable2)
Enum.zip(list_or_enum1, list_or_enum2)
end
end
defp zip_try_get_list(list, _enumerable) when is_list(list), do: list
defp zip_try_get_list(nil, enumerable), do: enumerable
defp zip_try_get_list(vector, _enumerable), do: RawVector.to_list(vector)
defp zip_lists(list1, list2, acc) when list1 == [] or list2 == [] do
:lists.reverse(acc)
end
defp zip_lists([head1 | tail1], [head2 | tail2], acc) do
zip_lists(tail1, tail2, [{head1, head2} | acc])
end
@doc """
Opposite of `zip/2`. Extracts two-element tuples from the given `enumerable`
and groups them together.
Mirrors `Enum.unzip/1` with higher performance for Aja structures.
"""
@spec unzip(t({val1, val2})) :: {list(val1), list(val2)} when val1: value, val2: value
def unzip(enumerable) do
case H.try_get_raw_vec_or_list(enumerable) do
nil ->
Enum.unzip(enumerable)
list when is_list(list) ->
Enum.unzip(list)
vector ->
{vector1, vector2} = RawVector.unzip(vector)
{RawVector.to_list(vector1), RawVector.to_list(vector2)}
end
end
# Private functions
defp dedup_list([]), do: []
defp dedup_list([elem, elem | rest]), do: dedup_list([elem | rest])
defp dedup_list([elem | rest]), do: [elem | dedup_list(rest)]
end
|
lib/enum.ex
| 0.798029 | 0.824391 |
enum.ex
|
starcoder
|
defmodule Ockam.SecureChannel.EncryptedTransportProtocol.AeadAesGcm do
@moduledoc false
alias Ockam.Message
alias Ockam.Router
alias Ockam.Vault
alias Ockam.Wire
def setup(_options, initial_state, data) do
{:ok, initial_state, data}
end
## TODO: batter name to not collide with Ockam.Worker.handle_message
def handle_message(message, state, data) do
first_address = message |> Message.onward_route() |> List.first()
cond do
first_address === data.ciphertext_address ->
decrypt_and_send_to_router(message, state, data)
first_address === data.plaintext_address ->
encrypt_and_send_to_peer(message, state, data)
true ->
{:next_state, state, data}
end
end
defp encrypt_and_send_to_peer(message, state, data) do
forwarded_message = Message.forward(message)
with {:ok, encoded} <- Wire.encode(forwarded_message),
{:ok, encrypted, data} <- encrypt(encoded, data) do
## TODO: optimise double encoding of binaries
## Rust implementation is using implicit encoding,
## which encodes binaries even if it's not necessary
payload = :bare.encode(encrypted, :data)
envelope = %{
payload: payload,
onward_route: data.peer.route,
return_route: [data.ciphertext_address]
}
Router.route(envelope)
{:next_state, state, data}
end
end
defp encrypt(plaintext, %{encrypted_transport: encrypted_transport, vault: vault} = data) do
%{encrypt: {k, n}} = encrypted_transport
## TODO: Should we use the hash from handshake here?
hash = ""
with {:ok, ciphertext} <- Vault.aead_aes_gcm_encrypt(vault, k, n, hash, plaintext),
{:ok, next_n} <- increment_nonce(n) do
data = Map.put(data, :encrypted_transport, %{encrypted_transport | encrypt: {k, next_n}})
{:ok, <<n::unsigned-big-integer-size(64)>> <> ciphertext, data}
end
end
## TODO: refactor these modules, use `state` instead of `data`
defp decrypt_and_send_to_router(envelope, state, data) do
payload = Message.payload(envelope)
## TODO: optimise double encoding of binaries
{:ok, encrypted, ""} = :bare.decode(payload, :data)
with {:ok, decrypted, data} <- decrypt(encrypted, data),
{:ok, decoded} <- Wire.decode(decrypted) do
message = Message.trace(decoded, data.plaintext_address)
Router.route(message)
{:next_state, state, data}
end
end
defp decrypt(<<n::unsigned-big-integer-size(64), ciphertext::binary>>, data) do
%{encrypted_transport: encrypted_transport, vault: vault} = data
%{decrypt: {k, _expected_n}} = encrypted_transport
## TODO: Should we use the hash from handshake here?
hash = ""
with {:ok, plaintext} <- Vault.aead_aes_gcm_decrypt(vault, k, n, hash, ciphertext),
{:ok, next_expected_n} <- increment_nonce(n) do
data =
Map.put(data, :encrypted_transport, %{encrypted_transport | decrypt: {k, next_expected_n}})
{:ok, plaintext, data}
end
end
# TODO: we can reuse a nonse, we must rotate keys
defp increment_nonce(65_535), do: {:error, nil}
defp increment_nonce(n), do: {:ok, n + 1}
end
|
implementations/elixir/ockam/ockam/lib/ockam/secure_channel/encrypted_transport_protocol/aead_aes_gcm.ex
| 0.547948 | 0.480418 |
aead_aes_gcm.ex
|
starcoder
|
defmodule Dust.Parsers.URI do
@moduledoc """
Parse document and returl all links/URIs to
styles with absolute urls.
"""
@css_url_regex ~r/url\(['"]?(?<uri>.*?)['"]?\)/
@doc """
Extract all CSS `url(...)` links
"""
@spec parse(String.t()) :: list(String.t())
def parse(content) do
@css_url_regex
|> Regex.scan(content)
|> Enum.map(&Enum.at(&1, 1))
|> Enum.reject(&is_empty?/1)
|> Enum.reject(&is_data_url?/1)
|> Enum.reject(&is_font?/1)
end
@doc """
Expands relative urls to absolute urls
and augments things like
```
protocol https
-> // -> https://..
relative paths
../../../some.css => example.com/styles/some.css
```
We also take care about default scheme which is `https`
if `relative_path` starts with `//example.com/my/awesome/style`
"""
@spec expand(String.t(), String.t()) :: String.t()
def expand(request_url, relative_path) do
uri = normalize(request_url)
# If relative path is an absolute url then
# we need to return it else we need to parse
# and return expanded url.
cond do
String.starts_with?(relative_path, "http") ->
relative_path
String.starts_with?(relative_path, "//") ->
"https://#{relative_path}"
true ->
expanded =
relative_path
|> Path.expand(Path.dirname(uri.path || "/"))
URI.to_string(%URI{uri | path: expanded})
end
end
@spec get_base_url(String.t()) :: URI.t() | any()
def get_base_url(uri, domain \\ true)
def get_base_url(uri, domain) do
url = URI.parse(uri)
base = %URI{
scheme: url.scheme || "https",
host: url.host,
port: url.port,
userinfo: url.userinfo,
query: nil,
fragment: nil
}
cond do
domain ->
URI.to_string(base)
Path.extname(url.path) == "" ->
URI.to_string(%URI{base | path: url.path})
# If we have extension .js, .css etc.
true ->
URI.to_string(%URI{base | path: Path.dirname(url.path)})
end
end
def normalize(url, as_string \\ false)
def normalize(url, as_string) do
uri = URI.parse(url)
url_to_string = fn uri ->
if as_string do
URI.to_string(uri)
else
uri
end
end
if is_nil(uri.scheme) do
url_to_string.(%URI{uri | scheme: "https"})
else
url_to_string.(uri)
end
end
def is_empty?(url) do
is_nil(url) || String.trim(url) == ""
end
def is_font?(url) do
String.contains?(url, ".ttf") ||
String.contains?(url, ".woff") ||
String.contains?(url, ".woff2") ||
String.contains?(url, ".otf") ||
String.contains?(url, ".eot") ||
String.contains?(url, ".ttc")
end
def is_data_url?(url) do
String.starts_with?(url, "data:image")
end
end
|
lib/dust/parsers/uri.ex
| 0.723016 | 0.546254 |
uri.ex
|
starcoder
|
if Code.ensure_loaded?(Ecto.Type) do
defmodule Money.Ecto.Map.Type do
@moduledoc """
Implements Ecto.Type behaviour for Money, where the underlying schema type
is a map.
This is the required option for databases such as MySQL that do not support
composite types.
In order to preserve precision, the amount is serialized as a string since the
JSON representation of a numeric value is either an integer or a float.
`Decimal.to_string/1` is not guaranteed to produce a string that will round-trip
convert back to the identical number.
"""
use Ecto.ParameterizedType
defdelegate init(params), to: Money.Ecto.Composite.Type
defdelegate cast(money), to: Money.Ecto.Composite.Type
defdelegate cast(money, params), to: Money.Ecto.Composite.Type
# New for ecto_sql 3.2
defdelegate embed_as(term), to: Money.Ecto.Composite.Type
defdelegate embed_as(term, params), to: Money.Ecto.Composite.Type
defdelegate equal?(term1, term2), to: Money.Ecto.Composite.Type
defdelegate equal?(term1, term2, params), to: Money.Ecto.Composite.Type
def type(_params) do
:map
end
def load(money, loader \\ nil, params \\ [])
def load(nil, _loader, _params) do
{:ok, nil}
end
def load(%{"currency" => currency, "amount" => amount}, _loader, params)
when is_binary(amount) do
with {amount, ""} <- Cldr.Decimal.parse(amount),
{:ok, currency} <- Money.validate_currency(currency) do
{:ok, Money.new(currency, amount, params)}
else
_ -> :error
end
end
def load(%{"currency" => currency, "amount" => amount}, _loader, params)
when is_integer(amount) do
with {:ok, currency} <- Money.validate_currency(currency) do
{:ok, Money.new(currency, amount, params)}
else
_ -> :error
end
end
def dump(money, dumper \\ nil, params \\ [])
def dump(%Money{currency: currency, amount: %Decimal{} = amount}, _dumper, _params) do
{:ok, %{"currency" => to_string(currency), "amount" => Decimal.to_string(amount)}}
end
def dump(nil, _, _) do
{:ok, nil}
end
def dump(_, _, _) do
:error
end
end
end
|
lib/money/ecto/money_ecto_map_type.ex
| 0.654784 | 0.463748 |
money_ecto_map_type.ex
|
starcoder
|
defmodule AttributeRepository.Write do
@moduledoc """
Callbacks for modification of entries
There are 3 callbacks:
- `put/3` that entirely replaces the resource with new attribute values
- `modify/3` that replaces some attributes
- `delete/2` that deletes an entire resource
"""
@doc """
Replaces a new resource
Replaces entirely the resource `resource_id` with the attributes of `resource`, or create
it if the resource does not exist.
When inserting `use AttributeRepository.Write` at the begining of an implementation,
the `put!/3` banged version will be automatically created.
## Example
```elixir
iex> run_opts = [instance: :users, bucket_type: "attr_rep"]
iex> AttributeRepositoryRiak.put("WCJBCL7SC2THS7TSRXB2KZH7OQ",
%{"first_name" => "Narivelo",
"last_name" => "Rajaonarimanana",
"shoe_size" => 41,
"subscription_date" => DateTime.from_iso8601("2017-06-06T21:01:43Z") |> elem(1),
"newsletter_subscribed" => false}, run_opts)
{:ok,
%{
"first_name" => "Narivelo",
"last_name" => "Rajaonarimanana",
"newsletter_subscribed" => false,
"shoe_size" => 41,
"subscription_date" => #DateTime<2017-06-06 21:01:43Z>
}}
```
"""
@callback put(
AttributeRepository.resource_id(),
AttributeRepository.resource(),
AttributeRepository.run_opts()
) ::
{:ok, AttributeRepository.resource()}
| {:error, %AttributeRepository.WriteError{}}
| {:error, %AttributeRepository.UnsupportedError{}}
@doc """
Modifies attributes of a resource
Applies the list of modification operations (`[modify_op]`) to a resource.
When inserting `use AttributeRepository.Write` at the begining of an implementation,
the`resource_id` `modify!/3` banged version will be automatically created.
## Example
```elixir
iex> run_opts = [instance: :users, bucket_type: "attr_rep"]
iex> AttributeRepositoryRiak.get("Y4HKZMJ3K5A7IMZFZ5O3O56VC4", :all, run_opts)
{:ok,
%{
"first_name" => "Lisa",
"last_name" => "Santana",
"newsletter_subscribed" => true,
"shoe_size" => 33,
"subscription_date" => #DateTime<2014-08-30 13:45:45Z>
}}
iex> AttributeRepositoryRiak.modify("Y4HKZMJ3K5A7IMZFZ5O3O56VC4",
[
{:replace, "shoe_size", 34},
{:add, "interests", ["rock climbing", "tango", "linguistics"]}
], run_opts)
:ok
iex> AttributeRepositoryRiak.get!("Y4HKZMJ3K5A7IMZFZ5O3O56VC4", :all, run_opts)
%{
"first_name" => "Lisa",
"interests" => ["linguistics", "rock climbing", "tango"],
"last_name" => "Santana",
"newsletter_subscribed" => true,
"shoe_size" => 34,
"subscription_date" => #DateTime<2014-08-30 13:45:45Z>
}
```
"""
@callback modify(
AttributeRepository.resource_id(),
[modify_op()],
AttributeRepository.run_opts()
) ::
:ok
| {:error, %AttributeRepository.WriteError{}}
| {:error, %AttributeRepository.ReadError{}}
| {:error, %AttributeRepository.Read.NotFoundError{}}
| {:error, %AttributeRepository.UnsupportedError{}}
@type modify_op :: modify_op_add() | modify_op_replace() | modify_op_delete()
@typedoc """
Adds an attribute to a resource
## Rules
- If the attribute already exists:
- If the attribute is multi-valued: add the new value to the multi-valued attribute
- Otherwise (the attribute is single-valued), replace the value of the target attribute
- Otherwise, add it as a new attribute
"""
@type modify_op_add ::
{:add, AttributeRepository.attribute_name(), AttributeRepository.attribute_value()}
@typedoc """
Modifies an attribute
## Rules
- The 3-tuple is equivalent to the `:add` operation
- Regarding the 4-tuple:
- if the existing attribute is a set:
- If the attribute already exists, replace it
- Otherwise, add it as a new attribute
- otherwise, add the new value as an attribute
"""
@type modify_op_replace ::
{:replace, AttributeRepository.attribute_name(), AttributeRepository.attribute_value()}
| {:replace, AttributeRepository.attribute_name(),
AttributeRepository.attribute_value(), AttributeRepository.attribute_value()}
@typedoc """
Deletes an attribute
## Rules
- 2-tuple: deletes the attribute
- 3-tuple:
- if the existing attribute is a set, delete the value if it exists
- otherwise, do not delete anything
"""
@type modify_op_delete ::
{:delete, AttributeRepository.attribute_name()}
| {:delete, AttributeRepository.attribute_name(), AttributeRepository.attribute_value()}
@callback delete(
AttributeRepository.resource_id(),
AttributeRepository.run_opts()
) ::
:ok
| {:error, %AttributeRepository.WriteError{}}
| {:error, %AttributeRepository.Read.NotFoundError{}}
defmacro __using__(_opts) do
quote do
def put!(resource_id, resource, opts) do
case put(resource_id, resource, opts) do
{:ok, resource} ->
resource
{:error, exception} ->
raise exception
end
end
def delete!(resource_id, opts) do
case delete(resource_id, opts) do
:ok ->
:ok
{:error, exception} ->
raise exception
end
end
end
end
defmodule NotFoundError do
@moduledoc """
Error returned when a resource expected to be found was not found
"""
defexception message: "Resource not found"
end
end
|
lib/attribute_repository/write.ex
| 0.884233 | 0.57827 |
write.ex
|
starcoder
|
defmodule Cerebrum.Genotype.Cypher do
alias Cerebrum.Neuron
alias Cerebrum.Sensor
alias Cerebrum.Actuator
def create_node(%Neuron{name: name, activation_function: activation_function, bias: bias}, graph_name) do
"CREATE (#{name}:Neuron {activation_function:'#{activation_function}', bias: #{bias}, #{graph_name}: true})"
end
def create_node(%Sensor{name: name, sense_function: sense_function, output_vector_length: output_vector_length}, graph_name) do
"CREATE (#{name}:Sensor {sense_function: '#{sense_function}', output_vector_length: #{output_vector_length}, #{graph_name}: true})"
end
def create_node(%Actuator{name: name, accumulator_function: accumulator_function, accumulated_actuation_vector_length: accumulated_actuation_vector_length}, graph_name) do
"CREATE (#{name}:Actuator {accumulator_function: '#{accumulator_function}', accumulated_actuation_vector_length: #{accumulated_actuation_vector_length}, #{graph_name}: true})"
end
def create_relationship(first_node, second_node, weights) do
"CREATE (#{first_node})-[:OUTPUT{weights: [#{Enum.join(weights, ", ")}]}]->(#{second_node})"
end
def relate_sensor_to_neurons(sensor, neurons, weight_function) do
weights = 1..sensor.output_vector_length |> Enum.map(&weight_function.(&1))
neurons |> Enum.map(&create_relationship(sensor.name, &1.name, weights))
end
def relate_actuator_to_neurons(actuator, neurons, weight_function) do
weights = [weight_function.(1)]
neurons |> Enum.map(&create_relationship(&1.name, actuator.name, weights))
end
def relate_neuron_to_neurons(neuron, neurons, weight_function) do
weights = [weight_function.(1)]
neurons |> Enum.map(&create_relationship(neuron.name, &1.name, weights))
end
def relate_neurons_to_neurons(neurons_left, neurons_right, weight_function) do
neurons_left
|> Enum.map(&relate_neuron_to_neurons(&1, neurons_right, weight_function))
|> List.flatten
end
def create_neural_network(sensor, actuator, hidden_layer_densities, bias_function, neuron_activation_function, weight_function, graph_name) do
neuron_layers = actuator
|> layer_densities(hidden_layer_densities)
|> Neuron.create_layers(bias_function, neuron_activation_function)
nodes = [sensor, actuator, neuron_layers] |> List.flatten |> Enum.map(&create_node(&1, graph_name))
relations = relate_network(sensor, neuron_layers, actuator, weight_function)
[nodes | relations] |> List.flatten
end
defp layer_densities(actuator, hidden_layer_densities) do
[actuator.accumulated_actuation_vector_length | hidden_layer_densities |> Enum.reverse] |> Enum.reverse
end
defp relate_network(nil, [last_neuron_layer | []], actuator, weight_function) do
[relate_actuator_to_neurons(actuator, last_neuron_layer, weight_function)]
end
defp relate_network(nil, [neuron_layer | [next_neuron_layer | _] = remaining_neuron_layers], actuator, weight_function) do
[
relate_neurons_to_neurons(neuron_layer, next_neuron_layer, weight_function)
| relate_network(nil, remaining_neuron_layers, actuator, weight_function)
]
end
defp relate_network(sensor, [first_neuron_layer | _] = neurons_by_layers, actuator, weight_function) do
[
relate_sensor_to_neurons(sensor, first_neuron_layer, weight_function)
| relate_network(nil, neurons_by_layers, actuator, weight_function)
]
end
end
|
lib/Genotype/cypher.ex
| 0.654453 | 0.647074 |
cypher.ex
|
starcoder
|
defmodule ExRaft.StateMachine do
@moduledoc """
A behaviour module for implementing consistently replicated state machines.
## Example
To start things off, let's see a code example implementing a simple
key value store in `ExRaft` style:
defmodule KeyValueStore do
@behaviour ExRaft.StateMachine
@impl true
def init(init_state) do
{:ok, init_state}
end
@impl true
def command?({:put, _, _}, _), do: true
def command?(_, _), do: false
@impl true
def handle_write({:put, key, value}, state) do
new_state = Map.put(state, key, value)
reply = {:ok, "I GOT IT BOSS"}
{reply, new_state}
end
@impl true
def handle_read(key, state) do
{:reply, Map.get(state, key)}
end
end
initial_config = [foo: node(), bar: node(), baz: node()]
init_state = %{}
{:ok, _} = ExRaft.start_server(KeyValueStore, init_state, name: :foo, initial_config: initial_config)
{:ok, _} = ExRaft.start_server(KeyValueStore, init_state, name: :bar, initial_config: initial_config)
{:ok, _} = ExRaft.start_server(KeyValueStore, init_state, name: :baz, initial_config: initial_config)
leader = ExRaft.await_leader(:foo)
# leader is now one of [{:foo, node()}, {:bar, node()}, {:baz, node()}]
ExRaft.read(leader, :some_key)
# nil
ExRaft.write(KeyValueStore, {:put, :some_key, :some_value})
# {:ok, "I GOT IT BOSS"}
ExRaft.read(leader, :some_key)
# :some_value
We start a member of our `KeyValueStore` cluster by calling `ExRaft.start_server/3`,
passing the module with the state machine implementation and its initial state
(in this example this is just an empty map).
In the example above we start a 3 server cluster with the names `:foo`, `:bar` and `:baz`.
Any of these servers may become the cluster leader at startup or when the old leader fails,
that is why we first wait for a leader to be elected by calling `ExRaft.await_leader/2`.
After a leader was elected we can write to- and read from our replicated key value store
by calling `ExRaft.write/3` and `ExRaft.read/3` respectively.
Once the `ExRaft.write/3` call returns with our state machine reply
(`{:ok, "I GOT IT BOSS"}`) we know that the majority of our cluster (2 servers in
this example) knows that `:some_key` is in fact `:some_value`.
This means that if the leader crashes or a network split happens between
the leader and the rest of the cluster, the remaining 2 servers will still
be able to elect a new leader and this new leader will still know of
`:some_key` being `:some_value`.
In fact if we were to issue an `ExRaft.read_dirty/3` call on the followers
after writing `:some_key` to the state at least one, if not both of them
would reply with `:some_value`.
## Improvements
In the above example we interacted with the key value store using the `ExRaft`
module. This is not ideal since we don't want our users to necessarily know
how to use `ExRaft`.
Also we started the servers by calling `ExRaft.start_server/3` directly.
It would be better if we started them as part of a supervision tree.
So let's fix these issues:
defmodule KeyValueStore do
use ExRaft.StateMachine
@init_state %{}
def start_link(opts),
do: ExRaft.start_server(__MODULE__, @init_state, opts)
def put(server, key, value),
do: ExRaft.write(server, {:put, key, value})
def get(server, key),
do: ExRaft.read(server, key)
@impl true
def init(init_state) do
{:ok, init_state}
end
@impl true
def command?({:put, _, _}, _), do: true
def command?(_, _), do: false
@impl true
def handle_write({:put, key, value}, state) do
new_state = Map.put(state, key, value)
reply = {:ok, "I GOT IT BOSS"}
{reply, new_state}
end
@impl true
def handle_read(key, state) do
{:reply, Map.get(state, key)}
end
end
Now we can simply call `KeyValueStore.put/3` and `KeyValueStore.get/3`
to write to- and read from our replicated key value store.
### Supervision
When we invoke `use ExRaft.StateMachine`, two things happen:
It defines that the current module implements the `ExRaft.StateMachine`
behaviour (`@behaviour ExRaft.StateMachine`).
It also defines an overridable `child_spec/1` function, that allows
us to start the `KeyValueStore` directly under a supervisor.
children = [
{KeyValueStore, name: :foo, initial_config: [...]}
]
Supervisor.start_link(children, strategy: :one_for_one)
This will invoke `KeyValueStore.start_link/1`, lucky for us
we already defined this function in the improved implementation.
## Note
Be aware that all callbacks (except for `c:init/1` and `c:terminate/2`)
block the server until they return, so it is recommended to try and keep
any heavy lifting outside of them or adjusting the `:min_election_timeout`
and `:max_election_timeout` options of the server (see `ExRaft.start_server/3`).
Also note that setting a high election timeout range may cause
the cluster to stay without leader and thus become unresponsive
for a longer period of time.
"""
@moduledoc since: "0.1.0"
@typedoc "The state machine state."
@typedoc since: "0.1.0"
@type state() :: any()
@typedoc "Side effect values."
@typedoc since: "0.1.0"
@type side_effect() :: {:mfa, mfa()}
@typedoc "Side effects executed only by the leader."
@typedoc since: "0.1.1"
@type side_effects() :: [side_effect()]
@typedoc "The state machine reply."
@typedoc since: "0.1.1"
@type reply() :: any()
@doc """
Invoked when the server is started.
`ExRaft.start_server/3` and `ExRaft.start_server/2` will block until it returns.
`init_arg` is the second argument passed to `ExRaft.start_server/3`
or `[]` when calling `ExRaft.start_server/2`.
Returning `{:ok, state}` will cause `start_link/3` to return
`{:ok, pid}` and the process to enter its loop.
Returning `{:stop, reason}` will cause `start_link/3` to return
`{:error, reason}` and the process to exit with reason `reason` without
entering the loop or calling `c:terminate/2`.
This callback is optional. If one is not implemented, `init_arg` will
be passed along as `state`.
"""
@doc since: "0.1.0"
@callback init(init_arg :: any()) :: {:ok, state()} | {:stop, any()}
@doc """
Invoked to check commands upon `ExRaft.write/3` calls.
Returning `true` will cause the server to continue with log replication
and eventually apply `command` to the `state`.
Returning `false` will make the server ignore the command,
causing the client to eventually time out.
This callback is optional. If one is not implemented, all commands
will be replicated and eventually applied to the `state`.
"""
@doc since: "0.1.0"
@callback command?(command :: any(), state :: state()) :: boolean()
@doc """
Invoked to handle commands from `ExRaft.write/3` calls.
Called when `command` is replicated to the majority of servers
and can be safely applied to the state.
Returning `{reply, new_state}` sends the response `reply` to the caller
and continues the loop with new state `new_state`.
Returning `{reply, new_state, side_effects}` is similar to `{reply, new_state}`
except it causes the leader to execute `side_effects` (see `t:side_effects/0`).
"""
@doc since: "0.1.0"
@callback handle_write(command :: any(), state :: state()) ::
{reply(), state()} | {reply(), state(), side_effects()}
@doc """
Invoked to handle queries from `ExRaft.read/3` and when enabled `ExRaft.read_dirty/3` calls.
Returning `{:reply, reply}` sends the response `reply` to the caller and continues the loop.
Returning `:noreply` does not send a response to the caller and continues the loop.
"""
@doc since: "0.1.0"
@callback handle_read(query :: any(), state :: state()) ::
{:reply, reply()} | :noreply
@doc """
Invoked to handle configuration changes.
Other internal command types may be added in future releases.
Returning `{:ok, new_state}` sends the response `:ok` to the caller
and continues the loop with new state `new_state`.
Returning `{:ok, new_state, side_effects}` is similar to `{:ok, new_state}`
except it causes the leader to execute `side_effects` (see `t:side_effects/0`).
"""
@doc since: "0.1.0"
@callback handle_system_write(type :: :config, state :: state()) ::
{:ok, state()} | {:ok, state(), side_effects()}
@doc """
Invoked when the server transitions to a new raft state.
The return value is ignored.
This callback is optional.
"""
@doc since: "0.1.0"
@callback transition(to_state :: :follower | :candidate | :leader, state :: state()) :: any()
@doc """
Invoked when the server is about to exit. It should do any cleanup required.
`reason` is exit reason and `state` is the current state of the state machine.
The return value is ignored.
`c:terminate/2` is called if the state machine traps exits (using `Process.flag/2`)
*and* the parent process sends an exit signal.
If `reason` is neither `:normal`, `:shutdown`, nor `{:shutdown, term}` an error is
logged.
For a more in-depth explanation, please read the "Shutdown values (:shutdown)"
section in the `Supervisor` module and the `c:GenServer.terminate/2`
callback documentation.
This callback is optional.
"""
@doc since: "0.1.0"
@callback terminate(reason :: any(), state :: state()) :: :ok
@optional_callbacks init: 1, command?: 2, handle_system_write: 2, transition: 2, terminate: 2
defstruct [:module, :state]
defmacro __using__(_) do
quote do
@behaviour unquote(__MODULE__)
def child_spec(init_arg),
do: %{id: __MODULE__, start: {__MODULE__, :start_link, [init_arg]}}
defoverridable child_spec: 1
end
end
@doc false
def init(module, init_arg) do
if function_exported?(module, :init, 1) do
case module.init(init_arg) do
{:ok, state} ->
{:ok, %__MODULE__{module: module, state: state}}
{:stop, reason} ->
{:stop, reason}
end
else
{:ok, %__MODULE__{module: module, state: init_arg}}
end
end
@doc false
def command?(%__MODULE__{module: module} = state_machine, command) do
if function_exported?(module, :command?, 2),
do: module.command?(command, state_machine.state),
else: true
end
@doc false
def handle_write(%__MODULE__{module: module} = state_machine, command) do
case module.handle_write(command, state_machine.state) do
{reply, state, side_effects} ->
{reply, %{state_machine | state: state}, side_effects}
{reply, state} ->
{reply, %{state_machine | state: state}, []}
end
end
@doc false
def handle_read(%__MODULE__{module: module} = state_machine, query),
do: module.handle_read(query, state_machine.state)
@doc false
def handle_system_write(%__MODULE__{module: module} = state_machine, type, content) do
if function_exported?(module, :handle_system_write, 3) do
case module.handle_system_write(type, content, state_machine.state) do
{:ok, state, side_effects} ->
{:ok, %{state_machine | state: state}, side_effects}
{:ok, state} ->
{:ok, %{state_machine | state: state}, []}
end
else
{:ok, state_machine, []}
end
end
@doc false
def transition(%__MODULE__{module: module} = state_machine, to_state) do
if function_exported?(module, :transition, 2),
do: module.transition(to_state, state_machine.state),
else: :ok
end
@doc false
def terminate(%__MODULE__{module: module} = state_machine, reason) do
if function_exported?(module, :terminate, 2),
do: module.terminate(reason, state_machine.state),
else: :ok
end
end
|
lib/ex_raft/state_machine.ex
| 0.889 | 0.600745 |
state_machine.ex
|
starcoder
|
defmodule CQL.Result.Rows do
@moduledoc """
Represents a CQL rows result
"""
import CQL.DataTypes.Decoder, except: [decode: 2]
defstruct [
:columns,
:columns_count,
:column_types,
:rows,
:rows_count,
:paging_state,
]
@doc false
def decode_meta(buffer) do
with {:ok, %CQL.Frame{body: body, operation: :RESULT}} <- CQL.Frame.decode(buffer),
{0x02, rest} <- int(body)
do
decode(rest, false)
else
_ -> CQL.Error.new("trying to decode meta from frame which is not a RESULT.ROWS")
end
end
def decode_rows(%__MODULE__{} = r) do
{rows, ""} = ntimes(r.rows_count, row_content(r.column_types, r.columns_count), r.rows)
%{r | rows: rows}
end
@doc false
def decode(buffer, decode_rows \\ true) do
{meta, buffer} = unpack buffer,
metadata: &CQL.MetaData.decode/1,
rows_count: :int
columns_count = meta.metadata.columns_count
{columns, column_types} = Enum.unzip(meta.metadata.column_types)
rows =
if decode_rows do
{rows, ""} = ntimes(meta.rows_count, row_content(column_types, columns_count), buffer)
rows
else
buffer
end
%__MODULE__{
columns: columns,
columns_count: columns_count,
column_types: column_types,
rows: rows,
rows_count: meta.rows_count,
paging_state: Map.get(meta.metadata, :paging_state),
}
end
@doc """
Joins a list of Rows, as they where result of a single query
"""
def join(rows_list) do
rows_list
|> Enum.reduce(fn row, %{rows_count: n, rows: list} = acc ->
%{acc | rows_count: n + row.rows_count, rows: list ++ row.rows}
end)
|> Map.put(:paging_state, nil)
end
@doc """
Converts a Rows struct to a list of keyword lists with column names as keys
"""
def to_keyword(%__MODULE__{columns: columns, rows: rows}) do
Enum.map(rows, &zip_to(columns, &1, []))
end
@doc """
Converts a Rows struct to a list of maps with column names as keys
"""
def to_map(%__MODULE__{columns: columns, rows: rows}) do
Enum.map(rows, &zip_to(columns, &1, %{}))
end
defp zip_to(keys, values, into) do
keys
|> Enum.zip(values)
|> Enum.into(into)
end
defp row_content(types, count) do
fn binary ->
{row, rest} = ntimes(count, &bytes/1, binary)
{parse(row, types), rest}
end
end
defp parse(row_content, types) do
types
|> Enum.zip(row_content)
|> Enum.map(&CQL.DataTypes.decode/1)
end
end
|
lib/cql/result/rows.ex
| 0.789518 | 0.512449 |
rows.ex
|
starcoder
|
defmodule Exchange.OrderBook do
@moduledoc """
The Order Book is the Exchange main data structure. It holds the Order Book
in Memory where the MatchingEngine realizes the matches and register the Trades.
Example of and Order Book for Physical Gold (AUX) in London Market
Orders with currency in Great British Pounds:
```
%Exchange.OrderBook{
name: :AUXLND,
currency: :GBP,
buy: %{},
sell: %{},
order_ids: MapSet.new(),
ask_min: 99_999,
bid_max: 0,
max_price: 99_999,
min_price: 0
}
```
## Buy and Sell Sides, price points and Orders
The OrderBook has a buy and sell keys that represent each of the sides.
Each side is a map indexed by an integer representing the `price_point`
That contains a Queue of orders ordered by First In First Out (FIFO)
The queues of Exchange.Order are implemented using Qex (an Elixir wrapper
for the erlang OTP :queue.
Example:
```
buy: %{
4001 => #Qex<[
%Exchange.Order{
acknowledged_at: ~U[2020-03-31 14:02:20.534364Z],
modified_at: ~U[2020-03-31 14:02:20.534374Z],
order_id: "e3fbecca-736d-11ea-b415-8c8590538575",
price: 3970,
side: :buy,
size: 750,
trader_id: "10995c7c-736e-11ea-a987-8c8590538575",
type: :limit
}
]>,
4000 => #Qex<[ Exchange.Order(1), ... Exchange.Order(n) ]>,
3980 => #Qex<[ Exchange.Order(1), ... Exchange.Order(n) ]>
```
## Other Attributes
- name: Is the name of the ticker and the Id of the exchange. The exchange
supports multiple matching engines identified by the different unique tickers.
- currency: The currency that is supported inside this OrderBook.
All orders must have prices in cents in that currency.
- order_ids: Is an index of ids of the orders to see if and order is waiting
for a match or not.
These are all attributes that represent prices in cents for currency:
- ask_min: is the current minimum ask price on the sell side.
- bid_max: is the current maximum bid price on the buy side.
- max_price: is the maximum price in cents that we accept a buy order
- min_price: is the minimum price in cents that we accept a sell order
"""
defstruct name: :AUXGBP,
currency: :GBP,
buy: %{},
sell: %{},
order_ids: Map.new(),
expiration_list: [],
expired_orders: [],
completed_trades: [],
ask_min: 99_999,
bid_max: 1,
max_price: 100_000,
min_price: 0
alias Exchange.{Order, OrderBook}
@type ticker :: atom
@type price_in_cents :: integer
@type size_in_grams :: integer
@type queue_of_orders :: %Qex{data: [Order.order()]}
@type order_book :: %Exchange.OrderBook{
name: atom,
currency: atom,
buy: %{optional(price_in_cents) => queue_of_orders},
sell: %{optional(price_in_cents) => queue_of_orders},
order_ids: %{optional(String.t()) => {atom, price_in_cents}},
completed_trades: list,
ask_min: price_in_cents,
bid_max: price_in_cents,
max_price: price_in_cents,
min_price: price_in_cents
}
@doc """
This is the core of the Matching Engine.
Our Matching Engine implements the Price-Time Matching Algorithm.
The first Orders arriving at that price point have priority.
## Parameters
- order_book:
- order:
"""
@spec price_time_match(
order_book :: Exchange.OrderBook.order_book(),
order :: Exchange.Order.order()
) ::
Exchange.OrderBook.order_book()
def price_time_match(
%{bid_max: bid_max, ask_min: ask_min} = order_book,
%Order{side: side, price: price, size: size} = order
)
when (price <= bid_max and side == :sell) or (price >= ask_min and side == :buy) do
case fetch_matching_order(order_book, order) do
:empty ->
order_book
|> queue_order(order)
{:ok, matched_order} ->
cond do
matched_order.size == size ->
order_book
|> register_trade(order, matched_order)
|> dequeue_order(matched_order)
matched_order.size < size ->
downsized_order = %{order | size: size - matched_order.size}
order_book
|> register_trade(order, matched_order)
|> dequeue_order(matched_order)
|> price_time_match(downsized_order)
matched_order.size > size ->
downsized_matched_order = %{matched_order | size: matched_order.size - size}
order_book
|> register_trade(order, matched_order)
|> update_order(downsized_matched_order)
end
end
end
def price_time_match(
%{bid_max: bid_max, ask_min: ask_min} = order_book,
%Order{side: side, price: price} = order
)
when (price > bid_max and side == :sell) or
(price < ask_min and side == :buy) do
queue_order(order_book, order)
end
@doc """
Generates a trade and adds it to the `completed_trades` of the order_book.
## Parameters
- order_book: OrderBook that will store the trade
- order: Newly placed order
- matched_order: Existing order that matched the criteria of `order`
"""
@spec register_trade(
order_book :: Exchange.OrderBook.order_book(),
order :: Exchange.Order.order(),
matched_order :: Exchange.Order.order()
) :: Exchange.OrderBook.order_book()
def register_trade(order_book, order, matched_order) do
type =
if order.initial_size <= matched_order.size do
:full_fill
else
:partial_fill
end
new_trade = Exchange.Trade.generate_trade(order, matched_order, type, order_book.currency)
trades = order_book.completed_trades ++ [new_trade]
%{order_book | completed_trades: trades}
end
@doc """
Returns the list of completed trades.
## Parameters
- order_book: OrderBook that stores the completed trades
"""
@spec completed_trades(order_book :: Exchange.OrderBook.order_book()) :: [Exchange.Trade]
def completed_trades(order_book) do
order_book.completed_trades
end
@doc """
Removes all the completed trades from the OrderBook.
## Parameters
- order_book: OrderBook that stores the completed trades
"""
@spec flush_trades!(order_book :: Exchange.OrderBook.order_book()) ::
Exchange.OrderBook.order_book()
def flush_trades!(order_book) do
%{order_book | completed_trades: []}
end
@doc """
Returns spread for this exchange by calculating the difference between `ask_min` and `bid_max`
## Parameters
- order_book: OrderBook that stores the current state of a exchange
"""
@spec spread(order_book :: Exchange.OrderBook.order_book()) :: number
def spread(order_book) do
order_book.ask_min - order_book.bid_max
end
@doc """
Try to fetch a matching buy/sell at the current bid_max/ask_min price
## Parameters
- order_book: OrderBook that contains the active orders
- order: `Exchange.Order` used to search a matching order
"""
@spec fetch_matching_order(
order_book :: Exchange.OrderBook.order_book(),
Exchange.Order.order()
) ::
atom() | {atom(), Exchange.Order.order()}
def fetch_matching_order(order_book, %Order{} = order) do
price_points_queue =
case order.side do
:buy -> Map.get(order_book.sell, order_book.ask_min)
:sell -> Map.get(order_book.buy, order_book.bid_max)
end
if price_points_queue == nil do
:empty
else
matched_order =
price_points_queue
|> Enum.filter(fn order ->
if is_integer(order.exp_time) do
current_time = DateTime.utc_now() |> DateTime.to_unix(:millisecond)
if order.exp_time < current_time do
false
end
end
true
end)
|> List.first()
case matched_order do
nil -> :empty
matched_order -> {:ok, matched_order}
end
end
end
@doc """
Try to fetch a matching buy/sell with an order_id
## Parameters
- order_book: OrderBook that contains the active orders
- order: `Exchange.Order` used to search an order
"""
@spec fetch_order_by_id(order_book :: Exchange.OrderBook.order_book(), order_id :: String.t()) ::
Order.order()
def fetch_order_by_id(order_book, order_id) do
index_of_order = Map.get(order_book.order_ids, order_id)
if index_of_order do
{side, price_point} = index_of_order
orders_queue =
order_book
|> Map.get(side)
|> Map.get(price_point)
Enum.find(orders_queue, fn o ->
o.order_id == order_id
end)
else
nil
end
end
@doc """
Queues an `Exchange.Order` in to the correct price_point in the Order Book
## Parameters
- order_book: OrderBook that contains the active orders
- order: `Exchange.Order` to be queued
"""
@spec queue_order(
order_book :: Exchange.OrderBook.order_book(),
order :: Exchange.Order.order()
) ::
Exchange.OrderBook.order_book()
def queue_order(order_book, %Order{} = order) do
order_book
|> insert_order_in_queue(order)
|> add_order_to_index(order)
|> add_order_to_expirations(order)
|> set_bid_max(order)
|> set_ask_min(order)
end
@doc """
Removes an `Exchange.Order` from the Order Book
## Parameters
- order_book: OrderBook that contains the active orders
- order: `Exchange.Order` to be removed
"""
@spec dequeue_order(
order_book :: Exchange.OrderBook.order_book(),
order :: Exchange.Order.order()
) ::
Exchange.OrderBook.order_book()
def dequeue_order(order_book, %Order{} = order) do
dequeue_order_by_id(order_book, order.order_id)
end
@doc """
Removes an `Exchange.Order` using its `order_id` from the Order Book
## Parameters
- order_book: OrderBook that contains the active orders
- order: `Exchange.Order` to be removed
"""
@spec dequeue_order_by_id(order_book :: Exchange.OrderBook.order_book(), order_id :: String.t()) ::
Exchange.OrderBook.order_book()
def dequeue_order_by_id(order_book, order_id) do
{side, price_point} = Map.get(order_book.order_ids, order_id)
orders_queue =
order_book
|> Map.get(side)
|> Map.get(price_point)
order_position =
Enum.find_index(orders_queue, fn o ->
o.order_id == order_id
end)
{q1, q2} = Qex.split(orders_queue, order_position)
{poped_order, q2} = Qex.pop!(q2)
new_queue = Qex.join(q1, q2)
order_book
|> update_queue(side, price_point, new_queue)
|> remove_order_from_index(poped_order)
|> calculate_min_max_prices(poped_order)
end
@doc """
Updates an `Exchange.OrderBook.queue_of_orders()` from the Order Book
## Parameters
- order_book: OrderBook that contains the active orders
- side: The side of the queue
- price_point: Key to get the queue
- new_queue: Queue to be updated under the `price_point`
"""
@spec update_queue(
order_book :: Exchange.OrderBook.order_book(),
side :: atom,
price_point :: Exchange.OrderBook.price_in_cents(),
new_queue :: Exchange.OrderBook.queue_of_orders()
) :: Exchange.OrderBook.order_book()
def update_queue(order_book, side, price_point, new_queue) do
len = Enum.count(new_queue)
case len do
0 ->
updated_side_order_book =
order_book
|> Map.fetch!(side)
|> Map.delete(price_point)
Map.put(order_book, side, updated_side_order_book)
_ ->
updated_side_order_book =
order_book
|> Map.fetch!(side)
|> Map.put(price_point, new_queue)
Map.put(order_book, side, updated_side_order_book)
end
end
@doc """
Inserts an `Exchange.Order` in to the queue.
The order is pushed to the end of the queue.
## Parameters
- order_book: OrderBook that contains the active orders
- order: `Exchange.Order` to be inserted
"""
@spec insert_order_in_queue(
order_book :: Exchange.OrderBook.order_book(),
order :: Exchange.Order.order()
) ::
Exchange.OrderBook.order_book()
def insert_order_in_queue(order_book, order) do
price_point = order.price
side_order_book = Map.fetch!(order_book, order.side)
orders_queue =
if Map.has_key?(side_order_book, price_point) do
old_orders_queue = Map.get(side_order_book, price_point)
Qex.push(old_orders_queue, order)
else
Qex.new([order])
end
side_order_book = Map.put(side_order_book, price_point, orders_queue)
Map.put(order_book, order.side, side_order_book)
end
@doc """
Updates an `Exchange.Order` in the Order Book
## Parameters
- order_book: OrderBook that contains the active orders
- order: `Exchange.Order` to be updated
"""
@spec update_order(
order_book :: Exchange.OrderBook.order_book(),
order :: Exchange.Order.order()
) ::
Exchange.OrderBook.order_book()
def update_order(order_book, order) do
price_point = order.price
side_order_book = Map.fetch!(order_book, order.side)
orders_queue =
if Map.has_key?(side_order_book, price_point) do
old_orders_queue = Map.get(side_order_book, price_point)
{{:value, _old}, orders_queue} = Qex.pop(old_orders_queue)
# replace front with the updated order
Qex.push_front(orders_queue, order)
else
Qex.new([order])
end
side_order_book = Map.put(side_order_book, price_point, orders_queue)
Map.put(order_book, order.side, side_order_book)
end
@doc """
Updates the Order Book setting bid_max
"""
@spec set_bid_max(
order_book :: Exchange.OrderBook.order_book(),
Exchange.Order.order()
) ::
Exchange.OrderBook.order_book()
def set_bid_max(%OrderBook{bid_max: bid_max} = order_book, %Order{side: :buy, price: price})
when bid_max < price do
%{order_book | bid_max: price}
end
def set_bid_max(order_book, %Order{}), do: order_book
@doc """
Updates the Order Book setting ask_min
"""
@spec set_ask_min(
order_book :: Exchange.OrderBook.order_book(),
Exchange.Order.order()
) ::
Exchange.OrderBook.order_book()
def set_ask_min(%OrderBook{ask_min: ask_min} = order_book, %Order{side: :sell, price: price})
when ask_min > price do
%{order_book | ask_min: price}
end
def set_ask_min(order_book, %Order{}), do: order_book
@doc """
When an order is matched and removed from the order book the `ask_min` or `bid_max` must be updated.
To update these values it is necessary to traverse the keys of the corresponding side of the Order Book, sort them and take the first element.
When one of the sides is empty the value is set to `max_price - 1` or `min_price + 1` to the `ask_min` or `bid_max`, respectively.
"""
@spec calculate_min_max_prices(
order_book :: Exchange.OrderBook.order_book(),
Exchange.Order.order()
) ::
Exchange.OrderBook.order_book()
def calculate_min_max_prices(order_book, %Order{side: :sell}) do
new_ask_min =
order_book.sell
|> Map.keys()
|> Enum.sort()
|> List.first()
new_ask_min =
case new_ask_min do
nil -> order_book.max_price - 1
_ -> new_ask_min
end
%{order_book | ask_min: new_ask_min}
end
def calculate_min_max_prices(order_book, %Order{side: :buy}) do
new_bid_max =
order_book.buy
|> Map.keys()
|> Enum.sort()
|> Enum.reverse()
|> List.first()
new_bid_max =
case new_bid_max do
nil -> order_book.min_price + 1
_ -> new_bid_max
end
%{order_book | bid_max: new_bid_max}
end
# OrderBook Index Management
@doc """
Verifies if an `Exchange.Order` with `order_id` exists in the Order Book
## Parameters
- order_book: OrderBook that contains the active orders
- order_id: Id to be searched in the `order_book`
"""
@spec order_exists?(order_book :: Exchange.OrderBook.order_book(), order_id :: String.t()) ::
boolean
def order_exists?(order_book, order_id) do
order_book.order_ids
|> Map.keys()
|> Enum.member?(order_id)
end
@doc """
Periodic function that is triggered every second.
This function is used to verify if there are expired orders.
The expired orders are added to the `expired_orders`, removed from the `expiration_list` and removed from the sell or buy side.
## Parameters
- order_book: OrderBook that contains the expired orders
"""
@spec check_expired_orders!(order_book :: Exchange.OrderBook.order_book()) ::
Exchange.OrderBook.order_book()
def(check_expired_orders!(order_book)) do
current_time = DateTime.utc_now() |> DateTime.to_unix(:millisecond)
order_book.expiration_list
|> Enum.take_while(fn {ts, _id} -> ts < current_time end)
|> Enum.map(fn {_ts, id} -> id end)
|> Enum.reduce(order_book, fn order_id, order_book ->
order_book
|> update_expired_orders(order_id)
|> pop_order_from_expiration
|> dequeue_order_by_id(order_id)
end)
end
@doc """
Fetches the order with `order_id` and adds it to the Order Book's `expired_orders`
## Parameters
- order_book: OrderBook that contains the `expired_orders`
"""
@spec update_expired_orders(
order_book :: Exchange.OrderBook.order_book(),
order_id :: String.t()
) :: Exchange.OrderBook.order_book()
def update_expired_orders(order_book, order_id) do
order = fetch_order_by_id(order_book, order_id)
%{order_book | expired_orders: order_book.expired_orders ++ [order]}
end
@doc """
Flushes all the expired orders from the OrderBook's `expired_orders`
## Parameters
- order_book: OrderBook that contains the `expired_orders`
"""
@spec flush_expired_orders!(order_book :: Exchange.OrderBook.order_book()) ::
Exchange.OrderBook.order_book()
def flush_expired_orders!(order_book) do
%{order_book | expired_orders: []}
end
@doc """
Removes the first element from the OrderBook's `experiration_list`
## Parameters
- order_book: OrderBook that contains the `experiration_list`
"""
@spec pop_order_from_expiration(order_book :: Exchange.OrderBook.order_book()) ::
Exchange.OrderBook.order_book()
def pop_order_from_expiration(order_book) do
[_pop | new_expiration_list] = order_book.expiration_list
%{order_book | expiration_list: new_expiration_list}
end
@doc """
Adds the expiring order to the Order Book's `expiration_list`, which is sorted by the `exp_time` afterwards.
## Parameters
- order_book: OrderBook that contains the `expiration_list`
"""
@spec add_order_to_expirations(
order_book :: Exchange.OrderBook.order_book(),
Exchange.Order.order()
) ::
Exchange.OrderBook.order_book()
def add_order_to_expirations(order_book, %Order{exp_time: exp} = order)
when is_integer(exp) and exp > 0 do
new_expiration =
(order_book.expiration_list ++ [{exp, order.order_id}])
|> Enum.sort_by(fn {ts, _id} -> ts end)
%{order_book | expiration_list: new_expiration}
end
def add_order_to_expirations(order_book, _order) do
order_book
end
@doc """
Adds the order to the Order Book's `order_ids`.
The `order_ids` is used to have a better performance when searching for specific order.
## Parameters
- order_book: OrderBook that contains the `order_ids`
"""
@spec add_order_to_index(
order_book :: Exchange.OrderBook.order_book(),
Exchange.Order.order()
) ::
Exchange.OrderBook.order_book()
def add_order_to_index(order_book, order) do
idx = Map.put(order_book.order_ids, order.order_id, {order.side, order.price})
Map.put(order_book, :order_ids, idx)
end
@doc """
Removes the order to the Order Book's `order_ids`.
## Parameters
- order_book: OrderBook that contains the `order_ids`
"""
@spec remove_order_from_index(
order_book :: Exchange.OrderBook.order_book(),
Exchange.Order.order()
) ::
Exchange.OrderBook.order_book()
def remove_order_from_index(order_book, order) do
Map.put(
order_book,
:order_ids,
Map.delete(order_book.order_ids, order.order_id)
)
end
@doc """
Returns the sum of the size of all buy orders
## Parameters
- order_book: OrderBook used to sum the size
"""
@spec highest_ask_volume(order_book :: Exchange.OrderBook.order_book()) :: number
def highest_ask_volume(order_book) do
highest_volume(order_book.sell)
end
@spec highest_volume(Map.t()) :: number
defp highest_volume(book) do
book
|> Enum.flat_map(fn {_k, v} -> v end)
|> Enum.reduce(0, fn order, acc -> order.size + acc end)
end
@doc """
Returns the sum of the size of all sell orders
## Parameters
- order_book: OrderBook used to sum the size
"""
@spec highest_bid_volume(order_book :: Exchange.OrderBook.order_book()) :: number
def highest_bid_volume(order_book) do
highest_volume(order_book.buy)
end
@spec total_orders(Exchange.OrderBook.queue_of_orders()) :: number
defp total_orders(book) do
book
|> Enum.flat_map(fn {_k, v} -> v end)
|> Enum.reduce(0, fn _order, acc -> 1 + acc end)
end
@doc """
Returns the number of active buy orders.
## Parameters
- order_book: OrderBook used to search the active orders
"""
@spec total_bid_orders(order_book :: Exchange.OrderBook.order_book()) :: number
def total_bid_orders(order_book) do
total_orders(order_book.buy)
end
@doc """
Returns the number of active sell orders.
## Parameters
- order_book: OrderBook used to search the active orders
"""
@spec total_ask_orders(order_book :: Exchange.OrderBook.order_book()) :: number
def total_ask_orders(order_book) do
total_orders(order_book.sell)
end
@doc """
Returns the list of open orders
## Parameters
- order_book: OrderBook used to search the active orders
"""
@spec open_orders(order_book :: Exchange.OrderBook.order_book()) :: [Exchange.Order.order()]
def open_orders(order_book) do
open_sell_orders = orders_to_list(order_book.sell)
open_buy_orders = orders_to_list(order_book.buy)
open_sell_orders ++ open_buy_orders
end
@doc """
Returns the list resulting of flattening a `Exchange.OrderBook.queue_of_orders()`
## Parameters
- order_book: OrderBook used to search the active orders
"""
@spec orders_to_list(Exchange.OrderBook.queue_of_orders()) :: [Exchange.Order.order()]
def orders_to_list(orders) do
orders
|> Enum.flat_map(fn {_k, v} -> v end)
end
@doc """
Returns the list of open orders from a trader by filtering the orders don't have `trader_id`
## Parameters
- order_book: OrderBook used to search the orders
- trader_id: The id that is used to filter orders
"""
@spec open_orders_by_trader(
order_book :: Exchange.OrderBook.order_book(),
trader_id :: String.t()
) :: [Exchange.Order.order()]
def open_orders_by_trader(order_book, trader_id) do
order_book
|> open_orders()
|> Enum.filter(fn order -> order.trader_id == trader_id end)
end
@doc """
Returns the lastest size from a side of the order book
## Parameters
- order_book: OrderBook used to search the orders
- side: Atom to decide which side of the book is used
"""
@spec last_size(
order_book :: Exchange.OrderBook.order_book(),
side :: atom
) :: number
def last_size(order_book, side) do
order = get_latest_order(order_book, side)
case order do
nil -> 0
_ -> order.size
end
end
@doc """
Returns the lastest price from a side of the order book
## Parameters
- order_book: OrderBook used to search the orders
- side: Atom to decide which side of the book is used
"""
@spec last_price(
order_book :: Exchange.OrderBook.order_book(),
side :: atom
) :: number
def last_price(order_book, side) do
order = get_latest_order(order_book, side)
order.price
end
@doc """
This function checks if there are any stop loss orders to activate. If yes then they are converted in market orders, removed and placed on the exchange.
## Parameters
- order_book: OrderBook to update
"""
@spec stop_loss_activation(order_book :: Exchange.OrderBook.order_book()) ::
Exchange.OrderBook.order_book()
def stop_loss_activation(order_book) do
activated_stop_loss_orders =
(Map.to_list(order_book.buy) ++ Map.to_list(order_book.sell))
|> Enum.flat_map(fn {_pp, queue} -> queue end)
|> Enum.filter(fn order ->
order.type == :stop_loss and
((order.price * (1 + order.stop / 100) < order_book.ask_min and order.side == :buy) or
(order.price * (1 - order.stop / 100) > order_book.bid_max and order.side == :sell))
end)
if activated_stop_loss_orders != [] do
order_book =
activated_stop_loss_orders
|> Enum.map(&Order.assign_prices(&1, order_book))
|> Enum.sort(fn a, b -> a.acknowledged_at < b.acknowledged_at end)
|> Enum.reduce(order_book, fn order, acc ->
acc
|> OrderBook.dequeue_order(order)
|> OrderBook.price_time_match(order)
end)
stop_loss_activation(order_book)
else
order_book
end
end
defp get_latest_order(order_book, side) do
case side do
:buy -> order_book.buy
:sell -> order_book.sell
end
|> Enum.flat_map(fn {_k, v} -> v end)
|> Enum.max_by(
fn order -> order.acknowledged_at end,
fn -> %Exchange.Order{} end
)
end
end
|
lib/exchange/order_book.ex
| 0.93034 | 0.924586 |
order_book.ex
|
starcoder
|
defmodule Kino.Output do
@moduledoc """
A number of output formats supported by Livebook.
"""
@typedoc """
Livebook cell output may be one of these values and gets rendered accordingly.
"""
@type t ::
ignored()
| text_inline()
| text_block()
| markdown()
| image()
| vega_lite_static()
| vega_lite_dynamic()
| table_dynamic()
| frame_dynamic()
@typedoc """
An empty output that should be ignored whenever encountered.
"""
@type ignored :: :ignored
@typedoc """
Regular text, adjacent such outputs can be treated as a whole.
"""
@type text_inline :: binary()
@typedoc """
Standalone text block.
"""
@type text_block :: {:text, binary()}
@typedoc """
Markdown content.
"""
@type markdown :: {:markdown, binary()}
@typedoc """
A raw image in the given format.
"""
@type image :: {:image, content :: binary(), mime_type :: binary()}
@typedoc """
[Vega-Lite](https://vega.github.io/vega-lite) graphic.
`spec` should be a valid Vega-Lite specification, essentially
JSON represented with Elixir data structures.
"""
@type vega_lite_static() :: {:vega_lite_static, spec :: map()}
@typedoc """
Interactive [Vega-Lite](https://vega.github.io/vega-lite) graphic
with data streaming capabilities.
There should be a server process responsible for communication
with subscribers.
## Communication protocol
A client process should connect to the server process by sending:
{:connect, pid()}
And expect the following reply:
{:connect_reply, %{spec: map()}}
The server process may then keep sending one of the following events:
{:push, %{data: list(), dataset: binary(), window: non_neg_integer()}}
"""
@type vega_lite_dynamic :: {:vega_lite_dynamic, pid()}
@typedoc """
Interactive data table.
There should be a server process that serves data requests,
filtering, sorting and slicing data as necessary.
## Communication protocol
A client process should connect to the server process by sending:
{:connect, pid()}
And expect the following reply:
@type column :: %{
key: term(),
label: binary()
}
{:connect_reply, %{
name: binary(),
columns: list(column()),
features: list(:refetch | :pagination | :sorting)
}}
The client may then query for table rows by sending the following requests:
@type rows_spec :: %{
offset: non_neg_integer(),
limit: pos_integer(),
order_by: nil | term(),
order: :asc | :desc,
}
{:get_rows, pid(), rows_spec()}
To which the server responds with retrieved data:
@type row :: %{
# An identifier, opaque to the client
id: term(),
# A string value for every column key
fields: list(%{term() => binary()})
}
{:rows, %{
rows: list(row()),
total_rows: non_neg_integer(),
# Possibly an updated columns specification
columns: :initial | list(column())
}}
"""
@type table_dynamic :: {:table_dynamic, pid()}
@typedoc """
Animable output.
There should be a server process responsible for communication
with subscribers.
## Communication protocol
A client process should connect to the server process by sending:
{:connect, pid()}
And expect the following reply:
{:connect_reply, %{output: Kino.Output.t() | nil}}
The server process may then keep sending one of the following events:
{:render, %{output: Kino.Output.t()}}
"""
@type frame_dynamic :: {:frame_dynamic, pid()}
@doc """
See `t:text_inline/0`.
"""
@spec text_inline(binary()) :: t()
def text_inline(text) when is_binary(text) do
text
end
@doc """
See `t:text_block/0`.
"""
@spec text_block(binary()) :: t()
def text_block(text) when is_binary(text) do
{:text, text}
end
@doc """
See `t:markdown/0`.
"""
@spec markdown(binary()) :: t()
def markdown(content) when is_binary(content) do
{:markdown, content}
end
@doc """
See `t:image/0`.
"""
@spec image(binary(), binary()) :: t()
def image(content, mime_type) when is_binary(content) and is_binary(mime_type) do
{:image, content, mime_type}
end
@doc """
See `t:vega_lite_static/0`.
"""
@spec vega_lite_static(vega_lite_spec :: map()) :: t()
def vega_lite_static(spec) when is_map(spec) do
{:vega_lite_static, spec}
end
@doc """
See `t:vega_lite_dynamic/0`.
"""
@spec vega_lite_dynamic(pid()) :: t()
def vega_lite_dynamic(pid) when is_pid(pid) do
{:vega_lite_dynamic, pid}
end
@doc """
See `t:table_dynamic/0`.
"""
@spec table_dynamic(pid()) :: t()
def table_dynamic(pid) when is_pid(pid) do
{:table_dynamic, pid}
end
@doc """
See `t:frame_dynamic/0`.
"""
@spec frame_dynamic(pid()) :: t()
def frame_dynamic(pid) when is_pid(pid) do
{:frame_dynamic, pid}
end
@doc """
Returns `t:text_block/0` with the inspectd term.
"""
@spec inspect(term()) :: t()
def inspect(term) do
inspected = inspect(term, inspect_opts())
text_block(inspected)
end
defp inspect_opts() do
default_opts = [pretty: true, width: 100, syntax_colors: syntax_colors()]
config_opts = Kino.Config.configuration(:inspect, [])
Keyword.merge(default_opts, config_opts)
end
defp syntax_colors() do
[
atom: :blue,
boolean: :magenta,
number: :blue,
nil: :magenta,
regex: :red,
string: :green,
reset: :reset
]
end
end
|
lib/kino/output.ex
| 0.854019 | 0.480296 |
output.ex
|
starcoder
|
defmodule Grizzly.ZWave.Commands.LearnModeSetStatus do
@moduledoc """
This command is used to indicate the progress of the Learn Mode Set command.
Params:
* `:seq_number` - the command sequence number
* `:status` - the outcome of the learn mode, one of :done, :failed or :security_failed
* `:new_node_id` - the new node id assigned to the device
* `:granted_keys` - indicates which network keys were granted during bootstrapping; a list with :s2_unauthenticated, :s2_authenticated,
:s2_access_control and/or :s0 (optional - v2)
* `:kex_fail_type` - indicates which error occurred in case S2 bootstrapping was not successful; one of :none, :key, :scheme, :curves,
:decrypt, :cancel, :auth, :get, :verify or :report -- see Grizzly.ZWave.Security (optional - v2)
* `:dsk` - the DSK of the including controller that performed S2 bootstrapping to the node (optional - v2)
"""
@behaviour Grizzly.ZWave.Command
alias Grizzly.ZWave
alias Grizzly.ZWave.{Command, DecodeError, DSK, Security}
alias Grizzly.ZWave.CommandClasses.NetworkManagementBasicNode
@type status :: :done | :failed | :security_failed
@type param ::
{:seq_number, ZWave.seq_number()}
| {:status, status}
| {:new_node_id, Grizzly.Node.id()}
| {:granted_keys, [Security.key()]}
| {:kex_fail_type, Security.key_exchange_fail_type()}
| {:dsk, DSK.dsk_string()}
@impl true
def new(params) do
command = %Command{
name: :learn_mode_set_status,
command_byte: 0x02,
command_class: NetworkManagementBasicNode,
params: params,
impl: __MODULE__
}
{:ok, command}
end
@impl true
def encode_params(command) do
seq_number = Command.param!(command, :seq_number)
status_byte = Command.param!(command, :status) |> encode_status()
new_node_id = Command.param!(command, :new_node_id)
granted_keys = Command.param(command, :granted_keys)
if granted_keys == nil do
<<seq_number, status_byte, 0x00, new_node_id>>
else
granted_keys_byte = Security.keys_to_byte(granted_keys)
kex_fail_type_byte =
Command.param!(command, :kex_fail_type) |> Security.failed_type_to_byte()
{:ok, dsk_binary} = Command.param!(command, :dsk) |> DSK.string_to_binary()
<<seq_number, status_byte, 0x00, new_node_id, granted_keys_byte, kex_fail_type_byte>> <>
dsk_binary
end
end
@impl true
def decode_params(<<seq_number, status_byte, 0x00, new_node_id>>) do
with {:ok, status} <- decode_status(status_byte) do
{:ok, [seq_number: seq_number, status: status, new_node_id: new_node_id]}
else
{:error, %DecodeError{}} = error ->
error
end
end
def decode_params(
<<seq_number, status_byte, 0x00, new_node_id, granted_keys_byte, kex_fail_type_byte,
dsk_binary::binary>>
) do
granted_keys = Security.byte_to_keys(granted_keys_byte)
kex_fail_type = Security.failed_type_from_byte(kex_fail_type_byte)
with {:ok, status} <- decode_status(status_byte),
{:ok, dsk} <- DSK.binary_to_string(dsk_binary) do
{:ok,
[
seq_number: seq_number,
status: status,
new_node_id: new_node_id,
granted_keys: granted_keys,
kex_fail_type: kex_fail_type,
dsk: dsk
]}
else
{:error, %DecodeError{}} = error ->
error
{:error, dsk_error} when dsk_error in [:dsk_too_long, :dsk_too_short] ->
{:error, %DecodeError{value: dsk_binary, param: :dsk, command: :learn_mode_set_status}}
end
end
defp encode_status(:done), do: 0x06
defp encode_status(:failed), do: 0x07
defp encode_status(:security_failed), do: 0x09
defp decode_status(0x06), do: {:ok, :done}
defp decode_status(0x07), do: {:ok, :failed}
defp decode_status(0x09), do: {:ok, :security_failed}
defp decode_status(byte),
do: {:error, %DecodeError{value: byte, param: :status, command: :learn_mode_set_status}}
end
|
lib/grizzly/zwave/commands/learn_mode_set_status.ex
| 0.847826 | 0.517327 |
learn_mode_set_status.ex
|
starcoder
|
defmodule RandomBytes do
@moduledoc ~S"""
Generate random strings in a few different formats.
"""
@doc """
Generates a random base62 string.
A `base64` string typically contains the `+` and `\/` characters as its extra 2 characters.
When the string will be used in a url, the `+` and `\/` are usually replaced with `-` and `_`.
This function generates a `base62` string, not a `base64` string. It returns only letters and
numbers and doesn't include the two special characters. The result string can contain the following
characters: `A-Z`, `a-z`, `0-9`.
The length of the result string is about 4/3 of `num_bytes`.
## Examples
iex> RandomBytes.base62
"zx1QBjpTMPuHKBHpQBv9IQ"
iex> RandomBytes.base62(30)
"io0i0jE70S2PmvBvnnE6272JbpBaoLbmxJmJXJUL"
iex> RandomBytes.base62(10)
"8BfF7DS2nxsPyg"
"""
def base62(num_bytes \\ 16) do
random_bytes(num_bytes)
|> Base.encode64(padding: false)
|> String.replace(~r/[+\/]/, random_char())
end
@doc """
Generates a random base16 string.
The result string can contain the following characters: `0-9`, `a-f`.
The length of the result string is twice `num_bytes`.
## Examples
iex> RandomBytes.base16
"442141c62390aa41c7c2561df1ba7c68"
iex> RandomBytes.base16(3)
"dc4bca"
"""
def base16(num_bytes \\ 16) do
random_bytes(num_bytes)
|> Base.encode16(case: :lower)
end
@doc """
Generates a UUID (universally unique identifier).
This is a [v4 UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29)
defined by [RFC 4122](https://tools.ietf.org/html/rfc4122).
## Examples
iex> RandomBytes.uuid
"5b1e4da9-bdf4-46d6-a741-21d2d1827e13"
iex> RandomBytes.uuid
"153282b3-0e2d-4e10-8839-cb0ee869e898"
"""
def uuid do
Regex.run(uuid_regex(), base16(), capture: :all_but_first)
|> Enum.join("-")
|> String.to_charlist()
|> List.replace_at(14, ?4)
|> List.replace_at(19, Enum.random('89ab'))
|> List.to_string()
end
defp uuid_regex do
~r/(.{8})(.{4})(.{4})(.{4})(.{12})/
end
@base62_alphabet 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
defp random_char do
[Enum.random(@base62_alphabet)] |> to_string
end
defp random_bytes(num) do
:crypto.strong_rand_bytes(num)
end
end
|
lib/random_bytes.ex
| 0.842653 | 0.619989 |
random_bytes.ex
|
starcoder
|
defmodule BSV.Util do
@moduledoc """
A collection of commonly used helper methods.
"""
@doc """
Encodes the given binary data with the specified encoding scheme.
## Options
The accepted encoding schemes are:
* `:base64` - Encodes the binary using Base64
* `:hex` - Encodes the binary using Base16 (hexidecimal), using lower character case
## Examples
iex> BSV.Util.encode("hello world", :base64)
"aGVsbG8gd29ybGQ="
iex> BSV.Util.encode("hello world", :hex)
"68656c6c6f20776f726c64"
"""
@spec encode(binary, atom) :: binary
def encode(data, encoding) do
case encoding do
:base64 -> Base.encode64(data)
:hex -> Base.encode16(data, case: :lower)
_ -> data
end
end
@doc """
Decodes the given binary data with the specified encoding scheme.
## Options
The accepted encoding schemes are:
* `:base64` - Encodes the binary using Base64
* `:hex` - Encodes the binary using Base16 (hexidecimal), using lower character case
## Examples
iex> BSV.Util.decode("aGVsbG8gd29ybGQ=", :base64)
"hello world"
iex> BSV.Util.decode("68656c6c6f20776f726c64", :hex)
"hello world"
"""
@spec decode(binary, atom) :: binary
def decode(data, encoding) do
case encoding do
:base64 -> Base.decode64!(data)
:hex -> Base.decode16!(data, case: :mixed)
_ -> data
end
end
@doc """
Generates random bits for the given number of bytes.
## Examples
iex> iv = BSV.Util.random_bytes(16)
...> bit_size(iv)
128
"""
@spec random_bytes(integer) :: binary
def random_bytes(bytes) when is_integer(bytes) do
:crypto.strong_rand_bytes(bytes)
end
@doc """
Reverses the order of the given binary data.
## Examples
iex> BSV.Util.reverse_bin("abcdefg")
"gfedcba"
"""
@spec reverse_bin(binary) :: binary
def reverse_bin(data) do
data
|> :binary.bin_to_list
|> Enum.reverse
|> :binary.list_to_bin
end
end
|
lib/bsv/util.ex
| 0.904217 | 0.613497 |
util.ex
|
starcoder
|
defmodule Phoenix.Config do
@moduledoc """
Handles Mix Config lookup and default values from Application env
Uses Mix.Config `:phoenix` settings as configuration with `@defaults` fallback
Each Router requires an `:endpoint` mapping with Router specific options.
See `@defaults` for a full list of available configuration options.
## Example `config.exs`
use Mix.Config
config :phoenix, MyApp.Router,
port: 4000,
ssl: false,
cookies: false
"""
@defaults [
router: [
port: 4000,
ssl: false,
host: "localhost",
static_assets: true,
static_assets_mount: "/",
parsers: true,
cookies: false,
session_key: nil,
session_secret: nil,
catch_errors: true,
debug_errors: false,
error_controller: Phoenix.Controller.ErrorController,
],
code_reloader: [
enabled: false
],
template_engines: [
eex: Phoenix.Template.EExEngine
],
topics: [
garbage_collect_after_ms: 60_000..300_000
]
]
defmodule UndefinedConfigError do
defexception [:message]
def exception(msg), do: %UndefinedConfigError{message: inspect(msg)}
end
@doc """
Returns the default configuration value given the path for get_in lookup
of `:phoenix` Application configuration
## Examples
iex> Config.default([:router, :port])
:error
"""
def default(path) do
get_in(@defaults, path)
end
def default!(path) do
case default(path) do
nil -> raise UndefinedConfigError, message: """
No default configuration found for #{inspect path}
"""
value -> value
end
end
@doc """
Returns the Keyword List of configuration given the path for get_in lookup
of `:phoenix` Application configuration
## Examples
iex> Config.get([:router, :port])
:info
"""
def get(path) do
case get_in(Application.get_all_env(:phoenix), path) do
nil -> default(path)
value -> value
end
end
@doc """
Returns the Keyword List of configuration given the path for get_in lookup
of :phoenix Application configuration.
Raises `UndefinedConfigError` if the value is nil
## Examples
iex> Config.get!([:router, :port])
:info
iex(2)> Phoenix.Config.get!([:router, :key_that_does_not_exist])
** (Phoenix.Config.UndefinedConfigError) [message: "No configuration found...
"""
def get!(path) do
case get(path) do
nil -> raise UndefinedConfigError, message: """
No configuration found for #{inspect path}
"""
value -> value
end
end
@doc """
Returns the Keyword List router Configuration, with merged Phoenix defaults
A get_in path can be supplied to narrow the config lookup
## Examples
iex> Config.router(MyApp.Router)
[port: 1234, ssl: false, endpoint: Router, ...]
iex> Config.router(MyApp.Router, [:port])
1234
"""
def router(mod) do
for {key, _value} <- Dict.merge(@defaults[:router], find_router_conf(mod)) do
{key, router(mod, [key])}
end
end
def router(module, path) do
case get_in(find_router_conf(module), path) do
nil -> default([:router] ++ path)
value -> value
end
end
@doc """
Returns the Keyword List router Configuration, with merged Phoenix defaults,
raises `UndefinedConfigError` if value does not exist. See `router/2` for details.
"""
def router!(module, path) do
case router(module, path) do
nil -> raise UndefinedConfigError, message: """
No configuration found for #{module} #{inspect path}
"""
value -> value
end
end
defp find_router_conf(module) do
Application.get_env :phoenix, module, @defaults[:router]
end
end
|
lib/phoenix/config.ex
| 0.861101 | 0.435841 |
config.ex
|
starcoder
|
defmodule Kukumo.Feature.MissingStepError do
@moduledoc """
Raises an error, because a feature step is missing its implementation.
The message of the error will give the user a useful code snippet where
variables in feature steps are converted to regex capture groups.
"""
defexception [:message]
@number_regex ~r/(^|\s)\d+(\s|$)/
@single_quote_regex ~r/'[^']+'/
@double_quote_regex ~r/"[^"]+"/
def exception(step_text: step_text, step_type: step_type, extra_vars: extra_vars) do
{converted_step_text, list_of_vars} =
{step_text, []}
|> convert_nums()
|> convert_double_quote_strings()
|> convert_single_quote_strings()
|> convert_extra_vars(extra_vars)
map_of_vars = vars_to_correct_format(list_of_vars)
message = """
Please add a matching step for:
"#{step_type} #{step_text}"
def#{step_type |> String.downcase()} ~r/^#{converted_step_text}$/, #{map_of_vars}, state do
# Your implementation here
end
"""
%__MODULE__{message: message}
end
defp convert_nums({step_text, vars}) do
@number_regex
|> Regex.split(step_text)
|> join_regex_split(1, :number, {"", vars})
end
defp convert_double_quote_strings({step_text, vars}) do
@double_quote_regex
|> Regex.split(step_text)
|> join_regex_split(1, :double_quote_string, {"", vars})
end
defp convert_single_quote_strings({step_text, vars}) do
@single_quote_regex
|> Regex.split(step_text)
|> join_regex_split(1, :single_quote_string, {"", vars})
end
defp convert_extra_vars({step_text, vars}, %{doc_string: doc_string, table: table}) do
vars = if doc_string == "", do: vars, else: vars ++ ["doc_string"]
vars = if table == [], do: vars, else: vars ++ ["table"]
{step_text, vars}
end
defp join_regex_split([], _count, _type, {acc, vars}) do
{String.trim(acc), vars}
end
defp join_regex_split([head | []], _count, _type, {acc, vars}) do
{String.trim(acc <> head), vars}
end
defp join_regex_split([head | tail], count, type, {acc, vars}) do
step_text = acc <> head <> get_regex_capture_string(type, count)
vars = vars ++ [get_var_string(type, count)]
join_regex_split(tail, count + 1, type, {step_text, vars})
end
defp get_regex_capture_string(:number, count), do: ~s/ (?<number_#{count}>\d+) /
defp get_regex_capture_string(:single_quote_string, count), do: ~s/'(?<string_#{count}>[^']+)'/
defp get_regex_capture_string(:double_quote_string, count), do: ~s/"(?<string_#{count}>[^"]+)"/
defp get_var_string(:number, count), do: "number_#{count}"
defp get_var_string(:single_quote_string, count), do: "string_#{count}"
defp get_var_string(:double_quote_string, count), do: "string_#{count}"
defp vars_to_correct_format([]), do: "_vars"
defp vars_to_correct_format(vars) do
joined_vars =
vars
|> Enum.map(fn var -> "#{var}: #{var}" end)
|> Enum.join(", ")
"%{#{joined_vars}}"
end
end
|
lib/cabbage/feature/missing_step_error.ex
| 0.52756 | 0.402921 |
missing_step_error.ex
|
starcoder
|
defmodule AWS.FraudDetector do
@moduledoc """
This is the Amazon Fraud Detector API Reference. This guide is for
developers who need detailed information about Amazon Fraud Detector API
actions, data types, and errors. For more information about Amazon Fraud
Detector features, see the [Amazon Fraud Detector User
Guide](https://docs.aws.amazon.com/frauddetector/latest/ug/).
"""
@doc """
Creates a batch of variables.
"""
def batch_create_variable(client, input, options \\ []) do
request(client, "BatchCreateVariable", input, options)
end
@doc """
Gets a batch of variables.
"""
def batch_get_variable(client, input, options \\ []) do
request(client, "BatchGetVariable", input, options)
end
@doc """
Creates a detector version. The detector version starts in a `DRAFT`
status.
"""
def create_detector_version(client, input, options \\ []) do
request(client, "CreateDetectorVersion", input, options)
end
@doc """
Creates a model using the specified model type.
"""
def create_model(client, input, options \\ []) do
request(client, "CreateModel", input, options)
end
@doc """
Creates a version of the model using the specified model type and model id.
"""
def create_model_version(client, input, options \\ []) do
request(client, "CreateModelVersion", input, options)
end
@doc """
Creates a rule for use with the specified detector.
"""
def create_rule(client, input, options \\ []) do
request(client, "CreateRule", input, options)
end
@doc """
Creates a variable.
"""
def create_variable(client, input, options \\ []) do
request(client, "CreateVariable", input, options)
end
@doc """
Deletes the detector. Before deleting a detector, you must first delete all
detector versions and rule versions associated with the detector.
"""
def delete_detector(client, input, options \\ []) do
request(client, "DeleteDetector", input, options)
end
@doc """
Deletes the detector version. You cannot delete detector versions that are
in `ACTIVE` status.
"""
def delete_detector_version(client, input, options \\ []) do
request(client, "DeleteDetectorVersion", input, options)
end
@doc """
Deletes the specified event.
"""
def delete_event(client, input, options \\ []) do
request(client, "DeleteEvent", input, options)
end
@doc """
Deletes the rule. You cannot delete a rule if it is used by an `ACTIVE` or
`INACTIVE` detector version.
"""
def delete_rule(client, input, options \\ []) do
request(client, "DeleteRule", input, options)
end
@doc """
Gets all versions for a specified detector.
"""
def describe_detector(client, input, options \\ []) do
request(client, "DescribeDetector", input, options)
end
@doc """
Gets all of the model versions for the specified model type or for the
specified model type and model ID. You can also get details for a single,
specified model version.
"""
def describe_model_versions(client, input, options \\ []) do
request(client, "DescribeModelVersions", input, options)
end
@doc """
Gets a particular detector version.
"""
def get_detector_version(client, input, options \\ []) do
request(client, "GetDetectorVersion", input, options)
end
@doc """
Gets all detectors or a single detector if a `detectorId` is specified.
This is a paginated API. If you provide a null `maxResults`, this action
retrieves a maximum of 10 records per page. If you provide a `maxResults`,
the value must be between 5 and 10. To get the next page results, provide
the pagination token from the `GetDetectorsResponse` as part of your
request. A null pagination token fetches the records from the beginning.
"""
def get_detectors(client, input, options \\ []) do
request(client, "GetDetectors", input, options)
end
@doc """
Gets all entity types or a specific entity type if a name is specified.
This is a paginated API. If you provide a null `maxResults`, this action
retrieves a maximum of 10 records per page. If you provide a `maxResults`,
the value must be between 5 and 10. To get the next page results, provide
the pagination token from the `GetEntityTypesResponse` as part of your
request. A null pagination token fetches the records from the beginning.
"""
def get_entity_types(client, input, options \\ []) do
request(client, "GetEntityTypes", input, options)
end
@doc """
Evaluates an event against a detector version. If a version ID is not
provided, the detector’s (`ACTIVE`) version is used.
"""
def get_event_prediction(client, input, options \\ []) do
request(client, "GetEventPrediction", input, options)
end
@doc """
Gets all event types or a specific event type if name is provided. This is
a paginated API. If you provide a null `maxResults`, this action retrieves
a maximum of 10 records per page. If you provide a `maxResults`, the value
must be between 5 and 10. To get the next page results, provide the
pagination token from the `GetEventTypesResponse` as part of your request.
A null pagination token fetches the records from the beginning.
"""
def get_event_types(client, input, options \\ []) do
request(client, "GetEventTypes", input, options)
end
@doc """
Gets the details for one or more Amazon SageMaker models that have been
imported into the service. This is a paginated API. If you provide a null
`maxResults`, this actions retrieves a maximum of 10 records per page. If
you provide a `maxResults`, the value must be between 5 and 10. To get the
next page results, provide the pagination token from the
`GetExternalModelsResult` as part of your request. A null pagination token
fetches the records from the beginning.
"""
def get_external_models(client, input, options \\ []) do
request(client, "GetExternalModels", input, options)
end
@doc """
Gets the encryption key if a Key Management Service (KMS) customer master
key (CMK) has been specified to be used to encrypt content in Amazon Fraud
Detector.
"""
def get_k_m_s_encryption_key(client, input, options \\ []) do
request(client, "GetKMSEncryptionKey", input, options)
end
@doc """
Gets all labels or a specific label if name is provided. This is a
paginated API. If you provide a null `maxResults`, this action retrieves a
maximum of 50 records per page. If you provide a `maxResults`, the value
must be between 10 and 50. To get the next page results, provide the
pagination token from the `GetGetLabelsResponse` as part of your request. A
null pagination token fetches the records from the beginning.
"""
def get_labels(client, input, options \\ []) do
request(client, "GetLabels", input, options)
end
@doc """
Gets the details of the specified model version.
"""
def get_model_version(client, input, options \\ []) do
request(client, "GetModelVersion", input, options)
end
@doc """
Gets one or more models. Gets all models for the AWS account if no model
type and no model id provided. Gets all models for the AWS account and
model type, if the model type is specified but model id is not provided.
Gets a specific model if (model type, model id) tuple is specified.
This is a paginated API. If you provide a null `maxResults`, this action
retrieves a maximum of 10 records per page. If you provide a `maxResults`,
the value must be between 1 and 10. To get the next page results, provide
the pagination token from the response as part of your request. A null
pagination token fetches the records from the beginning.
"""
def get_models(client, input, options \\ []) do
request(client, "GetModels", input, options)
end
@doc """
Gets one or more outcomes. This is a paginated API. If you provide a null
`maxResults`, this actions retrieves a maximum of 100 records per page. If
you provide a `maxResults`, the value must be between 50 and 100. To get
the next page results, provide the pagination token from the
`GetOutcomesResult` as part of your request. A null pagination token
fetches the records from the beginning.
"""
def get_outcomes(client, input, options \\ []) do
request(client, "GetOutcomes", input, options)
end
@doc """
Get all rules for a detector (paginated) if `ruleId` and `ruleVersion` are
not specified. Gets all rules for the detector and the `ruleId` if present
(paginated). Gets a specific rule if both the `ruleId` and the
`ruleVersion` are specified.
This is a paginated API. Providing null maxResults results in retrieving
maximum of 100 records per page. If you provide maxResults the value must
be between 50 and 100. To get the next page result, a provide a pagination
token from GetRulesResult as part of your request. Null pagination token
fetches the records from the beginning.
"""
def get_rules(client, input, options \\ []) do
request(client, "GetRules", input, options)
end
@doc """
Gets all of the variables or the specific variable. This is a paginated
API. Providing null `maxSizePerPage` results in retrieving maximum of 100
records per page. If you provide `maxSizePerPage` the value must be between
50 and 100. To get the next page result, a provide a pagination token from
`GetVariablesResult` as part of your request. Null pagination token fetches
the records from the beginning.
"""
def get_variables(client, input, options \\ []) do
request(client, "GetVariables", input, options)
end
@doc """
Lists all tags associated with the resource. This is a paginated API. To
get the next page results, provide the pagination token from the response
as part of your request. A null pagination token fetches the records from
the beginning.
"""
def list_tags_for_resource(client, input, options \\ []) do
request(client, "ListTagsForResource", input, options)
end
@doc """
Creates or updates a detector.
"""
def put_detector(client, input, options \\ []) do
request(client, "PutDetector", input, options)
end
@doc """
Creates or updates an entity type. An entity represents who is performing
the event. As part of a fraud prediction, you pass the entity ID to
indicate the specific entity who performed the event. An entity type
classifies the entity. Example classifications include customer, merchant,
or account.
"""
def put_entity_type(client, input, options \\ []) do
request(client, "PutEntityType", input, options)
end
@doc """
Creates or updates an event type. An event is a business activity that is
evaluated for fraud risk. With Amazon Fraud Detector, you generate fraud
predictions for events. An event type defines the structure for an event
sent to Amazon Fraud Detector. This includes the variables sent as part of
the event, the entity performing the event (such as a customer), and the
labels that classify the event. Example event types include online payment
transactions, account registrations, and authentications.
"""
def put_event_type(client, input, options \\ []) do
request(client, "PutEventType", input, options)
end
@doc """
Creates or updates an Amazon SageMaker model endpoint. You can also use
this action to update the configuration of the model endpoint, including
the IAM role and/or the mapped variables.
"""
def put_external_model(client, input, options \\ []) do
request(client, "PutExternalModel", input, options)
end
@doc """
Specifies the Key Management Service (KMS) customer master key (CMK) to be
used to encrypt content in Amazon Fraud Detector.
"""
def put_k_m_s_encryption_key(client, input, options \\ []) do
request(client, "PutKMSEncryptionKey", input, options)
end
@doc """
Creates or updates label. A label classifies an event as fraudulent or
legitimate. Labels are associated with event types and used to train
supervised machine learning models in Amazon Fraud Detector.
"""
def put_label(client, input, options \\ []) do
request(client, "PutLabel", input, options)
end
@doc """
Creates or updates an outcome.
"""
def put_outcome(client, input, options \\ []) do
request(client, "PutOutcome", input, options)
end
@doc """
Assigns tags to a resource.
"""
def tag_resource(client, input, options \\ []) do
request(client, "TagResource", input, options)
end
@doc """
Removes tags from a resource.
"""
def untag_resource(client, input, options \\ []) do
request(client, "UntagResource", input, options)
end
@doc """
Updates a detector version. The detector version attributes that you can
update include models, external model endpoints, rules, rule execution
mode, and description. You can only update a `DRAFT` detector version.
"""
def update_detector_version(client, input, options \\ []) do
request(client, "UpdateDetectorVersion", input, options)
end
@doc """
Updates the detector version's description. You can update the metadata for
any detector version (`DRAFT, ACTIVE,` or `INACTIVE`).
"""
def update_detector_version_metadata(client, input, options \\ []) do
request(client, "UpdateDetectorVersionMetadata", input, options)
end
@doc """
Updates the detector version’s status. You can perform the following
promotions or demotions using `UpdateDetectorVersionStatus`: `DRAFT` to
`ACTIVE`, `ACTIVE` to `INACTIVE`, and `INACTIVE` to `ACTIVE`.
"""
def update_detector_version_status(client, input, options \\ []) do
request(client, "UpdateDetectorVersionStatus", input, options)
end
@doc """
Updates a model. You can update the description attribute using this
action.
"""
def update_model(client, input, options \\ []) do
request(client, "UpdateModel", input, options)
end
@doc """
Updates a model version. Updating a model version retrains an existing
model version using updated training data and produces a new minor version
of the model. You can update the training data set location and data access
role attributes using this action. This action creates and trains a new
minor version of the model, for example version 1.01, 1.02, 1.03.
"""
def update_model_version(client, input, options \\ []) do
request(client, "UpdateModelVersion", input, options)
end
@doc """
Updates the status of a model version.
You can perform the following status updates:
<ol> <li> Change the `TRAINING_COMPLETE` status to `ACTIVE`.
</li> <li> Change `ACTIVE`to `INACTIVE`.
</li> </ol>
"""
def update_model_version_status(client, input, options \\ []) do
request(client, "UpdateModelVersionStatus", input, options)
end
@doc """
Updates a rule's metadata. The description attribute can be updated.
"""
def update_rule_metadata(client, input, options \\ []) do
request(client, "UpdateRuleMetadata", input, options)
end
@doc """
Updates a rule version resulting in a new rule version. Updates a rule
version resulting in a new rule version (version 1, 2, 3 ...).
"""
def update_rule_version(client, input, options \\ []) do
request(client, "UpdateRuleVersion", input, options)
end
@doc """
Updates a variable.
"""
def update_variable(client, input, options \\ []) do
request(client, "UpdateVariable", 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: "frauddetector"}
host = build_host("frauddetector", client)
url = build_url(host, client)
headers = [
{"Host", host},
{"Content-Type", "application/x-amz-json-1.1"},
{"X-Amz-Target", "AWSHawksNestServiceFacade.#{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/fraud_detector.ex
| 0.915393 | 0.671093 |
fraud_detector.ex
|
starcoder
|
defmodule LocalLedger.Transaction do
@moduledoc """
This module is responsible for preparing and formatting the transactions
before they are passed to an entry to be inserted in the database.
"""
alias LocalLedgerDB.{Balance, MintedToken, Transaction}
@doc """
Get or insert the given minted token and all the given addresses before
building a map representation usable by the LocalLedgerDB schemas.
"""
def build_all({debits, credits}, minted_token) do
{:ok, minted_token} = MintedToken.get_or_insert(minted_token)
sending = format(minted_token, debits, Transaction.debit_type)
receiving = format(minted_token, credits, Transaction.credit_type)
sending ++ receiving
end
@doc """
Extract the list of DEBIT addresses.
"""
def get_addresses(transactions) do
transactions
|> Enum.filter(fn transaction ->
transaction[:type] == Transaction.debit_type
end)
|> Enum.map(fn transaction -> transaction[:balance_address] end)
end
# Build a list of balance maps with the required details for DB insert.
defp format(minted_token, balances, type) do
Enum.map balances, fn attrs ->
{:ok, balance} = Balance.get_or_insert(attrs)
%{
type: type,
amount: attrs["amount"],
minted_token_friendly_id: minted_token.friendly_id,
balance_address: balance.address,
}
end
end
@doc """
Match when genesis is set to true and does... nothing.
"""
def check_balance(_, %{genesis: true}) do
:ok
end
@doc """
Match when genesis is false and run the balance check.
"""
def check_balance(transactions, %{genesis: _}) do
check_balance(transactions)
end
@doc """
Check the current balance amount for each DEBIT transaction.
"""
def check_balance(transactions) do
Enum.each transactions, fn transaction ->
if transaction[:type] == Transaction.debit_type do
Transaction.check_balance(%{
amount: transaction[:amount],
friendly_id: transaction[:minted_token_friendly_id],
address: transaction[:balance_address]
})
end
end
end
end
|
apps/local_ledger/lib/local_ledger/transaction.ex
| 0.820793 | 0.523055 |
transaction.ex
|
starcoder
|
defmodule LiveViewStudio.Boats do
@moduledoc """
The Boats context.
"""
import Ecto.Query, warn: false
alias LiveViewStudio.Repo
alias LiveViewStudio.Boats.Boat
# [type: "sporting", prices: ["$", "$$"]]
def list_boats(criteria) when is_list(criteria) do
query = from(b in Boat)
Enum.reduce(criteria, query, fn
{:type, ""}, query ->
query
{:type, type}, query ->
from q in query, where: q.type == ^type
{:prices, [""]}, query ->
query
{:prices, prices}, query ->
from q in query, where: q.price in ^prices
end)
|> Repo.all()
end
@doc """
Returns the list of boats.
## Examples
iex> list_boats()
[%Boat{}, ...]
"""
def list_boats do
Repo.all(Boat)
end
@doc """
Gets a single boat.
Raises `Ecto.NoResultsError` if the Boat does not exist.
## Examples
iex> get_boat!(123)
%Boat{}
iex> get_boat!(456)
** (Ecto.NoResultsError)
"""
def get_boat!(id), do: Repo.get!(Boat, id)
@doc """
Creates a boat.
## Examples
iex> create_boat(%{field: value})
{:ok, %Boat{}}
iex> create_boat(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_boat(attrs \\ %{}) do
%Boat{}
|> Boat.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a boat.
## Examples
iex> update_boat(boat, %{field: new_value})
{:ok, %Boat{}}
iex> update_boat(boat, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_boat(%Boat{} = boat, attrs) do
boat
|> Boat.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a boat.
## Examples
iex> delete_boat(boat)
{:ok, %Boat{}}
iex> delete_boat(boat)
{:error, %Ecto.Changeset{}}
"""
def delete_boat(%Boat{} = boat) do
Repo.delete(boat)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking boat changes.
## Examples
iex> change_boat(boat)
%Ecto.Changeset{data: %Boat{}}
"""
def change_boat(%Boat{} = boat, attrs \\ %{}) do
Boat.changeset(boat, attrs)
end
end
|
live_view_studio/lib/live_view_studio/boats.ex
| 0.850748 | 0.515132 |
boats.ex
|
starcoder
|
defmodule OpenTelemetry.Honeycomb.Json do
@moduledoc """
JSON back end.
The OpenTelemetry Honeycomb Exporter uses a `Jason`-style JSON encoder via a behaviour so you
can adapt it to your preferred JSON encoder or decode/encode options.
To use `Poison`, install it. The exporter defaults `json_backend` to
`OpenTelemetry.Honeycomb.Json.PoisonBackend`, which adapts `Poison` to the subset of the
`Jason` API we document with this behaviour.
To use `Jason`, install it and configure it as the `json_backend`:
```
config :opentelemetry,
processors: [
ot_batch_processor: %{
exporter: OpenTelemetry.Honeycomb.Exporter,
json_backend: Jason
}
]
```
"""
alias OpenTelemetry.Honeycomb.Json.PoisonBackend
@typedoc "A term that we can encode to JSON, or decode from JSON."
@type encodable_term ::
nil
| boolean()
| float()
| integer()
| String.t()
| [encodable_term]
| %{optional(String.t()) => encodable_term()}
@doc """
Decode a term from JSON.
"""
@callback decode!(iodata()) :: encodable_term() | no_return()
@doc """
Encode a term to JSON.
"""
@callback encode_to_iodata!(encodable_term()) :: iodata() | no_return()
@typedoc """
Configuration for `decode!/2` and `encode_to_iodata!/2`:
* `json_module`: the JSON back end module
"""
@type config_opt :: {:json_module, module()}
@doc """
Return the default configuration for `decode!/2` and `encode_to_iodata!/2`.
"""
def default_config, do: [json_module: PoisonBackend]
@doc """
Decode a term from JSON using the configured back end.
"""
@spec decode!(
config :: [config_opt()],
data :: iodata()
) :: encodable_term() | no_return()
def decode!(config, data) do
json_module = Keyword.fetch!(config, :json_module)
json_module.decode!(data)
end
@doc """
Encode a term to JSON using the configured back end.
"""
@spec encode_to_iodata!(
config :: [config_opt()],
term :: encodable_term()
) :: iodata() | no_return()
def encode_to_iodata!(config, term) do
json_module = Keyword.fetch!(config, :json_module)
json_module.encode_to_iodata!(term)
end
end
|
lib/open_telemetry/honeycomb/json.ex
| 0.909679 | 0.764056 |
json.ex
|
starcoder
|
defmodule Rackla do
@moduledoc Regex.replace(~r/```(elixir|json)(\n|.*)```/Us, File.read!("README.md"),
fn(_, _, code) -> Regex.replace(~r/^/m, code, " ") end)
import Plug.Conn
require Logger
@type t :: %__MODULE__{producers: [pid]}
defstruct producers: []
@doc """
Takes a single string (URL) or a `Rackla.Request` struct and executes a HTTP
request to the defined server. You can, by using the `Rackla.Request` struct,
specify more advanced options for your request such as which HTTP verb to use
but also individual connection timeout limits etc. You can also call this
function with a list of strings or `Rackla.Request` structs in order to
perform multiple requests concurrently.
This function will return a `Rackla` type which will contain the results
from the request(s) once available or an `:error` tuple in case of failures
such non-responding servers or DNS lookup failures. Per default, on success, it
will only contain the response payload but the entire response can be used by
setting the option `:full` to true.
Options:
* `:full` - If set to true, the `Rackla` type will contain a `Rackla.Response`
struct with the status code, headers and body (payload), default: false.
* `:connect_timeout` - Connection timeout limit in milliseconds, default:
`5_000`.
* `:receive_timeout` - Receive timeout limit in milliseconds, default:
`5_000`.
* `:insecure` - If set to true, SSL certificates will not be checked,
default: `false`.
* `:follow_redirect` - If set to true, Rackla will follow redirects,
default: `false`.
* `:max_redirect` - Maximum number of redirects, default: `5`.
* `:force_redirect` - Force follow redirect (e.g. POST), default: `false`.
* `:proxy` - Proxy to use, see `Rackla.Proxy`, default: `nil`.
If you specify any options in a `Rackla.Request` struct, these will overwrite
the options passed to the `request` function for that specific request.
"""
@spec request(String.t | Rackla.Request.t | [String.t] | [Rackla.Request.t], Keyword.t) :: t
def request(requests, options \\ [])
def request(requests, options) when is_list(requests) do
producers =
Enum.map(requests, fn(request) ->
request =
if is_binary(request) do
%Rackla.Request{url: request}
else
request
end
{:ok, producer} =
Task.start_link(fn ->
request_options = Map.get(request, :options, %{})
global_insecure = Keyword.get(options, :insecure, false)
global_connect_timeout = Keyword.get(options, :connect_timeout, 5_000)
global_receive_timeout = Keyword.get(options, :receive_timeout, 5_000)
global_follow_redirect = Keyword.get(options, :follow_redirect, false)
global_max_redirect = Keyword.get(options, :max_redirect, 5)
global_force_redirect = Keyword.get(options, :force_redirect, false)
global_proxy = Keyword.get(options, :proxy)
request_proxy = Map.get(request_options, :proxy)
rackla_proxy =
cond do
request_proxy -> request_proxy
global_proxy -> global_proxy
true -> nil
end
proxy_options =
case rackla_proxy do
%Rackla.Proxy{type: type, host: host, port: port, username: username, password: password, pool: pool} ->
proxy_basic_setting = [proxy: {type, String.to_char_list(host), port}]
auth_settings =
case type do
:socks5 ->
socks5_user = if username, do: [socks5_user: username], else: []
socks5_pass = if password, do: [socks5_pass: password], else: []
socks5_user ++ socks5_pass
:connect ->
if username && password do
[proxy_auth: {username, password}]
else
[]
end
end
pool_setting = if pool, do: [pool: pool], else: []
proxy_basic_setting ++ auth_settings ++ pool_setting
nil -> []
end
hackney_request =
:hackney.request(
Map.get(request, :method, :get),
Map.get(request, :url, ""),
Map.get(request, :headers, %{}) |> Enum.into([]),
Map.get(request, :body, ""),
[
insecure: Map.get(request_options, :insecure, global_insecure),
connect_timeout: Map.get(request_options, :connect_timeout, global_connect_timeout),
recv_timeout: Map.get(request_options, :receive_timeout, global_receive_timeout),
follow_redirect: Map.get(request_options, :follow_redirect, global_follow_redirect),
max_redirect: Map.get(request_options, :max_redirect, global_max_redirect),
force_redirect: Map.get(request_options, :force_redirect, global_force_redirect)
] ++ proxy_options
)
case hackney_request do
{:ok, {:maybe_redirect, _, _, _}} ->
warn_request(:force_redirect_disabled)
{:ok, status, headers, body_ref} ->
case :hackney.body(body_ref) do
{:ok, body} ->
consumer = receive do
{pid, :ready} -> pid
end
global_full = Keyword.get(options, :full, false)
response =
if Map.get(request_options, :full, global_full) do
%Rackla.Response{status: status, headers: headers |> Enum.into(%{}), body: body}
else
body
end
send(consumer, {self, {:ok, response}})
{:error, reason} ->
warn_request(reason)
end
{:error, {reason, _partial_body}} ->
warn_request(reason)
{:error, reason} ->
warn_request(reason)
end
end)
producer
end)
%Rackla{producers: producers}
end
def request(request, options) do
request([request], options)
end
@doc """
Takes any type an encapsulates it in a `Rackla` type.
Example:
Rackla.just([1,2,3]) |> Rackla.map(&IO.inspect/1)
[1, 2, 3]
"""
@spec just(any | [any]) :: t
def just(thing) do
{:ok, producers} =
Task.start_link(fn ->
consumer = receive do
{pid, :ready} -> pid
end
send(consumer, {self, {:ok, thing}})
end)
%Rackla{producers: [producers]}
end
@doc """
Takes a list of and encapsulates each of the containing elements separately
in a `Rackla` type.
Example:
Rackla.just_list([1,2,3]) |> Rackla.map(&IO.inspect/1)
3
2
1
"""
@spec just_list([any]) :: t
def just_list(things) when is_list(things) do
things
|> Enum.map(&just/1)
|> Enum.reduce(&(join &2, &1))
end
@doc """
Returns a new `Rackla` type, where each encapsulated item is the result of
invoking `fun` on each corresponding encapsulated item.
Example:
Rackla.just_list([1,2,3]) |> Rackla.map(fn(x) -> x * 2 end) |> Rackla.collect
[2, 4, 6]
"""
@spec map(t, (any -> any)) :: t
def map(%Rackla{producers: producers}, fun) when is_function(fun, 1) do
new_producers =
Enum.map(producers, fn(producer) ->
{:ok, new_producer} =
Task.start_link(fn ->
send(producer, {self, :ready})
response =
receive do
{^producer, {:rackla, nested_producers}} ->
{:rackla, map(nested_producers, fun)}
{^producer, {:ok, thing}} ->
{:ok, fun.(thing)}
{^producer, error} ->
{:ok, fun.(error)}
end
consumer = receive do
{pid, :ready} -> pid
end
send(consumer, {self, response})
end)
new_producer
end)
%Rackla{producers: new_producers}
end
@doc """
Takes a `Rackla` type, applies the specified function to each of the
elements encapsulated in it and returns a new `Rackla` type with the
results. The given function must return a `Rackla` type.
This function is useful when you want to create a new request pipeline based
on the results of a previous request. In those cases, you can use
`Rackla.flat_map` to access the response from a request and call
`Rackla.request` inside the function since `Rackla.request` returns a
`Rackla` type.
Example:
Rackla.just_list([1,2,3]) |> Rackla.flat_map(fn(x) -> Rackla.just(x * 2) end) |> Rackla.collect
[2, 4, 6]
"""
@spec flat_map(t, (any -> t)) :: t
def flat_map(%Rackla{producers: producers}, fun) do
new_producers =
Enum.map(producers, fn(producer) ->
{:ok, new_producer} =
Task.start_link(fn ->
send(producer, {self, :ready})
%Rackla{} = new_rackla =
receive do
{^producer, {:rackla, nested_rackla}} ->
flat_map(nested_rackla, fun)
{^producer, {:ok, thing}} ->
fun.(thing)
{^producer, error} ->
fun.(error)
end
receive do
{consumer, :ready} ->
send(consumer, {self, {:rackla, new_rackla}})
end
end)
new_producer
end)
%Rackla{producers: new_producers}
end
@doc """
Invokes `fun` for each element in the `Rackla` type passing that element and
the accumulator `acc` as arguments. `fun`s return value is stored in `acc`. The
first element of the collection is used as the initial value of `acc`. Returns
the accumulated value inside a `Rackla` type.
Example:
Rackla.just_list([1,2,3]) |> Rackla.reduce(fn (x, acc) -> x + acc end) |> Rackla.collect
6
"""
@spec reduce(t, (any, any -> any)) :: t
def reduce(%Rackla{} = rackla, fun) when is_function(fun, 2) do
{:ok, new_producer} =
Task.start_link(fn ->
thing = reduce_recursive(rackla, fun)
receive do
{consumer, :ready} -> send(consumer, {self, {:ok, thing}})
end
end)
%Rackla{producers: [new_producer]}
end
@doc """
Invokes `fun` for each element in the `Rackla` type passing that element and
the accumulator `acc` as arguments. fun's return value is stored in `acc`.
Returns the accumulated value inside a `Rackla` type.
Example:
Rackla.just_list([1,2,3]) |> Rackla.reduce(10, fn (x, acc) -> x + acc end) |> Rackla.collect
16
"""
def reduce(%Rackla{} = rackla, acc, fun) when is_function(fun, 2) do
{:ok, new_producer} =
Task.start_link(fn ->
thing = reduce_recursive(rackla, acc, fun)
receive do
{consumer, :ready} -> send(consumer, {self, {:ok, thing}})
end
end)
%Rackla{producers: [new_producer]}
end
@spec reduce_recursive(t, (any, any -> any)) :: any
defp reduce_recursive(%Rackla{producers: producers}, fun) do
[producer | tail_producers] = producers
send(producer, {self, :ready})
acc =
receive do
{^producer, {:rackla, nested_producers}} ->
reduce_recursive(nested_producers, fun)
{^producer, {:ok, thing}} ->
thing
{^producer, error} ->
error
end
reduce_recursive(%Rackla{producers: tail_producers}, acc, fun)
end
@spec reduce_recursive(t, any, (any, any -> any)) :: any
defp reduce_recursive(%Rackla{producers: producers}, acc, fun) do
Enum.reduce(producers, acc, fn(producer, acc) ->
send(producer, {self, :ready})
receive do
{^producer, {:rackla, nested_producers}} ->
reduce_recursive(nested_producers, acc, fun)
{^producer, {:ok, thing}} ->
fun.(thing, acc)
{^producer, error} ->
fun.(error, acc)
end
end)
end
@doc """
Returns the element encapsulated inside a `Rackla` type, or a list of
elements in case the `Rackla` type contains many elements.
Example:
Rackla.just_list([1,2,3]) |> Rackla.collect
[1,2,3]
"""
@spec collect(t) :: [any] | any
def collect(%Rackla{} = rackla) do
[single_response | rest] = list_responses = collect_recursive(rackla)
if rest == [], do: single_response, else: list_responses
end
@spec collect_recursive(t) :: [any]
defp collect_recursive(%Rackla{producers: producers}) do
Enum.flat_map(producers, fn(producer) ->
send(producer, {self, :ready})
receive do
{^producer, {:rackla, nested_rackla}} ->
collect_recursive(nested_rackla)
{^producer, {:ok, thing}} ->
[thing]
{^producer, error} ->
[error]
end
end)
end
@doc """
Returns a new `Rackla` type by joining the encapsulated elements from two
`Rackla` types.
Example:
Rackla.join(Rackla.just(1), Rackla.just(2)) |> Rackla.collect
[1, 2]
"""
@spec join(t, t) :: t
def join(%Rackla{producers: p1}, %Rackla{producers: p2}) do
%Rackla{producers: p1 ++ p2}
end
@doc """
Converts a `Rackla` type to a HTTP response and send it to the client by
using `Plug.Conn`. The `Plug.Conn` will be taken implicitly by looking for a
variable named `conn`. If you want to specify which `Plug.Conn` to use, you
can use `Rackla.response_conn`.
Strings will be sent as is to the client. If the `Rackla` type contains any
other type such as a list, it will be converted into a string by using `inspect`
on it. You can also convert Elixir data types to JSON format by setting the
option `:json` to true.
Using this macro is the same as writing:
conn = response_conn(rackla, conn, options)
Options:
* `:compress` - Compresses the response by applying a gzip compression to it.
When this option is used, the entire response has to be sent in one chunk.
You can't reuse the `conn` to send any more data after `Rackla.response` with
`:compress` set to `true` has been invoked. When set to `true`, Rackla will
check the request header `content-encoding` to make sure the client accepts
gzip responses. If you want to respond with gzip without checking the
request headers, you can set `:compress` to `:force`.
* `:json` - If set to true, the encapsulated elements will be converted into
a JSON encoded string before they are sent to the client. This will also set
the header "content-type" to the appropriate "application/json; charset=utf-8".
"""
defmacro response(rackla, options \\ []) do
quote do
var!(conn) = response_conn(unquote(rackla), var!(conn), unquote(options))
_ = var!(conn) # hack to get rid of "unused variable" compiler warning
end
end
@doc """
See documentation for `Rackla.response`.
"""
@spec response_conn(t, Plug.Conn.t, Keyword.t) :: Plug.Conn.t
def response_conn(%Rackla{} = rackla, conn, options \\ []) do
cond do
Keyword.get(options, :compress, false) || Keyword.get(options, :json, false) ->
response_sync(rackla, conn, options)
Keyword.get(options, :sync, false) ->
response_sync_chunk(rackla, conn, options)
true ->
response_async(rackla, conn, options)
end
end
@doc """
Convert an incoming request (from `Plug`) to a `Rackla.Request`.
If `options` is specified, it will be added to the `Rackla.Request`.
For valid options, see documentation for `Rackla.Request`.
Returns either `{:ok, Rackla.Request}` or `{:error, reason}` as per
`:gen_tcp.recv/2`.
The `Plug.Conn` will be taken implicitly by looking for a variable named
`conn`. If you want to specify which `Plug.Conn` to use, you can use
`Rackla.incoming_request_conn`.
Using this macro is the same as writing:
`conn = incoming_request_conn(conn, options)`
From `Plug.Conn` documentation:
Because the request body can be of any size, reading the body will only work
once, as Plug will not cache the result of these operations. If you need to
access the body multiple times, it is your responsibility to store it. Finally
keep in mind some plugs like Plug.Parsers may read the body, so the body may
be unavailable after being accessed by such plugs.
"""
@spec incoming_request(%{}) :: {:ok, Rackla.Request.t} | {:error, atom}
defmacro incoming_request(options) do
quote do
{var!(conn), rackla_request} = incoming_request_conn(var!(conn), unquote(options))
_ = var!(conn) # hack to get rid of "unused variable" compiler warning
rackla_request
end
end
@doc """
See see incoming_request with options.
"""
@spec incoming_request() :: {:ok, Rackla.Request.t} | {:error, atom}
defmacro incoming_request() do
quote do
{var!(conn), rackla_request} = incoming_request_conn(var!(conn))
_ = var!(conn) # hack to get rid of "unused variable" compiler warning
rackla_request
end
end
@doc """
See documentation for `Rackla.incoming_request`.
"""
@spec incoming_request_conn(Plug.Conn.t, %{}) :: {Plug.Conn.t, {:ok, Rackla.Request.t}} | {Plug.Conn.t, {:error, atom}}
def incoming_request_conn(conn, options \\ %{}) do
response_body =
Stream.unfold(Plug.Conn.read_body(conn), fn
:done ->
nil;
{:ok, body, new_conn} ->
{{new_conn, body}, :done};
{:more, partial_body, new_conn} ->
{partial_body, Plug.Conn.read_body(new_conn)};
{:error, term} ->
{{:error, term}, :done}
end)
|> Enum.reduce({"", conn}, fn
({:error, term}, {_body_acc, conn_acc}) -> {{:error, term}, conn_acc};
({new_conn, body}, {body_acc, _conn_acc}) -> {{:ok, body_acc <> body}, new_conn};
(partial_body, {body_acc, conn_acc}) -> {body_acc <> partial_body, conn_acc}
end)
case response_body do
{{:error, term}, final_conn} -> {final_conn, {:error, term}}
{{:ok, body}, final_conn} ->
method = conn.method |> String.downcase |> String.to_atom
query_string = if conn.query_string != "", do: "?#{conn.query_string}", else: ""
url = "#{Atom.to_string(conn.scheme)}://#{conn.host}:#{conn.port}#{conn.request_path}#{query_string}"
headers = Enum.into(conn.req_headers, %{})
rackla_request =
%Rackla.Request{
method: method,
url: url,
headers: headers,
body: body,
options: options
}
{final_conn, {:ok, rackla_request}}
end
end
@spec response_async(t, Plug.Conn.t, Keyword.t) :: Plug.Conn.t
defp response_async(%Rackla{} = rackla, conn, options) do
conn = prepare_conn(conn, Keyword.get(options, :status, 200), Keyword.get(options, :headers, %{}))
prepare_chunks(rackla)
|> send_chunks(conn)
end
@spec prepare_chunks(t) :: [pid]
defp prepare_chunks(%Rackla{producers: producers}) do
Enum.map(producers, fn(pid) ->
send(pid, {self, :ready})
pid
end)
end
@spec send_chunks([pid], Plug.Conn.t) :: Plug.Conn.t
defp send_chunks([], conn), do: conn
defp send_chunks(producers, conn) when is_list(producers) do
send_thing =
fn(thing, remaining_producers, conn) ->
thing = if is_binary(thing), do: thing, else: inspect(thing)
case chunk(conn, thing) do
{:ok, new_conn} ->
send_chunks(remaining_producers, new_conn)
{:error, reason} ->
warn_response(reason)
conn
end
end
receive do
{message_producer, thing} ->
{remaining_producers, current_producer} =
Enum.partition(producers, &(&1 != message_producer))
if (current_producer == []) do
send_chunks(remaining_producers, conn)
else
case thing do
{:rackla, nested_rackla} ->
send_chunks(remaining_producers ++ prepare_chunks(nested_rackla), conn)
{:ok, thing} ->
send_thing.(thing, remaining_producers, conn)
error ->
send_thing.(error, remaining_producers, conn)
end
end
end
end
@spec prepare_conn(Plug.Conn.t, integer, %{}) :: Plug.Conn.t
defp prepare_conn(conn, status, headers) do
if (conn.state == :chunked) do
conn
else
conn
|> set_headers(headers)
|> send_chunked(status)
end
end
@spec response_sync_chunk(t, Plug.Conn.t, Keyword.t) :: Plug.Conn.t
defp response_sync_chunk(%Rackla{} = rackla, conn, options) do
conn = prepare_conn(conn, Keyword.get(options, :status, 200), Keyword.get(options, :headers, %{}))
Enum.reduce(prepare_chunks(rackla), conn, fn(pid, conn) ->
receive do
{^pid, {:rackla, nested_rackla}} ->
response_sync_chunk(nested_rackla, conn, options)
{^pid, thing} ->
thing = if elem(thing, 0) == :ok, do: elem(thing, 1), else: thing
thing = if is_binary(thing), do: thing, else: inspect(thing)
case chunk(conn, thing) do
{:ok, new_conn} ->
new_conn
{:error, reason} ->
warn_response(reason)
conn
end
end
end)
end
@spec response_sync(t, Plug.Conn.t, Keyword.t) :: Plug.Conn.t
defp response_sync(%Rackla{} = rackla, conn, options) do
response_encoded =
if Keyword.get(options, :json, false) do
response = collect(rackla)
if is_list(response) do
Enum.map(response, fn(thing) ->
if is_binary(thing) do
case Poison.decode(thing) do
{:ok, decoded} -> decoded
{:error, _reason} -> thing
end
else
thing
end
end)
|> Poison.encode
else
if is_binary(response) do
case Poison.decode(response) do
{:ok, _decoded} -> {:ok, response}
{:error, _reason} -> Poison.encode(response)
end
else
Poison.encode(response)
end
end
else
binary =
Enum.map(collect_recursive(rackla), &(if is_binary(&1), do: &1, else: inspect(&1)))
|> Enum.join
{:ok, binary}
end
case response_encoded do
{:ok, response_binary} ->
headers = Keyword.get(options, :headers, %{})
compress = Keyword.get(options, :compress, false)
{response_binary, headers} =
if compress do
allow_gzip =
Plug.Conn.get_req_header(conn, "accept-encoding")
|> Enum.flat_map(fn(encoding) ->
String.split(encoding, ",", trim: true)
|> Enum.map(&String.strip/1)
end)
|> Enum.any?(&(Regex.match?(~r/(^(\*|gzip)(;q=(1$|1\.0{1,3}$|0\.[1-9]{1,3}$)|$))/, &1)))
if allow_gzip || compress == :force do
{:zlib.gzip(response_binary), Map.merge(headers, %{"content-encoding" => "gzip"})}
else
{response_binary, headers}
end
else
{response_binary, headers}
end
conn =
if Keyword.get(options, :json, false) do
put_resp_content_type(conn, "application/json")
else
conn
end
chunk_status =
prepare_conn(conn, Keyword.get(options, :status, 200), headers)
|> chunk(response_binary)
case chunk_status do
{:ok, new_conn} ->
new_conn
{:error, reason} ->
warn_response(reason)
conn
end
{:error, reason} ->
case Logger.error("Response decoding error: #{inspect(reason)}") do
{:error, logger_reason} ->
IO.puts(:std_err, "Unable to log \"Response decoding error: #{inspect(reason)}\", reason: #{inspect(logger_reason)}")
:ok -> :ok
end
conn
end
end
@spec set_headers(Plug.Conn.t, %{}) :: Plug.Conn.t
defp set_headers(conn, headers) do
Enum.reduce(headers, conn, fn({key, value}, conn) ->
put_resp_header(conn, key, value)
end)
end
@spec warn_response(any) :: :ok
defp warn_response(reason) do
case Logger.error("HTTP response error: #{inspect(reason)}") do
{:error, logger_reason} ->
IO.puts(:std_err, "Unable to log \"HTTP response error: #{inspect(reason)}\", reason: #{inspect(logger_reason)}")
:ok -> :ok
end
:ok
end
@spec warn_request(any) :: :ok
defp warn_request(reason) do
case Logger.warn("HTTP request error: #{inspect(reason)}") do
{:error, logger_reason} ->
IO.puts(:std_err, "Unable to log \"HTTP request error: #{inspect(reason)}\", reason: #{inspect(logger_reason)}")
:ok -> :ok
end
consumer = receive do
{pid, :ready} -> pid
end
send(consumer, {self, {:error, reason}})
:ok
end
end
defimpl Inspect, for: Rackla do
import Inspect.Algebra
def inspect(_rackla, _opts) do
concat ["#Rackla<>"]
end
end
|
lib/rackla.ex
| 0.728265 | 0.634458 |
rackla.ex
|
starcoder
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.