hexsha
stringlengths 40
40
| size
int64 2
991k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
208
| max_stars_repo_name
stringlengths 6
106
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
33.5k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
208
| max_issues_repo_name
stringlengths 6
106
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
16.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
208
| max_forks_repo_name
stringlengths 6
106
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
6.91k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 2
991k
| avg_line_length
float64 1
36k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f70047e45b24ccabf7e84e6af6eadcc9c0ab0135 | 6,398 | ex | Elixir | lib/monex/result.ex | youroff/monex | fe7d78880e41dc946fc9e2e3a0a133f3b380a39a | [
"MIT"
] | 7 | 2016-12-25T08:26:08.000Z | 2021-08-15T01:23:53.000Z | lib/monex/result.ex | youroff/monex | fe7d78880e41dc946fc9e2e3a0a133f3b380a39a | [
"MIT"
] | null | null | null | lib/monex/result.ex | youroff/monex | fe7d78880e41dc946fc9e2e3a0a133f3b380a39a | [
"MIT"
] | 1 | 2020-09-07T06:59:55.000Z | 2020-09-07T06:59:55.000Z | defmodule MonEx.Result do
@moduledoc """
Result module provides Result type with utility functions.
"""
alias MonEx.Option
defmacro ok(res) do
quote do
{:ok, unquote(res)}
end
end
defmacro error(err) do
quote do
{:error, unquote(err)}
end
end
@typedoc """
Result type.
`ok(res)` or `error(err)` unwraps into `{:ok, res}` or `{:error, err}`
"""
@type t(res, err) :: {:ok, res} | {:error, err}
@doc """
Returns true if argument is `ok()`, false if `error()`
## Examples
iex> is_ok(ok(5))
true
iex> is_error(ok(5))
false
"""
@spec is_ok(t(any, any)) :: boolean
def is_ok(ok(_)), do: true
def is_ok(error(_)), do: false
@doc """
Returns true if argument is `error()`, false if `ok()`
## Examples
iex> is_error(error("Error"))
true
iex> is_ok(error("Error"))
false
"""
@spec is_error(t(any, any)) :: boolean
def is_error(x), do: !is_ok(x)
@doc """
Returns value `x` if argument is `ok(x)`, raises `e` if `error(e)`.
Second argument is a fallback. It can by a lambda accepting error, or some precomputed default value.
## Examples
iex> unwrap(ok(5))
5
iex> unwrap(error(:uh_oh), fn _ -> 10 end)
10
iex> unwrap(error(:uh_oh), 10)
10
"""
@spec unwrap(t(res, err), res | (err -> res)) :: res when res: any, err: any
def unwrap(result, fallback \\ nil)
def unwrap(ok(x), _), do: x
def unwrap(error(m), nil), do: raise m
def unwrap(error(m), f) when is_function(f, 1), do: f.(m)
def unwrap(error(_), fallback), do: fallback
@doc """
Converts Result into Option: `ok(val)` -> `some(val)`, `error(e)` -> `none()`.
Useful when you don't care about the error value and only what to emphasize that
nothing has been found.
## Examples
iex> unwrap_option(ok(5))
{:some, 5} # same as some(5)
iex> unwrap_option(error(:uh_oh))
{:none} # none()
"""
@spec unwrap_option(t(res, any)) :: Option.t(res) when res: any
def unwrap_option(ok(x)), do: {:some, x}
def unwrap_option(error(_)), do: {:none}
@doc """
Returns self if it is `ok(x)`, or evaluates supplied lambda that expected
to return another `result`. Returns supplied fallback result, if second argument is not a function.
## Examples
iex> ok(5) |> fallback(fn _ -> 1 end)
ok(5)
iex> error("WTF") |> fallback(fn m -> ok("\#{m}LOL") end)
ok("WTFLOL")
iex> error("WTF") |> fallback(ok(5))
ok(5)
"""
@spec fallback(t(res, err), t(res, err) | (err -> t(res, err))) :: t(res, err) when res: any, err: any
def fallback(ok(x), _), do: ok(x)
def fallback(error(m), f) when is_function(f, 1) do
f.(m)
end
def fallback(error(_), any), do: any
@doc """
Filters and unwraps the collection of results, leaving only ok's
## Examples
iex> [ok(1), error("oops")] |> collect_ok
[1]
"""
@spec collect_ok([t(res, any)]) :: [res] when res: any
def collect_ok(results) when is_list(results) do
Enum.reduce(results, [], fn
ok(res), acc -> [res | acc]
error(_), acc -> acc
end) |> Enum.reverse
end
@doc """
Filters and unwraps the collection of results, leaving only errors:
## Examples
iex> [ok(1), error("oops")] |> collect_error
["oops"]
"""
@spec collect_error([t(res, err)]) :: [err] when res: any, err: any
def collect_error(results) when is_list(results) do
Enum.reduce(results, [], fn
ok(_), acc -> acc
error(err), acc -> [err | acc]
end) |> Enum.reverse
end
@doc """
Groups and unwraps the collection of results, forming a Map with keys `:ok` and `:error`:
## Examples
iex> [ok(1), error("oops"), ok(2)] |> partition
%{ok: [1, 2], error: ["oops"]}
iex> [ok(1)] |> partition
%{ok: [1], error: []}
"""
@spec partition([t(res, err)]) :: %{ok: [res], error: [err]} when res: any, err: any
def partition(results) when is_list(results) do
base = %{ok: [], error: []}
results = Enum.group_by(results, fn
ok(_) -> :ok
error(_) -> :error
end, fn
ok(res) -> res
error(err) -> err
end)
Map.merge(base, results)
end
@doc """
Retry in case of error.
Possible options:
* `:n` - times to retry
* `:delay` — delay between retries
## Examples
result = retry n: 3, delay: 3000 do
remote_service()
end
This will call `remove_service()` 4 times (1 time + 3 retries) with an interval of 3 seconds.
"""
defmacro retry(opts \\ [], do: exp) do
quote do
n = Keyword.get(unquote(opts), :n, 5)
delay = Keyword.get(unquote(opts), :delay, 0)
retry_rec(n, delay, fn -> unquote(exp) end)
end
end
@doc false
@spec retry_rec(integer, integer, (() -> t(res, err))) :: t(res, err) when res: any, err: any
def retry_rec(0, _delay, lambda), do: lambda.()
def retry_rec(n, delay, lambda) do
case lambda.() do
error(_) ->
:timer.sleep(delay)
retry_rec(n - 1, delay, lambda)
ok -> ok
end
end
@doc """
Wraps expression and returns exception wrapped into `error()` if it happens,
otherwise `ok(result of expression)`, in case if expression returns result
type, it won't be wrapped.
Possible modes:
* `:full` - returns exception struct intact (default)
* `:message` — returns error message only
* `:module` — returns error module only
## Examples
iex> try_result do
...> 5 + 5
...> end
ok(10)
iex> broken = fn -> raise ArithmeticError, [message: "bad argument"] end
...> try_result do
...> broken.()
...> end
error(%ArithmeticError{message: "bad argument"})
...> try_result :message do
...> broken.()
...> end
error("bad argument")
...> try_result :module do
...> broken.()
...> end
error(ArithmeticError)
"""
defmacro try_result(mode \\ :full, do: exp) do
error_handler = case mode do
:message -> quote do e -> error(e.message) end
:module -> quote do e -> error(e.__struct__) end
_ -> quote do e -> error(e) end
end
quote do
try do
case unquote(exp) do
ok(res) -> ok(res)
error(e) -> error(e)
x -> ok(x)
end
rescue
unquote(error_handler)
end
end
end
end
| 25.49004 | 104 | 0.571429 |
f700654e4685725725ead8db046a39c968e0c08c | 1,378 | ex | Elixir | clients/cloud_search/lib/google_api/cloud_search/v1/model/spell_result.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/cloud_search/lib/google_api/cloud_search/v1/model/spell_result.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/cloud_search/lib/google_api/cloud_search/v1/model/spell_result.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudSearch.V1.Model.SpellResult do
@moduledoc """
## Attributes
* `suggestedQuery` (*type:* `String.t`, *default:* `nil`) - The suggested spelling of the query.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:suggestedQuery => String.t()
}
field(:suggestedQuery)
end
defimpl Poison.Decoder, for: GoogleApi.CloudSearch.V1.Model.SpellResult do
def decode(value, options) do
GoogleApi.CloudSearch.V1.Model.SpellResult.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudSearch.V1.Model.SpellResult do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 29.319149 | 100 | 0.736575 |
f70074818b71a0cb48d3509586811e66e73a2243 | 2,338 | ex | Elixir | clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/location.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/location.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/location.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudTasks.V2beta2.Model.Location do
@moduledoc """
A resource that represents Google Cloud Platform location.
## Attributes
* `displayName` (*type:* `String.t`, *default:* `nil`) - The friendly name for this location, typically a nearby city name.
For example, "Tokyo".
* `labels` (*type:* `map()`, *default:* `nil`) - Cross-service attributes for the location. For example
{"cloud.googleapis.com/region": "us-east1"}
* `locationId` (*type:* `String.t`, *default:* `nil`) - The canonical id for this location. For example: `"us-east1"`.
* `metadata` (*type:* `map()`, *default:* `nil`) - Service-specific metadata. For example the available capacity at the given
location.
* `name` (*type:* `String.t`, *default:* `nil`) - Resource name for the location, which may vary between implementations.
For example: `"projects/example-project/locations/us-east1"`
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:displayName => String.t(),
:labels => map(),
:locationId => String.t(),
:metadata => map(),
:name => String.t()
}
field(:displayName)
field(:labels, type: :map)
field(:locationId)
field(:metadata, type: :map)
field(:name)
end
defimpl Poison.Decoder, for: GoogleApi.CloudTasks.V2beta2.Model.Location do
def decode(value, options) do
GoogleApi.CloudTasks.V2beta2.Model.Location.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudTasks.V2beta2.Model.Location do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.53125 | 129 | 0.690761 |
f70093a50210d9ff8af12d10d872138bde6080a3 | 3,216 | exs | Elixir | test/espy_web/api_test.exs | XRPL-Labs/XRPL-Webhook | 4b4194d3263ff957bbd3d654aefe06d1225fa73d | [
"MIT"
] | 9 | 2019-02-22T10:33:28.000Z | 2021-02-27T20:26:03.000Z | test/espy_web/api_test.exs | XRPL-Labs/XRPL-Webhook | 4b4194d3263ff957bbd3d654aefe06d1225fa73d | [
"MIT"
] | 11 | 2019-04-02T19:21:25.000Z | 2022-01-05T23:22:04.000Z | test/espy_web/api_test.exs | XRPL-Labs/XRPL-Webhook | 4b4194d3263ff957bbd3d654aefe06d1225fa73d | [
"MIT"
] | 6 | 2019-03-07T15:54:30.000Z | 2020-03-26T02:33:40.000Z | defmodule EspyWeb.ApiTest do
use EspyWeb.ConnCase
import EspyWeb.Factory
setup do
Supervisor.terminate_child(Espy.Supervisor, ConCache)
Supervisor.restart_child(Espy.Supervisor, ConCache)
:ok
end
test "/api/v1/webhooks", %{conn: conn} do
app1 = insert(:app)
# CREATE WEBHOOK INVALID URL
conn1 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> post(api_webhook_path(conn, :create), url: "https://invalid-url")
|> BlueBird.ConnLogger.save()
# CREATE WEBHOOK
conn1 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> post(api_webhook_path(conn, :create), url: "https://myapp.com/webhook")
|> BlueBird.ConnLogger.save()
response_create = json_response(conn1, 200)
webhook_id = Map.get(response_create, "webhook_id")
# GET LIST OF WEBHOOKS
conn2 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> get(api_webhook_path(conn, :list))
|> BlueBird.ConnLogger.save()
response_list = json_response(conn2, 200)
# DELETE WEBHOOK
conn3 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> delete(api_webhook_path(conn, :delete, webhook_id))
|> BlueBird.ConnLogger.save()
end
test "/api/v1/subscriptions", %{conn: conn} do
app1 = insert(:app)
# Invalid address
conn1 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> post(api_subscription_path(conn, :create), address: "invalid_address")
|> BlueBird.ConnLogger.save()
# Subscription an address
conn1 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> post(api_subscription_path(conn, :create), address: "rqAiBkWakRA9Jr5TCahtKrPS23KBYUZhj")
|> BlueBird.ConnLogger.save()
response_create = json_response(conn1, 200)
subscription_id = Map.get(response_create, "subscription_id")
# GET LIST OF SUBSCRIPTIONS
conn2 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> get(api_subscription_path(conn, :list))
|> BlueBird.ConnLogger.save()
response_list = json_response(conn2, 200)
# DEACTIVATE SUBSCRIPTION
conn3 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> delete(api_subscription_path(conn, :delete, subscription_id))
|> BlueBird.ConnLogger.save()
end
end
| 32.816327 | 97 | 0.664801 |
f700a389d06d19b1e2c4f273852e4c3149585893 | 3,906 | ex | Elixir | lib/jukee_web/channels/player_channel.ex | samuelbriole/Jukee | 1f0dd7616d63d742fac17daabaf50b406d9dbede | [
"MIT"
] | 3 | 2018-05-17T17:43:06.000Z | 2018-06-09T02:12:25.000Z | lib/jukee_web/channels/player_channel.ex | samuelbriole/Jukee | 1f0dd7616d63d742fac17daabaf50b406d9dbede | [
"MIT"
] | 2 | 2018-06-04T15:51:36.000Z | 2018-06-20T11:31:23.000Z | lib/jukee_web/channels/player_channel.ex | samuelbriole/jukee | 1f0dd7616d63d742fac17daabaf50b406d9dbede | [
"MIT"
] | null | null | null | defmodule JukeeWeb.PlayerChannel do
use JukeeWeb, :channel
alias Jukee.Players
alias JukeeWeb.PlayerView
alias Jukee.TrackSearch
alias Jukee.Tracks
alias JukeeWeb.PlayerPresence
require Logger
def join("player:" <> player_id, payload, socket) do
if authorized?(player_id, payload) do
send(self(), :after_join)
{:ok, socket}
else
{:error, %{reason: "unauthorized"}}
end
end
def terminate(_reason, socket) do
end_player_connection(socket)
end
def handle_info(:after_join, socket) do
socket = create_player_connection(socket)
push socket, "presence_state", PlayerPresence.list(socket)
{:ok, _} = PlayerPresence.track(socket, socket.assigns.user.id, %{
username: socket.assigns.user.username,
online_at: inspect(System.system_time(:seconds))
})
{:noreply, socket}
end
# Channels can be used in a request/response fashion
# by sending replies to requests from the client
def handle_in("ping", payload, socket) do
{:reply, {:ok, payload}, socket}
end
def handle_in("play_track", %{"playerTrackIndex" => player_track_index}, socket) do
player_id = get_player_id(socket)
Players.play_track_on_player(player_id, player_track_index)
{:reply, {:ok, %{ message: "new track playing" }}, socket}
end
def handle_in("play", _payload, socket) do
player_id = get_player_id(socket)
Players.play(player_id)
{:reply, {:ok, %{ message: "playing" }}, socket}
end
def handle_in("pause", _payload, socket) do
player_id = get_player_id(socket)
Players.pause(player_id)
{:reply, {:ok, %{ message: "paused" }}, socket}
end
def handle_in("toggle_pause", _payload, socket) do
player_id = get_player_id(socket)
Players.toggle_pause(player_id)
{:reply, {:ok, %{ message: "toggled" }}, socket}
end
def handle_in("seek", %{"to" => to}, socket) do
player_id = get_player_id(socket)
Players.seek(player_id, to)
{:reply, {:ok, %{ message: "seek success" }}, socket}
end
def handle_in("next", _payload, socket) do
player_id = get_player_id(socket)
Players.next(player_id)
{:reply, {:ok, %{ message: "next success" }}, socket}
end
def handle_in("previous", _payload, socket) do
player_id = get_player_id(socket)
Players.previous(player_id)
{:reply, {:ok, %{ message: "previous success" }}, socket}
end
def handle_in("add_track", %{"provider" => provider, "externalId" => external_id}, socket) do
player_id = get_player_id(socket)
track = TrackSearch.get_track(provider, external_id)
Players.add_track(player_id, track)
{:reply, {:ok, %{ message: "track added" }}, socket}
end
def handle_in("delete_track", %{"playerTrackIndex" => player_track_index}, socket) do
player_id = get_player_id(socket)
Players.delete_track_on_player(player_id, player_track_index)
{:reply, {:ok, %{ message: "track deleted" }}, socket}
end
def handle_in("autoplay", %{"autoplay" => autoplay}, socket) do
player_id = get_player_id(socket)
Players.set_autoplay(player_id, autoplay)
{:reply, {:ok, %{ message: "ok" }}, socket}
end
defp get_player_id(socket) do
"player:" <> player_id = socket.topic
player_id
end
# Everyone can join a player channel
defp authorized?(_player_id, _payload) do
true
end
defp create_player_connection(socket) do
user = socket.assigns.user
player_id = get_player_id(socket)
{:ok, player_connection} = Players.create_player_connection(%{
user_id: user.id,
player_id: player_id,
start_date: NaiveDateTime.utc_now()
})
Phoenix.Socket.assign(socket, :player_connection, player_connection)
end
defp end_player_connection(socket) do
player_connection = socket.assigns.player_connection
Players.update_player_connection(player_connection, %{ end_date: NaiveDateTime.utc_now() })
end
end
| 31 | 95 | 0.689196 |
f700ed269eb4d8e6666457796cce8fe603084df7 | 1,383 | exs | Elixir | mix.exs | appunite/proto_response | 6bb3e0023000e741598ea004bbb114abbc2278fd | [
"Apache-2.0"
] | 4 | 2017-09-19T12:21:13.000Z | 2021-01-04T16:29:43.000Z | mix.exs | appunite/proto_response | 6bb3e0023000e741598ea004bbb114abbc2278fd | [
"Apache-2.0"
] | 1 | 2017-10-20T12:14:51.000Z | 2017-10-20T12:14:51.000Z | mix.exs | appunite/proto_response | 6bb3e0023000e741598ea004bbb114abbc2278fd | [
"Apache-2.0"
] | 1 | 2017-09-23T03:52:47.000Z | 2017-09-23T03:52:47.000Z | defmodule ProtoResponse.Mixfile do
use Mix.Project
@version "0.4.1"
def project do
[
app: :proto_response,
deps: deps(System.get_env("PROTOBUF_PACKAGE")),
description: description(),
elixir: "~> 1.4",
elixirc_paths: elixirc_paths(Mix.env()),
package: package(),
version: @version
]
end
defp package do
[
name: :proto_response,
files: ~w(lib mix.exs README.md LICENSE),
maintainers: ["Tobiasz Małecki"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/appunite/proto_response"}
]
end
defp description do
"Provides helper function similar to Phoenix.ConnTest.json_response/2, but for protobuf"
end
def application do
[
extra_applications: [:logger]
]
end
defp elixirc_paths(:test), do: ["lib", "test/proto.ex"]
defp elixirc_paths(_), do: ["lib"]
# both libraries uses same module name :/
defp deps("exprotobuf") do
[
{:exprotobuf, "~> 1.0", optional: true},
{:phoenix, "~> 1.1"}
]
end
defp deps("protobuf") do
[
{:protobuf, "~> 0.3", optional: true},
{:phoenix, "~> 1.1"}
]
end
defp deps(_) do
[
{:exprotobuf, "~> 1.0", optional: true},
{:protobuf, "~> 0.3", optional: true},
{:phoenix, "~> 1.1"},
{:ex_doc, "~> 0.13", only: :dev}
]
end
end
| 21.276923 | 92 | 0.570499 |
f700f90fdd8771acfd6a54887dd63fe8ad2876fd | 143 | ex | Elixir | lib/demo_web/live/example_live/static_title_component.ex | pthompson/live_component_examples | e2e1be52a7ff1065fd5ef749c375d729d5d08c21 | [
"MIT"
] | 21 | 2019-12-15T19:14:56.000Z | 2022-02-07T16:04:30.000Z | lib/demo_web/live/example_live/static_title_component.ex | pthompson/live_component_examples | e2e1be52a7ff1065fd5ef749c375d729d5d08c21 | [
"MIT"
] | 4 | 2020-02-06T01:05:28.000Z | 2020-09-07T19:08:45.000Z | lib/demo_web/live/example_live/static_title_component.ex | pthompson/live_component_examples | e2e1be52a7ff1065fd5ef749c375d729d5d08c21 | [
"MIT"
] | 6 | 2019-12-15T19:15:02.000Z | 2021-09-16T20:35:53.000Z | defmodule DemoWeb.StaticTitleComponent do
use Phoenix.LiveComponent
def render(assigns) do
~L"""
<h1>Title</h1>
"""
end
end
| 14.3 | 41 | 0.664336 |
f700fda5320043e8b56a32eb3ff0a5251971236f | 3,989 | ex | Elixir | lib/apoc/hazmat/aead/aes-gcm.ex | auxesis/apoc | e650c21767f508a2720dad1bb3d14439bdcf39c4 | [
"Apache-2.0"
] | 6 | 2018-10-04T14:18:35.000Z | 2020-05-15T08:43:31.000Z | lib/apoc/hazmat/aead/aes-gcm.ex | auxesis/apoc | e650c21767f508a2720dad1bb3d14439bdcf39c4 | [
"Apache-2.0"
] | 3 | 2018-10-23T12:20:45.000Z | 2021-01-27T10:41:14.000Z | lib/apoc/hazmat/aead/aes-gcm.ex | auxesis/apoc | e650c21767f508a2720dad1bb3d14439bdcf39c4 | [
"Apache-2.0"
] | 2 | 2020-02-19T00:43:37.000Z | 2021-08-19T04:04:25.000Z | defmodule Apoc.Hazmat.AEAD.AESGCM do
@moduledoc """
Implementation of the AES block encryption
standard as per [FIPS PUB 197](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197.pdf).
The functions in this module operate in GCM (Galois/Counter Mode) to provide
fast Authenticated Encryption.
See [Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC](https://csrc.nist.gov/publications/detail/sp/800-38d/final).
Additionally, three block sizes are support (128, 192 and 256). For those particularly
paranoid users, a block size of 256 is recommended for defense against [Shore's algorithm](https://arxiv.org/abs/quant-ph/9508027).
Use a 32 byte key for a 256 bit block size. See `encrypt/2`.
"""
@type aes_key() :: <<_::16, _::_*8>> | <<_::24, _::_*8>> | <<_::32, _::_*8>>
@iv_byte_size 16
defguardp is_key_of_size(key, size) when is_binary(key) and byte_size(key) == size
defguardp is_valid_aad(aad) when aad in ["AES128GCM", "AES192GCM", "AES256GCM"]
@doc """
Encrypt a message using AES under the given key
The key should be a 16, 24 or 32 byte binary string
## Example
```elixir
Apoc.AES.encrypt("a secret message", Apoc.rand_bytes(16))
```
It's important that the key be as uniformly random as possible.
Consequently, avoid the temptation to do this:
```elixir
# Don't do this
k = Apoc.rand_bytes(16) |> Base.encode16
byte_size(k) # => 32
Apoc.AES.encrypt(message, k)
```
As the bytesize of the encoded key in this example is 32 bytes
the 256 bit block size will be used. However, this is not a uniformly
random key in `{0,1}^32`. Specifically, the probability of a key containing
a character other than [0-9a-f] is zero.
To avoid this issue, don't use ASCII (e.g. hex of base 64 encoded strings)
as the key. By all means, encode the key for storage purposes but make sure
your key has been generated with the correct number of bytes.
```elixir
k = Apoc.rand_bytes(32)
Apoc.AES.encrypt(message, k)
Apoc.encode(k) # => base 64 encoded for storage somewhere safe
```
"""
# TODO: Optional additional AD
@spec encrypt(String.t(), aes_key()) :: {:ok, binary()} | {:error, binary()}
def encrypt(msg, key) when is_binary(msg) and is_key_of_size(key, 16) do
do_encrypt(msg, "AES128GCM", key)
end
def encrypt(msg, key) when is_binary(msg) and is_key_of_size(key, 24) do
do_encrypt(msg, "AES192GCM", key)
end
def encrypt(msg, key) when is_binary(msg) and is_key_of_size(key, 32) do
do_encrypt(msg, "AES256GCM", key)
end
def encrypt(x, _) when not is_binary(x) do
{:error, "Message must be a binary"}
end
def encrypt(_, _) do
{:error, "Invalid key size"}
end
def encrypt!(msg, key) do
with {:ok, ct} <- encrypt(msg, key) do
ct
else
{:error, message} ->
raise Apoc.Error, message: message
end
end
@doc """
Decrypt a cipher text that has been encrypted under the given key.
## Example
```elixir
{:ok, plaintext} = Apoc.AES.decrypt(ciphertext, key)
```
"""
@spec decrypt(String.t(), aes_key) :: {:ok, binary} | {:error, String.t()}
def decrypt(payload, key) do
with {:ok, <<aad::binary-9, iv::binary-16, tag::binary-16, ct::binary>>} <-
Apoc.decode(payload) do
do_decrypt(ct, aad, iv, tag, key)
end
end
defp do_encrypt(msg, aad, key) do
iv = Apoc.rand_bytes(@iv_byte_size)
try do
with {ct, tag} <- :crypto.block_encrypt(:aes_gcm, key, iv, {aad, msg}) do
{:ok, Apoc.encode(aad <> iv <> tag <> ct)}
end
rescue
err in ArgumentError ->
{:error, err.message}
err ->
{:error, inspect(err)}
end
end
defp do_decrypt(ct, aad, iv, tag, key) when is_valid_aad(aad) do
:aes_gcm
|> :crypto.block_decrypt(key, iv, {aad, ct, tag})
|> case do
plain_text when is_binary(plain_text) ->
{:ok, plain_text}
_ ->
:error
end
end
end
| 29.548148 | 155 | 0.655051 |
f701022b8d97e5f4a5de3b2648eb7ee92865775b | 808 | ex | Elixir | lib/coherence/plugs/validate_option.ex | henb/coherence | 725247353bad46df464caffa12b9ea2788fe774f | [
"MIT"
] | null | null | null | lib/coherence/plugs/validate_option.ex | henb/coherence | 725247353bad46df464caffa12b9ea2788fe774f | [
"MIT"
] | null | null | null | lib/coherence/plugs/validate_option.ex | henb/coherence | 725247353bad46df464caffa12b9ea2788fe774f | [
"MIT"
] | 1 | 2019-09-11T10:21:21.000Z | 2019-09-11T10:21:21.000Z | defmodule Coherence.ValidateOption do
@moduledoc """
Plug to validate the given option is enabled in the project's configuration.
"""
import Coherence.Controller, only: [logged_out_url: 1]
import Plug.Conn
import Phoenix.Controller, only: [put_flash: 3, redirect: 2]
alias Coherence.Messages
@behaviour Plug
@dialyzer [
{:nowarn_function, call: 2},
{:nowarn_function, init: 1},
]
@spec init(Keyword.t | atom) :: [tuple]
def init(options) do
%{option: options}
end
@spec call(Plug.Conn.t, Map.t) :: Plug.Conn.t
def call(conn, opts) do
if Coherence.Config.has_option(opts[:option]) do
conn
else
conn
|> put_flash(:error, Messages.backend().invalid_request())
|> redirect(to: logged_out_url(conn))
|> halt
end
end
end
| 21.837838 | 78 | 0.659653 |
f7012f6d03c928c74a572130021e6c4258a7e3c5 | 2,242 | ex | Elixir | clients/monitoring/lib/google_api/monitoring/v3/model/typed_value.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/monitoring/lib/google_api/monitoring/v3/model/typed_value.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/monitoring/lib/google_api/monitoring/v3/model/typed_value.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Monitoring.V3.Model.TypedValue do
@moduledoc """
A single strongly-typed value.
## Attributes
* `boolValue` (*type:* `boolean()`, *default:* `nil`) - A Boolean value: true or false.
* `distributionValue` (*type:* `GoogleApi.Monitoring.V3.Model.Distribution.t`, *default:* `nil`) - A distribution value.
* `doubleValue` (*type:* `float()`, *default:* `nil`) - A 64-bit double-precision floating-point number. Its magnitude is approximately ±10±300 and it has 16 significant digits of precision.
* `int64Value` (*type:* `String.t`, *default:* `nil`) - A 64-bit integer. Its range is approximately ±9.2x1018.
* `stringValue` (*type:* `String.t`, *default:* `nil`) - A variable-length string value.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:boolValue => boolean(),
:distributionValue => GoogleApi.Monitoring.V3.Model.Distribution.t(),
:doubleValue => float(),
:int64Value => String.t(),
:stringValue => String.t()
}
field(:boolValue)
field(:distributionValue, as: GoogleApi.Monitoring.V3.Model.Distribution)
field(:doubleValue)
field(:int64Value)
field(:stringValue)
end
defimpl Poison.Decoder, for: GoogleApi.Monitoring.V3.Model.TypedValue do
def decode(value, options) do
GoogleApi.Monitoring.V3.Model.TypedValue.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Monitoring.V3.Model.TypedValue do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38 | 194 | 0.70785 |
f70142ac0dead99bb1eb2d8a7db06d555b05d8d1 | 149 | exs | Elixir | test/make_word_bot/base_test.exs | nulleof/make-word-bot | bf6ed80975f0d89697cdd5e1019d73c47dd335d4 | [
"MIT"
] | null | null | null | test/make_word_bot/base_test.exs | nulleof/make-word-bot | bf6ed80975f0d89697cdd5e1019d73c47dd335d4 | [
"MIT"
] | 5 | 2019-02-10T14:22:39.000Z | 2019-02-11T16:29:02.000Z | test/make_word_bot/base_test.exs | nulleof/make-word-bot | bf6ed80975f0d89697cdd5e1019d73c47dd335d4 | [
"MIT"
] | null | null | null | defmodule MakeWordBot.BaseTest do
use ExUnit.Case
doctest MakeWordBot
doctest MakeWordBot.ProcessMessage
doctest MakeWordBot.WordChecker
end
| 21.285714 | 36 | 0.838926 |
f7014928c025feb734460b4d6d668cfb64b55039 | 2,498 | ex | Elixir | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_addons_config.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | 1 | 2021-10-01T09:20:41.000Z | 2021-10-01T09:20:41.000Z | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_addons_config.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_addons_config.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AddonsConfig do
@moduledoc """
Add-on configurations for the Apigee organization.
## Attributes
* `advancedApiOpsConfig` (*type:* `GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AdvancedApiOpsConfig.t`, *default:* `nil`) - Configuration for the Advanced API Ops add-on.
* `integrationConfig` (*type:* `GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1IntegrationConfig.t`, *default:* `nil`) - Configuration for the Integration add-on.
* `monetizationConfig` (*type:* `GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1MonetizationConfig.t`, *default:* `nil`) - Configuration for the Monetization add-on.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:advancedApiOpsConfig =>
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AdvancedApiOpsConfig.t() | nil,
:integrationConfig =>
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1IntegrationConfig.t() | nil,
:monetizationConfig =>
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1MonetizationConfig.t() | nil
}
field(:advancedApiOpsConfig,
as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AdvancedApiOpsConfig
)
field(:integrationConfig, as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1IntegrationConfig)
field(:monetizationConfig, as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1MonetizationConfig)
end
defimpl Poison.Decoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AddonsConfig do
def decode(value, options) do
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AddonsConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AddonsConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 42.338983 | 175 | 0.760208 |
f70149449b7d97da2121163e4632ebd915daa9ff | 1,676 | ex | Elixir | lib/grakn/session.ex | liveforeverx/grakn_elixir | e64745fb200dd64956396c33b986b94706556ab4 | [
"MIT"
] | 1 | 2019-04-25T18:12:23.000Z | 2019-04-25T18:12:23.000Z | lib/grakn/session.ex | liveforeverx/grakn_elixir | e64745fb200dd64956396c33b986b94706556ab4 | [
"MIT"
] | null | null | null | lib/grakn/session.ex | liveforeverx/grakn_elixir | e64745fb200dd64956396c33b986b94706556ab4 | [
"MIT"
] | null | null | null | defmodule Grakn.Session do
@moduledoc false
@opaque t :: GRPC.Channel.t()
# every 5 min
@ping_rate 300_000
@spec new(String.t()) :: {:ok, t()} | {:error, any()}
def new(uri) do
GRPC.Stub.connect(uri, adapter_opts: %{http2_opts: %{keepalive: @ping_rate}})
end
@spec transaction(t(), String.t()) :: {:ok, Grakn.Transaction.t(), String.t()} | {:error, any()}
def transaction(channel, keyspace) do
channel
|> Grakn.Transaction.new(keyspace)
end
@spec command(t(), Grakn.Command.command(), keyword()) :: {:ok, any()} | {:error, any()}
def command(channel, :get_keyspaces, _) do
request = Keyspace.Keyspace.Retrieve.Req.new()
channel
|> Keyspace.KeyspaceService.Stub.retrieve(request)
|> case do
{:ok, %Keyspace.Keyspace.Retrieve.Res{names: names}} ->
{:ok, names}
{:error, reason} ->
{:error, reason}
resp ->
{:error, "Unexpected response from service #{inspect(resp)}"}
end
end
def command(channel, :create_keyspace, name: name) do
request = Keyspace.Keyspace.Create.Req.new(name: name)
channel
|> Keyspace.KeyspaceService.Stub.create(request)
|> case do
{:ok, %Keyspace.Keyspace.Create.Res{}} -> {:ok, nil}
error -> error
end
end
def command(channel, :delete_keyspace, name: name) do
request = Keyspace.Keyspace.Delete.Req.new(name: name)
channel
|> Keyspace.KeyspaceService.Stub.delete(request)
|> case do
{:ok, %Keyspace.Keyspace.Delete.Res{}} -> {:ok, nil}
error -> error
end
end
@spec close(t()) :: :ok
def close(channel) do
channel
|> GRPC.Stub.disconnect()
:ok
end
end
| 24.647059 | 98 | 0.618138 |
f7014def0560d0dce71f8f4c7e9cafbdd023f64f | 997 | ex | Elixir | web/views/error_helpers.ex | sgeos/memo_api | d57d0a1190296364a559510de9b4dd9d50b034e8 | [
"CC0-1.0"
] | null | null | null | web/views/error_helpers.ex | sgeos/memo_api | d57d0a1190296364a559510de9b4dd9d50b034e8 | [
"CC0-1.0"
] | null | null | null | web/views/error_helpers.ex | sgeos/memo_api | d57d0a1190296364a559510de9b4dd9d50b034e8 | [
"CC0-1.0"
] | null | null | null | defmodule MemoApi.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
if error = form.errors[field] do
content_tag :span, translate_error(error), class: "help-block"
end
end
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# Because error messages were defined within Ecto, we must
# call the Gettext module passing our Gettext backend. We
# also use the "errors" domain as translations are placed
# in the errors.po file. On your own code and templates,
# this could be written simply as:
#
# dngettext "errors", "1 file", "%{count} files", count
#
Gettext.dngettext(MemoApi.Gettext, "errors", msg, msg, opts[:count], opts)
end
def translate_error(msg) do
Gettext.dgettext(MemoApi.Gettext, "errors", msg)
end
end
| 27.694444 | 78 | 0.679037 |
f70190f0277a8ed36ef3050b36678f27aa12a095 | 1,536 | ex | Elixir | web/controllers/server_controller.ex | rob05c/tox | f54847ca058ad24b909341ad65d595a4069d2471 | [
"Apache-2.0"
] | 2 | 2016-11-16T17:24:21.000Z | 2019-02-15T05:38:27.000Z | web/controllers/server_controller.ex | rob05c/tox | f54847ca058ad24b909341ad65d595a4069d2471 | [
"Apache-2.0"
] | null | null | null | web/controllers/server_controller.ex | rob05c/tox | f54847ca058ad24b909341ad65d595a4069d2471 | [
"Apache-2.0"
] | null | null | null | defmodule Tox.ServerController do
use Tox.Web, :controller
alias Tox.Server
def index(conn, _params) do
servers = Repo.all(Server)
render(conn, "index.json", servers: servers)
end
def create(conn, %{"server" => server_params}) do
changeset = Server.changeset(%Server{}, server_params)
case Repo.insert(changeset) do
{:ok, server} ->
conn
|> put_status(:created)
|> put_resp_header("location", server_path(conn, :show, server))
|> render("show.json", server: server)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(Tox.ChangesetView, "error.json", changeset: changeset)
end
end
def show(conn, %{"id" => id}) do
server = Repo.get!(Server, id)
render(conn, "show.json", server: server)
end
def update(conn, %{"id" => id, "server" => server_params}) do
server = Repo.get!(Server, id)
changeset = Server.changeset(server, server_params)
case Repo.update(changeset) do
{:ok, server} ->
render(conn, "show.json", server: server)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(Tox.ChangesetView, "error.json", changeset: changeset)
end
end
def delete(conn, %{"id" => id}) do
server = Repo.get!(Server, id)
# Here we use delete! (with a bang) because we expect
# it to always work (and if it does not, it will raise).
Repo.delete!(server)
send_resp(conn, :no_content, "")
end
end
| 27.428571 | 72 | 0.61849 |
f701b34d822846e33faa33cebaf337e526076b8f | 3,494 | ex | Elixir | clients/games/lib/google_api/games/v1/model/player_leaderboard_score.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/games/lib/google_api/games/v1/model/player_leaderboard_score.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/player_leaderboard_score.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Games.V1.Model.PlayerLeaderboardScore do
@moduledoc """
This is a JSON template for a player leaderboard score object.
## Attributes
* `kind` (*type:* `String.t`, *default:* `games#playerLeaderboardScore`) - Uniquely identifies the type of this resource. Value is always the fixed string games#playerLeaderboardScore.
* `leaderboard_id` (*type:* `String.t`, *default:* `nil`) - The ID of the leaderboard this score is in.
* `publicRank` (*type:* `GoogleApi.Games.V1.Model.LeaderboardScoreRank.t`, *default:* `nil`) - The public rank of the score in this leaderboard. This object will not be present if the user is not sharing their scores publicly.
* `scoreString` (*type:* `String.t`, *default:* `nil`) - The formatted value of this score.
* `scoreTag` (*type:* `String.t`, *default:* `nil`) - Additional information about the score. Values must contain no more than 64 URI-safe characters as defined by section 2.3 of RFC 3986.
* `scoreValue` (*type:* `String.t`, *default:* `nil`) - The numerical value of this score.
* `socialRank` (*type:* `GoogleApi.Games.V1.Model.LeaderboardScoreRank.t`, *default:* `nil`) - The social rank of the score in this leaderboard.
* `timeSpan` (*type:* `String.t`, *default:* `nil`) - The time span of this score.
Possible values are:
- "ALL_TIME" - The score is an all-time score.
- "WEEKLY" - The score is a weekly score.
- "DAILY" - The score is a daily score.
* `writeTimestamp` (*type:* `String.t`, *default:* `nil`) - The timestamp at which this score was recorded, in milliseconds since the epoch in UTC.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => String.t(),
:leaderboard_id => String.t(),
:publicRank => GoogleApi.Games.V1.Model.LeaderboardScoreRank.t(),
:scoreString => String.t(),
:scoreTag => String.t(),
:scoreValue => String.t(),
:socialRank => GoogleApi.Games.V1.Model.LeaderboardScoreRank.t(),
:timeSpan => String.t(),
:writeTimestamp => String.t()
}
field(:kind)
field(:leaderboard_id)
field(:publicRank, as: GoogleApi.Games.V1.Model.LeaderboardScoreRank)
field(:scoreString)
field(:scoreTag)
field(:scoreValue)
field(:socialRank, as: GoogleApi.Games.V1.Model.LeaderboardScoreRank)
field(:timeSpan)
field(:writeTimestamp)
end
defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.PlayerLeaderboardScore do
def decode(value, options) do
GoogleApi.Games.V1.Model.PlayerLeaderboardScore.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.PlayerLeaderboardScore do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 46.586667 | 230 | 0.700057 |
f701d95899578b5b28f213b78eb2316130b1676b | 732 | exs | Elixir | test/nerves_hub/client/default_test.exs | aadavids/nerves_hub | 504f143381b2cc7c7e76a049febbb590ad5752f1 | [
"Apache-2.0"
] | null | null | null | test/nerves_hub/client/default_test.exs | aadavids/nerves_hub | 504f143381b2cc7c7e76a049febbb590ad5752f1 | [
"Apache-2.0"
] | null | null | null | test/nerves_hub/client/default_test.exs | aadavids/nerves_hub | 504f143381b2cc7c7e76a049febbb590ad5752f1 | [
"Apache-2.0"
] | null | null | null | defmodule NervesHub.Client.DefaultTest do
use ExUnit.Case, async: true
alias NervesHub.Client.Default
doctest Default
test "update_available/1" do
assert Default.update_available(-1) == :apply
end
describe "handle_fwup_message/1" do
test "progress" do
assert Default.handle_fwup_message({:progress, 25}) == :ok
end
test "error" do
assert Default.handle_fwup_message({:error, :any, "message"}) == :ok
end
test "warning" do
assert Default.handle_fwup_message({:warning, :any, "message"}) == :ok
end
test "any" do
assert Default.handle_fwup_message(:any) == :ok
end
end
test "handle_error/1" do
assert Default.handle_error(:error) == :ok
end
end
| 22.181818 | 76 | 0.670765 |
f701ddc702fd1180e83f428cab70fbdc9e210469 | 992 | ex | Elixir | apps/legion/lib/stereotype/stereotype.ex | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | 1 | 2021-01-04T11:06:12.000Z | 2021-01-04T11:06:12.000Z | apps/legion/lib/stereotype/stereotype.ex | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | 3 | 2021-01-30T06:40:37.000Z | 2021-01-30T06:41:08.000Z | apps/legion/lib/stereotype/stereotype.ex | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | null | null | null | defmodule Legion.Stereotype do
@moduledoc """
Defines stereotypes for the modules of the application.
"""
def model do
quote do
use Ecto.Schema
import Ecto
import Ecto.Changeset
import Ecto.Query
alias Legion.Repo
end
end
def virtual do
quote do
use Ecto.Schema
import Ecto
import Ecto.Query
alias Legion.Repo
end
end
def singleton do
quote do
use Ecto.Schema
import Ecto
import Ecto.Changeset
import Ecto.Query
alias Legion.Repo
end
end
def service do
quote do
import Ecto
import Ecto.Changeset
import Ecto.Query
alias Legion.Repo
end
end
def viewdecl do
quote do
use Legion.Stereotype.ViewDecl
use Legion.Stereotype, :model
end
end
@doc """
When used, dispatch to the appropriate stereotype.
"""
defmacro __using__(which) when is_atom(which),
do: apply(__MODULE__, which, [])
end
| 15.746032 | 57 | 0.629032 |
f701dea430ebd5735b2ba5cb96f32926ebf56630 | 5,323 | ex | Elixir | lib/api.ex | symmetrically/paypal | c775ef4cb8f8f169b2bd37bd2587e4edff1c25b3 | [
"MIT"
] | null | null | null | lib/api.ex | symmetrically/paypal | c775ef4cb8f8f169b2bd37bd2587e4edff1c25b3 | [
"MIT"
] | 1 | 2021-12-11T02:43:28.000Z | 2021-12-11T02:43:28.000Z | lib/api.ex | symmetrically/paypal | c775ef4cb8f8f169b2bd37bd2587e4edff1c25b3 | [
"MIT"
] | null | null | null | defmodule PayPal.API do
@moduledoc """
Documentation for PayPal.API. This module is about the base HTTP functionality
"""
@base_url_sandbox "https://api.sandbox.paypal.com/v1/"
@base_url_live "https://api.paypal.com/v1/"
@doc """
Requests an OAuth token from PayPal, returns a tuple containing the token and seconds till expiry.
Note: If your name is not Zen and you're reading this, unless you're sending me a PR (thanks!), you probably don't need this.
Possible returns:
- {:ok, {"XXXXXXXXXXXXXX", 32000}}
- {:error, :unauthorised}
- {:error, :bad_network}
## Examples
iex> PayPal.API.get_oauth_token
{:ok, {"XXXXXXXXXXXXXX", 32000}}
"""
@spec get_oauth_token :: {atom, any}
def get_oauth_token do
headers = %{"Content-Type" => "application/x-www-form-urlencoded"}
options = [hackney: [basic_auth: {PayPal.Config.get.client_id, PayPal.Config.get.client_secret}]]
form = {:form, [grant_type: "client_credentials"]}
case HTTPoison.post(base_url() <> "oauth2/token", form, headers, options) do
{:ok, %{status_code: 401}} ->
{:error, :unauthorised}
{:ok, %{body: body, status_code: 200}} ->
%{access_token: access_token, expires_in: expires_in} = Poison.decode!(body, keys: :atoms)
{:ok, {access_token, expires_in}}
_->
{:error, :bad_network}
end
end
@doc """
Make a HTTP GET request to the correct API depending on environment, adding needed auth header.
Note: If your name is not Zen and you're reading this, unless you're sending me a PR (thanks!), you probably don't need this.
Possible returns:
- {:ok, data}
- {:ok, :not_found}
- {:ok, :no_content}
- {:error, :bad_network}
- {:error, reason}
## Examples
iex> PayPal.API.get(url)
{:ok, {"XXXXXXXXXXXXXX", 32000}}
"""
@spec get(String.t) :: {atom, any}
def get(url) do
case HTTPoison.get(base_url() <> url, headers()) do
{:ok, %{status_code: 401}} ->
{:error, :unauthorised}
{:ok, %{body: body, status_code: 200}} ->
{:ok, Poison.decode!(body, keys: :atoms)}
{:ok, %{status_code: 404}} ->
{:ok, :not_found}
{:ok, %{status_code: 400}} ->
{:ok, :not_found}
{:ok, %{status_code: 204}} ->
{:ok, :no_content}
{:ok, %{body: body}}->
{:error, body}
_ ->
{:error, :bad_network}
end
end
@doc """
Make a HTTP POST request to the correct API depending on environment, adding needed auth header.
Note: If your name is not Zen and you're reading this, unless you're sending me a PR (thanks!), you probably don't need this.
Possible returns:
- {:ok, data}
- {:ok, :not_found}
- {:ok, :no_content}
- {:error, :bad_network}
- {:error, reason}
## Examples
iex> PayPal.API.post(url, data)
{:ok, {"XXXXXXXXXXXXXX", 32000}}
"""
@spec post(String.t, map) :: {atom, any}
def post(url, data) do
{:ok, data} = Poison.encode(data)
case HTTPoison.post(base_url() <> url, data, headers()) do
{:ok, %{status_code: 401}} ->
{:error, :unauthorised}
{:ok, %{body: body, status_code: 200}} ->
{:ok, Poison.decode!(body, keys: :atoms)}
{:ok, %{body: body, status_code: 201}} ->
{:ok, Poison.decode!(body, keys: :atoms)}
{:ok, %{status_code: 404}} ->
{:ok, :not_found}
{:ok, %{status_code: 204}} ->
{:ok, nil}
{:ok, %{status_code: 400}} ->
{:error, :malformed_request}
{:ok, %{body: body}} = resp ->
IO.inspect resp
{:error, body}
_ ->
{:error, :bad_network}
end
end
@doc """
Make a HTTP PATCH request to the correct API depending on environment, adding needed auth header.
Note: If your name is not Zen and you're reading this, unless you're sending me a PR (thanks!), you probably don't need this.
Possible returns:
- {:ok, data}
- {:ok, :not_found}
- {:ok, :no_content}
- {:error, :bad_network}
- {:error, reason}
## Examples
iex> PayPal.API.patch(url, data)
{:ok, {"XXXXXXXXXXXXXX", 32000}}
"""
@spec patch(String.t, map) :: {atom, any}
def patch(url, data) do
{:ok, data} = Poison.encode(data)
case HTTPoison.patch(base_url() <> url, data, headers()) do
{:ok, %{status_code: 401}} ->
{:error, :unauthorised}
{:ok, %{status_code: 200}} ->
{:ok, nil}
{:ok, %{body: body, status_code: 201}} ->
{:ok, Poison.decode!(body, keys: :atoms)}
{:ok, %{status_code: 404}} ->
{:ok, :not_found}
{:ok, %{status_code: 204}} ->
{:ok, :no_content}
{:ok, %{status_code: 400}} ->
{:error, :malformed_request}
{:ok, %{body: body}} = resp ->
IO.inspect resp
{:error, body}
_ ->
{:error, :bad_network}
end
end
@spec headers :: map
defp headers do
%{"Authorization" => "Bearer #{Application.get_env(:pay_pal, :access_token)}", "Content-Type" => "application/json"}
end
@spec base_url :: String.t
defp base_url do
case Application.get_env(:pay_pal, :env) do
:sandbox -> @base_url_sandbox
:live -> @base_url_live
_ ->
require Logger
Logger.warn "[PayPal] No `env` found in config, use `sandbox` as default."
@base_url_sandbox
end
end
end
| 28.929348 | 127 | 0.588014 |
f701fadbf33e0d3277a9561d2305055110b4c622 | 84 | exs | Elixir | legacy/artie/apps/pypool/test/python_process_test.exs | MaxStrange/ArtieInfant | 1edbb171a5405d2971227f2d2d83acb523c70034 | [
"MIT"
] | 1 | 2018-04-28T16:55:05.000Z | 2018-04-28T16:55:05.000Z | legacy/artie/apps/pypool/test/python_process_test.exs | MaxStrange/ArtieInfant | 1edbb171a5405d2971227f2d2d83acb523c70034 | [
"MIT"
] | null | null | null | legacy/artie/apps/pypool/test/python_process_test.exs | MaxStrange/ArtieInfant | 1edbb171a5405d2971227f2d2d83acb523c70034 | [
"MIT"
] | null | null | null | defmodule PythonProcessTest do
use ExUnit.Case
doctest Pypool.PythonProcess
end
| 16.8 | 30 | 0.833333 |
f702205e88e69c40e02640d593d43096ec88e0eb | 1,454 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/firewall_log_config.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/firewall_log_config.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/firewall_log_config.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Model.FirewallLogConfig do
@moduledoc """
The available logging options for a firewall rule.
## Attributes
* `enable` (*type:* `boolean()`, *default:* `nil`) - This field denotes whether to enable logging for a particular firewall rule.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:enable => boolean()
}
field(:enable)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.FirewallLogConfig do
def decode(value, options) do
GoogleApi.Compute.V1.Model.FirewallLogConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.FirewallLogConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 30.93617 | 133 | 0.73934 |
f7026023063a76dbd9cffc791045a366bf80f97b | 1,719 | ex | Elixir | lib/private.ex | rockneurotiko/private | 7e5cbec79b079ee456fcbaf53ff91e42c37f2ee6 | [
"Apache-2.0"
] | null | null | null | lib/private.ex | rockneurotiko/private | 7e5cbec79b079ee456fcbaf53ff91e42c37f2ee6 | [
"Apache-2.0"
] | null | null | null | lib/private.ex | rockneurotiko/private | 7e5cbec79b079ee456fcbaf53ff91e42c37f2ee6 | [
"Apache-2.0"
] | null | null | null | defmodule Private do
@moduledoc File.read!("README.md")
defmacro __using__(_opts) do
quote do
require Private
import Private, only: [ private: 1, private: 2 ]
end
end
@doc """
Define private functions:
private do
def ...
defp ...
end
All functions in the block will be defined as public if Mix.env is `:test`,
private otherwise. `def` and `defp` are effectively the same in the block.
See the documentation for the `Private` module for more information.
"""
defmacro private(do: block) do
quote do
unquote(do_private(block, Mix.env))
end
end
@doc false && """
Define private functions:
private(env) do
def ...
defp ...
end
All functions in the block will be defined as public if env is `:test`,
private otherwise. This is only provided for my own testing.
"""
defmacro private(env, do: block) do
quote do
unquote(do_private(block, env))
end
end
defp do_private(block, _env = :test) do
make_defs_public(block)
end
defp do_private(block, _env) do
make_defs_private(block)
end
defp make_defs_private(block) do
Macro.traverse(block, nil, &make_private/2, &identity/2)
end
defp make_defs_public(block) do
Macro.traverse(block, nil, &make_public/2, &identity/2)
end
defp make_private({:def, meta, code}, acc) do
{ {:defp, meta, code}, acc }
end
defp make_private(ast, acc), do: identity(ast, acc)
defp make_public({:defp, meta, code}, acc) do
{ {:def, meta, code}, acc }
end
defp make_public(ast, acc), do: identity(ast, acc)
defp identity(ast, acc) do
{ ast, acc }
end
end
| 20.464286 | 78 | 0.628854 |
f702b373e89fddf47a5306f9e8d8c80aa47cc8ef | 1,768 | ex | Elixir | lib/caddr.ex | jamesandariese/ex-utils-caddr | dca3ccae973cf5dda8874af343cac2eb207841e8 | [
"Apache-2.0"
] | null | null | null | lib/caddr.ex | jamesandariese/ex-utils-caddr | dca3ccae973cf5dda8874af343cac2eb207841e8 | [
"Apache-2.0"
] | null | null | null | lib/caddr.ex | jamesandariese/ex-utils-caddr | dca3ccae973cf5dda8874af343cac2eb207841e8 | [
"Apache-2.0"
] | null | null | null | defmodule Caddr do
@moduledoc """
Documentation for Elixir Utils by Caddr.
"""
@doc """
Uniq -c
## Examples
iex> Caddr.uniqc([1,2,3,1,2,3,1,2,4])
%{1 => 3, 2 => 3, 3 => 2, 4 => 1}
"""
def uniqc(e) do
Enum.map(e, &({&1}))
|> reduce_groups({0}, [{&Enum.count/1, 0}])
|> Map.to_list
|> Enum.map(fn {{x}, {y}} -> {x, y} end)
|> Map.new
end
@doc """
Reduce by groups. Similar to SELECT x, y, SUM(z), SUM(w) FROM stuff GROUP BY (x,y);
This will always return tuples even if single items in a list are passed in.
## Examples
iex(1)> Caddr.reduce_groups([1, 2, 3, 1, 2, 3], {0}, [{&Enum.count/1, 0}])
%{{1} => {2}, {2} => {2}, {3} => {2}}
iex> Caddr.reduce_groups([{1,2,3,5}, {1,2,1,5}, {1,1,1,5}], {0, 1}, [{&Enum.sum/1, 2}, {&Enum.sum/1, 3}])
%{{1, 2} => {4, 10}, {1, 1} => {1, 5}}
"""
def reduce_groups(e, gb, aggs) do
e
|> Enum.map(&tuplize/1)
|> Enum.group_by(&(select_from_tuple(&1, gb)))
|> Map.to_list
|> Enum.map(fn {g, n} ->
{g, aggregate_tuple(n, aggs)}
end)
|> Map.new
end
@doc """
Aggregate tuple
## Examples
iex> Caddr.aggregate_tuple([{1,2,3}, {3,4,5}], [{&Enum.sum/1, 2}, {&Enum.count/1, 0}])
{8, 2}
"""
def aggregate_tuple(_, []), do: {}
def aggregate_tuple(e, [{agg, aggn}| r]) do
Tuple.insert_at(aggregate_tuple(e, r), 0,
e |> Enum.map(&(elem(&1, aggn))) |> agg.()
)
end
@doc """
## Examples
iex> Caddr.select_from_tuple({1,2,3,4,5}, {3,2})
{4, 3}
"""
def select_from_tuple(t, el) do
Tuple.to_list(el)
|> Enum.reduce({}, fn y,x -> Tuple.append(x, elem(tuplize(t), y)) end)
end
defp tuplize(t) when is_tuple(t), do: t
defp tuplize(t), do: {t}
end
| 23.891892 | 111 | 0.511878 |
f702c5316b049e52813340529e4f9877fe87990a | 8,107 | ex | Elixir | lib/litmus/type/string.ex | lob/litmus | e7ffccc2e8897e280d3a69942a2ad6cbe4bbb965 | [
"MIT"
] | 38 | 2018-08-21T22:07:25.000Z | 2021-09-23T09:27:57.000Z | lib/litmus/type/string.ex | lob/litmus | e7ffccc2e8897e280d3a69942a2ad6cbe4bbb965 | [
"MIT"
] | 7 | 2018-07-17T17:47:08.000Z | 2019-07-09T21:18:58.000Z | lib/litmus/type/string.ex | lob/litmus | e7ffccc2e8897e280d3a69942a2ad6cbe4bbb965 | [
"MIT"
] | 6 | 2019-05-02T22:28:33.000Z | 2021-02-13T02:10:27.000Z | defmodule Litmus.Type.String do
@moduledoc """
This type validates and converts values to strings It converts boolean and
number values to strings.
## Options
* `:default` - Setting `:default` will populate a field with the provided
value, assuming that it is not present already. If a field already has a
value present, it will not be altered.
* `:min_length` - Specifies the minimum number of characters allowed in the
string. Allowed values are non-negative integers.
* `:max_length` - Specifies the maximum number of characters allowed in the
string. Allowed values are non-negative integers.
* `:length` - Specifies the exact number of characters allowed in the
string. Allowed values are non-negative integers.
* `:regex` - Specifies a Regular expression that a string must match. Use
the `Litmus.Type.String.Regex` struct with the options:
* `:pattern` - A `Regex.t()` to match
* `:error_message` - An error message to use when the pattern does not match
* `:replace` - Replaces occurences of a pattern with a string. Use the
`Litmus.Type.String.Replace` struct with the options:
* `:pattern` - A `Regex.t()`, `String.t()`, or compiled pattern to match
* `:replacement` - A `String.t()` to replace
* `:global` - When `true`, all occurences of the pattern are replaced.
When `false`, only the first occurence is replaced. Defaults to `true`.
* `:required` - Setting `:required` to `true` will cause a validation error
when a field is not present or the value is `nil`. Allowed values for
required are `true` and `false`. The default is `false`.
* `:trim` - Removes additional whitespace at the front and end of a string.
Allowed values are `true` and `false`. The default is `false`.
## Examples
iex> schema = %{
...> "username" => %Litmus.Type.String{
...> min_length: 3,
...> max_length: 10,
...> trim: true
...> },
...> "password" => %Litmus.Type.String{
...> length: 6,
...> regex: %Litmus.Type.String.Regex{
...> pattern: ~r/^[a-zA-Z0-9_]*$/,
...> error_message: "password must be alphanumeric"
...> }
...> }
...> }
iex> params = %{"username" => " user123 ", "password" => "root01"}
iex> Litmus.validate(params, schema)
{:ok, %{"username" => "user123", "password" => "root01"}}
iex> Litmus.validate(%{"password" => "ro!_@1"}, schema)
{:error, "password must be alphanumeric"}
iex> schema = %{
...> "username" => %Litmus.Type.String{
...> replace: %Litmus.Type.String.Replace{
...> pattern: ~r/\_/,
...> replacement: ""
...> }
...> }
...> }
iex> Litmus.validate(%{"username" => "one_two_three"}, schema)
{:ok, %{"username" => "onetwothree"}}
iex> schema = %{
...> "username" => %Litmus.Type.String{
...> default: "anonymous"
...> }
...> }
iex> Litmus.validate(%{}, schema)
{:ok, %{"username" => "anonymous"}}
"""
alias Litmus.{Default, Required}
alias Litmus.Type
defstruct [
:min_length,
:max_length,
:length,
default: Litmus.Type.Any.NoDefault,
regex: %Type.String.Regex{},
replace: %Type.String.Replace{},
trim: false,
required: false
]
@type t :: %__MODULE__{
default: any,
min_length: non_neg_integer | nil,
max_length: non_neg_integer | nil,
length: non_neg_integer | nil,
regex: Type.String.Regex.t(),
replace: Type.String.Replace.t(),
trim: boolean,
required: boolean
}
@spec validate_field(t, term, map) :: {:ok, map} | {:error, String.t()}
def validate_field(type, field, data) do
with {:ok, data} <- Required.validate(type, field, data),
{:ok, data} <- convert(type, field, data),
{:ok, data} <- trim(type, field, data),
{:ok, data} <- min_length_validate(type, field, data),
{:ok, data} <- max_length_validate(type, field, data),
{:ok, data} <- length_validate(type, field, data),
{:ok, data} <- regex_validate(type, field, data),
{:ok, data} <- replace(type, field, data) do
{:ok, data}
else
{:ok_not_present, data} -> Default.validate(type, field, data)
{:error, msg} -> {:error, msg}
end
end
@spec convert(t, term, map) :: {:ok, map} | {:error, String.t()}
defp convert(%__MODULE__{}, field, params) do
cond do
params[field] == nil ->
{:ok, params}
is_binary(params[field]) ->
{:ok, params}
is_number(params[field]) or is_boolean(params[field]) ->
{:ok, Map.update!(params, field, &to_string/1)}
true ->
{:error, "#{field} must be a string"}
end
end
@spec min_length_validate(t, term, map) :: {:ok, map} | {:error, String.t()}
defp min_length_validate(%__MODULE__{min_length: min_length}, field, params)
when is_integer(min_length) and min_length > 0 do
if params[field] == nil or String.length(params[field]) < min_length do
{:error, "#{field} length must be greater than or equal to #{min_length} characters"}
else
{:ok, params}
end
end
defp min_length_validate(%__MODULE__{}, _field, params) do
{:ok, params}
end
@spec max_length_validate(t, term, map) :: {:ok, map} | {:error, String.t()}
defp max_length_validate(%__MODULE__{max_length: nil}, _field, params) do
{:ok, params}
end
defp max_length_validate(%__MODULE__{max_length: max_length}, field, params)
when is_integer(max_length) and max_length >= 0 do
if Map.get(params, field) && String.length(params[field]) > max_length do
{:error, "#{field} length must be less than or equal to #{max_length} characters"}
else
{:ok, params}
end
end
@spec length_validate(t, term, map) :: {:ok, map} | {:error, String.t()}
defp length_validate(%__MODULE__{length: nil}, _field, params) do
{:ok, params}
end
defp length_validate(%__MODULE__{length: 0}, field, params) do
if params[field] in [nil, ""] do
{:ok, params}
else
{:error, "#{field} length must be 0 characters"}
end
end
defp length_validate(%__MODULE__{length: len}, field, params) when is_integer(len) do
if params[field] == nil || String.length(params[field]) != len do
{:error, "#{field} length must be #{len} characters"}
else
{:ok, params}
end
end
@spec replace(t, term, map) :: {:ok, map}
defp replace(%__MODULE__{replace: %__MODULE__.Replace{pattern: nil}}, _field, params) do
{:ok, params}
end
defp replace(%__MODULE__{replace: replace}, field, params) do
new_string =
String.replace(params[field], replace.pattern, replace.replacement, global: replace.global)
{:ok, Map.put(params, field, new_string)}
end
@spec regex_validate(t, term, map) :: {:ok, map} | {:error, String.t()}
defp regex_validate(%__MODULE__{regex: %__MODULE__.Regex{pattern: nil}}, _field, params) do
{:ok, params}
end
defp regex_validate(%__MODULE__{regex: regex}, field, params) do
if params[field] == nil or !Regex.match?(regex.pattern, params[field]) do
error_message = regex.error_message || "#{field} must be in a valid format"
{:error, error_message}
else
{:ok, params}
end
end
@spec trim(t, term, map) :: {:ok, map}
defp trim(%__MODULE__{trim: true}, field, params) do
if Map.get(params, field) do
trimmed_value = String.trim(params[field])
trimmed_params = Map.put(params, field, trimmed_value)
{:ok, trimmed_params}
else
{:ok, params}
end
end
defp trim(%__MODULE__{trim: false}, _field, params) do
{:ok, params}
end
defimpl Litmus.Type do
alias Litmus.Type
@spec validate(Type.t(), term, map) :: {:ok, map} | {:error, String.t()}
def validate(type, field, data), do: Type.String.validate_field(type, field, data)
end
end
| 33.639004 | 97 | 0.605526 |
f7030562008233f3dcfa29a3d46903cd3e774935 | 1,529 | ex | Elixir | clients/vault/lib/google_api/vault/v1/model/remove_held_accounts_request.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/vault/lib/google_api/vault/v1/model/remove_held_accounts_request.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/vault/lib/google_api/vault/v1/model/remove_held_accounts_request.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Vault.V1.Model.RemoveHeldAccountsRequest do
@moduledoc """
Remove a list of accounts from a hold.
## Attributes
- accountIds ([String.t]): Account ids to identify HeldAccounts to remove. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:accountIds => list(any())
}
field(:accountIds, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Vault.V1.Model.RemoveHeldAccountsRequest do
def decode(value, options) do
GoogleApi.Vault.V1.Model.RemoveHeldAccountsRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vault.V1.Model.RemoveHeldAccountsRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.854167 | 97 | 0.746893 |
f7034424d62d793744af617d6144b4b485cdce43 | 2,430 | exs | Elixir | config/dev.exs | buoy49/zcash-explorer | 3774ef15a46ef13379d5a808f7cea198b76c589a | [
"Apache-2.0"
] | 5 | 2021-11-04T20:19:35.000Z | 2022-02-15T06:55:49.000Z | config/dev.exs | buoy49/zcash-explorer | 3774ef15a46ef13379d5a808f7cea198b76c589a | [
"Apache-2.0"
] | 5 | 2021-09-12T01:36:25.000Z | 2022-02-18T07:28:42.000Z | config/dev.exs | buoy49/zcash-explorer | 3774ef15a46ef13379d5a808f7cea198b76c589a | [
"Apache-2.0"
] | 8 | 2021-07-23T17:11:41.000Z | 2022-03-17T17:07:55.000Z | use Mix.Config
# Configure your database
config :zcash_explorer, ZcashExplorer.Repo,
username: "postgres",
password: "postgres",
database: "zcash_explorer_dev",
hostname: "localhost",
show_sensitive_data_on_connection_error: true,
pool_size: 10
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with webpack to recompile .js and .css sources.
config :zcash_explorer, ZcashExplorerWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--watch-stdin",
cd: Path.expand("../assets", __DIR__)
]
]
config :zcash_explorer, Zcashex,
zcashd_hostname: "localhost",
zcashd_port: "38232",
zcashd_username: "zcashrpc",
zcashd_password: "changeme",
vk_cpus: "0.2",
vk_mem: "2048M",
vk_runnner_image: "nighthawkapps/vkrunner"
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.pem"
# ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Watch static and templates for browser reloading.
config :zcash_explorer, ZcashExplorerWeb.Endpoint,
live_reload: [
patterns: [
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/zcash_explorer_web/(live|views)/.*(ex)$",
~r"lib/zcash_explorer_web/templates/.*(eex)$"
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
| 28.255814 | 68 | 0.701646 |
f703447424f554b11ddc5d75cd2dab445e762ce1 | 2,965 | ex | Elixir | clients/you_tube/lib/google_api/you_tube/v3/model/playlist_list_response.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/you_tube/lib/google_api/you_tube/v3/model/playlist_list_response.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/you_tube/lib/google_api/you_tube/v3/model/playlist_list_response.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.YouTube.V3.Model.PlaylistListResponse do
@moduledoc """
## Attributes
- etag (String.t): Etag of this resource. Defaults to: `null`.
- eventId (String.t): Serialized EventId of the request which produced this response. Defaults to: `null`.
- items ([Playlist]): A list of playlists that match the request criteria. Defaults to: `null`.
- kind (String.t): Identifies what kind of resource this is. Value: the fixed string \"youtube#playlistListResponse\". Defaults to: `null`.
- nextPageToken (String.t): The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set. Defaults to: `null`.
- pageInfo (PageInfo): Defaults to: `null`.
- prevPageToken (String.t): The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set. Defaults to: `null`.
- tokenPagination (TokenPagination): Defaults to: `null`.
- visitorId (String.t): The visitorId identifies the visitor. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:etag => any(),
:eventId => any(),
:items => list(GoogleApi.YouTube.V3.Model.Playlist.t()),
:kind => any(),
:nextPageToken => any(),
:pageInfo => GoogleApi.YouTube.V3.Model.PageInfo.t(),
:prevPageToken => any(),
:tokenPagination => GoogleApi.YouTube.V3.Model.TokenPagination.t(),
:visitorId => any()
}
field(:etag)
field(:eventId)
field(:items, as: GoogleApi.YouTube.V3.Model.Playlist, type: :list)
field(:kind)
field(:nextPageToken)
field(:pageInfo, as: GoogleApi.YouTube.V3.Model.PageInfo)
field(:prevPageToken)
field(:tokenPagination, as: GoogleApi.YouTube.V3.Model.TokenPagination)
field(:visitorId)
end
defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.PlaylistListResponse do
def decode(value, options) do
GoogleApi.YouTube.V3.Model.PlaylistListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.PlaylistListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.180556 | 166 | 0.71602 |
f703a4645a24a5c36bfae17d86cdd6c837c0401a | 11,969 | ex | Elixir | lib/game/session/process.ex | jgsmith/ex_venture | 546adaa8fe80d45a72fde6de8d8d6906902c12d4 | [
"MIT"
] | 2 | 2019-05-14T11:36:44.000Z | 2020-07-01T08:54:04.000Z | lib/game/session/process.ex | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | null | null | null | lib/game/session/process.ex | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | 1 | 2021-01-29T14:12:40.000Z | 2021-01-29T14:12:40.000Z | defmodule Game.Session.Process do
@moduledoc """
GenServer process module, client access is at `Game.Session`
Holds knowledge if the player is logged in, who they are, what they're save is.
"""
use GenServer, restart: :temporary
require Logger
alias Game.Account
alias Game.Character
alias Game.Command.Move
alias Game.Command.Pager
alias Game.Environment
alias Game.Format
alias Game.Format.Players, as: FormatPlayers
alias Game.Hint
alias Game.Player
alias Game.Session
alias Game.Session.Channels
alias Game.Session.Character, as: SessionCharacter
alias Game.Session.Commands
alias Game.Session.Effects
alias Game.Session.Help
alias Game.Session.GMCP
alias Game.Session.Regen
alias Game.Session.SessionStats
alias Game.Session.State
alias Game.Socket
alias Game.World.Master, as: WorldMaster
alias Metrics.PlayerInstrumenter
@save_period 15_000
@force_disconnect_period 5_000
@heartbeat_timeout 60_000
@timeout_check 5000
@timeout_seconds Application.get_env(:ex_venture, :game)[:timeout_seconds]
#
# GenServer callbacks
#
@doc false
def start_link(socket) do
GenServer.start_link(__MODULE__, socket)
end
def init([socket]) do
Logger.info("New session started #{inspect(self())}", type: :session)
state = clean_state(socket)
Session.Registry.register_connection(state.id)
send(self(), :start)
{:ok, state}
end
def init([socket, player_id]) do
send(self(), {:recover_session, player_id})
PlayerInstrumenter.session_recovered()
Logger.info("Session recovering (#{player_id}) - #{inspect(self())}", type: :session)
{:ok, clean_state(socket)}
end
defp clean_state(socket) do
now = Timex.now()
%State{
id: UUID.uuid4(),
socket: socket,
state: "login",
session_started_at: now,
last_recv: now,
idle: Help.init_idle(now),
mode: "commands",
target: nil,
is_targeting: MapSet.new(),
regen: %{is_regenerating: false, count: 0},
reply_to: nil,
commands: %{},
skills: %{},
stats: %SessionStats{},
is_afk: false
}
end
# On a disconnect unregister the PID and stop the server
def handle_cast(:disconnect, state = %{state: "login"}) do
Logger.info(fn -> "Disconnecting the session" end, type: :session)
{:stop, :normal, state}
end
def handle_cast(:disconnect, state = %{state: "create"}) do
Logger.info(fn -> "Disconnecting the session" end, type: :session)
{:stop, :normal, state}
end
def handle_cast(:disconnect, state = %{state: "active"}) do
Logger.info(fn -> "Disconnecting the session" end, type: :session)
%{save: save, session_started_at: session_started_at, stats: stats} = state
Session.Registry.unregister()
Session.Registry.player_offline(state.character)
Environment.leave(save.room_id, state.character, :signout)
Environment.unlink(save.room_id)
Account.save_session(
state.user,
state.character,
save,
session_started_at,
Timex.now(),
stats
)
{:stop, :normal, state}
end
def handle_cast(:disconnect, state) do
Logger.info(fn -> "Disconnecting the session - Fall through" end, type: :session)
{:stop, :normal, state}
end
def handle_cast({:disconnect, opts}, state) when is_list(opts) do
case Keyword.get(opts, :reason) do
"server shutdown" ->
state |> Socket.echo("The server will be shutting down shortly.")
_ ->
state |> Socket.echo("You are being signed out.\nGood bye.")
end
Task.start(fn ->
Process.sleep(@force_disconnect_period)
state |> Socket.disconnect()
end)
{:noreply, state}
end
# forward the echo the socket pid
def handle_cast({:echo, message}, state) do
state |> Socket.echo(message)
{:noreply, state}
end
# Handle logging in
def handle_cast({:recv, name}, state = %{state: "login"}) do
state = Session.Login.process(name, state)
{:noreply, Map.merge(state, %{last_recv: Timex.now()})}
end
# Handle displaying message after signing in
def handle_cast({:recv, _name}, state = %{state: "after_sign_in"}) do
state = Session.Login.after_sign_in(state, self())
send(self(), :regen)
{:noreply, Map.merge(state, %{last_recv: Timex.now()})}
end
# Handle creating an account
def handle_cast({:recv, name}, state = %{state: "create"}) do
state = Session.CreateAccount.process(name, state)
{:noreply, Map.merge(state, %{last_recv: Timex.now()})}
end
def handle_cast({:recv, message}, state = %{state: "active", mode: "commands"}) do
state |> Commands.process_command(message)
end
def handle_cast({:recv, message}, state = %{state: "active", mode: "paginate"}) do
{:noreply, Pager.paginate(state, command: message, lines: state.save.config.pager_size)}
end
def handle_cast({:recv, _message}, state = %{state: "active", mode: "continuing"}) do
{:noreply, state}
end
def handle_cast({:recv, ""}, state = %{state: "active", mode: "editor"}) do
case state.editor_module.editor(:complete, state) do
{:update, state} ->
state =
state
|> Map.put(:mode, "commands")
|> Map.delete(:editor_module)
state |> prompt()
{:noreply, Map.put(state, :mode, "commands")}
end
end
def handle_cast({:recv, line}, state = %{state: "active", mode: "editor"}) do
case state.editor_module.editor({:text, line}, state) do
{:update, state} ->
{:noreply, state}
end
end
def handle_cast({:recv_gmcp, module, data}, state) do
case GMCP.handle_gmcp(state, module, data) do
:ok ->
{:noreply, state}
{:update, state} ->
{:noreply, state}
end
end
def handle_cast({:teleport, room_id}, state) do
{:update, state} = Move.move_to(state, room_id, :teleport, :teleport)
state |> prompt()
{:noreply, state}
end
# Handle logging in from the web client
def handle_cast({:sign_in, character_id}, state = %{state: "login"}) do
state = Session.Login.sign_in(character_id, state)
{:noreply, state}
end
#
# Character callbacks
#
def handle_cast({:targeted, player}, state) do
{:noreply, SessionCharacter.targeted(state, player)}
end
def handle_cast({:apply_effects, effects, from, description}, state = %{state: "active"}) do
{:noreply, SessionCharacter.apply_effects(state, effects, from, description)}
end
def handle_cast({:effects_applied, effects, target}, state = %{state: "active"}) do
{:noreply, SessionCharacter.effects_applied(state, effects, target)}
end
def handle_cast({:notify, event}, state) do
{:noreply, SessionCharacter.notify(state, event)}
end
def handle_call(:info, _from, state) do
{:reply, Character.to_simple(state.character), state}
end
#
# Channels
#
def handle_info({:channel, {:joined, channel}}, state) do
{:noreply, Channels.joined(state, channel)}
end
def handle_info({:channel, {:left, channel}}, state) do
{:noreply, Channels.left(state, channel)}
end
def handle_info({:channel, {:broadcast, channel, message}}, state) do
{:noreply, Channels.broadcast(state, channel, message)}
end
def handle_info({:channel, {:tell, from, message}}, state) do
{:noreply, Channels.tell(state, from, message)}
end
#
# General callback
#
def handle_info(:start, state) do
case WorldMaster.is_world_online?() do
true ->
state |> Session.Login.start()
false ->
state |> Socket.echo("The world is not online yet. Please try again shortly.")
self() |> Process.send_after({:disconnect, :world_not_alive}, 750)
end
{:noreply, state}
end
def handle_info({:authorize, character}, state) do
state = Session.Login.sign_in(character.id, state)
{:noreply, state}
end
def handle_info({:disconnect, :world_not_alive}, state) do
state |> Socket.disconnect()
{:noreply, state}
end
def handle_info({:recover_session, user_id}, state) do
state = Session.Login.recover_session(user_id, state)
self() |> schedule_save()
self() |> schedule_inactive_check()
self() |> schedule_heartbeat()
{:noreply, state}
end
def handle_info(:regen, state = %{save: _save}) do
{:noreply, Regen.tick(state)}
end
def handle_info({:continue, command}, state) do
command |> Commands.run_command(state)
end
def handle_info(:save, state = %{state: "active"}) do
%{save: save, session_started_at: session_started_at} = state
state.character |> Account.save(save)
state.character |> Account.update_time_online(session_started_at, Timex.now())
self() |> schedule_save()
{:noreply, state}
end
def handle_info(:save, state) do
self() |> schedule_save()
{:noreply, state}
end
def handle_info(:inactive_check, state) do
{:noreply, check_for_inactive(state)}
end
def handle_info(:heartbeat, state) do
state |> GMCP.heartbeat()
state |> Socket.nop()
self() |> schedule_heartbeat()
{:noreply, state}
end
def handle_info({:continuous_effect, effect_id}, state) do
Logger.debug(
fn ->
"Processing effect (#{effect_id})"
end,
type: :player
)
state =
state
|> Effects.handle_continuous_effect(effect_id)
|> Regen.maybe_trigger_regen()
{:noreply, state}
end
def handle_info({:continuous_effect, :clear, effect_id}, state) do
Logger.debug(
fn ->
"Clearing effect (#{effect_id})"
end,
type: :player
)
state = Character.Effects.clear_continuous_effect(state, effect_id)
{:noreply, state}
end
def handle_info({:skill, :ready, skill}, state) do
state |> Socket.echo("#{Format.skill_name(skill)} is ready.")
state |> GMCP.skill_state(skill, active: true)
skills = Map.delete(state.skills, skill.id)
state = Map.put(state, :skills, skills)
{:noreply, state}
end
def handle_info({:resurrect, graveyard_id}, state) do
%{save: %{stats: stats}} = state
case stats.health_points do
health_points when health_points < 1 ->
stats = Map.put(stats, :health_points, 1)
save = %{state.save | stats: stats}
state =
state
|> Player.update_save(save)
|> Regen.maybe_trigger_regen()
{:update, state} = Move.move_to(state, graveyard_id, :death, :respawn)
state |> prompt()
{:noreply, state}
_ ->
{:noreply, state}
end
end
@doc """
Send the prompt to the user's socket
"""
def prompt(state) do
state |> GMCP.vitals()
state |> Socket.prompt(FormatPlayers.prompt(state.save))
state
end
# Schedule an inactive check
def schedule_inactive_check(pid) do
:erlang.send_after(@timeout_check, pid, :inactive_check)
end
# Schedule a save
def schedule_save(pid) do
:erlang.send_after(@save_period, pid, :save)
end
# Schedule a heartbeat
def schedule_heartbeat(pid) do
:erlang.send_after(@heartbeat_timeout, pid, :heartbeat)
end
# Check if the session is inactive, disconnect if it is
defp check_for_inactive(state = %{is_afk: true}) do
self() |> schedule_inactive_check()
state
end
defp check_for_inactive(state = %{last_recv: last_recv}) do
self() |> schedule_inactive_check()
{:ok, state} = state |> Help.maybe_display_hints()
case Timex.diff(Timex.now(), last_recv, :seconds) do
time when time > @timeout_seconds ->
Logger.info("Idle player #{inspect(self())} - setting afk", type: :session)
state = %{state | is_afk: true}
Session.Registry.update(%{state.character | save: state.save}, state)
message = "You seem to be idle, setting you to {command}AFK{/command}."
state |> Socket.echo(message)
Hint.gate(state, "afk.started")
state
_ ->
state
end
end
end
| 26.716518 | 94 | 0.651516 |
f703bbdb6cf64f5b574832bc4b5f1eedf6b7ce71 | 1,065 | ex | Elixir | lib/tembeza_web/channels/user_socket.ex | AdolfodelSel/Tembeza | 20c19d6cc090e7c128bf35f016b7a3843cfc0dad | [
"Apache-2.0"
] | null | null | null | lib/tembeza_web/channels/user_socket.ex | AdolfodelSel/Tembeza | 20c19d6cc090e7c128bf35f016b7a3843cfc0dad | [
"Apache-2.0"
] | 1 | 2021-05-11T18:22:04.000Z | 2021-05-11T18:22:04.000Z | lib/tembeza_web/channels/user_socket.ex | AdolfodelSel/Tembeza | 20c19d6cc090e7c128bf35f016b7a3843cfc0dad | [
"Apache-2.0"
] | null | null | null | defmodule TembezaWeb.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", TembezaWeb.RoomChannel
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket, _connect_info) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# TembezaWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 31.323529 | 83 | 0.696714 |
f703e67482aa768518cd4a082154dcf7eb3bf23f | 1,562 | ex | Elixir | test/support/data_case.ex | DianaOlympos/remote_test | e222d4e937789871baab3a7b4fd8428b714c1af4 | [
"MIT"
] | 1 | 2020-09-18T03:32:45.000Z | 2020-09-18T03:32:45.000Z | test/support/data_case.ex | DianaOlympos/remote_test | e222d4e937789871baab3a7b4fd8428b714c1af4 | [
"MIT"
] | null | null | null | test/support/data_case.ex | DianaOlympos/remote_test | e222d4e937789871baab3a7b4fd8428b714c1af4 | [
"MIT"
] | null | null | null | defmodule RemotePoints.DataCase do
@moduledoc """
This module defines the setup for tests requiring
access to the application's data layer.
You may define functions here to be used as helpers in
your tests.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use RemotePoints.DataCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
alias RemotePoints.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import RemotePoints.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(RemotePoints.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(RemotePoints.Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transforms changeset errors into a map of messages.
assert {:error, changeset} = Accounts.create_user(%{password: "short"})
assert "password is too short" in errors_on(changeset).password
assert %{password: ["password is too short"]} = errors_on(changeset)
"""
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
| 27.892857 | 77 | 0.694622 |
f70424c89288999e5d18016254f06285a06fcc49 | 1,592 | ex | Elixir | lib/double_agent/listening_post.ex | felix-starman/double_agent | f35cc6012eb7793167d0151c74c23c436ec4d811 | [
"MIT"
] | null | null | null | lib/double_agent/listening_post.ex | felix-starman/double_agent | f35cc6012eb7793167d0151c74c23c436ec4d811 | [
"MIT"
] | null | null | null | lib/double_agent/listening_post.ex | felix-starman/double_agent | f35cc6012eb7793167d0151c74c23c436ec4d811 | [
"MIT"
] | null | null | null | defmodule DoubleAgent.ListeningPost do
use GenServer
### CLIENT
def fetch(module, func, args_arity_or_atom) do
GenServer.call(__MODULE__, {:fetch, {module, func, args_arity_or_atom}})
end
def list do
GenServer.call(__MODULE__, :list)
end
def record({_mod, _function_name, _args} = mfa) do
GenServer.call(__MODULE__, {:record, mfa})
end
### SERVER & CALLBACKS
@impl GenServer
def init(state \\ []) do
{:ok, state}
end
@impl GenServer
def handle_call({:fetch, fetch_args}, _from, state) do
result =
case Enum.filter(state, &invoke_matches?(&1, fetch_args)) do
[] -> :error
invokes -> {:ok, invokes}
end
{:reply, result, state}
end
def handle_call(:list, _from, state) do
{:reply, state, state}
end
def handle_call({:record, mfa}, {pid, _tag} = _from, state) do
state = [{pid, mfa} | state]
{:reply, state, state}
end
@type invocation :: {pid(), mfargs()}
@type mfargs :: {module :: atom(), function_name :: atom(), args :: list()}
@type matcher :: {module(), atom(), :any}
@type mfargs_mfa_or_matcher :: mfargs() | mfa() | matcher()
@spec invoke_matches?(invocation(), mfargs_mfa_or_matcher()) :: boolean()
def invoke_matches?({_pid, {mod, func, _args}}, {mod, func, :any}), do: true
def invoke_matches?({_pid, {m, f, args}}, {m, f, arity}) when is_integer(arity),
do: length(args) == arity
def invoke_matches?({_pid, {mod, func, args}}, {mod, func, args}) when is_list(args), do: true
def invoke_matches?({_pid, _invoked_mfa}, _fetch_args), do: false
end
| 26.983051 | 96 | 0.635678 |
f7042aee33d55f42603a61593d0d4d4d9f911cfe | 37,568 | exs | Elixir | test/ecto/association_test.exs | dgvncsz0f/ecto | bae06fe650328cc1060c09fe889a2de9a10edb1b | [
"Apache-2.0"
] | null | null | null | test/ecto/association_test.exs | dgvncsz0f/ecto | bae06fe650328cc1060c09fe889a2de9a10edb1b | [
"Apache-2.0"
] | null | null | null | test/ecto/association_test.exs | dgvncsz0f/ecto | bae06fe650328cc1060c09fe889a2de9a10edb1b | [
"Apache-2.0"
] | 1 | 2018-09-21T16:05:29.000Z | 2018-09-21T16:05:29.000Z | defmodule Ecto.AssociationTest do
use ExUnit.Case, async: true
doctest Ecto.Association
import Ecto
import Ecto.Query, only: [from: 2, dynamic: 2]
alias __MODULE__.Author
alias __MODULE__.Comment
alias __MODULE__.CommentWithPrefix
alias __MODULE__.Permalink
alias __MODULE__.Post
alias __MODULE__.PostWithPrefix
alias __MODULE__.Summary
alias __MODULE__.Email
alias __MODULE__.Profile
alias __MODULE__.AuthorPermalink
defmodule Post do
use Ecto.Schema
schema "posts" do
field :title, :string
field :upvotes, :integer
has_many :comments, Comment
has_one :permalink, Permalink
has_many :permalinks, Permalink
belongs_to :author, Author, defaults: [title: "World!"]
belongs_to :summary, Summary
end
def awesome() do
dynamic([row], row.upvotes >= 1000)
end
end
defmodule Comment do
use Ecto.Schema
schema "comments" do
field :text, :string
belongs_to :post, Post
has_one :permalink, Permalink
has_one :post_author, through: [:post, :author] # belongs -> belongs
has_one :post_permalink, through: [:post, :permalink] # belongs -> one
end
end
defmodule Permalink do
use Ecto.Schema
schema "permalinks" do
field :url, :string
field :special, :boolean
many_to_many :authors, Author, join_through: AuthorPermalink, defaults: [title: "m2m!"]
has_many :author_emails, through: [:authors, :emails]
end
def special() do
dynamic([row], row.special)
end
end
defmodule PostWithPrefix do
use Ecto.Schema
@schema_prefix "my_prefix"
schema "posts" do
belongs_to :author, Author
has_many :comments_with_prefix, CommentWithPrefix
end
end
defmodule CommentWithPrefix do
use Ecto.Schema
@schema_prefix "my_prefix"
schema "comments" do
belongs_to :posts_with_prefix, Post, foreign_key: :post_with_prefix_id
end
end
defmodule AuthorPermalink do
use Ecto.Schema
schema "authors_permalinks" do
field :author_id
field :permalink_id
field :deleted, :boolean
end
def active() do
dynamic([row], not(row.deleted))
end
end
defmodule Author do
use Ecto.Schema
schema "authors" do
field :title, :string
field :super_user, :boolean
has_many :posts, Post, on_replace: :delete
has_many :posts_comments, through: [:posts, :comments] # many -> many
has_many :posts_permalinks, through: [:posts, :permalink] # many -> one
has_many :emails, {"users_emails", Email}
has_many :awesome_posts, Post, where: {Post, :awesome, []}
has_one :profile, {"users_profiles", Profile},
defaults: [name: "default"], on_replace: :delete
many_to_many :permalinks, {"custom_permalinks", Permalink},
join_through: "authors_permalinks"
many_to_many :active_special_permalinks, Permalink,
join_through: AuthorPermalink,
join_through_where: {AuthorPermalink, :active, []},
where: {Permalink, :special, []}
many_to_many :special_permalinks, Permalink,
join_through: AuthorPermalink,
where: {Permalink, :special, []}
many_to_many :active_permalinks, Permalink,
join_through: AuthorPermalink,
join_through_where: {AuthorPermalink, :active, []}
has_many :posts_with_prefix, PostWithPrefix
has_many :comments_with_prefix, through: [:posts_with_prefix, :comments_with_prefix]
end
def super_users() do
dynamic([row], row.super_user)
end
end
defmodule Summary do
use Ecto.Schema
schema "summaries" do
has_one :post, Post, defaults: [title: "default"], on_replace: :nilify
has_one :awesome_post, Post, where: {Post, :awesome, []}
has_many :posts, Post, on_replace: :nilify
has_one :post_author, through: [:post, :author] # one -> belongs
has_many :post_comments, through: [:post, :comments] # one -> many
end
end
defmodule Email do
use Ecto.Schema
schema "emails" do
belongs_to :author, {"post_authors", Author}
belongs_to :super_user, Author, where: {Author, :super_users, []}, foreign_key: :author_id, define_field: false
end
end
defmodule Profile do
use Ecto.Schema
schema "profiles" do
field :name
belongs_to :author, Author
belongs_to :summary, Summary
end
end
test "has many" do
assoc = Post.__schema__(:association, :comments)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from p in Post, join: c in Comment, on: c.post_id == p.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from c in Comment, where: c.post_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from c in Comment, where: c.post_id in ^[1, 2, 3])
end
test "has many with specified source" do
assoc = Author.__schema__(:association, :emails)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from a in Author, join: e in {"users_emails", Email}, on: e.author_id == a.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from e in {"users_emails", Email}, where: e.author_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from e in {"users_emails", Email}, where: e.author_id in ^[1, 2, 3])
end
test "has many custom assoc query" do
assoc = Post.__schema__(:association, :comments)
query = from c in Comment, limit: 5
assert inspect(Ecto.Association.Has.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from c in Comment, where: c.post_id in ^[1, 2, 3], limit: 5)
end
test "has many query-based assoc query" do
assoc = Author.__schema__(:association, :awesome_posts)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from a in Author, join: p in ^(from p in Post, where: p.upvotes >= 1000), on: p.author_id == a.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.author_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.author_id in ^[1, 2, 3])
end
test "has many query-based assoc with custom query" do
assoc = Author.__schema__(:association, :awesome_posts)
query = from p in Post, limit: 5
assert inspect(Ecto.Association.Has.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.author_id in ^[1, 2, 3], limit: 5)
end
test "has one" do
assoc = Post.__schema__(:association, :permalink)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from p in Post, join: c in Permalink, on: c.post_id == p.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from c in Permalink, where: c.post_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1])) ==
inspect(from c in Permalink, where: c.post_id == ^1)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from c in Permalink, where: c.post_id in ^[1, 2, 3])
end
test "has one with specified source" do
assoc = Author.__schema__(:association, :profile)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from a in Author, join: p in {"users_profiles", Profile}, on: p.author_id == a.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from p in {"users_profiles", Profile}, where: p.author_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in {"users_profiles", Profile}, where: p.author_id in ^[1, 2, 3])
end
test "has one custom assoc query" do
assoc = Post.__schema__(:association, :permalink)
query = from c in Permalink, limit: 5
assert inspect(Ecto.Association.Has.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from c in Permalink, where: c.post_id in ^[1, 2, 3], limit: 5)
end
test "has one query-based assoc query" do
assoc = Summary.__schema__(:association, :awesome_post)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from s in Summary, join: p in ^(from p in Post, where: p.upvotes >= 1000), on: p.summary_id == s.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.summary_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.summary_id in ^[1, 2, 3])
end
test "has one query-based assoc with custom query" do
assoc = Summary.__schema__(:association, :awesome_post)
query = from p in Post, limit: 5
assert inspect(Ecto.Association.Has.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.summary_id in ^[1, 2, 3], limit: 5)
end
test "belongs to" do
assoc = Post.__schema__(:association, :author)
assert inspect(Ecto.Association.BelongsTo.joins_query(assoc)) ==
inspect(from p in Post, join: a in Author, on: a.id == p.author_id)
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [])) ==
inspect(from a in Author, where: a.id in ^[])
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [1])) ==
inspect(from a in Author, where: a.id == ^1)
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from a in Author, where: a.id in ^[1, 2, 3])
end
test "belongs to with specified source" do
assoc = Email.__schema__(:association, :author)
assert inspect(Ecto.Association.BelongsTo.joins_query(assoc)) ==
inspect(from e in Email, join: a in {"post_authors", Author}, on: a.id == e.author_id)
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [])) ==
inspect(from a in {"post_authors", Author}, where: a.id in ^[])
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [1])) ==
inspect(from a in {"post_authors", Author}, where: a.id == ^1)
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from a in {"post_authors", Author}, where: a.id in ^[1, 2, 3])
end
test "belongs to custom assoc query" do
assoc = Post.__schema__(:association, :author)
query = from a in Author, limit: 5
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from a in Author, where: a.id in ^[1, 2, 3], limit: 5)
end
test "belongs to query-based assoc query" do
assoc = Email.__schema__(:association, :super_user)
assert inspect(Ecto.Association.BelongsTo.joins_query(assoc)) ==
inspect(from e in Email, join: a in ^(from a in Author, where: a.super_user), on: a.id == e.author_id)
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [])) ==
inspect(from a in Author, where: a.super_user, where: a.id in ^[])
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from a in Author, where: a.super_user, where: a.id in ^[1, 2, 3])
end
test "belongs to query-based assoc with custom query" do
assoc = Email.__schema__(:association, :super_user)
query = from a in Author, limit: 5
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from a in Author, where: a.super_user, where: a.id in ^[1, 2, 3], limit: 5)
end
test "many to many" do
assoc = Permalink.__schema__(:association, :authors)
assert inspect(Ecto.Association.ManyToMany.joins_query(assoc)) ==
inspect(from p in Permalink,
join: m in AuthorPermalink, on: m.permalink_id == p.id,
join: a in Author, on: m.author_id == a.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [])) ==
inspect(from a in Author,
join: p in Permalink, on: p.id in ^[],
join: m in AuthorPermalink, on: m.permalink_id == p.id,
where: m.author_id == a.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from a in Author,
join: p in Permalink, on: p.id in ^[1, 2, 3],
join: m in AuthorPermalink, on: m.permalink_id == p.id,
where: m.author_id == a.id)
end
test "many to many with specified source" do
assoc = Author.__schema__(:association, :permalinks)
assert inspect(Ecto.Association.ManyToMany.joins_query(assoc)) ==
inspect(from a in Author,
join: m in "authors_permalinks", on: m.author_id == a.id,
join: p in {"custom_permalinks", Permalink}, on: m.permalink_id == p.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [])) ==
inspect(from p in {"custom_permalinks", Permalink},
join: a in Author, on: a.id in ^[],
join: m in "authors_permalinks", on: m.author_id == a.id,
where: m.permalink_id == p.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in {"custom_permalinks", Permalink},
join: a in Author, on: a.id in ^[1, 2, 3],
join: m in "authors_permalinks", on: m.author_id == a.id,
where: m.permalink_id == p.id)
end
test "many to many custom assoc query" do
assoc = Permalink.__schema__(:association, :authors)
query = from a in Author, limit: 5
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from a in Author,
join: p in Permalink, on: p.id in ^[1, 2, 3],
join: m in AuthorPermalink, on: m.permalink_id == p.id,
where: m.author_id == a.id, limit: 5)
end
test "many to many query-based assoc and query based join_through query" do
assoc = Author.__schema__(:association, :active_special_permalinks)
assert inspect(Ecto.Association.ManyToMany.joins_query(assoc)) ==
inspect(from a in Author,
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
join: p in ^(from p in Permalink, where: p.special),
on: m.permalink_id == p.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [])) ==
inspect(from p in Permalink, where: p.special,
join: a in Author, on: a.id in ^[],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in Permalink, where: p.special,
join: a in Author, on: a.id in ^[1, 2, 3],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
end
test "many to many query-based assoc and query based join through with custom query" do
assoc = Author.__schema__(:association, :active_special_permalinks)
query = from p in Permalink, limit: 5
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from p in Permalink,
join: a in Author,
on: a.id in ^[1, 2, 3],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: p.special(),
where: m.permalink_id == p.id,
limit: 5)
end
test "many to many query-based assoc query" do
assoc = Author.__schema__(:association, :special_permalinks)
assert inspect(Ecto.Association.ManyToMany.joins_query(assoc)) ==
inspect(from a in Author,
join: m in AuthorPermalink,
on: m.author_id == a.id,
join: p in ^(from p in Permalink, where: p.special),
on: m.permalink_id == p.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [])) ==
inspect(from p in Permalink, where: p.special,
join: a in Author, on: a.id in ^[],
join: m in AuthorPermalink,
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in Permalink, where: p.special,
join: a in Author, on: a.id in ^[1, 2, 3],
join: m in AuthorPermalink,
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
end
test "many to many query-based assoc query with custom query" do
assoc = Author.__schema__(:association, :special_permalinks)
query = from p in Permalink, limit: 5
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from p in Permalink,
join: a in Author,
on: a.id in ^[1, 2, 3],
join: m in AuthorPermalink,
on: m.author_id == a.id,
where: p.special(),
where: m.permalink_id == p.id,
limit: 5)
end
test "many to many query-based join through query" do
assoc = Author.__schema__(:association, :active_permalinks)
assert inspect(Ecto.Association.ManyToMany.joins_query(assoc)) ==
inspect(from a in Author,
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
join: p in Permalink,
on: m.permalink_id == p.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [])) ==
inspect(from p in Permalink,
join: a in Author, on: a.id in ^[],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in Permalink,
join: a in Author, on: a.id in ^[1, 2, 3],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
end
test "many to many query-based join through with custom query" do
assoc = Author.__schema__(:association, :active_permalinks)
query = from p in Permalink, limit: 5
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from p in Permalink,
join: a in Author,
on: a.id in ^[1, 2, 3],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: m.permalink_id == p.id,
limit: 5)
end
test "has many through many to many" do
assoc = Author.__schema__(:association, :posts_comments)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from a in Author, join: p in assoc(a, :posts), join: c in assoc(p, :comments))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from c in Comment, join: p in Post, on: p.author_id in ^[1, 2, 3],
where: c.post_id == p.id, distinct: true)
end
test "has many through many to one" do
assoc = Author.__schema__(:association, :posts_permalinks)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from a in Author, join: p in assoc(a, :posts), join: c in assoc(p, :permalink))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from l in Permalink, join: p in Post, on: p.author_id in ^[1, 2, 3],
where: l.post_id == p.id, distinct: true)
end
test "has one through belongs to belongs" do
assoc = Comment.__schema__(:association, :post_author)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from c in Comment, join: p in assoc(c, :post), join: a in assoc(p, :author))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from a in Author, join: p in Post, on: p.id in ^[1, 2, 3],
where: a.id == p.author_id, distinct: true)
end
test "has one through belongs to one" do
assoc = Comment.__schema__(:association, :post_permalink)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from c in Comment, join: p in assoc(c, :post), join: l in assoc(p, :permalink))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from l in Permalink, join: p in Post, on: p.id in ^[1, 2, 3],
where: l.post_id == p.id, distinct: true)
end
test "has many through one to many" do
assoc = Summary.__schema__(:association, :post_comments)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from s in Summary, join: p in assoc(s, :post), join: c in assoc(p, :comments))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from c in Comment, join: p in Post, on: p.summary_id in ^[1, 2, 3],
where: c.post_id == p.id, distinct: true)
end
test "has one through one to belongs" do
assoc = Summary.__schema__(:association, :post_author)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from s in Summary, join: p in assoc(s, :post), join: a in assoc(p, :author))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from a in Author, join: p in Post, on: p.summary_id in ^[1, 2, 3],
where: a.id == p.author_id, distinct: true)
end
test "has many through custom assoc many to many query" do
assoc = Author.__schema__(:association, :posts_comments)
query = from c in Comment, where: c.text == "foo", limit: 5
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, query, [1,2,3])) ==
inspect(from c in Comment, join: p in Post,
on: p.author_id in ^[1, 2, 3],
where: c.post_id == p.id, where: c.text == "foo",
distinct: true, limit: 5)
query = from c in {"custom", Comment}, where: c.text == "foo", limit: 5
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, query, [1,2,3])) ==
inspect(from c in {"custom", Comment}, join: p in Post,
on: p.author_id in ^[1, 2, 3],
where: c.post_id == p.id, where: c.text == "foo",
distinct: true, limit: 5)
query = from c in Comment, join: p in assoc(c, :permalink), limit: 5
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, query, [1,2,3])) ==
inspect(from c in Comment, join: p0 in Permalink, on: p0.comment_id == c.id,
join: p1 in Post, on: p1.author_id in ^[1, 2, 3],
where: c.post_id == p1.id,
distinct: true, limit: 5)
end
test "has many through many to many and has many" do
assoc = Permalink.__schema__(:association, :author_emails)
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from e in {"users_emails", Email},
join: p in Permalink, on: p.id in ^[1, 2, 3],
join: ap in AuthorPermalink, on: ap.permalink_id == p.id,
join: a in Author, on: ap.author_id == a.id,
where: e.author_id == a.id, distinct: true)
end
## Integration tests through Ecto
test "build/2" do
# has many
assert build_assoc(%Post{id: 1}, :comments) ==
%Comment{post_id: 1}
# has one
assert build_assoc(%Summary{id: 1}, :post) ==
%Post{summary_id: 1, title: "default"}
# belongs to
assert build_assoc(%Post{id: 1}, :author) ==
%Author{title: "World!"}
# many to many
assert build_assoc(%Permalink{id: 1}, :authors) ==
%Author{title: "m2m!"}
assert_raise ArgumentError, ~r"cannot build through association `:post_author`", fn ->
build_assoc(%Comment{}, :post_author)
end
end
test "build/2 with custom source" do
email = build_assoc(%Author{id: 1}, :emails)
assert email.__meta__.source == "users_emails"
profile = build_assoc(%Author{id: 1}, :profile)
assert profile.__meta__.source == "users_profiles"
profile = build_assoc(%Email{id: 1}, :author)
assert profile.__meta__.source == "post_authors"
permalink = build_assoc(%Author{id: 1}, :permalinks)
assert permalink.__meta__.source == "custom_permalinks"
end
test "build/3 with custom attributes" do
# has many
assert build_assoc(%Post{id: 1}, :comments, text: "Awesome!") ==
%Comment{post_id: 1, text: "Awesome!"}
assert build_assoc(%Post{id: 1}, :comments, %{text: "Awesome!"}) ==
%Comment{post_id: 1, text: "Awesome!"}
# has one
assert build_assoc(%Post{id: 1}, :comments, post_id: 2) ==
%Comment{post_id: 1}
# belongs to
assert build_assoc(%Post{id: 1}, :author, title: "Hello!") ==
%Author{title: "Hello!"}
# 2 belongs to
with author_post = build_assoc(%Author{id: 1}, :posts),
author_and_summary_post = build_assoc(%Summary{id: 2}, :posts, author_post) do
assert author_and_summary_post.author_id == 1
assert author_and_summary_post.summary_id == 2
end
# many to many
assert build_assoc(%Permalink{id: 1}, :authors, title: "Hello!") ==
%Author{title: "Hello!"}
# Overriding defaults
assert build_assoc(%Summary{id: 1}, :post, title: "Hello").title == "Hello"
# Should not allow overriding of __meta__
meta = %{__meta__: %{source: "posts"}}
comment = build_assoc(%Post{id: 1}, :comments, meta)
assert comment.__meta__.source == "comments"
end
test "assoc_loaded?/1 sets association to loaded/not loaded" do
refute Ecto.assoc_loaded?(%Post{}.comments)
assert Ecto.assoc_loaded?(%Post{comments: []}.comments)
assert Ecto.assoc_loaded?(%Post{comments: [%Comment{}]}.comments)
assert Ecto.assoc_loaded?(%Post{permalink: nil}.permalink)
end
test "assoc/2" do
assert inspect(assoc(%Post{id: 1}, :comments)) ==
inspect(from c in Comment, where: c.post_id == ^1)
assert inspect(assoc([%Post{id: 1}, %Post{id: 2}], :comments)) ==
inspect(from c in Comment, where: c.post_id in ^[1, 2])
end
test "assoc/2 with prefixes" do
author = %Author{id: 1}
assert Ecto.assoc(author, :posts_with_prefix).from.prefix == "my_prefix"
assert Ecto.assoc(author, :comments_with_prefix).from.prefix == "my_prefix"
end
test "assoc/2 filters nil ids" do
assert inspect(assoc([%Post{id: 1}, %Post{id: 2}, %Post{}], :comments)) ==
inspect(from c in Comment, where: c.post_id in ^[1, 2])
end
test "assoc/2 fails on empty list" do
assert_raise ArgumentError, ~r"cannot retrieve association :whatever for empty list", fn ->
assoc([], :whatever)
end
end
test "assoc/2 fails on missing association" do
assert_raise ArgumentError, ~r"does not have association :whatever", fn ->
assoc([%Post{}], :whatever)
end
end
test "assoc/2 fails on heterogeneous collections" do
assert_raise ArgumentError, ~r"expected a homogeneous list containing the same struct", fn ->
assoc([%Post{}, %Comment{}], :comments)
end
end
## Preloader
alias Ecto.Repo.Preloader
test "preload: normalizer" do
assert Preloader.normalize(:foo, nil, []) ==
[foo: {nil, nil, []}]
assert Preloader.normalize([foo: :bar], nil, []) ==
[foo: {nil, nil, [bar: {nil, nil, []}]}]
assert Preloader.normalize([foo: [:bar, baz: :bat], this: :that], nil, []) ==
[this: {nil, nil, [that: {nil, nil, []}]},
foo: {nil, nil, [baz: {nil, nil, [bat: {nil, nil, []}]},
bar: {nil, nil, []}]}]
end
test "preload: normalize with query" do
query = from(p in Post, limit: 1)
assert Preloader.normalize([foo: query], nil, []) ==
[foo: {nil, query, []}]
assert Preloader.normalize([foo: {query, :bar}], nil, []) ==
[foo: {nil, query, [bar: {nil, nil, []}]}]
assert Preloader.normalize([foo: {query, bar: :baz}], nil, []) ==
[foo: {nil, query, [bar: {nil, nil, [baz: {nil, nil, []}]}]}]
end
test "preload: normalize with take" do
assert Preloader.normalize([:foo], [foo: :id], []) ==
[foo: {[:id], nil, []}]
assert Preloader.normalize([foo: :bar], [foo: :id], []) ==
[foo: {[:id], nil, [bar: {nil, nil, []}]}]
assert Preloader.normalize([foo: :bar], [foo: [:id, bar: :id]], []) ==
[foo: {[:id, bar: :id], nil, [bar: {[:id], nil, []}]}]
assert Preloader.normalize([foo: [bar: :baz]], [foo: [:id, bar: :id]], []) ==
[foo: {[:id, bar: :id], nil, [bar: {[:id], nil, [baz: {nil, nil, []}]}]}]
end
test "preload: raises on invalid preload" do
assert_raise ArgumentError, ~r"invalid preload `123` in `123`", fn ->
Preloader.normalize(123, nil, 123)
end
assert_raise ArgumentError, ~r"invalid preload `{:bar, :baz}` in", fn ->
Preloader.normalize([foo: {:bar, :baz}], nil, []) == [foo: [bar: []]]
end
end
defp expand(schema, preloads, take \\ nil) do
Preloader.expand(schema, Preloader.normalize(preloads, take, preloads), {%{}, %{}})
end
test "preload: expand" do
assert {%{comments: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, nil, nil, []},
permalink: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, nil, nil, []}},
%{}} =
expand(Post, [:comments, :permalink])
assert {%{post: {{:assoc, %Ecto.Association.BelongsTo{}, {0, :id}}, nil, nil, [author: {nil, nil, []}]}},
%{}} =
expand(Comment, [post: :author])
assert {%{post: {{:assoc, %Ecto.Association.BelongsTo{}, {0, :id}}, nil, nil,
[author: {nil, nil, []}, permalink: {nil, nil, []}]}},
%{}} =
expand(Comment, [:post, post: :author, post: :permalink])
assert {%{posts: {{:assoc, %Ecto.Association.Has{}, {0, :author_id}}, nil, nil,
[comments: {nil, nil, [post: {nil, nil, []}]}]}},
%{posts_comments: {:through, %Ecto.Association.HasThrough{}, [:posts, :comments]}}} =
expand(Author, [posts_comments: :post])
assert {%{posts: {{:assoc, %Ecto.Association.Has{}, {0, :author_id}}, nil, nil,
[comments: _, comments: _]}},
%{posts_comments: {:through, %Ecto.Association.HasThrough{}, [:posts, :comments]}}} =
expand(Author, [:posts, posts_comments: :post, posts: [comments: :post]])
end
test "preload: expand with queries" do
query = from(c in Comment, limit: 1)
assert {%{permalink: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, nil, nil, []},
comments: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, nil, ^query, []}},
%{}} =
expand(Post, [:permalink, comments: query])
assert {%{posts: {{:assoc, %Ecto.Association.Has{}, {0, :author_id}}, nil, nil,
[comments: {nil, ^query, [post: {nil, nil, []}]}]}},
%{posts_comments: {:through, %Ecto.Association.HasThrough{}, [:posts, :comments]}}} =
expand(Author, [posts_comments: {query, :post}])
end
test "preload: expand with take" do
assert {%{permalink: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, [:id], nil, []},
comments: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, nil, nil, []}},
%{}} =
expand(Post, [:permalink, :comments], [permalink: :id])
assert {%{posts: {{:assoc, %Ecto.Association.Has{}, {0, :author_id}}, nil, nil,
[comments: {[:id], nil, [post: {nil, nil, []}]}]}},
%{posts_comments: {:through, %Ecto.Association.HasThrough{}, [:posts, :comments]}}} =
expand(Author, [posts_comments: :post], [posts_comments: :id])
end
test "preload: expand raises on duplicated entries" do
message = ~r"cannot preload `comments` as it has been supplied more than once with different queries"
assert_raise ArgumentError, message, fn ->
expand(Post, [comments: from(c in Comment, limit: 2),
comments: from(c in Comment, limit: 1)])
end
end
describe "after_compile_validation/2" do
defp after_compile_validation(assoc, name, opts) do
defmodule Sample do
use Ecto.Schema
schema "sample" do
opts = [cardinality: :one] ++ opts
throw assoc.after_compile_validation(assoc.struct(__MODULE__, name, opts),
%{__ENV__ | context_modules: [Ecto.AssociationTest]})
end
end
catch
result -> result
end
test "for has" do
assert after_compile_validation(Ecto.Association.Has, :post,
cardinality: :one, queryable: __MODULE__) ==
:ok
assert after_compile_validation(Ecto.Association.Has, :post,
cardinality: :one, queryable: Unknown) ==
{:error, "associated schema Unknown does not exist"}
assert after_compile_validation(Ecto.Association.Has, :post,
cardinality: :one, queryable: Ecto.Changeset) ==
{:error, "associated module Ecto.Changeset is not an Ecto schema"}
assert after_compile_validation(Ecto.Association.Has, :post,
cardinality: :one, queryable: Post) ==
{:error, "associated schema Ecto.AssociationTest.Post does not have field `sample_id`"}
assert after_compile_validation(Ecto.Association.Has, :post,
cardinality: :one, queryable: Post, foreign_key: :author_id) ==
:ok
end
test "for belongs_to" do
assert after_compile_validation(Ecto.Association.BelongsTo, :sample,
foreign_key: :post_id, queryable: __MODULE__) ==
:ok
assert after_compile_validation(Ecto.Association.BelongsTo, :sample,
foreign_key: :post_id, queryable: Unknown) ==
{:error, "associated schema Unknown does not exist"}
assert after_compile_validation(Ecto.Association.BelongsTo, :sample,
foreign_key: :post_id, queryable: Ecto.Changeset) ==
{:error, "associated module Ecto.Changeset is not an Ecto schema"}
assert after_compile_validation(Ecto.Association.BelongsTo, :sample,
foreign_key: :post_id, references: :non_id, queryable: Post) ==
{:error, "associated schema Ecto.AssociationTest.Post does not have field `non_id`"}
assert after_compile_validation(Ecto.Association.BelongsTo, :sample,
foreign_key: :post_id, references: :id, queryable: Post) ==
:ok
end
test "for many_to_many" do
assert after_compile_validation(Ecto.Association.ManyToMany, :sample,
join_through: "join", queryable: __MODULE__) ==
:ok
assert after_compile_validation(Ecto.Association.ManyToMany, :sample,
join_through: "join", queryable: Unknown) ==
{:error, "associated schema Unknown does not exist"}
assert after_compile_validation(Ecto.Association.ManyToMany, :sample,
join_through: "join", queryable: Ecto.Changeset) ==
{:error, "associated module Ecto.Changeset is not an Ecto schema"}
assert after_compile_validation(Ecto.Association.ManyToMany, :sample,
join_through: "join", queryable: Post) ==
:ok
end
end
end
| 41.328933 | 119 | 0.599127 |
f7043314a61147ef8af794ff83579d30b5e2ea15 | 1,989 | ex | Elixir | lib/git_hooks.ex | pojiro/elixir_git_hooks | 3b9448d535365e4b67b86b7f0ceb97d620c35b96 | [
"MIT"
] | null | null | null | lib/git_hooks.ex | pojiro/elixir_git_hooks | 3b9448d535365e4b67b86b7f0ceb97d620c35b96 | [
"MIT"
] | null | null | null | lib/git_hooks.ex | pojiro/elixir_git_hooks | 3b9448d535365e4b67b86b7f0ceb97d620c35b96 | [
"MIT"
] | null | null | null | defmodule GitHooks do
@moduledoc false
alias Mix.Tasks.GitHooks.Install
if Application.get_env(:git_hooks, :auto_install, true) do
Install.run(["--quiet"])
end
@typedoc """
A Git hook
"""
@type git_hook_type :: atom
@type git_hook_args :: list(String.t())
alias GitHooks.Tasks.Cmd
alias GitHooks.Tasks.File
alias GitHooks.Tasks.MFA
alias GitHooks.Tasks.Mix, as: MixTask
alias Mix.Tasks.GitHooks.Run
@type allowed_configs ::
{:file, String.t()}
| {:file, String.t(), Run.run_opts()}
| {:cmd, String.t()}
| {:cmd, String.t(), Run.run_opts()}
| {:mix_task, Mix.Task.task_name()}
| {:mix_task, Mix.Task.task_name(), [any]}
| mfa()
@spec new_task(allowed_configs(), git_hook_type(), git_hook_args()) ::
GitHooks.Task.t() | no_return
def new_task({:file, path}, git_hook_type, git_hook_args) do
File.new({:file, path, []}, git_hook_type, git_hook_args)
end
def new_task({:file, _path, _opts} = file_config, git_hook_type, git_hook_args) do
File.new(file_config, git_hook_type, git_hook_args)
end
def new_task({:cmd, command}, git_hook_type, git_hook_args) do
Cmd.new({:cmd, command, []}, git_hook_type, git_hook_args)
end
def new_task({:cmd, _command, _opts} = cmd, git_hook_type, git_hook_args) do
Cmd.new(cmd, git_hook_type, git_hook_args)
end
def new_task({:mix_task, task}, _git_hook_type, _git_hook_args) do
MixTask.new({:mix_task, task, []})
end
def new_task({:mix_task, _task, _args} = mix_task_config, _git_hook_type, _git_hook_args) do
MixTask.new(mix_task_config)
end
def new_task({_module, _function, _arity} = mfa, git_hook_type, git_hook_args) do
MFA.new(mfa, git_hook_type, git_hook_args)
end
def new_task(task_config, git_hook_type, _git_hook_args) do
raise """
Invalid task `#{inspect(task_config)}` for hook `#{inspect(git_hook_type)}`, please check documentation.
"""
end
end
| 29.686567 | 108 | 0.671694 |
f7043b1ab31b69778dc3edcfa268d03334acf384 | 2,491 | ex | Elixir | clients/service_control/lib/google_api/service_control/v1/model/authorization_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/service_control/lib/google_api/service_control/v1/model/authorization_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/service_control/lib/google_api/service_control/v1/model/authorization_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ServiceControl.V1.Model.AuthorizationInfo do
@moduledoc """
Authorization information for the operation.
## Attributes
* `granted` (*type:* `boolean()`, *default:* `nil`) - Whether or not authorization for `resource` and `permission` was granted.
* `permission` (*type:* `String.t`, *default:* `nil`) - The required IAM permission.
* `resource` (*type:* `String.t`, *default:* `nil`) - The resource being accessed, as a REST-style or cloud resource string. For example: bigquery.googleapis.com/projects/PROJECTID/datasets/DATASETID or projects/PROJECTID/datasets/DATASETID
* `resourceAttributes` (*type:* `GoogleApi.ServiceControl.V1.Model.Resource.t`, *default:* `nil`) - Resource attributes used in IAM condition evaluation. This field contains resource attributes like resource type and resource name. To get the whole view of the attributes used in IAM condition evaluation, the user must also look into `AuditLog.request_metadata.request_attributes`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:granted => boolean() | nil,
:permission => String.t() | nil,
:resource => String.t() | nil,
:resourceAttributes => GoogleApi.ServiceControl.V1.Model.Resource.t() | nil
}
field(:granted)
field(:permission)
field(:resource)
field(:resourceAttributes, as: GoogleApi.ServiceControl.V1.Model.Resource)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceControl.V1.Model.AuthorizationInfo do
def decode(value, options) do
GoogleApi.ServiceControl.V1.Model.AuthorizationInfo.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceControl.V1.Model.AuthorizationInfo do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.482143 | 386 | 0.738659 |
f70444a2a3ef4376b680efed34e63fd551612bee | 2,423 | ex | Elixir | clients/vision/lib/google_api/vision/v1/model/async_batch_annotate_images_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/vision/lib/google_api/vision/v1/model/async_batch_annotate_images_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/vision/lib/google_api/vision/v1/model/async_batch_annotate_images_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Vision.V1.Model.AsyncBatchAnnotateImagesRequest do
@moduledoc """
Request for async image annotation for a list of images.
## Attributes
* `outputConfig` (*type:* `GoogleApi.Vision.V1.Model.OutputConfig.t`, *default:* `nil`) - Required. The desired output location and metadata (e.g. format).
* `parent` (*type:* `String.t`, *default:* `nil`) - Optional. Target project and location to make a call. Format: `projects/{project-id}/locations/{location-id}`. If no parent is specified, a region will be chosen automatically. Supported location-ids: `us`: USA country only, `asia`: East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `projects/project-A/locations/eu`.
* `requests` (*type:* `list(GoogleApi.Vision.V1.Model.AnnotateImageRequest.t)`, *default:* `nil`) - Required. Individual image annotation requests for this batch.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:outputConfig => GoogleApi.Vision.V1.Model.OutputConfig.t() | nil,
:parent => String.t() | nil,
:requests => list(GoogleApi.Vision.V1.Model.AnnotateImageRequest.t()) | nil
}
field(:outputConfig, as: GoogleApi.Vision.V1.Model.OutputConfig)
field(:parent)
field(:requests, as: GoogleApi.Vision.V1.Model.AnnotateImageRequest, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.AsyncBatchAnnotateImagesRequest do
def decode(value, options) do
GoogleApi.Vision.V1.Model.AsyncBatchAnnotateImagesRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.AsyncBatchAnnotateImagesRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 45.716981 | 395 | 0.737928 |
f704590b6a5ce66b12731d325e93ae908b07ff90 | 362 | ex | Elixir | lib/twitchbot/application.ex | adigitalmonk/twitchbot | 2d2afd21032d8f94272d5cf2605f69451a24e08e | [
"MIT"
] | null | null | null | lib/twitchbot/application.ex | adigitalmonk/twitchbot | 2d2afd21032d8f94272d5cf2605f69451a24e08e | [
"MIT"
] | null | null | null | lib/twitchbot/application.ex | adigitalmonk/twitchbot | 2d2afd21032d8f94272d5cf2605f69451a24e08e | [
"MIT"
] | null | null | null | defmodule Twitchbot.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
children = [
Twitchbot.Client
]
opts = [strategy: :one_for_one, name: Twitchbot.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 21.294118 | 63 | 0.71547 |
f704c7e684d59a95e1ead5bd20f49667ee7ff226 | 1,486 | ex | Elixir | clients/vm_migration/lib/google_api/vm_migration/v1/model/add_group_migration_request.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/vm_migration/lib/google_api/vm_migration/v1/model/add_group_migration_request.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/vm_migration/lib/google_api/vm_migration/v1/model/add_group_migration_request.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.VMMigration.V1.Model.AddGroupMigrationRequest do
@moduledoc """
Request message for 'AddGroupMigration' request.
## Attributes
* `migratingVm` (*type:* `String.t`, *default:* `nil`) - The full path name of the MigratingVm to add.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:migratingVm => String.t() | nil
}
field(:migratingVm)
end
defimpl Poison.Decoder, for: GoogleApi.VMMigration.V1.Model.AddGroupMigrationRequest do
def decode(value, options) do
GoogleApi.VMMigration.V1.Model.AddGroupMigrationRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.VMMigration.V1.Model.AddGroupMigrationRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.617021 | 106 | 0.745626 |
f704d41e80148866f2e4295ddc2e221689526c76 | 1,824 | ex | Elixir | lib/espec/assertions/interface.ex | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 807 | 2015-03-25T14:00:19.000Z | 2022-03-24T08:08:15.000Z | lib/espec/assertions/interface.ex | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 254 | 2015-03-27T10:12:25.000Z | 2021-07-12T01:40:15.000Z | lib/espec/assertions/interface.ex | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 85 | 2015-04-02T10:25:19.000Z | 2021-01-30T21:30:43.000Z | defmodule ESpec.Assertions.Interface do
@moduledoc """
Defines the assertion interface.
There are 3 functions that should be defined in the 'assertion' module:
- `match/2`;
- `success_message/4`;
- `error_message/4`.
"""
defmacro __using__(_opts) do
quote do
def assert(subject, data, positive \\ true) do
case match(subject, data) do
{false, result} when positive -> raise_error(subject, data, result, positive)
{true, result} when not positive -> raise_error(subject, data, result, positive)
{true, result} when positive -> success_message(subject, data, result, positive)
{false, result} when not positive -> success_message(subject, data, result, positive)
end
end
def assert(subject, data, positive, stacktrace) do
case match(subject, data) do
{false, result} when positive ->
raise_error(subject, data, result, positive, stacktrace)
{true, result} when not positive ->
raise_error(subject, data, result, positive, stacktrace)
{true, result} when positive ->
success_message(subject, data, result, positive)
{false, result} when not positive ->
success_message(subject, data, result, positive)
end
end
defp raise_error(subject, data, result, positive, stacktrace \\ nil) do
e = error_message(subject, data, result, positive)
{message, extra} =
case e do
{_, _} -> e
_ -> {e, nil}
end
raise ESpec.AssertionError,
subject: subject,
data: data,
result: result,
assertion: __MODULE__,
message: message,
extra: extra,
stacktrace: stacktrace
end
end
end
end
| 32 | 95 | 0.602522 |
f70508d41ac05dc4e6a910127b0f0e2cbecae0c8 | 1,681 | ex | Elixir | web/web.ex | houshuang/survey | 948acaf20840af82af1d9af3147acca94cb4fcf8 | [
"Apache-2.0"
] | 48 | 2015-06-29T21:20:25.000Z | 2021-05-09T04:27:41.000Z | web/web.ex | houshuang/survey | 948acaf20840af82af1d9af3147acca94cb4fcf8 | [
"Apache-2.0"
] | null | null | null | web/web.ex | houshuang/survey | 948acaf20840af82af1d9af3147acca94cb4fcf8 | [
"Apache-2.0"
] | 15 | 2015-06-29T21:13:57.000Z | 2021-07-27T10:02:40.000Z | defmodule Survey.Web do
@moduledoc """
A module that keeps using definitions for controllers,
views and so on.
This can be used in your application as:
use Survey.Web, :controller
use Survey.Web, :view
The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below.
"""
def model do
quote do
use Ecto.Model
end
end
def controller do
quote do
use Phoenix.Controller
# Alias the data repository and import query/model functions
alias Survey.Repo
import Ecto.Model
import Ecto.Query, only: [from: 2]
# Import URL helpers from the router
import Survey.Router.Helpers
end
end
def view do
quote do
use Phoenix.View, root: "web/templates"
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
# Import URL helpers from the router
import Survey.Router.Helpers
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
end
end
def router do
quote do
use Phoenix.Router
end
end
def channel do
quote do
use Phoenix.Channel
# Alias the data repository and import query/model functions
alias Survey.Repo
import Ecto.Model
import Ecto.Query, only: [from: 2]
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
| 21.278481 | 88 | 0.66865 |
f7050c4d9ac290313b213a75965819355d3fe8e1 | 21,658 | ex | Elixir | lib/aws/generated/app_sync.ex | salemove/aws-elixir | debdf6482158a71a57636ac664c911e682093395 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/app_sync.ex | salemove/aws-elixir | debdf6482158a71a57636ac664c911e682093395 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/app_sync.ex | salemove/aws-elixir | debdf6482158a71a57636ac664c911e682093395 | [
"Apache-2.0"
] | null | null | null | # WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
# See https://github.com/aws-beam/aws-codegen for more details.
defmodule AWS.AppSync do
@moduledoc """
AWS AppSync provides API actions for creating and interacting with data sources
using GraphQL from your application.
"""
alias AWS.Client
alias AWS.Request
def metadata do
%AWS.ServiceMetadata{
abbreviation: nil,
api_version: "2017-07-25",
content_type: "application/x-amz-json-1.1",
credential_scope: nil,
endpoint_prefix: "appsync",
global?: false,
protocol: "rest-json",
service_id: "AppSync",
signature_version: "v4",
signing_name: "appsync",
target_prefix: nil
}
end
@doc """
Creates a cache for the GraphQL API.
"""
def create_api_cache(%Client{} = client, api_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/ApiCaches"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Creates a unique key that you can distribute to clients who are executing your
API.
"""
def create_api_key(%Client{} = client, api_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/apikeys"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Creates a `DataSource` object.
"""
def create_data_source(%Client{} = client, api_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/datasources"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Creates a `Function` object.
A function is a reusable entity. Multiple functions can be used to compose the
resolver logic.
"""
def create_function(%Client{} = client, api_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/functions"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Creates a `GraphqlApi` object.
"""
def create_graphql_api(%Client{} = client, input, options \\ []) do
url_path = "/v1/apis"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Creates a `Resolver` object.
A resolver converts incoming requests into a format that a data source can
understand and converts the data source's responses into GraphQL.
"""
def create_resolver(%Client{} = client, api_id, type_name, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/types/#{URI.encode(type_name)}/resolvers"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Creates a `Type` object.
"""
def create_type(%Client{} = client, api_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/types"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Deletes an `ApiCache` object.
"""
def delete_api_cache(%Client{} = client, api_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/ApiCaches"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Deletes an API key.
"""
def delete_api_key(%Client{} = client, api_id, id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/apikeys/#{URI.encode(id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Deletes a `DataSource` object.
"""
def delete_data_source(%Client{} = client, api_id, name, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/datasources/#{URI.encode(name)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Deletes a `Function`.
"""
def delete_function(%Client{} = client, api_id, function_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/functions/#{URI.encode(function_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Deletes a `GraphqlApi` object.
"""
def delete_graphql_api(%Client{} = client, api_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Deletes a `Resolver` object.
"""
def delete_resolver(%Client{} = client, api_id, field_name, type_name, input, options \\ []) do
url_path =
"/v1/apis/#{URI.encode(api_id)}/types/#{URI.encode(type_name)}/resolvers/#{
URI.encode(field_name)
}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Deletes a `Type` object.
"""
def delete_type(%Client{} = client, api_id, type_name, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/types/#{URI.encode(type_name)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Flushes an `ApiCache` object.
"""
def flush_api_cache(%Client{} = client, api_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/FlushCache"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Retrieves an `ApiCache` object.
"""
def get_api_cache(%Client{} = client, api_id, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/ApiCaches"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Retrieves a `DataSource` object.
"""
def get_data_source(%Client{} = client, api_id, name, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/datasources/#{URI.encode(name)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Get a `Function`.
"""
def get_function(%Client{} = client, api_id, function_id, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/functions/#{URI.encode(function_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Retrieves a `GraphqlApi` object.
"""
def get_graphql_api(%Client{} = client, api_id, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Retrieves the introspection schema for a GraphQL API.
"""
def get_introspection_schema(
%Client{} = client,
api_id,
format,
include_directives \\ nil,
options \\ []
) do
url_path = "/v1/apis/#{URI.encode(api_id)}/schema"
headers = []
query_params = []
query_params =
if !is_nil(include_directives) do
[{"includeDirectives", include_directives} | query_params]
else
query_params
end
query_params =
if !is_nil(format) do
[{"format", format} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Retrieves a `Resolver` object.
"""
def get_resolver(%Client{} = client, api_id, field_name, type_name, options \\ []) do
url_path =
"/v1/apis/#{URI.encode(api_id)}/types/#{URI.encode(type_name)}/resolvers/#{
URI.encode(field_name)
}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Retrieves the current status of a schema creation operation.
"""
def get_schema_creation_status(%Client{} = client, api_id, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/schemacreation"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Retrieves a `Type` object.
"""
def get_type(%Client{} = client, api_id, type_name, format, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/types/#{URI.encode(type_name)}"
headers = []
query_params = []
query_params =
if !is_nil(format) do
[{"format", format} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Lists the API keys for a given API.
API keys are deleted automatically 60 days after they expire. However, they may
still be included in the response until they have actually been deleted. You can
safely call `DeleteApiKey` to manually delete a key before it's automatically
deleted.
"""
def list_api_keys(
%Client{} = client,
api_id,
max_results \\ nil,
next_token \\ nil,
options \\ []
) do
url_path = "/v1/apis/#{URI.encode(api_id)}/apikeys"
headers = []
query_params = []
query_params =
if !is_nil(next_token) do
[{"nextToken", next_token} | query_params]
else
query_params
end
query_params =
if !is_nil(max_results) do
[{"maxResults", max_results} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Lists the data sources for a given API.
"""
def list_data_sources(
%Client{} = client,
api_id,
max_results \\ nil,
next_token \\ nil,
options \\ []
) do
url_path = "/v1/apis/#{URI.encode(api_id)}/datasources"
headers = []
query_params = []
query_params =
if !is_nil(next_token) do
[{"nextToken", next_token} | query_params]
else
query_params
end
query_params =
if !is_nil(max_results) do
[{"maxResults", max_results} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
List multiple functions.
"""
def list_functions(
%Client{} = client,
api_id,
max_results \\ nil,
next_token \\ nil,
options \\ []
) do
url_path = "/v1/apis/#{URI.encode(api_id)}/functions"
headers = []
query_params = []
query_params =
if !is_nil(next_token) do
[{"nextToken", next_token} | query_params]
else
query_params
end
query_params =
if !is_nil(max_results) do
[{"maxResults", max_results} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Lists your GraphQL APIs.
"""
def list_graphql_apis(%Client{} = client, max_results \\ nil, next_token \\ nil, options \\ []) do
url_path = "/v1/apis"
headers = []
query_params = []
query_params =
if !is_nil(next_token) do
[{"nextToken", next_token} | query_params]
else
query_params
end
query_params =
if !is_nil(max_results) do
[{"maxResults", max_results} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Lists the resolvers for a given API and type.
"""
def list_resolvers(
%Client{} = client,
api_id,
type_name,
max_results \\ nil,
next_token \\ nil,
options \\ []
) do
url_path = "/v1/apis/#{URI.encode(api_id)}/types/#{URI.encode(type_name)}/resolvers"
headers = []
query_params = []
query_params =
if !is_nil(next_token) do
[{"nextToken", next_token} | query_params]
else
query_params
end
query_params =
if !is_nil(max_results) do
[{"maxResults", max_results} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
List the resolvers that are associated with a specific function.
"""
def list_resolvers_by_function(
%Client{} = client,
api_id,
function_id,
max_results \\ nil,
next_token \\ nil,
options \\ []
) do
url_path = "/v1/apis/#{URI.encode(api_id)}/functions/#{URI.encode(function_id)}/resolvers"
headers = []
query_params = []
query_params =
if !is_nil(next_token) do
[{"nextToken", next_token} | query_params]
else
query_params
end
query_params =
if !is_nil(max_results) do
[{"maxResults", max_results} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Lists the tags for a resource.
"""
def list_tags_for_resource(%Client{} = client, resource_arn, options \\ []) do
url_path = "/v1/tags/#{URI.encode(resource_arn)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Lists the types for a given API.
"""
def list_types(
%Client{} = client,
api_id,
format,
max_results \\ nil,
next_token \\ nil,
options \\ []
) do
url_path = "/v1/apis/#{URI.encode(api_id)}/types"
headers = []
query_params = []
query_params =
if !is_nil(next_token) do
[{"nextToken", next_token} | query_params]
else
query_params
end
query_params =
if !is_nil(max_results) do
[{"maxResults", max_results} | query_params]
else
query_params
end
query_params =
if !is_nil(format) do
[{"format", format} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Adds a new schema to your GraphQL API.
This operation is asynchronous. Use to determine when it has completed.
"""
def start_schema_creation(%Client{} = client, api_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/schemacreation"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Tags a resource with user-supplied tags.
"""
def tag_resource(%Client{} = client, resource_arn, input, options \\ []) do
url_path = "/v1/tags/#{URI.encode(resource_arn)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Untags a resource.
"""
def untag_resource(%Client{} = client, resource_arn, input, options \\ []) do
url_path = "/v1/tags/#{URI.encode(resource_arn)}"
headers = []
{query_params, input} =
[
{"tagKeys", "tagKeys"}
]
|> Request.build_params(input)
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Updates the cache for the GraphQL API.
"""
def update_api_cache(%Client{} = client, api_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/ApiCaches/update"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Updates an API key.
The key can be updated while it is not deleted.
"""
def update_api_key(%Client{} = client, api_id, id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/apikeys/#{URI.encode(id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Updates a `DataSource` object.
"""
def update_data_source(%Client{} = client, api_id, name, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/datasources/#{URI.encode(name)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Updates a `Function` object.
"""
def update_function(%Client{} = client, api_id, function_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/functions/#{URI.encode(function_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Updates a `GraphqlApi` object.
"""
def update_graphql_api(%Client{} = client, api_id, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Updates a `Resolver` object.
"""
def update_resolver(%Client{} = client, api_id, field_name, type_name, input, options \\ []) do
url_path =
"/v1/apis/#{URI.encode(api_id)}/types/#{URI.encode(type_name)}/resolvers/#{
URI.encode(field_name)
}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Updates a `Type` object.
"""
def update_type(%Client{} = client, api_id, type_name, input, options \\ []) do
url_path = "/v1/apis/#{URI.encode(api_id)}/types/#{URI.encode(type_name)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
end
| 19.797075 | 100 | 0.556376 |
f70513f656a73783a43329fe170e9fc125f85b79 | 634 | ex | Elixir | web/views/form_helpers.ex | ClubNix/academy | 962be0defc1d8eedc5d19ac0a65e931c794c6538 | [
"MIT"
] | 3 | 2016-06-18T17:46:14.000Z | 2020-01-21T03:19:41.000Z | web/views/form_helpers.ex | ClubNix/academy | 962be0defc1d8eedc5d19ac0a65e931c794c6538 | [
"MIT"
] | 18 | 2016-06-18T18:05:43.000Z | 2018-03-06T08:19:41.000Z | web/views/form_helpers.ex | ClubNix/academy | 962be0defc1d8eedc5d19ac0a65e931c794c6538 | [
"MIT"
] | 3 | 2016-10-26T19:51:06.000Z | 2018-09-18T09:06:14.000Z | defmodule Academy.FormHelpers do
@moduledoc """
Conveniences for HTML forms.
"""
use Phoenix.HTML
@doc ~S"""
Build an input group. Usefull to have the class "invalid" in the div when
a field in the changeset is invalid.
Example:
input_group f, :name do
label f, :name
end
might give:
```html
<div class="input invalid">
<input type="text" id="form_name" name="form[name]">
</div>
```
"""
def input_group(form, field, fun) do
classes = "input"
classes = classes <> if form.errors[field], do: " invalid", else: ""
content_tag :div, [class: classes], fun
end
end
| 19.8125 | 75 | 0.623028 |
f7051d5437f73204e34b597526e13015318dc100 | 5,110 | ex | Elixir | lib/mix/tasks/nerves_hub.deployment.ex | pdgonzalez872/nerves_hub_cli | 0554bcb5931dee5effccd4359129ca7ee704884e | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/nerves_hub.deployment.ex | pdgonzalez872/nerves_hub_cli | 0554bcb5931dee5effccd4359129ca7ee704884e | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/nerves_hub.deployment.ex | pdgonzalez872/nerves_hub_cli | 0554bcb5931dee5effccd4359129ca7ee704884e | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.NervesHub.Deployment do
use Mix.Task
@shortdoc "Manages NervesHub deployments"
@moduledoc """
Manage NervesHub deployments
## list
mix nerves_hub.deployment list
### Command-line options
* `--product` - (Optional) Only show deployments for one product.
This defaults to the Mix Project config `:app` name.
## create
Create a new deployment
mix nerves_hub.deployment create
### Command-line options
* `--name` - (Optional) The deployment name
* `--firmware` - (Optional) The firmware UUID
* `--version` - (Optional) Can be blank. The version requirement the device's
version must meet to qualify for the deployment
* `--tag` - (Optional) Multiple tags can be set by passing this key multiple
times
## update
Update values on a deployment.
### Examples
Update active firmware version
mix nerves_hub.deployment update dev firmware fd53d87c-99ca-5770-5540-edb5058ced5b
Activate / Deactivate a deployment
mix nerves_hub.deployment update dev is_active true
General usage:
mix nerves_hub.firmware update [deployment_name] [key] [value]
"""
import Mix.NervesHubCLI.Utils
alias Mix.NervesHubCLI.Shell
@switches [
org: :string,
product: :string,
name: :string,
version: :string,
firmware: :string,
tag: :keep
]
def run(args) do
Application.ensure_all_started(:nerves_hub_cli)
{opts, args} = OptionParser.parse!(args, strict: @switches)
show_api_endpoint()
org = org(opts)
product = product(opts)
case args do
["list"] ->
list(org, product)
["create"] ->
create(org, product, opts)
["update", deployment, key, value] ->
update(deployment, key, value, org, product)
_ ->
render_help()
end
end
@spec render_help() :: no_return()
def render_help() do
Shell.raise("""
Invalid arguments to `mix nerves_hub.deployment`.
Usage:
mix nerves_hub.deployment list
mix nerves_hub.deployment create
mix nerves_hub.deployment update DEPLOYMENT_NAME KEY VALUE
Run `mix help nerves_hub.deployment` for more information.
""")
end
def list(org, product) do
auth = Shell.request_auth()
case NervesHubUserAPI.Deployment.list(org, product, auth) do
{:ok, %{"data" => []}} ->
Shell.info("No deployments have been created for product: #{product}")
{:ok, %{"data" => deployments}} ->
Shell.info("")
Shell.info("Deployments:")
Enum.each(deployments, fn params ->
Shell.info("------------")
render_deployment(params)
|> String.trim_trailing()
|> Shell.info()
end)
Shell.info("------------")
Shell.info("")
error ->
Shell.render_error(error)
end
end
def create(org, product, opts) do
name = opts[:name] || Shell.prompt("Deployment name:")
firmware = opts[:firmware] || Shell.prompt("Firmware uuid:")
vsn = opts[:version] || Shell.prompt("Version condition:")
# Tags may be specified using multiple `--tag` options or as `--tag "a, b, c"`
tags = Keyword.get_values(opts, :tag) |> Enum.flat_map(&split_tag_string/1)
tags =
if tags == [] do
Shell.prompt("One or more comma-separated device tags:")
|> split_tag_string()
else
tags
end
auth = Shell.request_auth()
case NervesHubUserAPI.Deployment.create(org, product, name, firmware, vsn, tags, auth) do
{:ok, %{"data" => %{} = _deployment}} ->
Shell.info("""
Deployment #{name} created.
This deployment is not activated by default. To activate it, run:
mix nerves_hub.deployment update #{name} is_active true
""")
error ->
Shell.render_error(error)
end
end
def update(deployment, key, value, org, product, auth \\ nil) do
auth = auth || Shell.request_auth()
case NervesHubUserAPI.Deployment.update(
org,
product,
deployment,
Map.put(%{}, key, value),
auth
) do
{:ok, %{"data" => deployment}} ->
Shell.info("")
Shell.info("Deployment updated:")
render_deployment(deployment)
|> String.trim_trailing()
|> Shell.info()
Shell.info("")
error ->
Shell.info("Failed to update deployment.\nReason: #{inspect(error)}")
end
end
defp render_deployment(params) do
"""
name: #{params["name"]}
is_active: #{params["is_active"]}
firmware: #{params["firmware_uuid"]}
#{render_conditions(params["conditions"])}
"""
end
defp render_conditions(conditions) do
"""
conditions:
""" <>
if Map.get(conditions, "version") != "" do
"""
version: #{conditions["version"]}
"""
else
""
end <>
"""
#{render_tags(conditions["tags"])}
"""
end
defp render_tags(tags) do
"""
device tags: [#{Enum.join(tags, ", ")}]
"""
end
end
| 23.122172 | 93 | 0.596282 |
f70527d152cf5f98089867549149ac313cc0b225 | 1,204 | exs | Elixir | test/husky/task/delete_test.exs | erlandsona/husky-elixir | 4f4998c8ab8570cfec01749ed855a371210ba27e | [
"MIT"
] | 43 | 2018-10-22T14:19:19.000Z | 2022-03-28T19:16:59.000Z | test/husky/task/delete_test.exs | erlandsona/husky-elixir | 4f4998c8ab8570cfec01749ed855a371210ba27e | [
"MIT"
] | 7 | 2019-01-04T21:21:03.000Z | 2020-07-22T16:27:03.000Z | test/husky/task/delete_test.exs | erlandsona/husky-elixir | 4f4998c8ab8570cfec01749ed855a371210ba27e | [
"MIT"
] | 7 | 2018-11-27T12:35:46.000Z | 2022-03-25T04:59:21.000Z | defmodule Husky.Task.DeleteTest do
import ExUnit.CaptureIO
use ExUnit.Case, async: false
alias Mix.Tasks.Husky.{Delete, Install}
alias Husky.{TestHelper, Util}
require TestHelper
@delete_message """
... running husky delete
"""
setup do
TestHelper.initialize_local()
capture_io(&Install.run/0)
:ok
end
describe "Mix.Tasks.Husky.Delete.run" do
test "should delete all git hooks that were installed by husky" do
n_scripts = Util.git_hooks_directory() |> File.ls!() |> length()
# Linux has 1 less default git script "fsmonitor-watchman.sample" exists on macOS but not on Linux
assert length(TestHelper.all_scripts()) == n_scripts ||
length(TestHelper.all_scripts()) - 1 == n_scripts
assert @delete_message == capture_io(&Delete.run/0)
scripts = Util.git_hooks_directory() |> File.ls!() |> Enum.sort()
assert Enum.all?(scripts, fn e -> e in TestHelper.git_default_scripts() end)
n_scripts = Util.git_hooks_directory() |> File.ls!() |> length()
assert length(TestHelper.git_default_scripts()) == n_scripts ||
length(TestHelper.git_default_scripts()) - 1 == n_scripts
end
end
end
| 31.684211 | 104 | 0.675249 |
f705292a9c8e8b13c8efa05e8756156cc7bc056b | 242 | ex | Elixir | lib/rotterdam/managed_node.ex | holandes22/rotterdam | d8b56079638c15a8492c08a6859ed14413163e62 | [
"MIT"
] | null | null | null | lib/rotterdam/managed_node.ex | holandes22/rotterdam | d8b56079638c15a8492c08a6859ed14413163e62 | [
"MIT"
] | null | null | null | lib/rotterdam/managed_node.ex | holandes22/rotterdam | d8b56079638c15a8492c08a6859ed14413163e62 | [
"MIT"
] | null | null | null | defmodule Rotterdam.Managed.Node do
defstruct id: nil,
label: nil,
role: nil,
host: nil,
port: "2376",
cert_path: nil,
status: :stopped,
status_msg: ""
end
| 22 | 35 | 0.466942 |
f705517e8450203b72ccbd98baf16a1b476ff26a | 1,248 | ex | Elixir | test/support/conn_case.ex | cognizant-softvision/birdcage | 2f766c7bc6d70f1243aab56ad9ac7f7d4c5014fb | [
"Apache-2.0"
] | 1 | 2022-02-10T13:54:39.000Z | 2022-02-10T13:54:39.000Z | test/support/conn_case.ex | cognizant-softvision/birdcage | 2f766c7bc6d70f1243aab56ad9ac7f7d4c5014fb | [
"Apache-2.0"
] | 11 | 2020-07-10T16:05:17.000Z | 2020-08-25T23:44:34.000Z | test/support/conn_case.ex | cognizant-softvision/birdcage | 2f766c7bc6d70f1243aab56ad9ac7f7d4c5014fb | [
"Apache-2.0"
] | 1 | 2020-08-06T18:56:52.000Z | 2020-08-06T18:56:52.000Z | defmodule BirdcageWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use BirdcageWeb.ConnCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
import Plug.Conn
import Phoenix.ConnTest
import BirdcageWeb.ConnCase
alias BirdcageWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint BirdcageWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Birdcage.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Birdcage.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 28.363636 | 70 | 0.725962 |
f7056033df91ade669abe0cb9237a3888a3fd1d1 | 1,462 | ex | Elixir | clients/container/lib/google_api/container/v1/model/big_query_destination.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/container/lib/google_api/container/v1/model/big_query_destination.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/container/lib/google_api/container/v1/model/big_query_destination.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Container.V1.Model.BigQueryDestination do
@moduledoc """
Parameters for using BigQuery as the destination of resource usage export.
## Attributes
* `datasetId` (*type:* `String.t`, *default:* `nil`) - The ID of a BigQuery Dataset.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:datasetId => String.t() | nil
}
field(:datasetId)
end
defimpl Poison.Decoder, for: GoogleApi.Container.V1.Model.BigQueryDestination do
def decode(value, options) do
GoogleApi.Container.V1.Model.BigQueryDestination.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Container.V1.Model.BigQueryDestination do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.106383 | 88 | 0.740766 |
f7056a25a700a555eeb2529e21c4431cba628009 | 3,619 | ex | Elixir | lib/elixir/lib/kernel/utils.ex | rcoppolo/elixir | c4092e071f8b42f5a9ad213dd8b3632918097213 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel/utils.ex | rcoppolo/elixir | c4092e071f8b42f5a9ad213dd8b3632918097213 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel/utils.ex | rcoppolo/elixir | c4092e071f8b42f5a9ad213dd8b3632918097213 | [
"Apache-2.0"
] | null | null | null | import Kernel, except: [destructure: 2, defdelegate: 2, defstruct: 2]
defmodule Kernel.Utils do
@moduledoc false
@doc """
Callback for destructure.
"""
def destructure(list, count) when is_list(list), do: destructure_list(list, count)
def destructure(nil, count), do: destructure_nil(count)
defp destructure_list(_, 0), do: []
defp destructure_list([], count), do: destructure_nil(count)
defp destructure_list([h | t], count), do: [h | destructure_list(t, count - 1)]
defp destructure_nil(0), do: []
defp destructure_nil(count), do: [nil | destructure_nil(count - 1)]
@doc """
Callback for defdelegate.
"""
def defdelegate(fun, opts) do
append_first = Keyword.get(opts, :append_first, false)
{name, args} =
case Macro.decompose_call(fun) do
{_, _} = pair -> pair
_ -> raise ArgumentError, "invalid syntax in defdelegate #{Macro.to_string(fun)}"
end
as_args_list = normalize_args(args)
as = Keyword.get(opts, :as, name)
:lists.map(fn as_args ->
formal_args = make_formal_args(as_args)
as_args = case append_first do
true -> tl(as_args) ++ [hd(as_args)]
false -> as_args
end
{name, formal_args, as, as_args}
end, as_args_list)
end
defp make_formal_args(args) do
fun = &match?({name, _, mod} when is_atom(name) and is_atom(mod), &1)
:lists.filter(fun, args)
end
defp normalize_args(raw_args) do
:lists.foldr(fn
({:\\, _, [arg, default_arg]}, [as_args | _] = as_args_list) ->
new_as_args = [default_arg | as_args]
[new_as_args | add_arg(as_args_list, arg)]
(arg, as_args_list) ->
add_arg(as_args_list, arg)
end, [[]], raw_args)
end
defp add_arg(as_args_list, {name, _, mod} = arg) when is_atom(name) and is_atom(mod),
do: :lists.map(&([arg | &1]), as_args_list)
defp add_arg(_, code) do
raise ArgumentError,
"defdelegate/2 only accepts function parameters, got: #{Macro.to_string(code)}"
end
@doc """
Callback for defstruct.
"""
def defstruct(module, fields) do
case fields do
fs when is_list(fs) ->
:ok
other ->
raise ArgumentError, "struct fields definition must be list, got: #{inspect other}"
end
fields = :lists.map(fn
{key, val} when is_atom(key) ->
try do
Macro.escape(val)
rescue
e in [ArgumentError] ->
raise ArgumentError, "invalid value for struct field #{key}, " <> Exception.message(e)
else
_ -> {key, val}
end
key when is_atom(key) ->
{key, nil}
other ->
raise ArgumentError, "struct field names must be atoms, got: #{inspect other}"
end, fields)
{:maps.put(:__struct__, module, :maps.from_list(fields)),
List.wrap(Module.get_attribute(module, :enforce_keys)),
Module.get_attribute(module, :derive)}
end
@doc """
Announcing callback for defstruct.
"""
def announce_struct(module) do
case :erlang.get(:elixir_compiler_pid) do
:undefined -> :ok
pid -> send(pid, {:struct_available, module})
end
end
@doc """
Callback for raise.
"""
def raise(msg) when is_binary(msg) do
RuntimeError.exception(msg)
end
def raise(atom) when is_atom(atom) do
atom.exception([])
end
def raise(%{__struct__: struct, __exception__: true} = exception) when is_atom(struct) do
exception
end
def raise(other) do
ArgumentError.exception("raise/1 expects an alias, string or exception as " <>
"the first argument, got: #{inspect other}")
end
end
| 29.185484 | 98 | 0.628903 |
f70572739984f0145a347cc12485da5495b4323a | 8,175 | ex | Elixir | lib/elixir_script/passes/translate/forms/pattern.ex | alex-min/elixirscript | a2bd2327d0b6bbacf98fb555198acf12c0c20916 | [
"MIT"
] | 1 | 2021-09-14T14:28:39.000Z | 2021-09-14T14:28:39.000Z | lib/elixir_script/passes/translate/forms/pattern.ex | alex-min/elixirscript | a2bd2327d0b6bbacf98fb555198acf12c0c20916 | [
"MIT"
] | null | null | null | lib/elixir_script/passes/translate/forms/pattern.ex | alex-min/elixirscript | a2bd2327d0b6bbacf98fb555198acf12c0c20916 | [
"MIT"
] | null | null | null | defmodule ElixirScript.Translate.Forms.Pattern do
alias ElixirScript.Translate.Forms.Pattern.Patterns, as: PM
alias ESTree.Tools.Builder, as: J
alias ElixirScript.Translate.Helpers
alias ElixirScript.Translate.Form
alias ElixirScript.Translate.Forms.Bitstring
@moduledoc false
@doc """
Handles all pattern matching translations
"""
@spec compile(list(), map()) :: {list(), list(), map()}
def compile(patterns, state) do
patterns
|> do_compile(state)
|> update_env(state)
end
defp do_compile(patterns, state) do
Enum.reduce(patterns, {[], []}, fn
x, {patterns, params} ->
{pattern, param} = process_pattern(x, state)
{patterns ++ List.wrap(pattern), params ++ List.wrap(param)}
end)
end
defp update_env({patterns, params}, state) do
{params, state} =
Enum.map_reduce(params, state, fn
%ESTree.Identifier{name: :undefined} = param, state ->
{param, state}
%ESTree.Identifier{} = param, state ->
state = update_variable(param.name, state)
new_name = get_variable_name(param.name, state)
{%{param | name: new_name}, state}
param, state ->
{param, state}
end)
{patterns, params, state}
end
@spec get_variable_name(atom(), map()) :: atom()
def get_variable_name(function, state) do
# TODO(alex): only happens on new elixir, investigate why
state =
if Map.has_key?(state, :vars) do
state
else
Map.put(state, :vars, %{})
end
number = Map.get(state.vars, function)
String.to_atom("#{function}#{number}")
end
defp update_variable(name, state) do
vars = Map.update(state.vars, name, 0, fn val -> val + 1 end)
Map.put(state, :vars, vars)
end
defp process_pattern(term, state)
when is_number(term) or is_binary(term) or is_boolean(term) or is_atom(term) or
is_nil(term) do
{[Form.compile!(term, state)], []}
end
defp process_pattern({:^, _, [value]}, state) do
{[PM.bound(Form.compile!(value, state))], []}
end
defp process_pattern({:_, _, _}, _) do
{[PM.parameter(J.literal("_"))], []}
end
defp process_pattern({a, b}, state) do
process_pattern({:{}, [], [a, b]}, state)
end
defp process_pattern({:{}, _, elements}, state) do
{patterns, params} =
elements
|> Enum.map(&do_compile([&1], state))
|> reduce_patterns(state)
pattern =
J.object_expression([
J.property(
J.identifier("values"),
J.array_expression(patterns)
)
])
tuple = Helpers.tuple()
{[PM.type(tuple, pattern)], params}
end
defp process_pattern([{:|, _, [head, tail]}], state) do
{head_patterns, head_params} = process_pattern(head, state)
{tail_patterns, tail_params} = process_pattern(tail, state)
params = head_params ++ tail_params
{[PM.head_tail(hd(head_patterns), hd(tail_patterns))], params}
end
defp process_pattern(list, state) when is_list(list) do
{patterns, params} =
list
|> Enum.map(&do_compile([&1], state))
|> reduce_patterns(state)
{[J.array_expression(patterns)], params}
end
defp process_pattern({:|, _, [head, tail]}, state) do
{head_patterns, head_params} = process_pattern(head, state)
{tail_patterns, tail_params} = process_pattern(tail, state)
params = head_params ++ tail_params
{[PM.head_tail(hd(head_patterns), hd(tail_patterns))], params}
end
defp process_pattern({{:., _, [:erlang, :++]}, context, [head, tail]}, state) do
process_pattern({:|, context, [head, tail]}, state)
end
defp process_pattern({:%, _, [module, {:%{}, _, props}]}, state) do
process_pattern({:%{}, [], [__module__struct__: module] ++ props}, state)
end
defp process_pattern({:%{}, _, props}, state) do
properties =
Enum.map(props, fn
{:__module__struct__, {_, _, nil} = var} ->
{pattern, params} = process_pattern(var, state)
a =
J.object_expression([
%ESTree.Property{
key: J.identifier("__MODULE__"),
value: hd(List.wrap(pattern))
}
])
property =
J.array_expression([
Form.compile!(:__struct__, state),
a
])
{property, params}
{:__module__struct__, module} ->
a =
J.object_expression([
%ESTree.Property{
key: J.identifier("__MODULE__"),
value: Helpers.symbol(to_string(module))
}
])
property =
J.array_expression([
Form.compile!(:__struct__, state),
a
])
{property, []}
{key, value} ->
{pattern, params} = process_pattern(value, state)
property =
case key do
{:^, _, [the_key]} ->
J.array_expression([
Form.compile!(the_key, state),
hd(List.wrap(pattern))
])
_ ->
J.array_expression([
Form.compile!(key, state),
hd(List.wrap(pattern))
])
end
{property, params}
end)
{props, params} =
Enum.reduce(properties, {[], []}, fn {prop, param}, {props, params} ->
{props ++ [prop], params ++ param}
end)
ast =
Helpers.new(
J.identifier("Map"),
[
J.array_expression(List.wrap(props))
]
)
{[ast], params}
end
defp process_pattern({:<<>>, _, elements}, state) do
params =
Enum.reduce(elements, [], fn
{:"::", _, [{_, _, params} = ast, _]}, state
when is_nil(params)
when is_list(params) and length(params) == 0 ->
var_str = make_identifier(ast)
var_atom = String.to_atom(var_str)
state ++ [ElixirScript.Translate.Identifier.make_identifier(var_atom)]
_, state ->
state
end)
elements =
Enum.map(elements, fn
{:"::", context, [{_, _, params}, options]} when is_atom(params) ->
Bitstring.compile_element(
{:"::", context, [ElixirScript.Translate.Forms.Pattern.Patterns, options]},
state
)
x ->
Bitstring.compile_element(x, state)
end)
{[PM.bitstring_match(elements)], params}
end
defp process_pattern({:<>, _, [prefix, value]}, state) do
{[PM.starts_with(prefix)], [Form.compile!(value, state)]}
end
defp process_pattern({:=, _, [{name, _, _} = target, right]}, state)
when name not in [:%, :{}, :^, :%{}, :<<>>] do
unify(target, right, state)
end
defp process_pattern({:=, _, [left, {name, _, _} = target]}, state)
when name not in [:%, :{}, :^, :%{}, :<<>>] do
unify(target, left, state)
end
defp process_pattern({_, _, a} = ast, _) when is_atom(a) do
var_str = make_identifier(ast)
var_atom = String.to_atom(var_str)
{[PM.parameter(J.literal(var_str))],
[ElixirScript.Translate.Identifier.make_identifier(var_atom)]}
end
defp process_pattern(ast, state) do
{[Form.compile!(ast, state)], []}
end
defp reduce_patterns(patterns, _) do
patterns
|> Enum.reduce({[], []}, fn {pattern, new_param}, {patterns, new_params} ->
{patterns ++ List.wrap(pattern), new_params ++ List.wrap(new_param)}
end)
end
defp unify(target, source, state) do
{patterns, params} = do_compile([source], state)
{[_], [param]} = process_pattern(target, state)
{[PM.capture(hd(patterns))], params ++ [param]}
end
@spec get_counter(keyword) :: binary
def get_counter(meta) do
# TODO(alex): check why it sends :env as meta
if is_atom(meta) do
""
else
case Keyword.get(meta, :counter, nil) do
nil ->
""
{_module, value} ->
value
|> Kernel.abs()
|> to_string()
end
end
end
defp make_identifier({var, meta, _}) do
counter = get_counter(meta)
to_string(var) <> counter
end
end
| 26.980198 | 87 | 0.56367 |
f70589b83dbdf73ad56defaaafb4b16f20eba733 | 312 | ex | Elixir | web/views/layout_view.ex | eqdw/warg | c60669a492bfecb829381357864a61ddb0438174 | [
"MIT"
] | null | null | null | web/views/layout_view.ex | eqdw/warg | c60669a492bfecb829381357864a61ddb0438174 | [
"MIT"
] | null | null | null | web/views/layout_view.ex | eqdw/warg | c60669a492bfecb829381357864a61ddb0438174 | [
"MIT"
] | null | null | null | defmodule Warg.LayoutView do
use Warg.Web, :view
def main_menu_links do
%{
"Home" => Warg.Router.Helpers.page_path(Warg.Endpoint, :index),
"Ehlo" => Warg.Router.Helpers.ehlo_path(Warg.Endpoint, :index),
"Users" => Warg.Router.Helpers.user_path(Warg.Endpoint, :index)
}
end
end
| 26 | 70 | 0.663462 |
f705b1168538a4f7e64cd981f458ef61101661a9 | 1,875 | ex | Elixir | test/support/pages/contact_investigation_quarantine_monitoring.ex | geometricservices/epi-viewpoin | ecb5316ea0f3f7299d5ff63e2de588539005ac1c | [
"Apache-2.0"
] | 5 | 2021-02-25T18:43:09.000Z | 2021-02-27T06:00:35.000Z | test/support/pages/contact_investigation_quarantine_monitoring.ex | geometricservices/epi-viewpoint | ecb5316ea0f3f7299d5ff63e2de588539005ac1c | [
"Apache-2.0"
] | 3 | 2021-12-13T17:52:47.000Z | 2021-12-17T01:35:31.000Z | test/support/pages/contact_investigation_quarantine_monitoring.ex | geometricservices/epi-viewpoint | ecb5316ea0f3f7299d5ff63e2de588539005ac1c | [
"Apache-2.0"
] | 1 | 2022-01-27T23:26:38.000Z | 2022-01-27T23:26:38.000Z | defmodule EpicenterWeb.Test.Pages.ContactInvestigationQuarantineMonitoring do
import ExUnit.Assertions
import Phoenix.LiveViewTest
alias Epicenter.ContactInvestigations.ContactInvestigation
alias Epicenter.Test
alias EpicenterWeb.Test.Pages
alias Phoenix.LiveViewTest.View
def visit(%Plug.Conn{} = conn, %ContactInvestigation{id: id}) do
conn |> Pages.visit("/contact-investigations/#{id}/quarantine-monitoring")
end
def assert_here(view_or_conn_or_html) do
view_or_conn_or_html |> Pages.assert_on_page("contact-investigation-quarantine-monitoring")
end
def assert_page_title(%View{} = view, expected_page_title) do
assert view
|> Pages.parse()
|> Test.Html.text(role: "quarantine-page-title") == expected_page_title
end
def assert_quarantine_date_started(%View{} = view, expected_date, expected_explanation_text) do
assert view
|> Pages.parse()
|> Test.Html.find!("input#contact-investigation-quarantine-monitoring-form_date_started")
|> Test.Html.attr("value") == [expected_date]
assert view
|> Pages.parse()
|> Test.Html.text(role: "exposed-date") == expected_explanation_text
view
end
def assert_quarantine_date_ended(%View{} = view, expected_date) do
assert view
|> Pages.parse()
|> Test.Html.find!("input#contact-investigation-quarantine-monitoring-form_date_ended")
|> Test.Html.attr("value") == [expected_date]
view
end
def assert_quarantine_recommended_length(%View{} = view, expected_text) do
assert view
|> Pages.parse()
|> Test.Html.text(role: "recommended-length") == expected_text
view
end
def change_form(view, attrs) do
view |> element("#contact-investigation-quarantine-monitoring-form") |> render_change(attrs)
view
end
end
| 31.25 | 100 | 0.696533 |
f705bfc6b512f1a42087b58e46c7511f9c2175d1 | 4,059 | ex | Elixir | lib/teiserver/agents/battlehost_agent_server.ex | marseel/teiserver | 7e085ae7853205d217183737d3eb69a4941bbe7e | [
"MIT"
] | null | null | null | lib/teiserver/agents/battlehost_agent_server.ex | marseel/teiserver | 7e085ae7853205d217183737d3eb69a4941bbe7e | [
"MIT"
] | null | null | null | lib/teiserver/agents/battlehost_agent_server.ex | marseel/teiserver | 7e085ae7853205d217183737d3eb69a4941bbe7e | [
"MIT"
] | null | null | null | defmodule Teiserver.Agents.BattlehostAgentServer do
use GenServer
alias Teiserver.Agents.AgentLib
alias Teiserver.Battle.Lobby
require Logger
@tick_period 5000
@inaction_chance 0.5
@leave_chance 0.5
@password_chance 0.5
@map_hash "1565299817"
@game_hash "393009621"
@game_name "Beyond All Reason test-18456-3542052"
@engine_version "105.1.1-714-ge909643 BAR105"
def handle_info(:startup, state) do
socket = AgentLib.get_socket()
AgentLib.login(socket, %{
name: "Battlehost_#{state.name}",
email: "Battlehost_#{state.name}@agent_email",
bot: true
})
:timer.send_interval(@tick_period, self(), :tick)
{:noreply, %{state | socket: socket}}
end
def handle_info(:tick, state) do
battle = Lobby.get_battle(state.lobby_id)
new_state = cond do
# Chance of doing nothing
:rand.uniform() <= state.inaction_chance ->
state
battle == nil ->
open_battle(state)
state
state.always_leave ->
leave_battle(state)
battle.player_count == 0 and battle.spectator_count == 0 ->
if :rand.uniform() <= state.leave_chance do
leave_battle(state)
else
state
end
# There are players in a battle, we do nothing
true ->
state
end
{:noreply, new_state}
end
def handle_info({:ssl, _socket, data}, state) do
new_state = data
|> AgentLib.translate
|> Enum.reduce(state, fn data, acc ->
handle_msg(data, acc)
end)
{:noreply, new_state}
end
defp handle_msg(nil, state), do: state
defp handle_msg(%{"cmd" => "s.lobby.request_to_join", "userid" => userid}, %{reject: true} = state) do
cmd = %{cmd: "c.lobby.respond_to_join_request", userid: userid, response: "reject", reason: "because"}
AgentLib._send(state.socket, cmd)
state
end
defp handle_msg(%{"cmd" => "s.lobby.request_to_join", "userid" => userid}, %{reject: false} = state) do
cmd = %{cmd: "c.lobby.respond_to_join_request", userid: userid, response: "approve"}
AgentLib._send(state.socket, cmd)
state
end
defp handle_msg(%{"cmd" => "s.lobby.leave", "result" => "success"}, state) do
%{state | lobby_id: nil}
end
defp handle_msg(%{"cmd" => "s.lobby.create", "lobby" => %{"id" => lobby_id}}, state) do
%{state | lobby_id: lobby_id}
end
defp handle_msg(%{"cmd" => "s.communication.direct_message"}, state), do: state
defp handle_msg(%{"cmd" => "s.lobby.announce"}, state), do: state
defp handle_msg(%{"cmd" => "s.lobby.message"}, state), do: state
defp open_battle(state) do
password = if :rand.uniform() <= state.password_chance, do: "password"
cmd = %{
cmd: "c.lobby.create",
lobby: %{
cmd: "c.battles.create",
name: "BH #{state.name} - #{:rand.uniform(9999)}",
nattype: "none",
password: password,
port: 1234,
game_hash: @game_hash,
map_hash: @map_hash,
map_name: "Comet Catcher Remake 1.8",
game_name: @game_name,
engine_name: "spring",
engine_version: @engine_version,
settings: %{
max_players: 12
}
}
}
AgentLib._send(state.socket, cmd)
end
defp leave_battle(state) do
AgentLib._send(state.socket, %{cmd: "c.lobby.leave"})
AgentLib.post_agent_update(state.id, "left battle")
%{state | lobby_id: nil}
end
# Startup
def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, opts[:data], opts)
end
def init(opts) do
send(self(), :startup)
{:ok,
%{
id: opts.id,
number: opts.number,
name: Map.get(opts, :name, opts.number),
lobby_id: nil,
socket: nil,
reject: Map.get(opts, :reject, false),
leave_chance: Map.get(opts, :leave_chance, @leave_chance),
inaction_chance: Map.get(opts, :leave_chance, @inaction_chance),
always_leave: Map.get(opts, :always_leave, false),
password_chance: Map.get(opts, :password_chance, @password_chance)
}}
end
end
| 27.993103 | 106 | 0.621335 |
f705cd8b66ac35ddf3c02078ad9da503f7979dd9 | 1,017 | ex | Elixir | apps/customer/lib/customer/web/models/favorite_job.ex | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 102 | 2017-05-21T18:24:04.000Z | 2022-03-10T12:53:20.000Z | apps/customer/lib/customer/web/models/favorite_job.ex | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 2 | 2017-05-21T01:53:30.000Z | 2017-12-01T00:27:06.000Z | apps/customer/lib/customer/web/models/favorite_job.ex | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 18 | 2017-05-22T09:51:36.000Z | 2021-09-24T00:57:01.000Z | defmodule Customer.Web.FavoriteJob do
use Customer.Web, :model
schema "favorite_jobs" do
field :interest, :integer, default: 1
field :remarks, :string
field :status, :integer
timestamps()
belongs_to :user, User
belongs_to :job, Job
end
@required_fields ~w(user_id job_id)a
@optional_fields ~w(interest remarks status)a
@doc """
"""
def changeset(favorite_job \\ %__MODULE__{}, params \\ %{}) do
cast(favorite_job, params, @required_fields ++ @optional_fields)
|> validate_required(@required_fields)
|> validate_inclusion(:interest, 1..5)
|> validate_number(:status, less_than_or_equal_to: 5)
|> foreign_key_constraint(:user_id)
|> foreign_key_constraint(:job_id)
|> unique_constraint(:job_id, name: :favorite_job_user_id_and_job_id_unique_index)
end
def build(%{user_id: user_id, job_id: job_id} = params) do
changeset(%__MODULE__{}, params)
end
def update(favorite_job, params) do
changeset(favorite_job, params)
end
end | 25.425 | 86 | 0.703048 |
f705dc702929ac44a778ae1bc40bfb11484d74ea | 1,601 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/tag_settings.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/tag_settings.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/tag_settings.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V33.Model.TagSettings do
@moduledoc """
Dynamic and Image Tag Settings.
## Attributes
* `dynamicTagEnabled` (*type:* `boolean()`, *default:* `nil`) - Whether dynamic floodlight tags are enabled.
* `imageTagEnabled` (*type:* `boolean()`, *default:* `nil`) - Whether image tags are enabled.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:dynamicTagEnabled => boolean(),
:imageTagEnabled => boolean()
}
field(:dynamicTagEnabled)
field(:imageTagEnabled)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.TagSettings do
def decode(value, options) do
GoogleApi.DFAReporting.V33.Model.TagSettings.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.TagSettings do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.02 | 112 | 0.730793 |
f7061a03164843f43f6e1640abb5a76002ce9d53 | 3,435 | ex | Elixir | implementations/absinthe-federation/lib/products_web/schema.ex | destumme/apollo-federation-subgraph-compatibility | fe1a6c79557edf462a4454abcf3bb18b8fa7f354 | [
"MIT"
] | 18 | 2021-08-31T09:57:28.000Z | 2022-03-25T03:59:36.000Z | implementations/absinthe-federation/lib/products_web/schema.ex | destumme/apollo-federation-subgraph-compatibility | fe1a6c79557edf462a4454abcf3bb18b8fa7f354 | [
"MIT"
] | 36 | 2021-08-17T04:58:50.000Z | 2022-03-31T00:48:03.000Z | implementations/absinthe-federation/lib/products_web/schema.ex | destumme/apollo-federation-subgraph-compatibility | fe1a6c79557edf462a4454abcf3bb18b8fa7f354 | [
"MIT"
] | 14 | 2021-08-22T04:48:10.000Z | 2022-02-10T13:46:07.000Z | defmodule ProductsWeb.Schema do
use Absinthe.Schema
use Absinthe.Federation.Schema
defmodule Product do
defstruct [:id, :sku, :package, :variation]
end
defmodule User do
defstruct [:email, :name, :total_products_created]
end
@desc """
extend type User @key(fields: "email") {
email: ID! @external
totalProductsCreated: Int @external
}
"""
object :user do
extends()
key_fields("email")
field(:email, non_null(:id)) do
external()
end
field :total_products_created, :integer do
external()
end
field(:_resolve_reference, :user) do
resolve(fn %{"email" => email}, _ -> {:ok, Enum.find(users(), &(&1.email == email))} end)
end
end
@desc """
type ProductDimension {
size: String
weight: Float
}
"""
object :product_dimension do
field(:size, :string)
field(:weight, :float)
end
@desc """
type ProductVariation {
id: ID!
}
"""
object :product_variation do
field(:id, non_null(:id))
end
@desc """
type Product @key(fields: "id") @key(fields: "sku package") @key(fields: "sku variation { id }") {
id: ID!
sku: String
package: String
variation: ProductVariation
dimensions: ProductDimension
createdBy: User @provides(fields: "totalProductsCreated")
}
"""
object :product do
key_fields(["id", "sku package", "sku variation { id }"])
field(:id, non_null(:id))
field(:sku, :string)
field(:package, :string)
field(:variation, :product_variation)
field(:dimensions, :product_dimension) do
resolve(&resolve_product_dimensions/3)
end
field :created_by, :user do
provides_fields("totalProductsCreated")
resolve(&resolve_product_created_by/3)
end
field :_resolve_reference, :product do
resolve(&resolve_product_reference/2)
end
end
@desc """
extend type Query {
product(id: ID!): Product
}
"""
query name: "Query" do
extends()
field :product, :product do
arg(:id, non_null(:id))
resolve(&resolve_product/3)
end
end
defp resolve_product(_parent, %{id: id}, _ctx) do
{:ok, Enum.find(products(), &(&1.id == id))}
end
defp resolve_product_created_by(_product, _, _ctx) do
{:ok, List.first(users())}
end
defp resolve_product_dimensions(_product, _, _ctx) do
{:ok, %{size: 1, weight: 1}}
end
defp resolve_product_reference(%{id: id}, _ctx) do
{:ok, Enum.find(products(), &(&1.id == id))}
end
defp resolve_product_reference(%{sku: sku, package: package}, _ctx) do
{:ok, Enum.find(products(), &(&1.sku == sku and &1.package == package))}
end
# TODO: Fix this nested string -> atom conversion
defp resolve_product_reference(%{sku: sku, variation: %{"id" => variation_id}}, _ctx) do
{:ok, Enum.find(products(), &(&1.sku == sku and &1.variation.id == variation_id))}
end
defp products(),
do: [
%Product{
id: "apollo-federation",
sku: "federation",
package: "@apollo/federation",
variation: %{
id: "OSS"
}
},
%Product{
id: "apollo-studio",
sku: "studio",
package: "",
variation: %{
id: "platform"
}
}
]
defp users(),
do: [
%User{
email: "support@apollographql.com",
name: "Apollo Studio Support",
total_products_created: 1337
}
]
end
| 22.16129 | 100 | 0.601747 |
f70620ed2a01c09cba6419ac97d98b0082127cad | 1,037 | exs | Elixir | test/shouldi/should_test.exs | szTheory/power_assert_ex | 0ae79b6b1e801bd5395a689a203c577650ae774d | [
"Apache-2.0"
] | null | null | null | test/shouldi/should_test.exs | szTheory/power_assert_ex | 0ae79b6b1e801bd5395a689a203c577650ae774d | [
"Apache-2.0"
] | null | null | null | test/shouldi/should_test.exs | szTheory/power_assert_ex | 0ae79b6b1e801bd5395a689a203c577650ae774d | [
"Apache-2.0"
] | null | null | null | defmodule ShouldTest do
use ShouldI
use PowerAssert
should "inside should" do
assert 1 + 2 == 3
end
should "use power assert inside should" do
try do
assert [1,2,3] |> Enum.take(1) |> Enum.empty?
rescue
error ->
msg = """
[1, 2, 3] |> Enum.take(1) |> Enum.empty?()
| |
[1] false
"""
ExUnit.Assertions.assert error.message <> "\n" == msg
end
end
having "use power assert inside having" do
setup context do
Map.put context, :arr, [1,2,3]
end
should "use power assert", context do
try do
array = context.arr
assert array |> Enum.take(1) |> Enum.empty?
rescue
error ->
msg = """
array |> Enum.take(1) |> Enum.empty?()
| | |
[1, 2, 3] [1] false
"""
ExUnit.Assertions.assert error.message <> "\n" == msg
end
end
end
end
| 24.116279 | 63 | 0.455159 |
f70628cf79330d785dfc1bec646c95c9e1e39c01 | 2,000 | exs | Elixir | mix.exs | duzzifelipe/jaxon | a0c0ff1d1007fe257fb936d7fad18c4ca5c3436c | [
"Apache-2.0"
] | null | null | null | mix.exs | duzzifelipe/jaxon | a0c0ff1d1007fe257fb936d7fad18c4ca5c3436c | [
"Apache-2.0"
] | null | null | null | mix.exs | duzzifelipe/jaxon | a0c0ff1d1007fe257fb936d7fad18c4ca5c3436c | [
"Apache-2.0"
] | null | null | null | defmodule Jaxon.MixProject do
use Mix.Project
def project do
[
app: :jaxon,
name: "Jaxon",
version: "2.0.0",
elixir: "~> 1.7",
compilers: [:elixir_make] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
deps: deps(),
aliases: aliases(),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
"bench.encode": :bench,
"bench.decode": :bench,
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
source_url: "https://github.com/boudra/jaxon",
description: description(),
package: package()
]
end
defp description() do
"Jaxon is an efficient and simple event-based JSON parser for Elixir, it's main goal is to be able to parse huge JSON files with minimal memory footprint."
end
defp package() do
[
name: "jaxon",
files: ["lib", "mix.exs", "README.md", "LICENSE.md", "Makefile", "c_src/*.[ch]"],
maintainers: ["Mohamed Boudra"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/boudra/jaxon"}
]
end
defp aliases() do
[
"bench.encode": ["run bench/encode.exs"],
"bench.decode": ["run bench/decode.exs"]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:benchee, "~> 1.0", only: :bench},
{:benchee_html, "~> 1.0", only: :bench},
{:poison, ">= 0.0.0", only: [:bench]},
{:jason, ">= 0.0.0", only: [:bench, :test, :docs]},
{:jiffy, ">= 0.0.0", only: :bench},
{:ex_doc, ">= 0.0.0", only: [:docs, :dev]},
{:dialyxir, "~> 1.0.0-rc.7", only: [:test, :dev], runtime: false},
{:inch_ex, github: "rrrene/inch_ex", only: [:docs, :test]},
{:elixir_make, "~> 0.4", runtime: false},
{:excoveralls, "~> 0.8", only: :test}
]
end
end
| 28.169014 | 159 | 0.5515 |
f7063324fba7cba130aab09f4cabda3675a0d7b7 | 2,138 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/machine_image_list_warning.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/compute/lib/google_api/compute/v1/model/machine_image_list_warning.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/compute/lib/google_api/compute/v1/model/machine_image_list_warning.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Model.MachineImageListWarning do
@moduledoc """
[Output Only] Informational warning message.
## Attributes
* `code` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning code, if applicable. For example, Compute Engine returns NO_RESULTS_ON_PAGE if there are no results in the response.
* `data` (*type:* `list(GoogleApi.Compute.V1.Model.MachineImageListWarningData.t)`, *default:* `nil`) - [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": "scope", "value": "zones/us-east1-d" }
* `message` (*type:* `String.t`, *default:* `nil`) - [Output Only] A human-readable description of the warning code.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:code => String.t() | nil,
:data => list(GoogleApi.Compute.V1.Model.MachineImageListWarningData.t()) | nil,
:message => String.t() | nil
}
field(:code)
field(:data, as: GoogleApi.Compute.V1.Model.MachineImageListWarningData, type: :list)
field(:message)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.MachineImageListWarning do
def decode(value, options) do
GoogleApi.Compute.V1.Model.MachineImageListWarning.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.MachineImageListWarning do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.339623 | 243 | 0.721703 |
f7063e93fa3c14a06c0799963091f491145af43c | 9,862 | ex | Elixir | lib/workflows/rule.ex | fracek/workflows | 6ef7ad3e280127f544f00fd098901bb6526a80cb | [
"Apache-2.0"
] | 94 | 2021-04-02T15:20:15.000Z | 2022-03-21T10:46:09.000Z | lib/workflows/rule.ex | fracek/workflows | 6ef7ad3e280127f544f00fd098901bb6526a80cb | [
"Apache-2.0"
] | null | null | null | lib/workflows/rule.ex | fracek/workflows | 6ef7ad3e280127f544f00fd098901bb6526a80cb | [
"Apache-2.0"
] | 6 | 2021-04-02T23:29:46.000Z | 2021-12-24T10:55:44.000Z | defmodule Workflows.Rule do
@moduledoc """
Choice state rule.
"""
@type t :: %__MODULE__{
next: String.t(),
rule: (map() -> boolean())
}
defstruct [:next, :rule]
@doc """
Create a rule that can be matched on an input.
"""
def create(%{"Next" => next} = rule) do
case do_create(rule) do
{:ok, rule} ->
{:ok, %__MODULE__{next: next, rule: rule}}
err ->
err
end
end
def create(_rule) do
{:error, :missing_next}
end
def call(%__MODULE__{rule: rule}, args) do
rule.(args)
end
## Private
defp do_create(%{"Not" => inner_case}) do
with {:ok, inner_rule} <- do_create(inner_case) do
rule = fn args ->
not inner_rule.(args)
end
{:ok, rule}
end
end
defp do_create(%{"Or" => cases}) do
with {:ok, inner_rules} <- do_create_cases(cases) do
rule = fn args ->
Enum.any?(inner_rules, fn rule -> rule.(args) end)
end
{:ok, rule}
end
end
defp do_create(%{"And" => cases}) do
with {:ok, inner_rules} <- do_create_cases(cases) do
rule = fn args ->
Enum.all?(inner_rules, fn rule -> rule.(args) end)
end
{:ok, rule}
end
end
defp do_create(%{"StringEquals" => value, "Variable" => variable}),
do: compare_with_value(&==/2, &is_binary/1, variable, value)
defp do_create(%{"StringEqualsPath" => value, "Variable" => variable}),
do: compare_with_path_value(&==/2, &is_binary/1, variable, value)
defp do_create(%{"StringLessThan" => value, "Variable" => variable}),
do: compare_with_value(&</2, &is_binary/1, variable, value)
defp do_create(%{"StringLessThanPath" => value, "Variable" => variable}),
do: compare_with_path_value(&</2, &is_binary/1, variable, value)
defp do_create(%{"StringGreaterThan" => value, "Variable" => variable}),
do: compare_with_value(&>/2, &is_binary/1, variable, value)
defp do_create(%{"StringGreaterThanPath" => value, "Variable" => variable}),
do: compare_with_path_value(&>/2, &is_binary/1, variable, value)
defp do_create(%{"StringLessThanEquals" => value, "Variable" => variable}),
do: compare_with_value(&<=/2, &is_binary/1, variable, value)
defp do_create(%{"StringLessThanEqualsPath" => value, "Variable" => variable}),
do: compare_with_path_value(&<=/2, &is_binary/1, variable, value)
defp do_create(%{"StringGreaterThanEquals" => value, "Variable" => variable}),
do: compare_with_value(&>=/2, &is_binary/1, variable, value)
defp do_create(%{"StringGreaterThanEqualsPath" => value, "Variable" => variable}),
do: compare_with_path_value(&>=/2, &is_binary/1, variable, value)
defp do_create(%{"StringMatches" => _value, "Variable" => _variable}),
do: {:error, "Not implemented"}
defp do_create(%{"NumericEquals" => value, "Variable" => variable}),
do: compare_with_value(&==/2, &is_number/1, variable, value)
defp do_create(%{"NumericEqualsPath" => value, "Variable" => variable}),
do: compare_with_path_value(&==/2, &is_number/1, variable, value)
defp do_create(%{"NumericLessThan" => value, "Variable" => variable}),
do: compare_with_value(&</2, &is_number/1, variable, value)
defp do_create(%{"NumericLessThanPath" => value, "Variable" => variable}),
do: compare_with_path_value(&</2, &is_number/1, variable, value)
defp do_create(%{"NumericGreaterThan" => value, "Variable" => variable}),
do: compare_with_value(&>/2, &is_number/1, variable, value)
defp do_create(%{"NumericGreaterThanPath" => value, "Variable" => variable}),
do: compare_with_path_value(&>/2, &is_number/1, variable, value)
defp do_create(%{"NumericLessThanEquals" => value, "Variable" => variable}),
do: compare_with_value(&<=/2, &is_number/1, variable, value)
defp do_create(%{"NumericLessThanEqualsPath" => value, "Variable" => variable}),
do: compare_with_path_value(&<=/2, &is_number/1, variable, value)
defp do_create(%{"NumericGreaterThanEquals" => value, "Variable" => variable}),
do: compare_with_value(&>=/2, &is_number/1, variable, value)
defp do_create(%{"NumericGreaterThanEqualsPath" => value, "Variable" => variable}),
do: compare_with_path_value(&>=/2, &is_number/1, variable, value)
defp do_create(%{"BooleanEquals" => value, "Variable" => variable}),
do: compare_with_value(&==/2, &is_boolean/1, variable, value)
defp do_create(%{"BooleanEqualsPath" => value, "Variable" => variable}),
do: compare_with_path_value(&==/2, &is_boolean/1, variable, value)
defp do_create(%{"TimestampEquals" => value, "Variable" => variable}),
do: compare_with_value(×tamp_eq/2, &is_timestamp/1, variable, value)
defp do_create(%{"TimestampEqualsPath" => value, "Variable" => variable}),
do: compare_with_path_value(×tamp_eq/2, &is_timestamp/1, variable, value)
defp do_create(%{"TimestampLessThan" => value, "Variable" => variable}),
do: compare_with_value(×tamp_lt/2, &is_timestamp/1, variable, value)
defp do_create(%{"TimestampLessThanPath" => value, "Variable" => variable}),
do: compare_with_path_value(×tamp_lt/2, &is_timestamp/1, variable, value)
defp do_create(%{"TimestampGreaterThan" => value, "Variable" => variable}),
do: compare_with_value(×tamp_gt/2, &is_timestamp/1, variable, value)
defp do_create(%{"TimestampGreaterThanPath" => value, "Variable" => variable}),
do: compare_with_path_value(×tamp_gt/2, &is_timestamp/1, variable, value)
defp do_create(%{"TimestampLessThanEquals" => value, "Variable" => variable}),
do: compare_with_value(×tamp_lte/2, &is_timestamp/1, variable, value)
defp do_create(%{"TimestampLessThanEqualsPath" => value, "Variable" => variable}),
do: compare_with_path_value(×tamp_lte/2, &is_timestamp/1, variable, value)
defp do_create(%{"TimestampGreaterThanEquals" => value, "Variable" => variable}),
do: compare_with_value(×tamp_gte/2, &is_timestamp/1, variable, value)
defp do_create(%{"TimestampGreaterThanEqualsPath" => value, "Variable" => variable}),
do: compare_with_path_value(×tamp_gte/2, &is_timestamp/1, variable, value)
defp do_create(%{"IsNull" => true, "Variable" => variable}) do
with {:ok, variable_fn} <- path_value(variable, result_type: :value_path) do
rule = fn args ->
case variable_fn.(args) do
# returned nil because the value is not present
{nil, ""} -> false
# returned nil because the value is null
{nil, _} -> true
# value not null
{_, _} -> false
end
end
{:ok, rule}
end
end
defp do_create(%{"IsPresent" => true, "Variable" => variable}) do
with {:ok, variable_fn} <- path_value(variable, result_type: :path) do
rule = fn args ->
case variable_fn.(args) do
"" -> false
_ -> true
end
end
{:ok, rule}
end
end
defp do_create(%{"IsNumeric" => true, "Variable" => variable}),
do: is_type(&is_number/1, variable)
defp do_create(%{"IsString" => true, "Variable" => variable}),
do: is_type(&is_binary/1, variable)
defp do_create(%{"IsBoolean" => true, "Variable" => variable}),
do: is_type(&is_boolean/1, variable)
defp do_create(%{"IsTimestamp" => true, "Variable" => variable}),
do: is_type(&is_timestamp/1, variable)
defp do_create(_rule) do
{:error, :invalid_rule}
end
defp do_create_cases(cases) when is_list(cases) do
do_create_cases(cases, [])
end
defp do_create_cases(_cases) do
{:error, :invalid_rule_cases}
end
defp do_create_cases([], acc), do: {:ok, acc}
defp do_create_cases([rule | cases], acc) do
case do_create(rule) do
{:ok, rule} -> do_create_cases(cases, [rule | acc])
err -> err
end
end
defp compare_with_value(compare, check_type, variable, value) do
with {:ok, variable_fn} <- path_value(variable) do
rule = fn args ->
variable_value = variable_fn.(args)
check_type.(variable_value) and
check_type.(value) and
compare.(variable_value, value)
end
{:ok, rule}
end
end
defp compare_with_path_value(compare, check_type, variable, value) do
with {:ok, variable_fn} <- path_value(variable),
{:ok, value_fn} <- path_value(value) do
rule = fn args ->
variable_value = variable_fn.(args)
value_value = value_fn.(args)
check_type.(variable_value) and
check_type.(value_value) and
compare.(variable_value, value_value)
end
{:ok, rule}
end
end
defp is_type(check_type, variable) do
with {:ok, variable_fn} <- path_value(variable) do
rule = fn args ->
variable_value = variable_fn.(args)
check_type.(variable_value)
end
{:ok, rule}
end
end
defp path_value(path, opts \\ []) do
with {:ok, expr} <- Warpath.Expression.compile(path) do
value_fn = fn args -> Warpath.query!(args, expr, opts) end
{:ok, value_fn}
end
end
defp timestamp_eq(ts1, ts2),
do: timestamp_compare(ts1, ts2) == :eq
defp timestamp_lt(ts1, ts2),
do: timestamp_compare(ts1, ts2) == :lt
defp timestamp_gt(ts1, ts2),
do: timestamp_compare(ts1, ts2) == :gt
defp timestamp_lte(ts1, ts2) do
cmp = timestamp_compare(ts1, ts2)
cmp == :lt || cmp == :eq
end
defp timestamp_gte(ts1, ts2) do
cmp = timestamp_compare(ts1, ts2)
cmp == :gt || cmp == :eq
end
defp timestamp_compare(ts1, ts2) do
with {:ok, ts1, _} <- DateTime.from_iso8601(ts1),
{:ok, ts2, _} <- DateTime.from_iso8601(ts2) do
DateTime.compare(ts1, ts2)
else
_ -> :error
end
end
defp is_timestamp(value) do
case DateTime.from_iso8601(value) do
{:ok, _, _} -> true
_ -> false
end
end
end
| 31.710611 | 87 | 0.642263 |
f70641b32c13339b967a6b6cc6d0d85ea8b3a718 | 717 | ex | Elixir | lib/conversor_web/gettext.ex | wagncarv/CurrencyExchange | 3e626681d97a17a68385be31d8c8a82fd4bfcd59 | [
"MIT"
] | 1 | 2022-03-28T19:10:45.000Z | 2022-03-28T19:10:45.000Z | lib/conversor_web/gettext.ex | wagner-de-carvalho/currency_exchange | 6c784dcab0af3345c71a41ca606158298a447d49 | [
"MIT"
] | null | null | null | lib/conversor_web/gettext.ex | wagner-de-carvalho/currency_exchange | 6c784dcab0af3345c71a41ca606158298a447d49 | [
"MIT"
] | null | null | null | defmodule ConversorWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import ConversorWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :conversor
end
| 28.68 | 72 | 0.680614 |
f70656d699fa7fc982f8b51bbde84933b136aa69 | 1,135 | exs | Elixir | apps/subs_services/config/config.exs | gitter-badger/opensubs.io | 76d5b4d355a530c8f496efe3ac2095d87f078997 | [
"MIT"
] | 36 | 2018-02-03T10:58:51.000Z | 2020-09-19T20:52:17.000Z | apps/subs_services/config/config.exs | joaquimadraz/subs | 9a26144ed660d5ece849ee447a9e5de53a311408 | [
"MIT"
] | 8 | 2018-01-17T17:15:48.000Z | 2020-07-06T08:56:54.000Z | apps/subs_services/config/config.exs | joaquimadraz/subs | 9a26144ed660d5ece849ee447a9e5de53a311408 | [
"MIT"
] | 10 | 2018-05-21T18:20:32.000Z | 2022-01-29T14:25:48.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure your application as:
#
# config :subs_services, key: :value
#
# and access this configuration in your application as:
#
# Application.get_env(:subs_services, :key)
#
# You can also configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 36.612903 | 73 | 0.754185 |
f7065a5222cb0783c2b4dd862a261431a652038d | 448 | exs | Elixir | test/integeration/log_in_test.exs | smpallen99/ucx_chat | 0dd98d0eb5e0537521844520ea2ba63a08fd3f19 | [
"MIT"
] | 60 | 2017-05-09T19:08:26.000Z | 2021-01-20T11:09:42.000Z | test/integeration/log_in_test.exs | smpallen99/ucx_chat | 0dd98d0eb5e0537521844520ea2ba63a08fd3f19 | [
"MIT"
] | 6 | 2017-05-10T15:43:16.000Z | 2020-07-15T07:14:41.000Z | test/integeration/log_in_test.exs | smpallen99/ucx_chat | 0dd98d0eb5e0537521844520ea2ba63a08fd3f19 | [
"MIT"
] | 10 | 2017-05-10T04:13:54.000Z | 2020-12-28T10:30:27.000Z | defmodule UcxChat.LogInTest do
# use UcxChat.AcceptanceCase
use UcxChat.ConnCase
import UcxChat.TestHelpers
require Logger
use Hound.Helpers
hound_session()
setup do
subs = insert_subscription()
current_window_handle() |> maximize_window
{:ok, subs: subs, user: subs.user}
end
# broken
# test "login in user", %{user: user} do
# login_user(user)
# assert find_element(:class, "rooms-list")
# end
end
| 17.92 | 47 | 0.6875 |
f706b2441919772c9f715c8d89974d71b27366ff | 2,883 | ex | Elixir | apps/ewallet/lib/ewallet/web/v1/serializers/transaction_request_serializer.ex | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | 1 | 2018-12-07T06:21:21.000Z | 2018-12-07T06:21:21.000Z | apps/ewallet/lib/ewallet/web/v1/serializers/transaction_request_serializer.ex | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | null | null | null | apps/ewallet/lib/ewallet/web/v1/serializers/transaction_request_serializer.ex | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | null | null | null | defmodule EWallet.Web.V1.TransactionRequestSerializer do
@moduledoc """
Serializes transaction request data into V1 JSON response format.
"""
alias Ecto.Association.NotLoaded
alias EWallet.Web.V1.{
AccountSerializer,
PaginatorSerializer,
TokenSerializer,
UserSerializer,
WalletSerializer
}
alias EWallet.Web.{Date, Paginator}
alias EWalletConfig.Helpers.Assoc
alias EWalletDB.TransactionRequest
def serialize(%Paginator{} = paginator) do
PaginatorSerializer.serialize(paginator, &serialize/1)
end
def serialize(%TransactionRequest{} = transaction_request) do
transaction_request = TransactionRequest.load_consumptions_count(transaction_request)
%{
object: "transaction_request",
id: transaction_request.id,
formatted_id: transaction_request.id,
socket_topic: "transaction_request:#{transaction_request.id}",
type: transaction_request.type,
amount: transaction_request.amount,
status: transaction_request.status,
correlation_id: transaction_request.correlation_id,
token_id: Assoc.get(transaction_request, [:token, :id]),
token: TokenSerializer.serialize(transaction_request.token),
address: transaction_request.wallet_address,
user_id: Assoc.get(transaction_request, [:user, :id]),
user: UserSerializer.serialize(transaction_request.user),
account_id: Assoc.get(transaction_request, [:account, :id]),
account: AccountSerializer.serialize(transaction_request.account),
exchange_account_id: Assoc.get(transaction_request, [:exchange_account, :id]),
exchange_account: AccountSerializer.serialize(transaction_request.exchange_account),
exchange_wallet_address: Assoc.get(transaction_request, [:exchange_wallet, :address]),
exchange_wallet:
WalletSerializer.serialize_without_balances(transaction_request.exchange_wallet),
require_confirmation: transaction_request.require_confirmation,
current_consumptions_count: transaction_request.consumptions_count,
max_consumptions: transaction_request.max_consumptions,
max_consumptions_per_user: transaction_request.max_consumptions_per_user,
consumption_lifetime: transaction_request.consumption_lifetime,
expiration_reason: transaction_request.expiration_reason,
allow_amount_override: transaction_request.allow_amount_override,
metadata: transaction_request.metadata || %{},
encrypted_metadata: transaction_request.encrypted_metadata || %{},
expiration_date: Date.to_iso8601(transaction_request.expiration_date),
expired_at: Date.to_iso8601(transaction_request.expired_at),
created_at: Date.to_iso8601(transaction_request.inserted_at),
updated_at: Date.to_iso8601(transaction_request.updated_at)
}
end
def serialize(%NotLoaded{}), do: nil
def serialize(nil), do: nil
end
| 43.681818 | 92 | 0.772806 |
f706c8e49b0a70aa6a5307cde44702da7c4efa4a | 1,404 | exs | Elixir | exercises/01-elixir/01-basics/08-guards/tests.exs | DennisWinnepenninckx/distributed-applications | 06743e4e2a09dc52ff52be831e486bb073916173 | [
"BSD-3-Clause"
] | 1 | 2021-09-22T09:52:11.000Z | 2021-09-22T09:52:11.000Z | exercises/01-elixir/01-basics/08-guards/tests.exs | DennisWinnepenninckx/distributed-applications | 06743e4e2a09dc52ff52be831e486bb073916173 | [
"BSD-3-Clause"
] | 22 | 2019-06-19T18:58:13.000Z | 2020-03-16T14:43:06.000Z | exercises/01-elixir/01-basics/08-guards/tests.exs | DennisWinnepenninckx/distributed-applications | 06743e4e2a09dc52ff52be831e486bb073916173 | [
"BSD-3-Clause"
] | 32 | 2019-09-19T03:25:11.000Z | 2020-10-06T15:01:47.000Z | defmodule Setup do
@script "shared.exs"
def setup(directory \\ ".") do
path = Path.join(directory, @script)
if File.exists?(path) do
Code.require_file(path)
Shared.setup(__DIR__)
else
setup(Path.join(directory, ".."))
end
end
end
Setup.setup
defmodule Tests do
use ExUnit.Case, async: true
import Shared
check that: Numbers.odd?(1), is_equal_to: true
check that: Numbers.odd?(5), is_equal_to: true
check that: Numbers.odd?(7), is_equal_to: true
check that: Numbers.odd?(19), is_equal_to: true
check that: Numbers.odd?(-19), is_equal_to: true
check that: Numbers.odd?(0), is_equal_to: false
check that: Numbers.odd?(2), is_equal_to: false
check that: Numbers.odd?(4), is_equal_to: false
check that: Numbers.odd?(80), is_equal_to: false
check that: Numbers.odd?(-78), is_equal_to: false
check that: Numbers.even?(0), is_equal_to: true
check that: Numbers.even?(2), is_equal_to: true
check that: Numbers.even?(8), is_equal_to: true
check that: Numbers.even?(16), is_equal_to: true
check that: Numbers.even?(-16), is_equal_to: true
check that: Numbers.even?(1), is_equal_to: false
check that: Numbers.even?(5), is_equal_to: false
check that: Numbers.even?(-5), is_equal_to: false
must_raise(FunctionClauseError) do
Numbers.odd?("abc")
end
must_raise(FunctionClauseError) do
Numbers.even?("abc")
end
end
| 27.529412 | 51 | 0.696581 |
f706ddd6227352361f7e17b912b946f601ee8ba9 | 5,913 | exs | Elixir | test/payloader_test.exs | membraneframework/membrane_rtp_vp9_plugin | 7dac9476a76a3eea1ed3b90b65aad5660663a98b | [
"Apache-2.0"
] | null | null | null | test/payloader_test.exs | membraneframework/membrane_rtp_vp9_plugin | 7dac9476a76a3eea1ed3b90b65aad5660663a98b | [
"Apache-2.0"
] | 3 | 2020-12-14T10:28:19.000Z | 2021-01-05T08:35:15.000Z | test/payloader_test.exs | membraneframework/membrane_rtp_vp9_plugin | 7dac9476a76a3eea1ed3b90b65aad5660663a98b | [
"Apache-2.0"
] | null | null | null | defmodule Membrane.RTP.VP9.PayloaderTest do
use ExUnit.Case
alias Membrane.RTP.VP9.Payloader
alias Membrane.RTP.VP9.Payloader.State
alias Membrane.RTP.VP9.PayloadDescriptor
alias Membrane.Buffer
test "fragmentation not required" do
input_payload = <<1, 1, 1>>
input_buffer = %Buffer{payload: input_payload}
expected_payload_descriptor =
%PayloadDescriptor{first_octet: <<12>>} |> PayloadDescriptor.serialize()
expected_output_payload = expected_payload_descriptor <> input_payload
{:ok, payloader_state} = Payloader.handle_init(%Payloader{max_payload_size: 3})
assert {{:ok,
[
buffer:
{:output,
[
%Buffer{
metadata: %{rtp: %{marker: true}},
payload: expected_output_payload
}
]},
redemand: :output
]},
payloader_state} ==
Payloader.handle_process(:input, input_buffer, nil, payloader_state)
end
test "three complete chunks" do
input_payload = <<1, 2, 3, 4, 5, 6, 7, 8, 9>>
input_buffer = %Buffer{payload: input_payload}
begin_descriptor = %PayloadDescriptor{first_octet: <<8>>} |> PayloadDescriptor.serialize()
middle_descriptor = %PayloadDescriptor{first_octet: <<0>>} |> PayloadDescriptor.serialize()
end_descriptor = %PayloadDescriptor{first_octet: <<4>>} |> PayloadDescriptor.serialize()
{:ok, payloader_state} = Payloader.handle_init(%Payloader{max_payload_size: 3})
assert {{:ok,
[
buffer:
{:output,
[
%Buffer{
metadata: %{rtp: %{marker: false}},
payload: begin_descriptor <> <<1, 2, 3>>
},
%Buffer{
metadata: %{rtp: %{marker: false}},
payload: middle_descriptor <> <<4, 5, 6>>
},
%Buffer{
metadata: %{rtp: %{marker: true}},
payload: end_descriptor <> <<7, 8, 9>>
}
]},
redemand: :output
]},
payloader_state} ==
Payloader.handle_process(:input, input_buffer, nil, payloader_state)
end
test "keyframe buffer" do
{input_payload, buffers} =
File.read!("test/fixtures/keyframe_buffer.dump") |> :erlang.binary_to_term()
input_buffer = %Buffer{payload: input_payload}
begin_descriptor = %PayloadDescriptor{first_octet: <<8>>} |> PayloadDescriptor.serialize()
middle_descriptor = %PayloadDescriptor{first_octet: <<0>>} |> PayloadDescriptor.serialize()
end_descriptor = %PayloadDescriptor{first_octet: <<4>>} |> PayloadDescriptor.serialize()
{:ok, payloader_state} = Payloader.handle_init(%Payloader{})
{{:ok,
[
buffer:
{:output,
[
%Buffer{
metadata: %{rtp: %{marker: false}},
payload: <<8, payload_1::binary()>>
},
%Buffer{
metadata: %{rtp: %{marker: false}},
payload: <<0, payload_2::binary()>>
},
%Buffer{
metadata: %{rtp: %{marker: false}},
payload: <<0, payload_3::binary()>>
},
%Buffer{
metadata: %{rtp: %{marker: false}},
payload: <<0, payload_4::binary()>>
},
%Buffer{
metadata: %{rtp: %{marker: true}},
payload: <<4, payload_5::binary()>>
}
]},
redemand: :output
]}, %State{}} = Payloader.handle_process(:input, input_buffer, nil, payloader_state)
<<input_payload_1::binary-size(1207), input_payload_2::binary-size(1207),
input_payload_3::binary-size(1207), input_payload_4::binary-size(1207),
input_payload_5::binary-size(1205)>> = input_payload
output_payload = payload_1 <> payload_2 <> payload_3 <> payload_4 <> payload_5
assert byte_size(output_payload) == byte_size(input_payload)
assert payload_1 == input_payload_1
assert payload_2 == input_payload_2
assert payload_3 == input_payload_3
assert payload_4 == input_payload_4
assert payload_5 == input_payload_5
end
test "two complete chunks one incomplete" do
input_payload = <<1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11>>
input_buffer = %Buffer{payload: input_payload}
begin_descriptor = %PayloadDescriptor{first_octet: <<8>>} |> PayloadDescriptor.serialize()
middle_descriptor = %PayloadDescriptor{first_octet: <<0>>} |> PayloadDescriptor.serialize()
end_descriptor = %PayloadDescriptor{first_octet: <<4>>} |> PayloadDescriptor.serialize()
{:ok, payloader_state} = Payloader.handle_init(%Payloader{max_payload_size: 3})
assert {{:ok,
[
buffer:
{:output,
[
%Buffer{
metadata: %{rtp: %{marker: false}},
payload: begin_descriptor <> <<1, 2, 3>>
},
%Buffer{
metadata: %{rtp: %{marker: false}},
payload: middle_descriptor <> <<4, 5, 6>>
},
%Buffer{
metadata: %{rtp: %{marker: false}},
payload: middle_descriptor <> <<7, 8, 9>>
},
%Buffer{
metadata: %{rtp: %{marker: true}},
payload: end_descriptor <> <<10, 11>>
}
]},
redemand: :output
]},
payloader_state} ==
Payloader.handle_process(:input, input_buffer, nil, payloader_state)
end
end
| 36.5 | 95 | 0.527989 |
f706eb280e352d37c43a69d6a7d822f4890e00ba | 5,302 | ex | Elixir | lib/bacen/ccs/serializer/schema_converter.ex | aleDsz/bacen_ccs | 573634bd4cad5f068a120850fe8ef846d270a604 | [
"MIT"
] | 3 | 2021-10-30T20:02:52.000Z | 2021-11-12T22:55:30.000Z | lib/bacen/ccs/serializer/schema_converter.ex | aleDsz/bacen_ccs | 573634bd4cad5f068a120850fe8ef846d270a604 | [
"MIT"
] | 7 | 2021-11-18T00:39:10.000Z | 2022-03-23T11:11:26.000Z | lib/bacen/ccs/serializer/schema_converter.ex | aleDsz/bacen_ccs | 573634bd4cad5f068a120850fe8ef846d270a604 | [
"MIT"
] | null | null | null | defmodule Bacen.CCS.Serializer.SchemaConverter do
@moduledoc """
The Bacen's CCS schema converter.
It reads all `Ecto.Schema` defined on `Message`
schema and generates a tuple-formatted XML, allowing
the application to serialize it properly and convert
to String.
"""
alias Bacen.CCS.Message
alias Bacen.CCS.{ACCS001, ACCS002, ACCS003, ACCS004}
@typep attrs :: {atom(), charlist()}
@typep xml :: {:CCSDOC, list(attrs()), nonempty_maybe_improper_list()}
@accs_modules [ACCS001, ACCS002, ACCS003, ACCS004]
@doc """
Convert an `t:Ecto.Schema` into a tuple-formatted XML.
## Examples
iex> message = %Bacen.CCS.Message{
iex> message: %Bacen.CCS.Message.BaseMessage{
iex> body: %Bacen.CCS.ACCS002{
iex> response: %Bacen.CCS.ACCS002.Response{
iex> error: nil,
iex> last_file_id: "000000000000",
iex> movement_date: ~D[2021-05-07],
iex> reference_date: ~U[2021-05-07 05:04:00Z],
iex> status: "A"
iex> }
iex> },
iex> header: %Bacen.CCS.Message.BaseMessage.Header{
iex> file_id: "000000000000",
iex> file_name: "ACCS001",
iex> issuer_id: "69930846",
iex> recipient_id: "25992990"
iex> }
iex> }
iex> }
iex> Bacen.CCS.Serializer.SchemaConverter.to_xml(message, 'foo')
{:ok, {:CCSDOC, [xmlns: 'foo'],
[
BCARQ: [
{:IdentdEmissor, ['69930846']},
{:IdentdDestinatario, ['25992990']},
{:NomArq, ['ACCS001']},
{:NumRemessaArq, ['000000000000']}
],
SISARQ: [
CCSArqAtlzDiariaRespArq: [
{:SitArq, ['A']},
{:UltNumRemessaArq, ['000000000000']},
{:DtHrBC, ['2021-05-07T05:04:00']},
{:DtMovto, ['2021-05-07']}
]
]
]
}}
"""
@spec to_xml(Message.t(), charlist()) :: {:ok, xml()} | {:error, any()}
def to_xml(message = %Message{}, xmlns) when is_list(xmlns) do
{element, attrs, content} =
message
|> build_xml_map()
|> build_xml(xmlns)
xml = {element, attrs, order_fields(content, [:BCARQ, :SISARQ])}
{:ok, xml}
end
defp build_xml_map(data = [%{__struct__: _} | _]), do: Enum.map(data, &build_xml_map/1)
defp build_xml_map(data = %{__struct__: module}) do
fields = get_fields(module)
Enum.reduce(fields, %{}, fn field, acc ->
source = get_source(module, field)
if source == field do
data
|> Map.get(field)
|> build_xml_map()
else
value = get_value(data, field, source)
Map.put_new(acc, source, value)
end
end)
end
defp get_fields(module) when is_atom(module), do: module.__schema__(:fields)
defp get_source(module, field) when is_atom(module) and is_atom(field),
do: module.__schema__(:field_source, field)
defp get_value(data, field, _source) do
do_get_value(Map.get(data, field))
end
defp do_get_value(date_time = %DateTime{}),
do: Timex.format!(date_time, "{YYYY}-{0M}-{0D}T{h24}:{0m}:{0s}")
defp do_get_value(date = %Date{}), do: Date.to_string(date)
defp do_get_value(list_of_structs) when is_list(list_of_structs),
do: Enum.map(list_of_structs, &do_get_value/1)
defp do_get_value(struct) when is_struct(struct), do: build_xml_map(struct)
defp do_get_value(value), do: value
defp build_xml(data_struct, xmlns) when is_map(data_struct) and is_list(xmlns) do
childrens = build_child_xml(data_struct)
build_root_xml(xmlns, childrens)
end
defp build_root_xml(xmlns, childrens = [_ | _]) do
{:CCSDOC, [{:xmlns, xmlns}], childrens}
end
defp build_child_xml(%{CCSDOC: ccs_doc}) when is_map(ccs_doc) do
build_child_xml(ccs_doc)
end
defp build_child_xml(map) when is_map(map) do
Enum.reduce(map, [], fn
{key, value}, acc when is_map(value) ->
value = build_child_xml(value)
fields_sequence = sequence(key, value)
ordered_value = order_fields(value, fields_sequence)
Keyword.put_new(acc, key, ordered_value)
{key, value}, acc when is_binary(value) ->
Keyword.put_new(acc, key, [to_charlist(value)])
{_key, nil}, acc ->
acc
{key, values}, acc when is_list(values) ->
values = Enum.map(values, &build_child_xml/1)
Keyword.put_new(acc, key, values)
{key, value}, acc ->
value =
value
|> to_string()
|> to_charlist()
Keyword.put_new(acc, key, value)
end)
end
defp order_fields(content, fields) do
index = fn list, item -> Enum.find_index(list, &Kernel.==(&1, item)) end
Enum.sort_by(content, fn {key, _} -> index.(fields, key) end)
end
defp sequence(:BCARQ, _), do: Message.sequence(:BCARQ)
defp sequence(:SISARQ, content), do: Keyword.keys(content)
defp sequence(element_name, _content) do
Enum.reduce_while(@accs_modules, [], fn module, acc ->
if data = maybe_get_sequence(module, element_name) do
{:halt, data}
else
{:cont, acc}
end
end)
end
defp maybe_get_sequence(module, element_name) do
module.sequence(element_name)
rescue
_ -> nil
end
end
| 28.972678 | 89 | 0.605055 |
f706f2170575eae904fa84dd1321adec14532d3b | 1,588 | ex | Elixir | clients/spanner/lib/google_api/spanner/v1/model/partition.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/spanner/lib/google_api/spanner/v1/model/partition.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/spanner/lib/google_api/spanner/v1/model/partition.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Spanner.V1.Model.Partition do
@moduledoc """
Information returned for each partition returned in a
PartitionResponse.
## Attributes
* `partitionToken` (*type:* `String.t`, *default:* `nil`) - This token can be passed to Read, StreamingRead, ExecuteSql, or
ExecuteStreamingSql requests to restrict the results to those identified by
this partition token.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:partitionToken => String.t()
}
field(:partitionToken)
end
defimpl Poison.Decoder, for: GoogleApi.Spanner.V1.Model.Partition do
def decode(value, options) do
GoogleApi.Spanner.V1.Model.Partition.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Spanner.V1.Model.Partition do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.76 | 127 | 0.740554 |
f70708829b4a0a645e291d79b499a917aeaa6220 | 1,150 | ex | Elixir | lib/oli_web/live/products/payments/create_codes.ex | malav2110/oli-torus | 8af64e762a7c8a2058bd27a7ab8e96539ffc055f | [
"MIT"
] | 45 | 2020-04-17T15:40:27.000Z | 2022-03-25T00:13:30.000Z | lib/oli_web/live/products/payments/create_codes.ex | malav2110/oli-torus | 8af64e762a7c8a2058bd27a7ab8e96539ffc055f | [
"MIT"
] | 944 | 2020-02-13T02:37:01.000Z | 2022-03-31T17:50:07.000Z | lib/oli_web/live/products/payments/create_codes.ex | malav2110/oli-torus | 8af64e762a7c8a2058bd27a7ab8e96539ffc055f | [
"MIT"
] | 23 | 2020-07-28T03:36:13.000Z | 2022-03-17T14:29:02.000Z | defmodule OliWeb.Products.Payments.CreateCodes do
use Surface.LiveComponent
alias OliWeb.Router.Helpers, as: Routes
prop product_slug, :string, required: true
prop count, :integer, required: true
prop click, :event, required: true
prop change, :event, required: true
prop disabled, :boolean, required: true
data something, :any, default: true
def render(assigns) do
~F"""
<div>
<div class="form-inline">
<p>Download a new batch of payment codes:</p>
<input class="ml-2 form-control form-control-sm" disabled={@disabled} type="number" value={@count} style="width: 90px;" :on-blur={@change} :on-keyup={@change}/>
<a class="btn btn-primary btn-sm ml-1" href={route_or_disabled(assigns)}>Create</a>
</div>
<div>
<small class="text-muted">You will need to refresh this page to see these newly created codes</small>
</div>
</div>
"""
end
defp route_or_disabled(assigns) do
case assigns.disabled do
true ->
"#"
_ ->
Routes.payment_path(OliWeb.Endpoint, :download_codes, assigns.product_slug, assigns.count)
end
end
end
| 29.487179 | 168 | 0.656522 |
f70779c0f01cd21511248450ca229148a59e0daf | 1,821 | ex | Elixir | lib/day7.ex | erljef/adventofcode-2020 | fdae924b34eb9b324e529b02e2aed45a79078102 | [
"WTFPL"
] | null | null | null | lib/day7.ex | erljef/adventofcode-2020 | fdae924b34eb9b324e529b02e2aed45a79078102 | [
"WTFPL"
] | null | null | null | lib/day7.ex | erljef/adventofcode-2020 | fdae924b34eb9b324e529b02e2aed45a79078102 | [
"WTFPL"
] | null | null | null | defmodule Day7 do
require Graph
def from_file(path) do
File.read!(path)
end
def parse(input) do
input
|> String.split("\n", trim: true)
|> Enum.map(fn x -> Regex.run(~r/(.*) bags contain (.*)\./, x, capture: :all_but_first) end)
|> Enum.map(fn [type, contains] -> [type, parse_contains(contains)] end)
|> Map.new(fn [k, v] -> {k, v} end)
end
def parse_contains(contains) do
contains
|> String.split(", ")
|> Enum.map(&(Regex.run(~r/(\d+) (.+) bag/, &1, capture: :all_but_first)))
|> Enum.filter(&(&1 != nil))
|> Map.new(fn [k, v] -> {v, k} end)
end
def to_graph(map) do
map
|> Map.to_list
|> Enum.map(fn {k, v} -> Enum.zip(Stream.cycle([k]), Map.keys(v) |> Enum.map(fn k -> {k, Map.get(v, k)} end)) end)
|> Enum.filter(fn v -> !Enum.empty?(v) end)
|> List.flatten
|> Enum.reduce(Graph.new, fn {v1, {v2, w}}, g -> Graph.add_edge(g, v1, v2, weight: String.to_integer(w)) end)
end
def can_contain(graph, bag) do
graph
|> Graph.reaching([bag])
|> Enum.filter(&(&1 != bag))
end
def contains(graph, bag) do
paths(graph, bag)
|> Enum.map(&bags/1)
|> Enum.map(&sum/1)
|> List.flatten
|> Enum.sum
end
def paths(graph, bag) do
graph
|> Graph.out_edges(bag)
|> Enum.map(fn %{v2: v, weight: w} -> {v, w} end)
|> Enum.map(fn {v, w} -> [{v, w} | paths(graph, v)] end)
end
def bags([{_, w} | paths]) do
[w | paths |> Enum.map(&bags/1)]
end
def sum([w1 | bags]) do
[w1 | bags |> Enum.map(fn [w2 | tail] -> sum([w1 * w2 | tail]) end)]
end
def solution do
IO.puts("#{from_file("day7_input.txt") |> parse |> to_graph |> can_contain("shiny gold") |> length}")
IO.puts("#{from_file("day7_input.txt") |> parse |> to_graph |> contains("shiny gold")}")
end
end
| 27.179104 | 118 | 0.55464 |
f7077b09db8796f69a6052539b1af3308998d022 | 254 | ex | Elixir | seminars/transport/lib/netw.ex | Murre3/ID1019 | 8240d07be35843610c6c14a40bcb3ed21b3ea36f | [
"MIT"
] | null | null | null | seminars/transport/lib/netw.ex | Murre3/ID1019 | 8240d07be35843610c6c14a40bcb3ed21b3ea36f | [
"MIT"
] | null | null | null | seminars/transport/lib/netw.ex | Murre3/ID1019 | 8240d07be35843610c6c14a40bcb3ed21b3ea36f | [
"MIT"
] | null | null | null | defmodule Netw do
defstruct src: 0, dst: 0, data: nil
defimpl String.Chars, for: Netw do
def to_string(%Netw{src: s, dst: d, data: msg}) do
"Netw<src: #{s}, dst: #{d}, data: " <> String.Chars.to_string(msg) <> ">"
end
end
end
| 16.933333 | 79 | 0.57874 |
f707a274a6547dea28cf52b20184bf5658229ef6 | 1,774 | ex | Elixir | clients/content/lib/google_api/content/v2/model/carriers_carrier.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/carriers_carrier.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/carriers_carrier.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Content.V2.Model.CarriersCarrier do
@moduledoc """
## Attributes
* `country` (*type:* `String.t`, *default:* `nil`) - The CLDR country code of the carrier (e.g., "US"). Always present.
* `name` (*type:* `String.t`, *default:* `nil`) - The name of the carrier (e.g., "UPS"). Always present.
* `services` (*type:* `list(String.t)`, *default:* `nil`) - A list of supported services (e.g., "ground") for that carrier. Contains at least one service.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:country => String.t(),
:name => String.t(),
:services => list(String.t())
}
field(:country)
field(:name)
field(:services, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.CarriersCarrier do
def decode(value, options) do
GoogleApi.Content.V2.Model.CarriersCarrier.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.CarriersCarrier do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.471698 | 158 | 0.697294 |
f707a480381ce019ffee852e4a08693090f3f633 | 1,266 | ex | Elixir | lib/money/currency/ecto_type.ex | stefanluptak/money | 51b4b403787f76e21b12fc162270113a6cfe6a08 | [
"MIT"
] | 350 | 2019-02-21T02:25:03.000Z | 2022-03-10T02:35:50.000Z | lib/money/currency/ecto_type.ex | stefanluptak/money | 51b4b403787f76e21b12fc162270113a6cfe6a08 | [
"MIT"
] | 68 | 2019-02-21T07:19:17.000Z | 2022-03-29T03:13:12.000Z | lib/money/currency/ecto_type.ex | stefanluptak/money | 51b4b403787f76e21b12fc162270113a6cfe6a08 | [
"MIT"
] | 70 | 2015-08-28T16:45:57.000Z | 2019-02-06T01:11:11.000Z | if Code.ensure_loaded?(Ecto.Type) do
defmodule Money.Currency.Ecto.Type do
@moduledoc """
Provides a type for Ecto to store a currency.
The underlying data type is a string.
## Migration
create table(:my_table) do
add :currency, :string
end
## Schema
schema "my_table" do
field :currency, Money.Currency.Ecto.Type
end
"""
alias Money.Currency
if macro_exported?(Ecto.Type, :__using__, 1) do
use Ecto.Type
else
@behaviour Ecto.Type
end
@spec type :: :string
def type, do: :string
@spec cast(Money.t() | String.t()) :: {:ok, atom()}
def cast(val)
def cast(%Money{currency: currency}), do: {:ok, currency}
def cast(str) when is_binary(str) do
{:ok, Currency.to_atom(str)}
rescue
_ -> :error
end
def cast(atom) when is_atom(atom) do
if Currency.exists?(atom), do: {:ok, atom}, else: :error
end
def cast(_), do: :error
@spec load(String.t()) :: {:ok, atom()}
def load(str) when is_binary(str), do: {:ok, Currency.to_atom(str)}
@spec dump(atom()) :: {:ok, String.t()}
def dump(atom) when is_atom(atom), do: {:ok, Atom.to_string(atom)}
def dump(_), do: :error
end
end
| 22.210526 | 71 | 0.587678 |
f707c109ca90aa51e95bb7cf82454a1a4a81dedd | 2,164 | ex | Elixir | lib/core/env.ex | doctorcorral/gyx | f44990f817cd2cbac01510b3c72cdc374820ac8b | [
"BSD-2-Clause"
] | 19 | 2019-02-02T02:41:12.000Z | 2021-07-05T21:14:45.000Z | lib/core/env.ex | doctorcorral/gyx | f44990f817cd2cbac01510b3c72cdc374820ac8b | [
"BSD-2-Clause"
] | 37 | 2018-11-27T06:41:07.000Z | 2022-01-28T19:39:00.000Z | lib/core/env.ex | doctorcorral/gyx | f44990f817cd2cbac01510b3c72cdc374820ac8b | [
"BSD-2-Clause"
] | 2 | 2018-11-26T22:06:18.000Z | 2019-05-02T19:13:42.000Z | defmodule Gyx.Core.Env do
@moduledoc """
This behaviour is intended to be followed for any `Environment` implementation
The most critical function to be exposed is `step/1` , which serves as a direct bridge
between the environment and any agent.
Here, an important design question to address is the fundamental difference between
the environment state (its internal representation) and an _observation_ of such state.
In principle, the environment returns an observation as part of step/1 response.
Should it be a way to obtain an evironment state abstraction as suposed to be shown
to an agent? i.e. an indirect observation.
"""
alias Gyx.Core.Exp
@type initial_state :: Exp.t()
@type observation :: any()
@type action :: any()
@type environment :: any()
@doc "Sets the state of the environment to its default"
@callback reset(environment) :: initial_state()
@doc "Gets an environment representation usable by the agent"
@callback observe(environment) :: observation()
@doc """
Recieves an agent's `action` and responds to it,
informing the agent back with a reward, a modified environment
and a termination signal
"""
@callback step(environment, action()) :: Exp.t() | {:error, reason :: String.t()}
defmacro __using__(_params) do
quote do
@before_compile Gyx.Core.Env
@behaviour Gyx.Core.Env
@enforce_keys [:action_space, :observation_space]
@impl true
def observe(environment), do: GenServer.call(environment, :observe)
@impl true
def step(environment, action) do
case action_checked = GenServer.call(environment, {:check, action}) do
{:error, _} -> action_checked
{:ok, action} -> GenServer.call(environment, {:act, action})
end
end
end
end
defmacro __before_compile__(_) do
quote do
def handle_call({:check, action}, _from, state = %__MODULE__{action_space: action_space}) do
case Gyx.Core.Spaces.contains?(action_space, action) do
false -> {:reply, {:error, "invalid_action"}, state}
_ -> {:reply, {:ok, action}, state}
end
end
end
end
end
| 33.292308 | 98 | 0.684843 |
f7084eba8538c91d539b1dc1bb488ba628458d96 | 1,368 | ex | Elixir | lib/web/controllers/profile_controller.ex | smartlogic/stein_example | 7ef369757989a9a56d04e87f6421675bf69193a2 | [
"MIT"
] | 7 | 2019-12-13T19:23:47.000Z | 2022-01-22T23:02:42.000Z | lib/web/controllers/profile_controller.ex | smartlogic/stein_example | 7ef369757989a9a56d04e87f6421675bf69193a2 | [
"MIT"
] | 11 | 2021-03-10T01:57:00.000Z | 2021-08-31T18:30:54.000Z | lib/web/controllers/profile_controller.ex | smartlogic/stein_example | 7ef369757989a9a56d04e87f6421675bf69193a2 | [
"MIT"
] | null | null | null | defmodule Web.ProfileController do
use Web, :controller
alias SteinExample.Users
def show(conn, _params) do
%{current_user: user} = conn.assigns
conn
|> assign(:user, user)
|> render("show.html")
end
def edit(conn, _params) do
%{current_user: user} = conn.assigns
conn
|> assign(:user, user)
|> assign(:changeset, Users.edit(user))
|> render("edit.html")
end
def update(conn, %{"user" => params = %{"current_password" => password}}) do
%{current_user: user} = conn.assigns
case Users.change_password(user, password, params) do
{:ok, _user} ->
conn
|> put_flash(:info, "Password updated.")
|> redirect(to: Routes.profile_path(conn, :show))
{:error, :invalid} ->
conn
|> put_flash(:error, "Could not update your password.")
|> redirect(to: Routes.profile_path(conn, :edit))
end
end
def update(conn, %{"user" => params}) do
%{current_user: user} = conn.assigns
case Users.update(user, params) do
{:ok, _user} ->
conn
|> put_flash(:info, "Profile updated")
|> redirect(to: Routes.profile_path(conn, :show))
{:error, changeset} ->
conn
|> assign(:user, user)
|> assign(:changeset, changeset)
|> put_status(422)
|> render("edit.html")
end
end
end
| 24 | 78 | 0.584064 |
f70897183c94a2fdc593bec82325566b91a3bb33 | 1,200 | ex | Elixir | lib/central/admin/tasks/delete_user_task.ex | badosu/teiserver | 19b623aeb7c2ab28756405f7486e92b714777c54 | [
"MIT"
] | 4 | 2021-07-29T16:23:20.000Z | 2022-02-23T05:34:36.000Z | lib/central/admin/tasks/delete_user_task.ex | badosu/teiserver | 19b623aeb7c2ab28756405f7486e92b714777c54 | [
"MIT"
] | 14 | 2021-08-01T02:36:14.000Z | 2022-01-30T21:15:03.000Z | lib/central/admin/tasks/delete_user_task.ex | badosu/teiserver | 19b623aeb7c2ab28756405f7486e92b714777c54 | [
"MIT"
] | 7 | 2021-05-13T12:55:28.000Z | 2022-01-14T06:39:06.000Z | defmodule Central.Admin.DeleteUserTask do
@moduledoc false
alias Central.{Account, Config, Communication, Logging}
def delete_user(userid) when is_integer(userid) do
case Account.get_user(userid) do
nil -> nil
user -> do_delete_user(user)
end
end
def delete_user(%Account.User{} = user) do
do_delete_user(user)
end
defp do_delete_user(%{id: userid} = user) do
# Reports
Account.list_reports(search: [user_id: userid])
|> Enum.each(fn report ->
Account.delete_report(report)
end)
# Group memberships
Account.list_group_memberships(user_id: userid)
|> Enum.each(fn ugm ->
Account.delete_group_membership(ugm)
end)
# Next up, configs
Config.list_user_configs(userid)
|> Enum.each(fn ugm ->
Config.delete_user_config(ugm)
end)
# Notifications
Communication.list_user_notifications(userid)
|> Enum.each(fn notification ->
Communication.delete_notification(notification)
end)
# Page view logs
Logging.list_page_view_logs(search: [user_id: userid])
|> Enum.each(fn log ->
Logging.delete_page_view_log(log)
end)
Account.delete_user(user)
end
end
| 24 | 58 | 0.683333 |
f7089a67e2bba580f4896b161d745da21e0ca3f2 | 2,984 | exs | Elixir | apps/omg_watcher_info/test/omg_watcher_info/release_tasks/set_tracer_test.exs | boolafish/elixir-omg | 46b568404972f6e4b4da3195d42d4fb622edb934 | [
"Apache-2.0"
] | null | null | null | apps/omg_watcher_info/test/omg_watcher_info/release_tasks/set_tracer_test.exs | boolafish/elixir-omg | 46b568404972f6e4b4da3195d42d4fb622edb934 | [
"Apache-2.0"
] | null | null | null | apps/omg_watcher_info/test/omg_watcher_info/release_tasks/set_tracer_test.exs | boolafish/elixir-omg | 46b568404972f6e4b4da3195d42d4fb622edb934 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019-2020 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule OMG.WatcherInfo.ReleaseTasks.SetTracerTest do
use ExUnit.Case, async: true
import ExUnit.CaptureLog, only: [capture_log: 1]
alias OMG.WatcherInfo.ReleaseTasks.SetTracer
alias OMG.WatcherInfo.Tracer
@app :omg_watcher_info
setup do
{:ok, pid} = __MODULE__.System.start_link([])
nil = Process.put(__MODULE__.System, pid)
:ok
end
test "if environment variables get applied in the configuration" do
:ok = __MODULE__.System.put_env("DD_DISABLED", "TRUE")
:ok = __MODULE__.System.put_env("APP_ENV", "YOLO")
assert capture_log(fn ->
config = SetTracer.load([], system_adapter: __MODULE__.System)
disabled = config |> Keyword.fetch!(@app) |> Keyword.fetch!(Tracer) |> Keyword.fetch!(:disabled?)
env = config |> Keyword.fetch!(@app) |> Keyword.fetch!(Tracer) |> Keyword.fetch!(:env)
assert disabled == true
# if it's disabled, env doesn't matter, so we set it to an empty string
assert env == ""
end)
end
test "if default configuration is used when there's no environment variables" do
:ok = __MODULE__.System.put_env("HOSTNAME", "this is my tracer test 3")
assert capture_log(fn ->
config = SetTracer.load([], system_adapter: __MODULE__.System)
# we set env to an empty string because disabled? is set to true!
configuration = @app |> Application.get_env(Tracer) |> Keyword.put(:env, "") |> Enum.sort()
tracer_config = config |> Keyword.get(@app) |> Keyword.get(Tracer) |> Enum.sort()
assert configuration == tracer_config
end)
end
test "if exit is thrown when faulty configuration is used" do
:ok = __MODULE__.System.put_env("DD_DISABLED", "TRUEeee")
catch_exit(SetTracer.load([], system_adapter: __MODULE__.System))
end
defmodule System do
def start_link(args), do: GenServer.start_link(__MODULE__, args, [])
def get_env(key), do: __MODULE__ |> Process.get() |> GenServer.call({:get_env, key})
def put_env(key, value), do: __MODULE__ |> Process.get() |> GenServer.call({:put_env, key, value})
def init(_), do: {:ok, %{}}
def handle_call({:get_env, key}, _, state) do
{:reply, state[key], state}
end
def handle_call({:put_env, key, value}, _, state) do
{:reply, :ok, Map.put(state, key, value)}
end
end
end
| 39.263158 | 110 | 0.668231 |
f708a1ab5e41ea8f41fc14b33c9683889241c7cb | 7,350 | ex | Elixir | lib/plug/upload.ex | rzcastilho/plug | 542870dfefb710ae9e508c345da9067d2c8c4149 | [
"Apache-2.0"
] | 1,218 | 2017-07-14T15:13:32.000Z | 2022-03-30T16:42:42.000Z | lib/plug/upload.ex | rzcastilho/plug | 542870dfefb710ae9e508c345da9067d2c8c4149 | [
"Apache-2.0"
] | 502 | 2017-07-19T15:36:44.000Z | 2022-03-31T06:47:36.000Z | lib/plug/upload.ex | rzcastilho/plug | 542870dfefb710ae9e508c345da9067d2c8c4149 | [
"Apache-2.0"
] | 376 | 2017-07-17T15:47:55.000Z | 2022-03-23T19:24:30.000Z | defmodule Plug.UploadError do
defexception [:message]
end
defmodule Plug.Upload do
@moduledoc """
A server (a `GenServer` specifically) that manages uploaded files.
Uploaded files are stored in a temporary directory
and removed from that directory after the process that
requested the file dies.
During the request, files are represented with
a `Plug.Upload` struct that contains three fields:
* `:path` - the path to the uploaded file on the filesystem
* `:content_type` - the content type of the uploaded file
* `:filename` - the filename of the uploaded file given in the request
**Note**: as mentioned in the documentation for `Plug.Parsers`, the `:plug`
application has to be started in order to upload files and use the
`Plug.Upload` module.
## Security
The `:content_type` and `:filename` fields in the `Plug.Upload` struct are
client-controlled. These values should be validated, via file content
inspection or similar, before being trusted.
"""
use GenServer
defstruct [:path, :content_type, :filename]
@type t :: %__MODULE__{
path: Path.t(),
filename: binary,
content_type: binary | nil
}
@dir_table __MODULE__.Dir
@path_table __MODULE__.Path
@max_attempts 10
@temp_env_vars ~w(PLUG_TMPDIR TMPDIR TMP TEMP)s
@doc """
Requests a random file to be created in the upload directory
with the given prefix.
"""
@spec random_file(binary) ::
{:ok, binary}
| {:too_many_attempts, binary, pos_integer}
| {:no_tmp, [binary]}
def random_file(prefix) do
case ensure_tmp() do
{:ok, tmp} ->
open_random_file(prefix, tmp, 0)
{:no_tmp, tmps} ->
{:no_tmp, tmps}
end
end
@doc """
Assign ownership of the given upload file to another process.
Useful if you want to do some work on an uploaded file in another process
since it means that the file will survive the end of the request.
"""
@spec give_away(t | binary, pid, pid) :: :ok | {:error, binary}
def give_away(upload, to_pid, from_pid \\ self())
def give_away(%__MODULE__{path: path}, to_pid, from_pid) do
give_away(path, to_pid, from_pid)
end
def give_away(path, to_pid, from_pid)
when is_binary(path) and is_pid(to_pid) and is_pid(from_pid) do
with [{^from_pid, _tmp}] <- :ets.lookup(@dir_table, from_pid),
true <- is_path_owner?(from_pid, path) do
case :ets.lookup(@dir_table, to_pid) do
[{^to_pid, _tmp}] ->
:ets.insert(@path_table, {to_pid, path})
:ets.delete_object(@path_table, {from_pid, path})
:ok
[] ->
server = plug_server()
{:ok, tmps} = GenServer.call(server, :roots)
{:ok, tmp} = generate_tmp_dir(tmps)
:ok = GenServer.call(server, {:give_away, to_pid, tmp, path})
:ets.delete_object(@path_table, {from_pid, path})
:ok
end
else
_ ->
{:error, :unknown_path}
end
end
defp ensure_tmp() do
pid = self()
case :ets.lookup(@dir_table, pid) do
[{^pid, tmp}] ->
{:ok, tmp}
[] ->
server = plug_server()
{:ok, tmps} = GenServer.call(server, {:monitor, pid})
with {:ok, tmp} <- generate_tmp_dir(tmps) do
true = :ets.insert_new(@dir_table, {pid, tmp})
{:ok, tmp}
end
end
end
defp generate_tmp_dir(tmp_roots) do
{mega, _, _} = :os.timestamp()
subdir = "/plug-" <> i(mega)
if tmp = Enum.find_value(tmp_roots, &make_tmp_dir(&1 <> subdir)) do
{:ok, tmp}
else
{:no_tmp, tmp_roots}
end
end
defp make_tmp_dir(path) do
case File.mkdir_p(path) do
:ok -> path
{:error, _} -> nil
end
end
defp open_random_file(prefix, tmp, attempts) when attempts < @max_attempts do
path = path(prefix, tmp)
case :file.write_file(path, "", [:write, :raw, :exclusive, :binary]) do
:ok ->
:ets.insert(@path_table, {self(), path})
{:ok, path}
{:error, reason} when reason in [:eexist, :eacces] ->
open_random_file(prefix, tmp, attempts + 1)
end
end
defp open_random_file(_prefix, tmp, attempts) do
{:too_many_attempts, tmp, attempts}
end
defp path(prefix, tmp) do
sec = :os.system_time(:second)
rand = :rand.uniform(999_999_999_999_999)
scheduler_id = :erlang.system_info(:scheduler_id)
tmp <> "/" <> prefix <> "-" <> i(sec) <> "-" <> i(rand) <> "-" <> i(scheduler_id)
end
defp is_path_owner?(pid, path) do
owned_paths = :ets.lookup(@path_table, pid)
Enum.any?(owned_paths, fn {_pid, p} -> p == path end)
end
@compile {:inline, i: 1}
defp i(integer), do: Integer.to_string(integer)
@doc """
Requests a random file to be created in the upload directory
with the given prefix. Raises on failure.
"""
@spec random_file!(binary) :: binary | no_return
def random_file!(prefix) do
case random_file(prefix) do
{:ok, path} ->
path
{:too_many_attempts, tmp, attempts} ->
raise Plug.UploadError,
"tried #{attempts} times to create an uploaded file at #{tmp} but failed. " <>
"Set PLUG_TMPDIR to a directory with write permission"
{:no_tmp, _tmps} ->
raise Plug.UploadError,
"could not create a tmp directory to store uploads. " <>
"Set PLUG_TMPDIR to a directory with write permission"
end
end
defp plug_server do
Process.whereis(__MODULE__) ||
raise Plug.UploadError,
"could not find process Plug.Upload. Have you started the :plug application?"
end
@doc false
def start_link(_) do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
## Callbacks
@impl true
def init(:ok) do
Process.flag(:trap_exit, true)
tmp = Enum.find_value(@temp_env_vars, "/tmp", &System.get_env/1) |> Path.expand()
cwd = Path.join(File.cwd!(), "tmp")
:ets.new(@dir_table, [:named_table, :public, :set])
:ets.new(@path_table, [:named_table, :public, :duplicate_bag])
{:ok, [tmp, cwd]}
end
@impl true
def handle_call({:monitor, pid}, _from, dirs) do
Process.monitor(pid)
{:reply, {:ok, dirs}, dirs}
end
def handle_call(:roots, _from, dirs) do
{:reply, {:ok, dirs}, dirs}
end
def handle_call({:give_away, pid, tmp, path}, _from, dirs) do
# Since we are writing in behalf of another process, we need to make sure
# the monitor and writing to the tables happen within the same operation.
Process.monitor(pid)
:ets.insert_new(@dir_table, {pid, tmp})
:ets.insert(@path_table, {pid, path})
{:reply, :ok, dirs}
end
@impl true
def handle_info({:DOWN, _ref, :process, pid, _reason}, state) do
case :ets.lookup(@dir_table, pid) do
[{pid, _tmp}] ->
:ets.delete(@dir_table, pid)
@path_table
|> :ets.lookup(pid)
|> Enum.each(&delete_path/1)
:ets.delete(@path_table, pid)
[] ->
:ok
end
{:noreply, state}
end
def handle_info(_msg, state) do
{:noreply, state}
end
@impl true
def terminate(_reason, _state) do
folder = fn entry, :ok -> delete_path(entry) end
:ets.foldl(folder, :ok, @path_table)
end
defp delete_path({_pid, path}) do
:file.delete(path)
:ok
end
end
| 26.727273 | 92 | 0.621224 |
f708a30509aa69012631b65395f261dd52fd10ba | 1,570 | ex | Elixir | clients/video_intelligence/lib/google_api/video_intelligence/v1beta1/model/google_cloud_videointelligence_v1_annotate_video_progress.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/video_intelligence/lib/google_api/video_intelligence/v1beta1/model/google_cloud_videointelligence_v1_annotate_video_progress.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/video_intelligence/lib/google_api/video_intelligence/v1beta1/model/google_cloud_videointelligence_v1_annotate_video_progress.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.VideoIntelligence.V1beta1.Model.GoogleCloudVideointelligenceV1_AnnotateVideoProgress do
@moduledoc """
Video annotation progress. Included in the `metadata` field of the `Operation` returned by the `GetOperation` call of the `google::longrunning::Operations` service.
"""
@derive [Poison.Encoder]
defstruct [
:"annotationProgress"
]
end
defimpl Poison.Decoder, for: GoogleApi.VideoIntelligence.V1beta1.Model.GoogleCloudVideointelligenceV1_AnnotateVideoProgress do
import GoogleApi.VideoIntelligence.V1beta1.Deserializer
def decode(value, options) do
value
|> deserialize(:"annotationProgress", :list, GoogleApi.VideoIntelligence.V1beta1.Model.GoogleCloudVideointelligenceV1_VideoAnnotationProgress, options)
end
end
| 40.25641 | 206 | 0.780892 |
f708a78c302e435caad6f212d1e2d3c4374da6ed | 1,437 | ex | Elixir | clients/drive_activity/lib/google_api/drive_activity/v2/model/system_event.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/drive_activity/lib/google_api/drive_activity/v2/model/system_event.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/drive_activity/lib/google_api/drive_activity/v2/model/system_event.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DriveActivity.V2.Model.SystemEvent do
@moduledoc """
Event triggered by system operations instead of end users.
## Attributes
* `type` (*type:* `String.t`, *default:* `nil`) - The type of the system event that may triggered activity.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:type => String.t()
}
field(:type)
end
defimpl Poison.Decoder, for: GoogleApi.DriveActivity.V2.Model.SystemEvent do
def decode(value, options) do
GoogleApi.DriveActivity.V2.Model.SystemEvent.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DriveActivity.V2.Model.SystemEvent do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 30.574468 | 111 | 0.736952 |
f708a97fe8615b82328b1767cf17c99fd1d2045b | 2,353 | exs | Elixir | config/prod.exs | nicohartto/headland-back | 413febe835dafc15b4dae731998ff42aa755496b | [
"MIT"
] | null | null | null | config/prod.exs | nicohartto/headland-back | 413febe835dafc15b4dae731998ff42aa755496b | [
"MIT"
] | null | null | null | config/prod.exs | nicohartto/headland-back | 413febe835dafc15b4dae731998ff42aa755496b | [
"MIT"
] | null | null | null | use Mix.Config
# For production, we configure the host to read the PORT
# from the system environment. Therefore, you will need
# to set PORT=80 before running your server.
#
# You should also configure the url host to something
# meaningful, we use this information when generating URLs.
#
# Finally, we also include the path to a manifest
# containing the digested version of static files. This
# manifest is generated by the mix phoenix.digest task
# which you typically run after static files are built.
config :headland, Headland.Endpoint,
http: [port: {:system, "PORT"}],
url: [scheme: "https", host: "polar-temple-67773.herokuapp.com", port: 443],
force_ssl: [rewrite_on: [:x_forwarded_proto]],
cache_static_manifest: "priv/static/manifest.json",
secret_key_base: System.get_env("SECRET_KEY_BASE")
# Do not print debug messages in production
config :logger, level: :info
# Configure your database
config :headland, Headland.Repo,
adapter: Ecto.Adapters.Postgres,
url: System.get_env("DATABASE_URL"),
pool_size: 20
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :headland, Headland.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :headland, Headland.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :headland, Headland.Endpoint, server: true
#
# You will also need to set the application root to `.` in order
# for the new static assets to be served after a hot upgrade:
#
# config :headland, Headland.Endpoint, root: "."
| 33.614286 | 78 | 0.715257 |
f708adcfe88e698288ad18fec3747bd70cdd7bbc | 2,443 | ex | Elixir | lib/policr_mini_bot/plugs/resp_login_cmd_plug.ex | uxh/policr-mini | bad33834a9bd6405afb241b74000cec2cb78ef21 | [
"MIT"
] | 487 | 2020-06-08T03:04:21.000Z | 2022-03-31T14:51:36.000Z | lib/policr_mini_bot/plugs/resp_login_cmd_plug.ex | uxh/policr-mini | bad33834a9bd6405afb241b74000cec2cb78ef21 | [
"MIT"
] | 141 | 2020-06-11T01:03:29.000Z | 2022-03-30T20:23:32.000Z | lib/policr_mini_bot/plugs/resp_login_cmd_plug.ex | uxh/policr-mini | bad33834a9bd6405afb241b74000cec2cb78ef21 | [
"MIT"
] | 61 | 2020-06-10T05:25:03.000Z | 2022-03-23T15:54:26.000Z | defmodule PolicrMiniBot.RespLoginCmdPlug do
@moduledoc """
登录命令。
"""
use PolicrMiniBot, plug: [commander: :login]
alias PolicrMini.Logger
alias PolicrMini.PermissionBusiness
@doc """
处理登录命令。
此命令会提示用户私聊使用,也仅限于私聊使用。
"""
def handle(%{chat: %{type: "private"}} = message, state) do
%{chat: %{id: chat_id}, from: %{id: user_id}} = message
with {:ok, :isadmin} <- check_user(user_id),
{:ok, token} <- PolicrMiniWeb.create_token(user_id) do
text = t("login.success", %{token: token})
reply_markup = make_markup(user_id, token)
case send_message(chat_id, text, reply_markup: reply_markup, parse_mode: "MarkdownV2ToHTML") do
{:ok, _} ->
{:ok, state}
e ->
Logger.unitized_error("Command response", command: "/login", returns: e)
{:error, state}
end
else
{:error, :nonadmin} ->
send_message(chat_id, t("login.non_admin"), parse_mode: "MarkdownV2ToHTML")
{:ok, state}
{:error, :notfound} ->
send_message(chat_id, t("login.not_found"), parse_mode: "MarkdownV2ToHTML")
{:ok, state}
end
end
def handle(message, state) do
%{chat: %{id: chat_id}, message_id: message_id} = message
text = t("login.only_private")
case reply_message(chat_id, message_id, text) do
{:ok, sended_message} ->
Cleaner.delete_message(chat_id, sended_message.message_id, delay_seconds: 8)
e ->
Logger.unitized_error("Command response", command: "/login", returns: e)
end
Cleaner.delete_message(chat_id, message_id)
{:ok, %{state | deleted: true}}
end
@spec make_markup(integer, String.t()) :: InlineKeyboardMarkup.t()
defp make_markup(user_id, token) do
root_url = PolicrMiniWeb.root_url(has_end_slash: false)
%InlineKeyboardMarkup{
inline_keyboard: [
[
%InlineKeyboardButton{
text: t("login.revoke_text"),
callback_data: "revoke:v1:#{user_id}"
}
],
[
%InlineKeyboardButton{
text: t("login.join_text"),
url: "#{root_url}/admin?token=#{token}"
}
]
]
}
end
@spec check_user(integer()) :: {:ok, :isadmin} | {:error, :nonadmin}
defp check_user(user_id) do
list = PermissionBusiness.find_list(user_id: user_id)
if length(list) > 0, do: {:ok, :isadmin}, else: {:error, :nonadmin}
end
end
| 26.268817 | 101 | 0.607041 |
f708b121993fc0d1300f1962bc188c47b48bea06 | 1,308 | ex | Elixir | apps/tai/lib/tai/orders/transitions/expire.ex | yurikoval/tai | 94254b45d22fa0307b01577ff7c629c7280c0295 | [
"MIT"
] | null | null | null | apps/tai/lib/tai/orders/transitions/expire.ex | yurikoval/tai | 94254b45d22fa0307b01577ff7c629c7280c0295 | [
"MIT"
] | 78 | 2020-10-12T06:21:43.000Z | 2022-03-28T09:02:00.000Z | apps/tai/lib/tai/orders/transitions/expire.ex | yurikoval/tai | 94254b45d22fa0307b01577ff7c629c7280c0295 | [
"MIT"
] | null | null | null | defmodule Tai.Orders.Transitions.Expire do
@moduledoc """
The order was not filled or partially filled and removed from the order book
"""
@type client_id :: Tai.Orders.Order.client_id()
@type venue_order_id :: Tai.Orders.Order.venue_order_id()
@type t :: %__MODULE__{
client_id: client_id,
venue_order_id: venue_order_id,
cumulative_qty: Decimal.t(),
leaves_qty: Decimal.t(),
last_received_at: integer,
last_venue_timestamp: DateTime.t() | nil
}
@enforce_keys ~w[
client_id
venue_order_id
cumulative_qty
leaves_qty
last_received_at
last_venue_timestamp
]a
defstruct ~w[
client_id
venue_order_id
cumulative_qty
leaves_qty
last_received_at
last_venue_timestamp
]a
defimpl Tai.Orders.Transition do
def required(_), do: :enqueued
def attrs(transition) do
{:ok, last_received_at} = Tai.Time.monotonic_to_date_time(transition.last_received_at)
%{
status: :expired,
venue_order_id: transition.venue_order_id,
cumulative_qty: transition.cumulative_qty,
leaves_qty: transition.leaves_qty,
last_received_at: last_received_at,
last_venue_timestamp: transition.last_venue_timestamp
}
end
end
end
| 25.647059 | 92 | 0.681193 |
f708d5c87894389924bd986c088e53e23ff50528 | 407 | exs | Elixir | mt9x9.exs | bluebat/mt9x9 | 0758ed7bba325ecc3a08a919ea7f38f6b9795306 | [
"Unlicense"
] | null | null | null | mt9x9.exs | bluebat/mt9x9 | 0758ed7bba325ecc3a08a919ea7f38f6b9795306 | [
"Unlicense"
] | null | null | null | mt9x9.exs | bluebat/mt9x9 | 0758ed7bba325ecc3a08a919ea7f38f6b9795306 | [
"Unlicense"
] | 1 | 2019-06-01T07:12:12.000Z | 2019-06-01T07:12:12.000Z | #!/usr/bin/elixir
# 9x9 multiplication table in Elixir
# CC0, Wei-Lun Chao <bluebat@member.fsf.org>, 2021.
# ./mt9x9.exs || elixir mt9x9.exs
Enum.each(Stream.take_every(1..9, 3), fn i ->
Enum.each(Enum.sort(1..9), fn j ->
Enum.each([i, i+1, i+2], fn k ->
IO.write "#{k}x#{j}=#{String.pad_leading(to_string(k*j),2)}\t"
end)
IO.write "\n"
end)
IO.puts ""
end)
| 27.133333 | 74 | 0.565111 |
f708f5e76caf7017fab6d42f4b779248215e50d6 | 207 | exs | Elixir | test/controllers/page_controller_test.exs | matsubara0507/pastry-chef-test | 05c0fc3a3864e5469690da980e7bf3d2dbdb3919 | [
"MIT"
] | 1 | 2017-09-20T23:46:35.000Z | 2017-09-20T23:46:35.000Z | test/controllers/page_controller_test.exs | matsubara0507/pastry-chef-test | 05c0fc3a3864e5469690da980e7bf3d2dbdb3919 | [
"MIT"
] | null | null | null | test/controllers/page_controller_test.exs | matsubara0507/pastry-chef-test | 05c0fc3a3864e5469690da980e7bf3d2dbdb3919 | [
"MIT"
] | null | null | null | defmodule PastryChefTest.PageControllerTest do
use PastryChefTest.ConnCase
test "GET /", %{conn: conn} do
conn = get conn, "/"
assert html_response(conn, 200) =~ "Welcome to Phoenix!"
end
end
| 23 | 60 | 0.695652 |
f7090783fbac9a76f06cc92823231421fa551947 | 7,878 | ex | Elixir | lib/codes/codes_d31.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_d31.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_d31.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_D31 do
alias IcdCode.ICDCode
def _D3100 do
%ICDCode{full_code: "D3100",
category_code: "D31",
short_code: "00",
full_name: "Benign neoplasm of unspecified conjunctiva",
short_name: "Benign neoplasm of unspecified conjunctiva",
category_name: "Benign neoplasm of unspecified conjunctiva"
}
end
def _D3101 do
%ICDCode{full_code: "D3101",
category_code: "D31",
short_code: "01",
full_name: "Benign neoplasm of right conjunctiva",
short_name: "Benign neoplasm of right conjunctiva",
category_name: "Benign neoplasm of right conjunctiva"
}
end
def _D3102 do
%ICDCode{full_code: "D3102",
category_code: "D31",
short_code: "02",
full_name: "Benign neoplasm of left conjunctiva",
short_name: "Benign neoplasm of left conjunctiva",
category_name: "Benign neoplasm of left conjunctiva"
}
end
def _D3110 do
%ICDCode{full_code: "D3110",
category_code: "D31",
short_code: "10",
full_name: "Benign neoplasm of unspecified cornea",
short_name: "Benign neoplasm of unspecified cornea",
category_name: "Benign neoplasm of unspecified cornea"
}
end
def _D3111 do
%ICDCode{full_code: "D3111",
category_code: "D31",
short_code: "11",
full_name: "Benign neoplasm of right cornea",
short_name: "Benign neoplasm of right cornea",
category_name: "Benign neoplasm of right cornea"
}
end
def _D3112 do
%ICDCode{full_code: "D3112",
category_code: "D31",
short_code: "12",
full_name: "Benign neoplasm of left cornea",
short_name: "Benign neoplasm of left cornea",
category_name: "Benign neoplasm of left cornea"
}
end
def _D3120 do
%ICDCode{full_code: "D3120",
category_code: "D31",
short_code: "20",
full_name: "Benign neoplasm of unspecified retina",
short_name: "Benign neoplasm of unspecified retina",
category_name: "Benign neoplasm of unspecified retina"
}
end
def _D3121 do
%ICDCode{full_code: "D3121",
category_code: "D31",
short_code: "21",
full_name: "Benign neoplasm of right retina",
short_name: "Benign neoplasm of right retina",
category_name: "Benign neoplasm of right retina"
}
end
def _D3122 do
%ICDCode{full_code: "D3122",
category_code: "D31",
short_code: "22",
full_name: "Benign neoplasm of left retina",
short_name: "Benign neoplasm of left retina",
category_name: "Benign neoplasm of left retina"
}
end
def _D3130 do
%ICDCode{full_code: "D3130",
category_code: "D31",
short_code: "30",
full_name: "Benign neoplasm of unspecified choroid",
short_name: "Benign neoplasm of unspecified choroid",
category_name: "Benign neoplasm of unspecified choroid"
}
end
def _D3131 do
%ICDCode{full_code: "D3131",
category_code: "D31",
short_code: "31",
full_name: "Benign neoplasm of right choroid",
short_name: "Benign neoplasm of right choroid",
category_name: "Benign neoplasm of right choroid"
}
end
def _D3132 do
%ICDCode{full_code: "D3132",
category_code: "D31",
short_code: "32",
full_name: "Benign neoplasm of left choroid",
short_name: "Benign neoplasm of left choroid",
category_name: "Benign neoplasm of left choroid"
}
end
def _D3140 do
%ICDCode{full_code: "D3140",
category_code: "D31",
short_code: "40",
full_name: "Benign neoplasm of unspecified ciliary body",
short_name: "Benign neoplasm of unspecified ciliary body",
category_name: "Benign neoplasm of unspecified ciliary body"
}
end
def _D3141 do
%ICDCode{full_code: "D3141",
category_code: "D31",
short_code: "41",
full_name: "Benign neoplasm of right ciliary body",
short_name: "Benign neoplasm of right ciliary body",
category_name: "Benign neoplasm of right ciliary body"
}
end
def _D3142 do
%ICDCode{full_code: "D3142",
category_code: "D31",
short_code: "42",
full_name: "Benign neoplasm of left ciliary body",
short_name: "Benign neoplasm of left ciliary body",
category_name: "Benign neoplasm of left ciliary body"
}
end
def _D3150 do
%ICDCode{full_code: "D3150",
category_code: "D31",
short_code: "50",
full_name: "Benign neoplasm of unspecified lacrimal gland and duct",
short_name: "Benign neoplasm of unspecified lacrimal gland and duct",
category_name: "Benign neoplasm of unspecified lacrimal gland and duct"
}
end
def _D3151 do
%ICDCode{full_code: "D3151",
category_code: "D31",
short_code: "51",
full_name: "Benign neoplasm of right lacrimal gland and duct",
short_name: "Benign neoplasm of right lacrimal gland and duct",
category_name: "Benign neoplasm of right lacrimal gland and duct"
}
end
def _D3152 do
%ICDCode{full_code: "D3152",
category_code: "D31",
short_code: "52",
full_name: "Benign neoplasm of left lacrimal gland and duct",
short_name: "Benign neoplasm of left lacrimal gland and duct",
category_name: "Benign neoplasm of left lacrimal gland and duct"
}
end
def _D3160 do
%ICDCode{full_code: "D3160",
category_code: "D31",
short_code: "60",
full_name: "Benign neoplasm of unspecified site of unspecified orbit",
short_name: "Benign neoplasm of unspecified site of unspecified orbit",
category_name: "Benign neoplasm of unspecified site of unspecified orbit"
}
end
def _D3161 do
%ICDCode{full_code: "D3161",
category_code: "D31",
short_code: "61",
full_name: "Benign neoplasm of unspecified site of right orbit",
short_name: "Benign neoplasm of unspecified site of right orbit",
category_name: "Benign neoplasm of unspecified site of right orbit"
}
end
def _D3162 do
%ICDCode{full_code: "D3162",
category_code: "D31",
short_code: "62",
full_name: "Benign neoplasm of unspecified site of left orbit",
short_name: "Benign neoplasm of unspecified site of left orbit",
category_name: "Benign neoplasm of unspecified site of left orbit"
}
end
def _D3190 do
%ICDCode{full_code: "D3190",
category_code: "D31",
short_code: "90",
full_name: "Benign neoplasm of unspecified part of unspecified eye",
short_name: "Benign neoplasm of unspecified part of unspecified eye",
category_name: "Benign neoplasm of unspecified part of unspecified eye"
}
end
def _D3191 do
%ICDCode{full_code: "D3191",
category_code: "D31",
short_code: "91",
full_name: "Benign neoplasm of unspecified part of right eye",
short_name: "Benign neoplasm of unspecified part of right eye",
category_name: "Benign neoplasm of unspecified part of right eye"
}
end
def _D3192 do
%ICDCode{full_code: "D3192",
category_code: "D31",
short_code: "92",
full_name: "Benign neoplasm of unspecified part of left eye",
short_name: "Benign neoplasm of unspecified part of left eye",
category_name: "Benign neoplasm of unspecified part of left eye"
}
end
end
| 35.327354 | 83 | 0.621351 |
f7092a0aece354bec660c312b483a441d6fe8f6f | 25,117 | ex | Elixir | lib/type_system/evaluator.ex | tpoulsen/terp | a11b2452bec7b3dd558b5b51a27b44a5b7dda009 | [
"BSD-2-Clause"
] | 23 | 2017-09-22T07:13:34.000Z | 2021-06-08T14:50:06.000Z | lib/type_system/evaluator.ex | smpoulsen/terp | a11b2452bec7b3dd558b5b51a27b44a5b7dda009 | [
"BSD-2-Clause"
] | 5 | 2017-08-26T18:40:54.000Z | 2017-09-28T00:24:50.000Z | lib/type_system/evaluator.ex | smpoulsen/terp | a11b2452bec7b3dd558b5b51a27b44a5b7dda009 | [
"BSD-2-Clause"
] | 4 | 2017-09-27T23:14:59.000Z | 2021-06-08T14:50:12.000Z | defmodule Terp.TypeSystem.Evaluator do
@moduledoc """
The primary type inference module.
"""
alias Terp.Error
alias Terp.TypeSystem.Type
alias Terp.TypeSystem.Annotation
alias Terp.TypeSystem.TypeVars
alias Terp.TypeSystem.Environment
alias Terp.TypeSystem.Match
@type scheme :: {[Type.t], Type.t}
@type type_environment :: map()
@type substitution :: %{required(Type.t) => Type.t}
@type errors :: [String.t]
@spec run_infer(RoseTree.t) :: Type.t
def run_infer(%RoseTree{} = expr) do
case TypeVars.start_link() do
{:ok, _} -> :ok
{:error, _} -> TypeVars.reset()
end
case infer(expr, %{}) do
{:ok, {_substitution, type}} ->
if expr.node == :__type do
{:ok, {null_substitution(), type}}
else
case Annotation.reconcile_annotation(expr, type) do
{:ok, annotated_type_scheme} ->
{:ok, substitute_type_vars(annotated_type_scheme)}
{:error, {:type, {:annotation, _map}}} = error ->
error
%Error{} = error ->
error
_ ->
type_scheme = generalize(%{}, type)
Environment.extend_environment(expr, type)
{:ok, substitute_type_vars(type_scheme)}
end
end
{:error, _e} = error ->
error
%Error{} = error ->
%{error | in_expression: expr}
end
end
defp format_constructor(defn) do
[constructor | vars] = defn
|> Enum.map(&(&1.node))
{constructor, vars}
end
@spec infer(RoseTree.t, type_environment) :: {substitution, Type.t}
def infer(%RoseTree{node: node, children: children} = expr, type_env) do
case node do
:__data ->
[type_constructor | [data_constructors | []]] = children
{name, vars} = format_constructor(type_constructor.node)
data_constructors = Enum.map(data_constructors.node, &format_constructor/1)
t = Type.sum_type(name, vars, data_constructors)
Environment.define_type(name, t)
{:ok, {%{}, t}}
:__type ->
[fn_name | [type_info | []]] = children
Annotation.annotate_type(fn_name, type_info.node)
x when is_integer(x) ->
{:ok, {null_substitution(), Type.int()}}
x when is_boolean(x) ->
{:ok, {null_substitution(), Type.bool()}}
:__string ->
{:ok, {null_substitution(), Type.string()}}
:"__#t" -> # Seems spurious, but probably don't need the when boolean?
{:ok, {null_substitution(), Type.bool()}}
:"__#f" ->
{:ok, {null_substitution(), Type.bool()}}
:__quote ->
{type_env, sub, types} = children
|> Enum.reduce({type_env, %{}, []},
fn (_expr, {:error, e}) -> {:error, e}
(expr, {type_env, sub1, types}) ->
case infer(expr, type_env) do
{:ok, {sub2, type}} ->
{type_env, compose(sub1, sub2), [type | types]}
error ->
error
end
end
)
unique_types = types
|> Enum.uniq()
|> Enum.group_by(&(&1.constructor == :Tvar))
case unique_types[false] do
nil ->
case unique_types[true] do
nil ->
tv = TypeVars.fresh()
{:ok, {sub, Type.list(tv)}}
[t | _ts] ->
{:ok, {sub, Type.list(t)}}
end
[t | []] ->
case unique_types[true] do
nil ->
{:ok, {sub, Type.list(t)}}
vars ->
case unify_list_types(Enum.map(vars, &{&1, t})) do
{:ok, sub} ->
{:ok, {sub, Type.list(t)}}
error ->
error
end
end
ts ->
type_strings = ts
|> Enum.map(&(to_string(&1)))
|> Enum.join(", ")
{:error, {:type, "Unable to unify list types: #{type_strings}"}}
end
:__empty? ->
tv = TypeVars.fresh()
t = build_up_arrows([Type.list(tv), Type.bool()])
{:ok, {null_substitution(), t}}
:__cons ->
tv = TypeVars.fresh()
t = build_up_arrows([tv, Type.list(tv), Type.list(tv)])
{:ok, {null_substitution(), t}}
:__car ->
tv = TypeVars.fresh()
t = build_up_arrows([Type.list(tv), tv])
{:ok, {null_substitution(), t}}
:__cdr ->
tv = TypeVars.fresh()
t = build_up_arrows([Type.list(tv), Type.list(tv)])
{:ok, {null_substitution(), t}}
:__cond ->
infer_cond(type_env, children)
:__match ->
case infer_match(type_env, children) do
%Error{} = error ->
%{error | in_expression: expr}
res ->
res
end
:__let_values ->
[%RoseTree{node: bindings} | [expr | []]] = children
{type_env, _subs} = Enum.reduce(bindings, {type_env, null_substitution()},
fn ([var | [val | []]], {type_env, subs}) ->
{:ok, {s, t}} = infer(val, type_env)
t_prime = generalize(type_env, t)
type_env = extend(type_env, {var.node, t_prime})
{type_env, compose(s, subs)}
end
)
infer(expr, type_env)
:__apply ->
[operator | operands] = children
case operator.node do
:"__+" ->
t = Type.function(Type.int(), Type.function(Type.int(), Type.int()))
infer_binary_op(type_env, t, {Enum.at(operands, 0), Enum.at(operands, 1)})
:"__-" ->
t = Type.function(Type.int(), Type.function(Type.int(), Type.int()))
infer_binary_op(type_env, t, {Enum.at(operands, 0), Enum.at(operands, 1)})
:"__*" ->
t = Type.function(Type.int(), Type.function(Type.int(), Type.int()))
infer_binary_op(type_env, t, {Enum.at(operands, 0), Enum.at(operands, 1)})
:__div ->
t = Type.function(Type.int(), Type.function(Type.int(), Type.int()))
infer_binary_op(type_env, t, {Enum.at(operands, 0), Enum.at(operands, 1)})
:__equal? ->
# Using a single type variable because equality between different types would be ill-typed
tv = TypeVars.fresh()
t = Type.function(tv, Type.function(tv, Type.bool()))
infer_binary_op(type_env, t, {Enum.at(operands, 0), Enum.at(operands, 1)})
:__car ->
[lst | []] = operands
with {:ok, {s1, car_type}} <- infer(operator, type_env),
{:ok, {s2, list_type}} <- infer(lst, type_env),
%Type{constructor: :Tlist, t: t} = list_type do
{:ok, s3} = unify(car_type, build_up_arrows([list_type, t]))
{:ok, {compose(s3, compose(s2, s1)), t}}
else
error ->
error
end
:__cdr ->
[lst | []] = operands
with {:ok, {s1, cdr_type}} <- infer(operator, type_env),
{:ok, {s2, list_type}} <- infer(lst, type_env) do
{:ok, s3} = unify(cdr_type, build_up_arrows([list_type, list_type]))
{:ok, {compose(s3, compose(s2, s1)), list_type}}
else
error ->
error
end
:__empty? ->
[lst | []] = operands
with {:ok, {s1, empty_type}} <- infer(operator, type_env),
{:ok, {s2, list_type}} <- infer(lst, type_env) do
{:ok, s3} = unify(empty_type, build_up_arrows([list_type, Type.bool()]))
{:ok, {compose(s3, compose(s2, s1)), Type.bool()}}
else
error ->
error
end
:__cons ->
[elem | [lst | []]] = operands
tv = TypeVars.fresh()
{:ok, {s1, cons_type}} = infer(operator, type_env)
infer_binary_op(type_env, cons_type, {elem, lst})
:__let ->
[name | [bound | []]] = operands
tv = TypeVars.fresh()
{s1, t1} = {null_substitution(), tv}
type_env = apply_sub(s1, type_env)
t1_prime = generalize(type_env, t1)
type_env = extend(type_env, {name.node, t1_prime})
infer(bound, type_env)
:__letrec ->
[name | [bound | []]] = operands
tv = TypeVars.fresh()
{s1, t1} = {null_substitution(), tv}
type_env = apply_sub(s1, type_env)
t1_prime = generalize(type_env, t1)
type_env = extend(type_env, {name.node, t1_prime})
with {:ok, {s1, t}} <- infer(bound, type_env) do
fn_type = apply_sub(s1, tv)
s2 = reconcile(t, fn_type)
{:ok, {s1, apply_sub(s2, t)}}
else
{:error, e} -> {:error, e}
end
:__if ->
[test | [consequent | [alternative | []]]] = operands
with {:ok, {s1, t1}} <- infer(test, type_env),
{:ok, {s2, t2}} <- infer(consequent, apply_sub(s1, type_env)),
{:ok, {s3, t3}} <- infer(alternative, apply_sub(s1, type_env)),
{:ok, s4} <- unify(t1, Type.bool()),
{:ok, s5} = unify(t2, t3) do
composed_substitution = s5
|> compose(s4)
|> compose(s3)
|> compose(s2)
|> compose(s1)
{:ok, {composed_substitution, apply_sub(s5, t2)}}
else
error -> error
end
:__lambda ->
[%RoseTree{node: :__apply, children: args} | [body | []]] = operands
# Generate a fresh type variable for each argument
type_vars = args
|> Enum.map(fn (_arg) -> TypeVars.fresh() end)
# Extend the type environment with the arguments
type_env = args
|> Enum.zip(type_vars)
|> Enum.reduce(
type_env,
fn ({arg, var}, acc) ->
extend(acc, {arg.node, generalize(type_env, var)})
end)
# Infer the type of the function body
fn_type = infer(body, type_env)
case fn_type do
{:ok, {s, t}} ->
substituted_type_vars = type_vars
|> Enum.map(&apply_sub(s, &1))
arrows = build_up_arrows((substituted_type_vars ++ List.wrap(t)))
{:ok, {s, arrows}}
{:error, e} ->
{:error, e}
%Error{} = error ->
error
end
:__apply ->
# applying a lambda
# why does this not work with infer_application/3?
tv = TypeVars.fresh()
with {:ok, {s1, t1}} <- infer(operator, type_env),
{:ok, {_type_env, {s2, ts}}} <- infer_operands(operands, apply_sub(s1, type_env)),
arrows = build_up_arrows(Enum.reverse([tv | ts])),
{:ok, s3} <- unify(apply_sub(s2, t1), arrows) do
composed_substitution = compose(s3, compose(s2, s1))
{:ok, {composed_substitution, apply_sub(s3, tv)}}
else
{:error, e} ->
{:error, e}
%Error{} = error ->
error
end
:__provide ->
# TODO filter our provide nodes
{:ok, {null_substitution(), TypeVars.fresh()}}
:__beam ->
fn_name = operator.children
|> Enum.map(&(&1.node))
|> Enum.join()
infer_application(fn_name, operands, type_env)
_ ->
infer_application(operator.node, operands, type_env)
end
_ ->
lookup(type_env, node)
end
end
@doc """
Infers function application.
"""
def infer_application(operator, operands, type_env) do
tv = TypeVars.fresh()
with {:ok, {s1, t1}} <- lookup(type_env, operator),
{:ok, {_type_env, {s2, ts}}} <- infer_operands(operands, apply_sub(s1, type_env)),
arrows = build_up_arrows(Enum.reverse([tv | ts])),
{:ok, s3} <- unify(apply_sub(s2, t1), arrows) do
composed_substitution = compose(s3, compose(s2, s1))
{:ok, {composed_substitution, apply_sub(s3, tv)}}
else
{:error, e} ->
{:error, e}
%Error{} = error ->
Error.evaluating_lens
|> Focus.over(error, fn x -> Map.put(x, :expr, operands) end)
end
end
def type_for_constructor(name) do
case Type.constructor_for_type(name) do
{:error, _e} = error -> error
%Error{} = error -> error
{:ok, t} ->
{:ok, value_constructor} = Type.value_constructor(name)
{:ok, build_up_arrows(Enum.reverse([t | value_constructor.t]))}
end
end
@spec infer_operands([RoseTree.t], type_environment, [RoseTree.t]) :: {:ok, {type_environment, [Type.t]}} | {:error, any()}
def infer_operands(operands, type_env, result_type \\ []) do
operands
|> Enum.reduce({:ok, {type_env, {%{}, result_type}}},
fn (_expr, {:error, _} = error) -> error
(_expr, %Error{} = error) -> error
(expr, {:ok, {t_env, {s1, types}}}) ->
case infer(expr, t_env) do
{:ok, {s2, type}} ->
subbed_env = apply_sub(s2, type_env)
composed_sub = compose(s1, s2)
{:ok, {subbed_env, {composed_sub, apply_sub(s2, [type | List.wrap(types)])}}}
{:error, e} ->
{:error, e}
%Error{} = error ->
error
end
end)
end
@spec infer_binary_op(type_environment, Type.t, {RoseTree.t, RoseTree.t}) :: {substitution, Type.t}
def infer_binary_op(type_env, binary_type, {arg1, arg2}) do
tv = TypeVars.fresh()
with {:ok, {s1, t1}} <- infer(arg1, type_env),
{:ok, {s2, t2}} <- infer(arg2, type_env),
inferred_op_type <- build_up_arrows([t1, t2, tv]),
{:ok, s3} <- unify(inferred_op_type, binary_type) do
composed_substitution = compose(s1, compose(s2, s3))
{:ok, {composed_substitution, apply_sub(s3, tv)}}
else
error ->
error
end
end
def infer_cond(type_env, expr) do
# This is a bit kludgy.
# Cond is ({Bool, a} -> a)
tv = TypeVars.fresh()
cond_type = Type.function(Type.tuple(Type.bool(), tv), tv)
{s, test_t, res_t} = expr
|> Enum.reduce({%{}, nil, nil},
fn (_expr, {:error, _} = e) -> e
(%RoseTree{node: [test | [res | []]]}, {subs, test_types, res_types}) ->
{:ok, {s1, t1}} = infer(test, type_env)
{:ok, {s2, t2}} = infer(res, type_env)
test_type = if test_types == nil || t1 == test_types, do: t1, else: {:error, {:bad_type, t1}}
res_type = if res_types == nil || t2 == res_types, do: t2, else: {:error, {:bad_type, t2}}
{compose(s1, compose(s2, subs)), test_type, res_type}
end)
case test_t do
{:error, {:bad_type, x}} ->
{:error, {:type, {:unification, %{expected: Type.bool(), received: x}}}}
%Type{t: :Bool} ->
case res_t do
{:error, {:bad_type, x}} ->
{:error, {:type, {:unification, %{expected: Type.bool(), received: x}}}}
%Type{} = t ->
expr_type = Type.function(Type.tuple(Type.bool(), t), t)
with {:ok, s3} <- unify(expr_type, cond_type) do
composed_substitution = compose(s3, s)
{:ok, {composed_substitution, apply_sub(s3, tv)}}
end
end
end
end
def infer_match(type_env, expr) do
[match_var | match_exprs] = expr
exhaustive = Match.exhaustive_matches?(match_exprs)
case exhaustive do
:ok ->
Match.match_type(match_var, match_exprs, type_env)
error ->
error
end
end
@spec build_up_arrows([Type.t]) :: Type.t
def build_up_arrows([type | []]), do: type
def build_up_arrows([type1 | types]) do
Type.function(type1, build_up_arrows(types))
end
def unify_list_types(types), do: unify_list_types(types, %{})
def unify_list_types([], unification), do: {:ok, unification}
def unify_list_types([{type_var, type} | types], unification) do
case unify(type_var, type) do
{:ok, unification2} ->
unify_list_types(types, compose(unification, unification2))
{:error, e} ->
{:error, e}
end
end
@spec extend(type_environment, {atom() | String.t, scheme}) :: type_environment
def extend(%{} = type_env, {var, scheme}) do
Map.put_new(type_env, var, scheme)
end
@spec restrict(type_environment, atom() | String.t) :: type_environment
def restrict(%{} = type_env, var) do
Map.drop(type_env, var)
end
@spec lookup(type_environment, atom() | String.t) ::
{:ok, scheme} | {:error, {:unbound, atom() | String.t}}
def lookup(type_environment, var) do
case Map.get(type_environment, var) do
nil ->
case type_for_constructor(var) do
{:error, _e} ->
Environment.lookup(var)
{:ok, t} ->
{:ok, {null_substitution(), t}}
end
x ->
{:ok, {null_substitution(), instantiate(x)}}
end
end
@doc """
Instantiate a type
"""
def instantiate({xs, t}) do
fresh_type_vars = xs
|> Enum.map(fn (_x) -> TypeVars.fresh() end)
xs
|> Enum.zip(fresh_type_vars)
|> Map.new()
|> apply_sub(t)
end
@doc """
Generalize a bound type
"""
@spec generalize(type_environment, Type.t) :: scheme
def generalize(type_env, type) do
xs = type
|> ftv()
|> MapSet.difference(ftv(type_env))
|> MapSet.to_list()
{xs, type}
end
## Substitutions
def null_substitution() do
Map.new()
end
@spec compose(substitution, substitution) :: substitution
def compose(sub1, sub2) do
sub2
|> Map.merge(sub1, fn _k, v1, _v2 -> v1 end)
|> Enum.map(fn {t_var, t_scheme} -> {t_var, apply_sub(sub1, t_scheme)} end)
|> Map.new()
end
@spec apply_sub(substitution, Type.t) :: Type.t
def apply_sub(_, %Type{constructor: :Tconst} = type), do: type
def apply_sub(substitution, %Type{constructor: :Tlist, t: %Type{constructor: :Tlist, t: t}}) do
# Not sure why/where the super nested lists are coming from.
# cons, I think, but haven't yet investigated.
Type.list(apply_sub(substitution, t))
end
def apply_sub(substitution, %Type{constructor: :Tlist, t: t}) do
Type.list(apply_sub(substitution, t))
end
def apply_sub(substitution, %Type{constructor: :Tvar, t: t} = type) do
Map.get(substitution, t, type)
end
def apply_sub(substitution, %Type{constructor: :Ttuple, t: {t1, t2}}) do
Type.tuple(apply_sub(substitution, t1), apply_sub(substitution, t2))
end
def apply_sub(substitution, %Type{constructor: :Tarrow, t: {t1, t2}}) do
Type.function(apply_sub(substitution, t1), apply_sub(substitution, t2))
end
def apply_sub(substitution, %Type{t: ts} = type) when is_list(ts) do
updated_ts = Enum.map(ts, &apply_sub(substitution, &1))
updated_vars = Enum.map(type.vars,
fn var ->
case Map.get(substitution, var) do
nil -> var
type -> to_string(type)
end
end)
%{type | t: updated_ts, vars: updated_vars}
end
def apply_sub(substitution, {as, t} = _type_scheme) do
substitution_prime = as
|> Enum.reduce(substitution, fn (type_var, new_sub) ->
Map.delete(new_sub, type_var) end
)
t_prime = apply_sub(substitution_prime, t)
{as, t_prime}
end
def apply_sub(substitution, xs) when is_list(xs) do
Enum.map(xs, &apply_sub(substitution, &1))
end
def apply_sub(substitution, %{} = type_env) do
type_env
|> Enum.map(fn {k, v} -> {k, apply_sub(substitution, v)} end)
|> Map.new()
end
@doc """
Query free type variables.
"""
@spec ftv(Type.t | scheme | [Type.t] | type_environment) :: MapSet.t
def ftv(%Type{constructor: :Tconst}), do: MapSet.new()
def ftv(%Type{constructor: :Tlist, t: t}), do: ftv(t)
def ftv(%Type{constructor: :Ttuple, t: {t1, t2}}) do
MapSet.union(ftv(t1), ftv(t2))
end
def ftv(%Type{constructor: :Tvar} = type), do: MapSet.new([type])
def ftv(%Type{constructor: :Tarrow, t: {t1, t2}}) do
MapSet.union(ftv(t1), ftv(t2))
end
def ftv(%Type{t: ts}) when is_list(ts) do
# ADTs; t consists of a list of constructors.
ts
|> Enum.map(&ftv/1)
|> Enum.reduce(MapSet.new(), fn (t, acc) -> MapSet.union(t, acc) end)
end
def ftv({as, type}) do
MapSet.difference(ftv(type), MapSet.new(as))
end
def ftv(xs) when is_list(xs) do
Enum.reduce(xs, MapSet.new(), fn (x, acc) -> MapSet.union(ftv(x), acc) end)
end
def ftv(%{} = type_env) do
type_env
|> Map.values()
|> ftv()
end
## Type unification
@spec unify(Type.t, Type.t) :: {substitution, Type.t}
def unify(%Type{constructor: :Tvar, t: a}, type), do: bind(a, type)
def unify(type, %Type{constructor: :Tvar, t: a}), do: bind(a, type)
def unify(%Type{constructor: :Tconst, t: a}, %Type{constructor: :Tconst, t: a}) do
{:ok, null_substitution()}
end
def unify(%Type{constructor: :Tlist, t: t1}, %Type{constructor: :Tlist, t: t2}) do
unify(t1, t2)
end
def unify(%Type{constructor: :Ttuple, t: {l1, r1}}, %Type{constructor: :Ttuple, t: {l2, r2}}) do
with {:ok, s1} <- unify(l1, l2),
{:ok, s2} <- unify(apply_sub(s1, r1), apply_sub(s1, r2)) do
{:ok, compose(s2, s1)}
else
{:error, e} ->
{:error, e}
end
end
def unify(%Type{constructor: :Tarrow, t: {l1, r1}}, %Type{constructor: :Tarrow, t: {l2, r2}}) do
with {:ok, s1} <- unify(l1, l2),
{:ok, s2} <- unify(apply_sub(s1, r1), apply_sub(s1, r2)) do
{:ok, compose(s2, s1)}
else
error ->
error
end
end
def unify(%Type{type_constructor: c, vars: v1}, %Type{type_constructor: c, vars: v2})
when is_list(v1) and is_list(v2) do
v1_types = Enum.map(v1, &Type.to_type/1)
v2_types = Enum.map(v2, &Type.to_type/1)
Enum.reduce(Enum.zip(v1_types, v2_types), {:ok, %{}},
fn (_, {:error, _e} = error) -> error
({t1, t2}, {:ok, subs}) ->
case unify(t1, t2) do
{:ok, s} ->
{:ok, compose(s, subs)}
e -> e
end
end)
end
def unify(t1, t2) do
%Error{kind: :type,
type: :unification,
message: "Unable to unify types",
evaluating: %{expected: t1, actual: t2}}
end
@spec bind(Type.t, Type.t) :: {:ok, substitution} | {:error, {:type, String.t}}
def bind(a, type) do
cond do
a == type.t -> {:ok, null_substitution()}
occurs_check(a, type) -> {:error, {:type, "Unable to construct infinite type"}}
true -> {:ok, %{a => type}}
end
end
def occurs_check(a, type) do
MapSet.member?(ftv(type), a)
end
@doc """
Reconcile arrows with the inferred type of a function.
This is kind of a hack to unify/reconcile higher order functions.
The returned type of the higher order function wasn't correctly
unifying with the overall types inferred for the function.
"""
def reconcile(t1, t2, substitution \\ %{})
def reconcile(%Type{t: {l1, r1}}, %Type{t: {l2, r2}}, substitution) do
s2 = case unify(r2, r1) do
{:ok, s} ->
s
{:error, _e} ->
%{}
s ->
s
end
reconcile(l1, l2, Map.merge(substitution, s2, fn _k, v1, _v2 -> v1 end))
end
def reconcile(_, _, substitution), do: substitution
@doc """
Goes through and replaces type variables with fresh ones (after
resetting TypeVars state).
## Examples
iex> {[%Type{constructor: :Tvar, t: :b], %Type{constructor: :Tvar, t: :b}
...> |> substitute_type_vars()
{[%Type{constructor: :Tvar, t: :a}], %Type{constructor: :Tvar, t: :a}}
"""
def substitute_type_vars({vars, type}) do
TypeVars.reset()
fresh_vars = for _var <- vars, do: TypeVars.finalize()
zipped = Enum.zip(vars, fresh_vars)
updated_type = Enum.reduce(zipped, type, fn (var, type) -> substitute_type_var(type, var) end)
{fresh_vars, updated_type}
end
defp substitute_type_var(%Type{constructor: :Tvar, t: t} = type, {old_var, new_var}) do
if t == old_var.t, do: new_var, else: type
end
defp substitute_type_var(%Type{constructor: :Tlist, t: t} = type, vars) do
subbed_t = substitute_type_var(t, vars)
%{type | t: subbed_t}
end
defp substitute_type_var(%Type{constructor: :Ttuple, t: {t1, t2}} = type, vars) do
subbed_t1 = substitute_type_var(t1, vars)
subbed_t2 = substitute_type_var(t2, vars)
%{type | t: {subbed_t1, subbed_t2}}
end
defp substitute_type_var(%Type{constructor: :Tarrow, t: {t1, t2}} = type, vars) do
subbed_t1 = substitute_type_var(t1, vars)
subbed_t2 = substitute_type_var(t2, vars)
%{type | t: {subbed_t1, subbed_t2}}
end
defp substitute_type_var(%Type{t: ts} = type, vars) when is_list(ts) do
Type.replace_type_var(type, {to_string(elem(vars, 0)), to_string(elem(vars, 1))})
end
defp substitute_type_var(type, _vars), do: type
end
| 35.62695 | 125 | 0.547597 |
f7092e1731a1c11c0225cd887444c8f7f2fc79e8 | 742 | ex | Elixir | lib/multipster_web/controllers/account_controller.ex | adamniedzielski/multipster | 1abf95d545ab8d6bac3f26e0cfb632e2ba69c7d7 | [
"MIT"
] | 2 | 2018-01-24T08:31:09.000Z | 2019-04-14T11:06:02.000Z | lib/multipster_web/controllers/account_controller.ex | adamniedzielski/multipster | 1abf95d545ab8d6bac3f26e0cfb632e2ba69c7d7 | [
"MIT"
] | 5 | 2017-12-20T16:51:06.000Z | 2017-12-28T13:54:08.000Z | lib/multipster_web/controllers/account_controller.ex | adamniedzielski/multipster | 1abf95d545ab8d6bac3f26e0cfb632e2ba69c7d7 | [
"MIT"
] | null | null | null | defmodule MultipsterWeb.AccountController do
use MultipsterWeb, :controller
alias Multipster.Repo
alias Multipster.User
alias MultipsterWeb.SignIn.Link
def new(conn, _params) do
changeset = User.changeset(%User{}, %{})
render(conn, "new.html", changeset: changeset)
end
def create(conn, %{"user" => user_params}) do
changeset = User.changeset(%User{}, user_params)
case Repo.insert(changeset) do
{:ok, user} ->
Link.send_to_user(user)
conn
|> put_flash(:info, "Account created successfully. Please check your mailbox.")
|> redirect(to: sign_in_link_path(conn, :new))
{:error, changeset} ->
render(conn, "new.html", changeset: changeset)
end
end
end
| 26.5 | 87 | 0.661725 |
f709392d63a23368986aa0dd9019b44f7e86c86b | 4,637 | ex | Elixir | lib/scenic/primitive/style/style.ex | bruceme/scenic | bd8a1e63c122c44cc263e1fb5dfab2547ce8ef43 | [
"Apache-2.0"
] | null | null | null | lib/scenic/primitive/style/style.ex | bruceme/scenic | bd8a1e63c122c44cc263e1fb5dfab2547ce8ef43 | [
"Apache-2.0"
] | null | null | null | lib/scenic/primitive/style/style.ex | bruceme/scenic | bd8a1e63c122c44cc263e1fb5dfab2547ce8ef43 | [
"Apache-2.0"
] | null | null | null | #
# Created by Boyd Multerer on 2017-05-06.
# Copyright © 2017-2021 Kry10 Limited. All rights reserved.
#
defmodule Scenic.Primitive.Style do
@moduledoc """
Modify the look of a primitive by applying a Style.
Styles are optional modifiers that you can put on any primitive. Each style does a
specific thing and some only affect certain primitives.
```elixir
Graph.build()
|> rect( {100, 50}, fill: blue, stroke: {2, :yellow} )
```
The above example draws a rectangle, that is filled with blue and outlined in yellow.
The primitive is `Scenic.Primitive.Rectangle` and the styles are `:fill` and `:stroke`.
### Inheritance
Styles are inherited by primitives that are placed in a group. This allows you to set
styles that will be used by many primitives. Those primitives can override the style
set on the group by setting it again.
Example:
```elixir
Graph.build( font: :roboto, font_size: 24 )
|> text( "Some text drawn using roboto" )
|> text( "Text using roboto_mono", font: :roboto_mono )
|> text( "back to drawing in roboto" )
```
In the above example, the text primitives inherit the fonts set on the root group
when the Graph is created. The middle text primitive overrides the `:font` style,
but keeps using the `:font_size` set on the group.
### Components
In general, styles are NOT inherited across a component boundary unless they are
explicitly set on the component itself. This allows components to manage their own
consistent look and feel.
The exception to this rule is the `:theme` style. This IS inherited across groups
and into components. This allows you to set an overall color scheme such as
`:light` or `:dark` that makes sense with the components.
"""
alias Scenic.Primitive.Style
# import IEx
@type t :: %{
[
:cap
| :fill
| :font
| :font_size
| :hidden
| :input
| :join
| :line_height
| :miter_limit
| :scissor
| :stroke
| :text_align
| :text_base
| :theme
] => any
}
@opts_map %{
:cap => Style.Cap,
:fill => Style.Fill,
:font => Style.Font,
:font_size => Style.FontSize,
:hidden => Style.Hidden,
:input => Style.Input,
:join => Style.Join,
:line_height => Style.LineHeight,
:miter_limit => Style.MiterLimit,
:scissor => Style.Scissor,
:stroke => Style.Stroke,
:text_align => Style.TextAlign,
:text_base => Style.TextBase,
:theme => Style.Theme
}
@valid_styles @opts_map
|> Enum.map(fn {k, _v} -> k end)
|> Enum.sort()
@opts_schema [
cap: [type: {:custom, Style.Cap, :validate, []}],
fill: [type: {:custom, Style.Fill, :validate, []}],
font: [type: {:custom, Style.Font, :validate, []}],
font_size: [type: {:custom, Style.FontSize, :validate, []}],
hidden: [type: {:custom, Style.Hidden, :validate, []}],
input: [type: {:custom, Style.Input, :validate, []}],
join: [type: {:custom, Style.Join, :validate, []}],
line_height: [type: {:custom, Style.LineHeight, :validate, []}],
miter_limit: [type: {:custom, Style.MiterLimit, :validate, []}],
scissor: [type: {:custom, Style.Scissor, :validate, []}],
stroke: [type: {:custom, Style.Stroke, :validate, []}],
text_align: [type: {:custom, Style.TextAlign, :validate, []}],
text_base: [type: {:custom, Style.TextBase, :validate, []}],
theme: [type: {:custom, Style.Theme, :validate, []}]
]
@callback validate(data :: any) :: {:ok, data :: any} | {:error, String.t()}
@doc false
def opts_map(), do: @opts_map
@doc false
def opts_schema(), do: @opts_schema
@doc "List of the valid style types"
def valid_styles(), do: @valid_styles
# --------------------------------------------------------
@default_styles %{
font: :roboto,
font_size: 24,
text_align: :left,
text_base: :alphabetic,
line_height: 1.2
}
@doc """
The default styles if none are set.
```elixir
#{inspect(@default_styles)}
```
"""
def default(), do: @default_styles
# ===========================================================================
# defmodule FormatError do
# defexception message: nil, module: nil, data: nil
# end
# ===========================================================================
# defmacro __using__([type_code: type_code]) when is_integer(type_code) do
defmacro __using__(_opts) do
quote do
@behaviour Scenic.Primitive.Style
end
end
end
| 30.11039 | 89 | 0.592625 |
f70957d39343e0fbd2a6bcea5778b900d2fef03e | 398 | ex | Elixir | lib/exshome/datatype/string.ex | exshome/exshome | ef6b7a89f11dcd2016856dd49517b74aeebb6513 | [
"MIT"
] | 2 | 2021-12-21T16:32:56.000Z | 2022-02-22T17:06:39.000Z | lib/exshome/datatype/string.ex | exshome/exshome | ef6b7a89f11dcd2016856dd49517b74aeebb6513 | [
"MIT"
] | null | null | null | lib/exshome/datatype/string.ex | exshome/exshome | ef6b7a89f11dcd2016856dd49517b74aeebb6513 | [
"MIT"
] | null | null | null | defmodule Exshome.DataType.String do
@moduledoc """
String datatype.
"""
use Exshome.DataType
@impl Ecto.Type
def type, do: :string
@impl Ecto.Type
def cast(data) when is_binary(data), do: {:ok, data}
def cast(_), do: :error
@impl Ecto.Type
def dump(term) when is_binary(term), do: {:ok, term}
@impl Ecto.Type
def load(term) when is_binary(term), do: {:ok, term}
end
| 18.952381 | 54 | 0.658291 |
f7095db4c9cba90e3ff07dde7e40ac24bd8785df | 1,139 | exs | Elixir | config/config.exs | staring-frog/cth_readable | ca924c8c0de3107b086f51e6683bdbac84f8c270 | [
"BSD-3-Clause"
] | null | null | null | config/config.exs | staring-frog/cth_readable | ca924c8c0de3107b086f51e6683bdbac84f8c270 | [
"BSD-3-Clause"
] | null | null | null | config/config.exs | staring-frog/cth_readable | ca924c8c0de3107b086f51e6683bdbac84f8c270 | [
"BSD-3-Clause"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# third-party users, it should be done in your "mix.exs" file.
# You can configure your application as:
#
# config :cth_readable, key: :value
#
# and access this configuration in your application as:
#
# Application.get_env(:cth_readable, :key)
#
# You can also configure a third-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env()}.exs"
| 36.741935 | 73 | 0.753292 |
f7097861df284421e4e40474447b1835ed34331f | 1,309 | ex | Elixir | lib/alchemetrics/backends/console_backend.ex | panoramix360/alchemetrics | 7aa973bf951d5b892311831d46285a45cda0cee4 | [
"MIT"
] | 32 | 2017-07-06T13:40:00.000Z | 2021-10-17T23:56:17.000Z | lib/alchemetrics/backends/console_backend.ex | panoramix360/alchemetrics | 7aa973bf951d5b892311831d46285a45cda0cee4 | [
"MIT"
] | 20 | 2017-07-06T14:05:33.000Z | 2021-12-02T01:04:31.000Z | lib/alchemetrics/backends/console_backend.ex | panoramix360/alchemetrics | 7aa973bf951d5b892311831d46285a45cda0cee4 | [
"MIT"
] | 6 | 2017-07-06T14:45:38.000Z | 2021-10-08T12:27:49.000Z | defmodule Alchemetrics.ConsoleBackend do
use Alchemetrics.CustomBackend
@moduledoc """
Backend to print the datasets measurements on the console.
## Using it with IEx
```elixir
iex(1)> Alchemetrics.ConsoleBackend.enable
:ok
Starting Elixir.Alchemetrics.ConsoleBackend with following options: []
iex(2)> Alchemetrics.increment(:my_metric)
:ok
iex(3)> Alchemetrics.increment(:my_metric)
:ok
iex(4)> Alchemetrics.increment(:my_metric)
:ok
iex(5)> %{datapoint: :last_interval, name: :my_metric, options: [], value: 3}
%{datapoint: :total, name: :my_metric, options: [], value: 3}
```
## Starting on application boot
To start `Alchemetrics.ConsoleBackend` at application boot, just add it to the `:backends` config option. Start up parameters are set in `opts` option.
```elixir
# on config/config.exs
config :alchemetrics, backends: [
{Alchemetrics.ConsoleBackend, []}
]
```
"""
def init(options) do
IO.puts "Starting #{__MODULE__} with following options: #{inspect options}"
{:ok, options}
end
def report(metadata, datapoint, value, options) do
metadata = Enum.into(metadata, %{})
base_report = %{datapoint: datapoint, value: value, options: options}
IO.inspect Map.merge(base_report, metadata)
{:ok, options}
end
end
| 27.851064 | 153 | 0.698243 |
f7098fb06347661c34908912c3ba561cffbd680e | 5,112 | exs | Elixir | test/absinthe/schema/sdl_render_test.exs | tristan-secord/absinthe | 8bde654ea5b10b1386fc363d6d6ba015f979a938 | [
"MIT"
] | 1 | 2020-08-12T12:34:40.000Z | 2020-08-12T12:34:40.000Z | test/absinthe/schema/sdl_render_test.exs | tristan-secord/absinthe | 8bde654ea5b10b1386fc363d6d6ba015f979a938 | [
"MIT"
] | null | null | null | test/absinthe/schema/sdl_render_test.exs | tristan-secord/absinthe | 8bde654ea5b10b1386fc363d6d6ba015f979a938 | [
"MIT"
] | null | null | null | defmodule SdlRenderTest do
use ExUnit.Case
defmodule SdlTestSchema do
use Absinthe.Schema
alias Absinthe.Blueprint.Schema
@sdl """
schema {
query: Query
}
directive @foo(name: String!) on OBJECT | SCALAR
interface Animal {
legCount: Int!
}
\"""
A submitted post
Multiline description
\"""
type Post {
old: String @deprecated(reason: \"""
It's old
Really old
\""")
sweet: SweetScalar
"Something"
title: String!
}
input ComplexInput {
foo: String
}
scalar SweetScalar
type Query {
echo(
category: Category!
"The number of times"
times: Int = 10
): [Category!]!
posts: Post
search(limit: Int, sort: SorterInput!): [SearchResult]
defaultBooleanArg(boolean: Boolean = false): String
defaultInputArg(input: ComplexInput = {foo: "bar"}): String
defaultListArg(things: [String] = ["ThisThing"]): [String]
defaultEnumArg(category: Category = NEWS): Category
animal: Animal
}
type Dog implements Pet & Animal {
legCount: Int!
name: String!
}
"Simple description"
enum Category {
"Just the facts"
NEWS
\"""
What some rando thinks
Take with a grain of salt
\"""
OPINION
CLASSIFIED
}
interface Pet {
name: String!
}
"One or the other"
union SearchResult = Post | User
"Sort this thing"
input SorterInput {
"By this field"
field: String!
}
type User {
name: String!
}
"""
import_sdl @sdl
def sdl, do: @sdl
def hydrate(%Schema.InterfaceTypeDefinition{identifier: :animal}, _) do
{:resolve_type, &__MODULE__.resolve_type/1}
end
def hydrate(%{identifier: :pet}, _) do
{:resolve_type, &__MODULE__.resolve_type/1}
end
def hydrate(_node, _ancestors), do: []
def resolve_type(_), do: false
end
test "Render SDL from blueprint defined with SDL" do
assert Absinthe.Schema.to_sdl(SdlTestSchema) ==
SdlTestSchema.sdl()
end
describe "Render SDL" do
test "for a type" do
assert_rendered("""
type Person implements Entity {
name: String!
baz: Int
}
""")
end
test "for an interface" do
assert_rendered("""
interface Entity {
name: String!
}
""")
end
test "for an input" do
assert_rendered("""
"Description for Profile"
input Profile {
"Description for name"
name: String!
}
""")
end
test "for a union" do
assert_rendered("""
union Foo = Bar | Baz
""")
end
test "for a scalar" do
assert_rendered("""
scalar MyGreatScalar
""")
end
test "for a directive" do
assert_rendered("""
directive @foo(name: String!) on OBJECT | SCALAR
""")
end
test "for a schema declaration" do
assert_rendered("""
schema {
query: Query
}
""")
end
end
defp assert_rendered(sdl) do
rendered_sdl =
with {:ok, %{input: doc}} <- Absinthe.Phase.Parse.run(sdl),
%Absinthe.Language.Document{definitions: [node]} <- doc,
blueprint = Absinthe.Blueprint.Draft.convert(node, doc) do
Inspect.inspect(blueprint, %Inspect.Opts{pretty: true})
end
assert sdl == rendered_sdl
end
defmodule MacroTestSchema do
use Absinthe.Schema
query do
field :echo, :string do
arg :times, :integer, default_value: 10, description: "The number of times"
arg :time_interval, :integer
end
field :search, :search_result
end
enum :order_status do
value :delivered
value :processing
value :picking
end
object :order do
field :id, :id
field :name, :string
field :status, :order_status
import_fields :imported_fields
end
object :category do
field :name, :string
end
union :search_result do
types [:order, :category]
end
object :imported_fields do
field :imported, non_null(:boolean)
end
end
test "Render SDL from blueprint defined with macros" do
assert Absinthe.Schema.to_sdl(MacroTestSchema) ==
"""
schema {
query: RootQueryType
}
type RootQueryType {
echo(
"The number of times"
times: Int
timeInterval: Int
): String
search: SearchResult
}
type Category {
name: String
}
union SearchResult = Order | Category
enum OrderStatus {
DELIVERED
PROCESSING
PICKING
}
type Order {
imported: Boolean!
id: ID
name: String
status: OrderStatus
}
"""
end
end
| 19.813953 | 83 | 0.545383 |
f7099b3d53a560bb28b2effef6cbe84c3fb8aa52 | 963 | exs | Elixir | run-length-encoding/rle.exs | mauricius/exercism-elixir | c6babb343f9f024a84cfa8328c6adf7a8aa504a5 | [
"MIT"
] | null | null | null | run-length-encoding/rle.exs | mauricius/exercism-elixir | c6babb343f9f024a84cfa8328c6adf7a8aa504a5 | [
"MIT"
] | null | null | null | run-length-encoding/rle.exs | mauricius/exercism-elixir | c6babb343f9f024a84cfa8328c6adf7a8aa504a5 | [
"MIT"
] | null | null | null | defmodule RunLengthEncoder do
@doc """
Generates a string where consecutive elements are represented as a data value and count.
"AABBBCCCC" => "2A3B4C"
For this example, assume all input are strings, that are all uppercase letters.
It should also be able to reconstruct the data into its original form.
"2A3B4C" => "AABBBCCCC"
"""
@spec encode(String.t()) :: String.t()
def encode(string) do
Regex.scan(~r/([a-zA-Z\s])\1*/, string)
|> Enum.map_join(fn [run, c] ->
times = String.length(run)
if times == 1 do
c
else
"#{times}#{c}"
end
end)
end
@spec decode(String.t()) :: String.t()
def decode(string) do
# The char that comes after one or more digits
Regex.scan(~r/(\d*)(.)/, string)
|> Enum.map_join(fn [_, n, c] ->
times =
if n == "" do
1
else
String.to_integer(n)
end
String.duplicate(c, times)
end)
end
end | 25.342105 | 90 | 0.583593 |
f709bfd5acb44f0e16c9810772ef55fc76947844 | 478 | ex | Elixir | lib/bike_brigade_web/views/error_view.ex | bikebrigade/dispatch | eb622fe4f6dab7c917d678d3d7a322a01f97da44 | [
"Apache-2.0"
] | 28 | 2021-10-11T01:53:53.000Z | 2022-03-24T17:45:55.000Z | lib/bike_brigade_web/views/error_view.ex | bikebrigade/dispatch | eb622fe4f6dab7c917d678d3d7a322a01f97da44 | [
"Apache-2.0"
] | 20 | 2021-10-21T08:12:31.000Z | 2022-03-31T13:35:53.000Z | lib/bike_brigade_web/views/error_view.ex | bikebrigade/dispatch | eb622fe4f6dab7c917d678d3d7a322a01f97da44 | [
"Apache-2.0"
] | null | null | null | defmodule BikeBrigadeWeb.ErrorView do
use BikeBrigadeWeb, :view
def render("403.html", %{reason: %BikeBrigadeWeb.DeliveryExpiredError{}}) do
"This delivery is now over. Thank you for riding with The Bike Brigade!"
end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| 31.866667 | 78 | 0.753138 |
f709c0eae15eae702cb26cad02bb9c7cc66e2a45 | 904 | exs | Elixir | mix.exs | RobinDaugherty/gh_webhook_plug | c8561be5303ca8cb12ec6102cf4a5a7b3f971906 | [
"MIT"
] | 1 | 2017-10-04T15:03:59.000Z | 2017-10-04T15:03:59.000Z | mix.exs | RobinDaugherty/github_webhook_authentication_plug | c8561be5303ca8cb12ec6102cf4a5a7b3f971906 | [
"MIT"
] | null | null | null | mix.exs | RobinDaugherty/github_webhook_authentication_plug | c8561be5303ca8cb12ec6102cf4a5a7b3f971906 | [
"MIT"
] | null | null | null | defmodule GithubWebhookAuthenticationPlug.Mixfile do
use Mix.Project
def project do
[
app: :github_webhook_authentication_plug,
version: "0.0.3",
elixir: "~> 1.1",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
]
end
def application do
[
applications: [:plug, :logger],
]
end
defp deps do
[
{:plug, "~>1.1"},
]
end
defp description do
"""
This Plug makes it easy to authenticate Github webhook requests
in your Elixir apps.
"""
end
defp package do
[
files: ["lib", "mix.exs", "README.md"],
maintainers: ["Robin Daugherty", "Emil Soman"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/RobinDaugherty/github_webhook_authentication_plug"},
]
end
end
| 20.088889 | 99 | 0.590708 |
f709d36071f6421de87c59726a555b0131c6c1b3 | 4,850 | ex | Elixir | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/client.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/client.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/client.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.AdExchangeBuyer.V2beta1.Model.Client do
@moduledoc """
A client resource represents a client buyer&mdash;an agency, a brand, or an advertiser customer of the sponsor buyer. Users associated with the client buyer have restricted access to the Ad Exchange Marketplace and certain other sections of the Ad Exchange Buyer UI based on the role granted to the client buyer. All fields are required unless otherwise specified.
## Attributes
- clientAccountId (String.t): The globally-unique numerical ID of the client. The value of this field is ignored in create and update operations. Defaults to: `null`.
- clientName (String.t): Name used to represent this client to publishers. You may have multiple clients that map to the same entity, but for each client the combination of `clientName` and entity must be unique. You can specify this field as empty. Defaults to: `null`.
- entityId (String.t): Numerical identifier of the client entity. The entity can be an advertiser, a brand, or an agency. This identifier is unique among all the entities with the same type. A list of all known advertisers with their identifiers is available in the [advertisers.txt](https://storage.googleapis.com/adx-rtb-dictionaries/advertisers.txt) file. A list of all known brands with their identifiers is available in the [brands.txt](https://storage.googleapis.com/adx-rtb-dictionaries/brands.txt) file. A list of all known agencies with their identifiers is available in the [agencies.txt](https://storage.googleapis.com/adx-rtb-dictionaries/agencies.txt) file. Defaults to: `null`.
- entityName (String.t): The name of the entity. This field is automatically fetched based on the type and ID. The value of this field is ignored in create and update operations. Defaults to: `null`.
- entityType (String.t): The type of the client entity: `ADVERTISER`, `BRAND`, or `AGENCY`. Defaults to: `null`.
- Enum - one of [ENTITY_TYPE_UNSPECIFIED, ADVERTISER, BRAND, AGENCY]
- partnerClientId (String.t): Optional arbitrary unique identifier of this client buyer from the standpoint of its Ad Exchange sponsor buyer. This field can be used to associate a client buyer with the identifier in the namespace of its sponsor buyer, lookup client buyers by that identifier and verify whether an Ad Exchange counterpart of a given client buyer already exists. If present, must be unique among all the client buyers for its Ad Exchange sponsor buyer. Defaults to: `null`.
- role (String.t): The role which is assigned to the client buyer. Each role implies a set of permissions granted to the client. Must be one of `CLIENT_DEAL_VIEWER`, `CLIENT_DEAL_NEGOTIATOR` or `CLIENT_DEAL_APPROVER`. Defaults to: `null`.
- Enum - one of [CLIENT_ROLE_UNSPECIFIED, CLIENT_DEAL_VIEWER, CLIENT_DEAL_NEGOTIATOR, CLIENT_DEAL_APPROVER]
- status (String.t): The status of the client buyer. Defaults to: `null`.
- Enum - one of [CLIENT_STATUS_UNSPECIFIED, DISABLED, ACTIVE]
- visibleToSeller (boolean()): Whether the client buyer will be visible to sellers. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:clientAccountId => any(),
:clientName => any(),
:entityId => any(),
:entityName => any(),
:entityType => any(),
:partnerClientId => any(),
:role => any(),
:status => any(),
:visibleToSeller => any()
}
field(:clientAccountId)
field(:clientName)
field(:entityId)
field(:entityName)
field(:entityType)
field(:partnerClientId)
field(:role)
field(:status)
field(:visibleToSeller)
end
defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.Client do
def decode(value, options) do
GoogleApi.AdExchangeBuyer.V2beta1.Model.Client.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.Client do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 64.666667 | 696 | 0.745773 |
f709e2d6ca28aa96a0d2fe221a2037916b8e6fd7 | 11,525 | exs | Elixir | test/test_helper.exs | FarmBot/farmbot_os | 5ebdca3afd672eb6b0af5c71cfca02488b32569a | [
"MIT"
] | 843 | 2016-10-05T23:46:05.000Z | 2022-03-14T04:31:55.000Z | test/test_helper.exs | FarmBot/farmbot_os | 5ebdca3afd672eb6b0af5c71cfca02488b32569a | [
"MIT"
] | 455 | 2016-10-15T08:49:16.000Z | 2022-03-15T12:23:04.000Z | test/test_helper.exs | FarmBot/farmbot_os | 5ebdca3afd672eb6b0af5c71cfca02488b32569a | [
"MIT"
] | 261 | 2016-10-10T04:37:06.000Z | 2022-03-13T21:07:38.000Z | Application.ensure_all_started(:mimic)
Application.ensure_all_started(:farmbot)
defmodule Helpers do
alias FarmbotCore.Asset.{Repo, Point}
@wait_time 180
@fake_jwt "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhZ" <>
"G1pbkBhZG1pbi5jb20iLCJpYXQiOjE1MDIxMjcxMTcsImp0a" <>
"SI6IjlhZjY2NzJmLTY5NmEtNDhlMy04ODVkLWJiZjEyZDlhY" <>
"ThjMiIsImlzcyI6Ii8vbG9jYWxob3N0OjMwMDAiLCJleHAiO" <>
"jE1MDU1ODMxMTcsIm1xdHQiOiJsb2NhbGhvc3QiLCJvc191c" <>
"GRhdGVfc2VydmVyIjoiaHR0cHM6Ly9hcGkuZ2l0aHViLmNvb" <>
"S9yZXBvcy9mYXJtYm90L2Zhcm1ib3Rfb3MvcmVsZWFzZXMvb" <>
"GF0ZXN0IiwiZndfdXBkYXRlX3NlcnZlciI6Imh0dHBzOi8vY" <>
"XBpLmdpdGh1Yi5jb20vcmVwb3MvRmFybUJvdC9mYXJtYm90L" <>
"WFyZHVpbm8tZmlybXdhcmUvcmVsZWFzZXMvbGF0ZXN0IiwiY" <>
"m90IjoiZGV2aWNlXzE1In0.XidSeTKp01ngtkHzKD_zklMVr" <>
"9ZUHX-U_VDlwCSmNA8ahOHxkwCtx8a3o_McBWvOYZN8RRzQV" <>
"LlHJugHq1Vvw2KiUktK_1ABQ4-RuwxOyOBqqc11-6H_GbkM8" <>
"dyzqRaWDnpTqHzkHGxanoWVTTgGx2i_MZLr8FPZ8prnRdwC1" <>
"x9zZ6xY7BtMPtHW0ddvMtXU8ZVF4CWJwKSaM0Q2pTxI9GRqr" <>
"p5Y8UjaKufif7bBPOUbkEHLNOiaux4MQr-OWAC8TrYMyFHzt" <>
"eXTEVkqw7rved84ogw6EKBSFCVqwRA-NKWLpPMV_q7fRwiEG" <>
"Wj7R-KZqRweALXuvCLF765E6-ENxA"
@pub_key "-----BEGIN PUBLIC KEY-----\n" <>
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqi880lw9oeNp60qx5Oow\n" <>
"9czLrvExJSGO6Yic7G+dvoqea9gLT3Xf0x4Iy4TmUfnFT2cJ1I79o/JS6WmfMVdr\n" <>
"5Z0TaoVWYe9T01+kv6xWY+hENZTemAyCxSyPD7n6BgQYjXVoKSrdIuAoawtozQG+\n" <>
"5KrS+KnRI70kVO2hgz1NXiEXuHF2Za4umCBONXBdpBSXVq1G5mpF6JURqu7oaTmE\n" <>
"QNCmXfsJXE2srVwEshg80sb5rRtuoQAF7lAGZ3khV7DzKear5You9BWYNsl6etJZ\n" <>
"lOSiNeGsDyUEocSIJ9Mn+y8jphJICbBADoKXO3ZkznnJRtLSE5cuh9KVL99LUWAk\n" <>
"+wIDAQAB\n" <>
"-----END PUBLIC KEY-----\n" <>
""
@priv_key "-----BEGIN RSA PRIVATE KEY-----\n" <>
"MIIEpAIBAAKCAQEAqi880lw9oeNp60qx5Oow9czLrvExJSGO6Yic7G+dvoqea9gL\n" <>
"T3Xf0x4Iy4TmUfnFT2cJ1I79o/JS6WmfMVdr5Z0TaoVWYe9T01+kv6xWY+hENZTe\n" <>
"mAyCxSyPD7n6BgQYjXVoKSrdIuAoawtozQG+5KrS+KnRI70kVO2hgz1NXiEXuHF2\n" <>
"Za4umCBONXBdpBSXVq1G5mpF6JURqu7oaTmEQNCmXfsJXE2srVwEshg80sb5rRtu\n" <>
"oQAF7lAGZ3khV7DzKear5You9BWYNsl6etJZlOSiNeGsDyUEocSIJ9Mn+y8jphJI\n" <>
"CbBADoKXO3ZkznnJRtLSE5cuh9KVL99LUWAk+wIDAQABAoIBAFczFQsEUGAe0irJ\n" <>
"fxU4GhYX9VWSKAhKhZuLcDyFhGIZTMsdS85PK3xVK1R8qDbgsATbWuIa0kOq6mjG\n" <>
"wdbaYGKqdURjRbuwkVcA7r13ZFyUqj56JQPrhSXaiwMX29AxURNKUTCm0eAI0yzm\n" <>
"D7DbcCBilu7qtEqHo5IQoG1Kf9X2cFYr7ikY8cx0E90RUTZ+P2RCuWskGEKxbUWJ\n" <>
"epB2BwvxBAJrCSvt3DoXYWNkuxXo32SepqACyqyFPgWImvlz+5CACwrP8fXAhaut\n" <>
"QbULN+4ltLnl7JQgKKMrGaKOGxvSwLFge9HyNg8ggdIkIjatxOJXLNNLyNgt6fNL\n" <>
"FuICNSECgYEA4VRl4P3kFcAAIxdlDm0zm5bzegFTidr9QY9r1akzGIKGmT4uOAKX\n" <>
"vWxQuR2R7LhYXeDW67BIkeYDZd+PW+eH6oVzb2W4MAggu6FeQgCa+uwnp6En13LE\n" <>
"AX7NdH37h4SmbK4ssQQbb6S5oCuOzBKCVQCPlIRbEnk7MjluZBJfYnUCgYEAwVlP\n" <>
"KBNL466T+8gKh5mQCXuV1bGKtYlbT/pnmNlz7gfXVPkj+UaBslOmDthEVbGvL4gY\n" <>
"4T0vhP4VmIz8VqLw+jcCSezv0DjQVXYzZ8l+mNzHkacnnytM4VLQEYQnPB827Mo1\n" <>
"FF2SjrfciQSyxxg+HOhHVUPovKvExsLtm8tzm68CgYEAl8o25x2hLFWuwfTcip9d\n" <>
"iI5jbei+0brHqAZpagEU/onPCiQtFmYIuf3hUxJsXr7AKF1x6ktSV5ZO661x8UNC\n" <>
"9+T2IjCvpwuSoVLPID8wJ6A2BmI1aJlTGH7HAJZtfpkJU2Txjj1qDgc1VISDKU2+\n" <>
"pmw+TJnsj8FC805k4tzNjJECgYEAsDI+A2xKTStLqjgq+FWFwE6CReHsYPDSaLjt\n" <>
"7YnErtcwcTw1fzW0fZjjDEYjR+CLoAoreh8zDcQqVAGu9xi3951nlYy5IgyUNj1o\n" <>
"LR2fI5iWuXIVlmR0RCYefMfspUpg2DqRUoTPSQXekHLapLq/58H5N4eSMVVrFiKP\n" <>
"O9mU+fsCgYALD10wthhtfYIMvcTaZ0rAF+X0chBvQzj1YaPbEf0YSocLysotcBjT\n" <>
"M1m91bRjjR9vBhrg5RDOz3RCIlJ3ipkaE+cfxyUs0+AXwIXIPs2hVJNFRT8d7Z4e\n" <>
"boWHfxAwHFqoEYzskZCdPArDzshm2bFetCh6Cpw7HsWdtS18X8M8+g==\n" <>
"-----END RSA PRIVATE KEY-----\n" <>
""
def priv_key(), do: @priv_key
def pub_key(), do: @pub_key
def fake_jwt(), do: @fake_jwt
defmacro fake_jwt_object() do
quote do
FarmbotExt.JWT.decode!(unquote(@fake_jwt))
end
end
defmacro use_fake_jwt() do
quote do
cb = fn :string, "authorization", "token" ->
Helpers.fake_jwt()
end
expect(FarmbotCore.Config, :get_config_value, 1, cb)
end
end
defmacro expect_log(msg) do
quote do
expect(FarmbotCore.LogExecutor, :execute, 1, fn log ->
assert log.message =~ unquote(msg)
end)
end
end
defmacro expect_logs(strings) do
log_count = Enum.count(strings)
quote do
expect(FarmbotCore.LogExecutor, :execute, unquote(log_count), fn log ->
assert Enum.member?(unquote(strings), log.message)
end)
end
end
# Base case: We have a pid
def wait_for(pid) when is_pid(pid), do: check_on_mbox(pid)
# Failure case: We failed to find a pid for a module.
def wait_for(nil), do: raise("Attempted to wait on bad module/pid")
# Edge case: We have a module and need to try finding its pid.
def wait_for(mod), do: wait_for(Process.whereis(mod))
# Enter recursive loop
defp check_on_mbox(pid) do
Process.sleep(@wait_time)
wait(pid, Process.info(pid, :message_queue_len))
end
# Exit recursive loop (mbox is clear)
defp wait(_, {:message_queue_len, 0}), do: Process.sleep(@wait_time * 3)
# Exit recursive loop (pid is dead)
defp wait(_, nil), do: Process.sleep(@wait_time * 3)
# Continue recursive loop
defp wait(pid, {:message_queue_len, _n}), do: check_on_mbox(pid)
def delete_all_points(), do: Repo.delete_all(Point)
def create_point(%{id: id} = params) do
%Point{
id: id,
name: "point #{id}",
meta: %{},
plant_stage: "planted",
created_at: ~U[2222-12-10 02:22:22.222222Z],
pointer_type: "Plant",
pullout_direction: 2,
radius: 10.0,
tool_id: nil,
discarded_at: nil,
gantry_mounted: false,
x: 0.0,
y: 0.0,
z: 0.0
}
|> Map.merge(params)
|> Point.changeset()
|> Repo.insert!()
end
end
# Use this to stub out calls to `state.reset.reset()` in firmware.
defmodule StubReset do
def reset(), do: :ok
end
defmodule NoOp do
use GenServer
def new(opts \\ []) do
{:ok, pid} = start_link(opts)
pid
end
def stop(pid) do
_ = Process.unlink(pid)
:ok = GenServer.stop(pid, :normal, 3_000)
end
def last_message(pid) do
:sys.get_state(pid)
end
def start_link(opts) do
GenServer.start_link(__MODULE__, [], opts)
end
def init([]) do
{:ok, :no_message_yet}
end
def handle_info(next_message, _last_message) do
{:noreply, next_message}
end
end
defmodule SimpleCounter do
def new(starting_value \\ 0) do
Agent.start_link(fn -> starting_value end)
end
def get_count(pid) do
Agent.get(pid, fn count -> count end)
end
def incr(pid, by \\ 1) do
Agent.update(pid, fn count -> count + by end)
pid
end
# Increment the counter by one and get the current count.
def bump(pid, by \\ 1) do
pid |> incr(by) |> get_count()
end
end
defmodule Farmbot.TestSupport.AssetFixtures do
alias FarmbotCore.Asset.{
Device,
FarmEvent,
Regimen,
RegimenInstance,
Repo,
Sequence
}
def regimen_instance(regimen_params, farm_event_params, params \\ %{}) do
regimen = regimen(regimen_params)
farm_event = regimen_event(regimen, farm_event_params)
params = Map.merge(%{id: :rand.uniform(10000), monitor: false}, params)
RegimenInstance.changeset(%RegimenInstance{}, params)
|> Ecto.Changeset.put_assoc(:regimen, regimen)
|> Ecto.Changeset.put_assoc(:farm_event, farm_event)
|> Repo.insert!()
end
def sequence(params \\ %{}) do
default = %{
id: :rand.uniform(10000),
monitor: false,
kind: "sequence",
args: %{locals: %{kind: "scope_declaration", args: %{}}},
body: []
}
Sequence
|> struct()
|> Sequence.changeset(Map.merge(default, params))
|> Repo.insert!()
end
def regimen(params \\ %{}) do
default = %{id: :rand.uniform(10000), monitor: false, regimen_items: []}
Regimen
|> struct()
|> Regimen.changeset(Map.merge(default, params))
|> Repo.insert!()
end
def regimen_event(regimen, params \\ %{}) do
now = DateTime.utc_now()
params =
Map.merge(
%{
id: :rand.uniform(1_000_000),
monitor: false,
executable_type: "Regimen",
executable_id: regimen.id,
start_time: now,
end_time: now,
repeat: 0,
time_unit: "never"
},
params
)
FarmEvent
|> struct()
|> FarmEvent.changeset(params)
|> Repo.insert!()
end
@doc """
Instantiates, but does not create, a %Device{}
"""
def device_init(params \\ %{}) do
defaults = %{id: :rand.uniform(1_000_000), monitor: false}
params = Map.merge(defaults, params)
Device
|> struct()
|> Device.changeset(params)
|> Ecto.Changeset.apply_changes()
end
end
timeout = System.get_env("EXUNIT_TIMEOUT") || "5000"
System.put_env("LOG_SILENCE", "true")
ExUnit.configure(
max_cases: 1,
assert_receive_timeout: String.to_integer(timeout)
)
[
Circuits.UART,
Ecto.Changeset,
ExTTY,
FarmbotCore.Asset,
FarmbotCore.Asset.Command,
FarmbotCore.Asset.Device,
FarmbotCore.Asset.FbosConfig,
FarmbotCore.Asset.FirmwareConfig,
FarmbotCore.Asset.Private,
FarmbotCore.Asset.Repo,
FarmbotCore.BotState,
FarmbotCore.Celery,
FarmbotCore.Celery.Compiler.Lua,
FarmbotCore.Celery.Scheduler,
FarmbotCore.Celery.SpecialValue,
FarmbotCore.Celery.SysCallGlue,
FarmbotCore.Celery.SysCallGlue.Stubs,
FarmbotCore.Config,
FarmbotCore.FarmwareRuntime,
FarmbotCore.Firmware.Avrdude,
FarmbotCore.Firmware.Command,
FarmbotCore.Firmware.ConfigUploader,
FarmbotCore.Firmware.Flash,
FarmbotCore.Firmware.FlashUtils,
FarmbotCore.Firmware.Resetter,
FarmbotCore.Firmware.TxBuffer,
FarmbotCore.Firmware.UARTCore,
FarmbotCore.Firmware.UARTCoreSupport,
FarmbotCore.Firmware.UARTDetector,
FarmbotCore.FirmwareEstopTimer,
FarmbotCore.Leds,
FarmbotCore.LogExecutor,
FarmbotCore.Logger,
FarmbotExt.API,
FarmbotExt.API.Reconciler,
FarmbotExt.API.SyncGroup,
FarmbotExt.APIFetcher,
FarmbotExt.Bootstrap.Authorization,
FarmbotExt.Bootstrap.DropPasswordSupport,
FarmbotExt.EagerLoader.Supervisor,
FarmbotExt.MQTT,
FarmbotExt.MQTT.LogHandlerSupport,
FarmbotExt.MQTT.Support,
FarmbotExt.MQTT.SyncHandlerSupport,
FarmbotExt.MQTT.TerminalHandlerSupport,
FarmbotExt.MQTT.TopicSupervisor,
FarmbotExt.Time,
FarmbotOS.Configurator.ConfigDataLayer,
FarmbotOS.Configurator.DetsTelemetryLayer,
FarmbotOS.Configurator.FakeNetworkLayer,
FarmbotOS.HTTP,
FarmbotOS.Lua.DataManipulation,
FarmbotOS.Lua.Firmware,
FarmbotOS.Lua.Info,
FarmbotOS.SysCalls,
FarmbotOS.SysCalls.ChangeOwnership.Support,
FarmbotOS.SysCalls.Farmware,
FarmbotOS.SysCalls.Movement,
FarmbotOS.SysCalls.ResourceUpdate,
FarmbotOS.UpdateSupport,
FarmbotTelemetry,
File,
MuonTrap,
System,
Timex,
Tortoise
]
|> Enum.map(&Mimic.copy/1)
ExUnit.start()
| 31.317935 | 85 | 0.686941 |
f70a735a2b5376c8c2244a3c841ad33a2fe4dbf6 | 2,272 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_environment_test_cases_config.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_environment_test_cases_config.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_environment_test_cases_config.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3EnvironmentTestCasesConfig do
@moduledoc """
The configuration for continuous tests.
## Attributes
* `enableContinuousRun` (*type:* `boolean()`, *default:* `nil`) - Whether to run test cases in TestCasesConfig.test_cases periodically. Default false. If set to ture, run once a day.
* `enablePredeploymentRun` (*type:* `boolean()`, *default:* `nil`) - Whether to run test cases in TestCasesConfig.test_cases before deploying a flow version to the environment. Default false.
* `testCases` (*type:* `list(String.t)`, *default:* `nil`) - A list of test case names to run. They should be under the same agent. Format of each test case name: `projects//locations/ /agents//testCases/`
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:enableContinuousRun => boolean() | nil,
:enablePredeploymentRun => boolean() | nil,
:testCases => list(String.t()) | nil
}
field(:enableContinuousRun)
field(:enablePredeploymentRun)
field(:testCases, type: :list)
end
defimpl Poison.Decoder,
for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3EnvironmentTestCasesConfig do
def decode(value, options) do
GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3EnvironmentTestCasesConfig.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3EnvironmentTestCasesConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.172414 | 209 | 0.739877 |
f70a7ad188c2ef651699214898ff697eda2731cc | 1,124 | ex | Elixir | lib/ex_money/saltedge/account.ex | van-mronov/ex_money | 39010f02fd822657e3b5694e08b872bd2ab72c26 | [
"0BSD"
] | 184 | 2015-11-23T20:51:50.000Z | 2022-03-30T01:01:39.000Z | lib/ex_money/saltedge/account.ex | van-mronov/ex_money | 39010f02fd822657e3b5694e08b872bd2ab72c26 | [
"0BSD"
] | 15 | 2015-11-26T16:00:20.000Z | 2018-05-25T20:13:39.000Z | lib/ex_money/saltedge/account.ex | van-mronov/ex_money | 39010f02fd822657e3b5694e08b872bd2ab72c26 | [
"0BSD"
] | 21 | 2015-11-26T21:34:40.000Z | 2022-03-26T02:56:42.000Z | defmodule ExMoney.Saltedge.Account do
require Logger
alias ExMoney.{Account, Repo}
def sync(user_id, saltedge_login_id) do
endpoint = "accounts?login_id=#{saltedge_login_id}"
case ExMoney.Saltedge.Client.request(:get, endpoint) do
{:ok, response} ->
Enum.each response["data"], fn(se_account) ->
account = se_account
|> Map.put("saltedge_account_id", se_account["id"])
|> Map.put("saltedge_login_id", se_account["login_id"])
|> Map.put("user_id", user_id)
|> Map.drop(["id", "login_id"])
existing_account = Account.by_saltedge_account_id(account["saltedge_account_id"])
|> Repo.one
persist!(existing_account, account)
end
{:error, reason} ->
Logger.error("Could not sync accounts due to -> #{inspect(reason)}")
end
end
defp persist!(nil, account_params) do
Account.changeset(%Account{}, account_params) |> Repo.insert!
end
defp persist!(existing_account, account_params) do
Account.update_saltedge_changeset(existing_account, account_params) |> Repo.update!
end
end
| 32.114286 | 91 | 0.658363 |
f70a844002638ad888fe0fb3415497da25704d6c | 713 | ex | Elixir | web/gettext.ex | robinsonj/ptdb | a804b3eabd1026342089be6ed951642ee0a74dcb | [
"MIT"
] | null | null | null | web/gettext.ex | robinsonj/ptdb | a804b3eabd1026342089be6ed951642ee0a74dcb | [
"MIT"
] | null | null | null | web/gettext.ex | robinsonj/ptdb | a804b3eabd1026342089be6ed951642ee0a74dcb | [
"MIT"
] | null | null | null | defmodule PokeTeamDb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import PokeTeamDb.Gettext
# Simple translation
gettext "Here is the string to translate"
# Plural translation
ngettext "Here is the string to translate",
"Here are the strings to translate",
3
# Domain-based translation
dgettext "errors", "Here is the error message to translate"
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :poke_team_db
end
| 28.52 | 72 | 0.683029 |
f70a8605230b6737e697fafdb9a0b32eee667bf8 | 826 | ex | Elixir | lib/elm/ecto/name.ex | HenkPoley/ellie | 045212b56142341fc95b79659c3ca218b0d5d282 | [
"BSD-3-Clause"
] | 377 | 2018-04-05T03:36:00.000Z | 2022-03-30T19:12:44.000Z | lib/elm/ecto/name.ex | HenkPoley/ellie | 045212b56142341fc95b79659c3ca218b0d5d282 | [
"BSD-3-Clause"
] | 91 | 2018-05-24T21:56:06.000Z | 2022-02-26T03:54:04.000Z | lib/elm/ecto/name.ex | HenkPoley/ellie | 045212b56142341fc95b79659c3ca218b0d5d282 | [
"BSD-3-Clause"
] | 34 | 2018-05-29T03:54:35.000Z | 2022-01-13T07:12:46.000Z | defmodule Elm.Ecto.Name do
alias Elm.Name
@behaviour Ecto.Type
def up do
Ecto.Migration.execute("""
do $$ begin
if not exists (select 1 from pg_type where typname = 'elm_name') then
create type elm_name as (
username varchar(255),
project varchar(255)
);
end if;
end $$;
""")
end
def down do
Ecto.Migration.execute("drop type if exists elm_name;")
end
def type, do: :elm_name
def cast(%Name{} = name), do: {:ok, name}
def cast(_), do: :error
def load({user, project}) when is_binary(user) and is_binary(project) do
{:ok, %Name{user: user, project: project}}
end
def load(_), do: :error
def dump(%Name{user: user, project: project}) do
{:ok, {user, project}}
end
def dump(_), do: :error
end
| 20.65 | 77 | 0.588378 |