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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f78589cc33a85377598a201d157f296abafd617d | 123 | exs | Elixir | config/prod.exs | bryanhuntesl/ex_bench_runner | b669f13e1777ad51308b5d0a2b265a294339bd3c | [
"Apache-2.0"
] | 2 | 2020-04-25T09:05:49.000Z | 2020-04-29T03:56:38.000Z | config/prod.exs | bryanhuntesl/ex_bench_runner | b669f13e1777ad51308b5d0a2b265a294339bd3c | [
"Apache-2.0"
] | 1 | 2020-01-27T07:57:33.000Z | 2020-01-27T07:57:33.000Z | config/prod.exs | bryanhuntesl/ex_bench_runner | b669f13e1777ad51308b5d0a2b265a294339bd3c | [
"Apache-2.0"
] | null | null | null | use Mix.Config
config :logger,
backends: [:console],
compile_time_purge_matching: [
[level_lower_than: :info]
]
| 15.375 | 32 | 0.699187 |
f786350c6d6b9cb2bf290a04555d01b6b22edccf | 15,576 | ex | Elixir | lib/kaffy_web/controllers/order_controller.ex | functionaryco/komos_admin | 20e0c3d302c5dd8ac72da795f6073d496e327d52 | [
"MIT"
] | 1 | 2021-02-10T09:47:21.000Z | 2021-02-10T09:47:21.000Z | lib/kaffy_web/controllers/order_controller.ex | functionaryco/komos_admin | 20e0c3d302c5dd8ac72da795f6073d496e327d52 | [
"MIT"
] | null | null | null | lib/kaffy_web/controllers/order_controller.ex | functionaryco/komos_admin | 20e0c3d302c5dd8ac72da795f6073d496e327d52 | [
"MIT"
] | null | null | null | defmodule KaffyWeb.OrderController do
use Phoenix.Controller, namespace: KaffyWeb
use Phoenix.HTML
alias Kaffy.Pagination
def new(conn, %{"context" => context, "resource" => resource}) do
my_resource = Kaffy.Utils.get_resource(conn, context, resource)
resource_name = Kaffy.ResourceAdmin.singular_name(my_resource)
case can_proceed?(my_resource, conn) do
false ->
unauthorized_access(conn)
true ->
changeset = Kaffy.ResourceAdmin.create_changeset(my_resource, %{}) |> Map.put(:errors, [])
render(conn, "show.html",
layout: {KaffyWeb.LayoutView, "app.html"},
changeset: changeset,
context: context,
resource: resource,
resource_name: resource_name,
my_resource: my_resource
)
end
end
def add_to_cart(
conn,
%{"context" => context, "id" => order_id, "resource" => "order_item" = resource} = params
) do
my_resource = Kaffy.Utils.get_resource(conn, context, resource)
order_item_params = Map.put(params["order_item"], "order_id", order_id)
params = Map.put(params, "order_item", order_item_params)
params = Kaffy.ResourceParams.decode_map_fields("order_item", my_resource[:schema], params)
changes = Map.get(params, "order_item", %{})
case can_proceed?(my_resource, conn) do
false ->
unauthorized_access(conn)
true ->
case Kaffy.ResourceCallbacks.add_to_cart(conn, my_resource, changes) do
{:ok, _entry} ->
put_flash(conn, :success, "Item added to cart successfully")
|> redirect(
to: Kaffy.Utils.router().kaffy_order_path(conn, :cart, context, "order", order_id)
)
{:error, %Ecto.Changeset{} = _changeset} ->
redirect(conn,
to: Kaffy.Utils.router().kaffy_order_path(conn, :cart, context, "order", order_id)
)
# render(conn, "cart.html",
# layout: {KaffyWeb.LayoutView, "app.html"},
# cart_changeset: changeset,
# context: context,
# resource: resource,
# resource_name: "order",
# my_resource: my_resource
# )
end
end
end
def clear_cart(conn, %{"context" => context, "id" => order_id, "resource" => "order" = resource}) do
my_resource = Kaffy.Utils.get_resource(conn, context, resource)
conn = Plug.Conn.assign(conn, :order_id, order_id)
Kaffy.ResourceAdmin.clear_cart(conn, my_resource, :ok)
redirect(conn,
to: Kaffy.Utils.router().kaffy_resource_path(conn, :new, context, resource)
)
end
def cart(conn, %{
"context" => context,
"resource" => "order" = resource,
"order_id" => id
}) do
my_resource = Kaffy.Utils.get_resource(conn, context, resource)
schema = my_resource[:schema]
resource_name = Kaffy.ResourceAdmin.singular_name(my_resource)
cart_resource = Kaffy.Utils.get_resource(conn, context, "order_item")
variant_resource = Kaffy.Utils.get_resource(conn, "product", "variant")
{_filtered_count, items_list} = Kaffy.ResourceQuery.list_resource(conn, cart_resource, %{})
cart_changeset =
Kaffy.ResourceAdmin.create_changeset(cart_resource, %{}) |> Map.put(:errors, [])
{_filtered_count, variants_list} =
Kaffy.ResourceQuery.list_resource(conn, variant_resource, %{})
case can_proceed?(my_resource, conn) do
false ->
unauthorized_access(conn)
true ->
if entry = Kaffy.ResourceQuery.fetch_resource(conn, my_resource, id) do
changeset = Ecto.Changeset.change(entry)
render(conn, "cart.html",
layout: {KaffyWeb.LayoutView, "app.html"},
changeset: changeset,
context: context,
resource: resource,
my_resource: my_resource,
resource_name: resource_name,
schema: schema,
entry: entry,
cart_resource: cart_resource,
items: items_list,
variants: variants_list,
cart_changeset: cart_changeset
)
else
put_flash(conn, :error, "The resource you are trying to visit does not exist!")
|> redirect(
to: Kaffy.Utils.router().kaffy_resource_path(conn, :index, context, resource)
)
end
end
end
def new_address(conn, %{"context" => context, "resource" => resource, "order_id" => order_id}) do
my_resource = Kaffy.Utils.get_resource(conn, context, resource)
resource_name = Kaffy.ResourceAdmin.singular_name(my_resource)
case can_proceed?(my_resource, conn) do
false ->
unauthorized_access(conn)
true ->
changeset = Kaffy.ResourceAdmin.create_changeset(my_resource, %{}) |> Map.put(:errors, [])
render(conn, "new_address.html",
layout: {KaffyWeb.LayoutView, "app.html"},
changeset: changeset,
context: context,
resource: resource,
resource_name: resource_name,
my_resource: my_resource,
order_id: order_id
)
end
end
def create_address(
conn,
%{"context" => context, "resource" => resource, "order_id" => order_id} = params
) do
my_resource = Kaffy.Utils.get_resource(conn, context, resource)
params = Kaffy.ResourceParams.decode_map_fields(resource, my_resource[:schema], params)
changes = Map.get(params, resource, %{})
resource_name = Kaffy.ResourceAdmin.singular_name(my_resource)
case can_proceed?(my_resource, conn) do
false ->
unauthorized_access(conn)
true ->
case Kaffy.ResourceCallbacks.create_callbacks(conn, my_resource, changes) do
{:ok, _entry} ->
case Map.get(params, "submit", "Save") do
"Save" ->
put_flash(conn, :success, "Created a new #{resource_name} successfully")
|> redirect(
to:
Kaffy.Utils.router().kaffy_order_path(
conn,
:order_customer,
"order",
"order",
order_id
)
)
end
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new_address.html",
layout: {KaffyWeb.LayoutView, "app.html"},
changeset: changeset,
context: context,
resource: resource,
resource_name: resource_name,
my_resource: my_resource,
order_id: order_id
)
{:error, {entry, error}} when is_binary(error) ->
changeset = Ecto.Changeset.change(entry)
conn
|> put_flash(:error, error)
|> render("new_address.html",
layout: {KaffyWeb.LayoutView, "app.html"},
changeset: changeset,
context: context,
resource: resource,
resource_name: resource_name,
my_resource: my_resource,
order_id: order_id
)
end
end
end
def order_customer(conn, %{
"context" => context,
"resource" => "order" = resource,
"order_id" => id
}) do
my_resource = Kaffy.Utils.get_resource(conn, context, resource)
schema = my_resource[:schema]
resource_name = Kaffy.ResourceAdmin.singular_name(my_resource)
customer_resource = Kaffy.Utils.get_resource(conn, "account", "user")
address_resource = Kaffy.Utils.get_resource(conn, "account", "address")
{_filtered_count, customers_list} =
Kaffy.ResourceQuery.list_resource(conn, customer_resource, %{})
{_filtered_count, address_list} =
Kaffy.ResourceQuery.list_resource(conn, address_resource, %{})
case can_proceed?(my_resource, conn) do
false ->
unauthorized_access(conn)
true ->
if entry = Kaffy.ResourceQuery.fetch_resource(conn, my_resource, id) do
changeset = Ecto.Changeset.change(entry)
render(conn, "order_customer.html",
layout: {KaffyWeb.LayoutView, "app.html"},
changeset: changeset,
context: context,
resource: resource,
my_resource: my_resource,
resource_name: resource_name,
customer_resource: customer_resource,
schema: schema,
entry: entry,
users: customers_list,
address_resource: address_resource,
address_list: address_list
)
else
put_flash(conn, :error, "The resource you are trying to visit does not exist!")
|> redirect(
to: Kaffy.Utils.router().kaffy_resource_path(conn, :index, context, resource)
)
end
end
end
def adjustments(conn, %{
"context" => context,
"resource" => "order" = resource,
"order_id" => id
}) do
my_resource = Kaffy.Utils.get_resource(conn, context, resource)
schema = my_resource[:schema]
resource_name = Kaffy.ResourceAdmin.singular_name(my_resource)
adjustments_resource = Kaffy.Utils.get_resource(conn, "calculation", "adjustment")
{_filtered_count, adjustments_list} =
Kaffy.ResourceQuery.list_resource(conn, adjustments_resource, %{})
case can_proceed?(my_resource, conn) do
false ->
unauthorized_access(conn)
true ->
if entry = Kaffy.ResourceQuery.fetch_resource(conn, my_resource, id) do
render(conn, "adjustments_index.html",
layout: {KaffyWeb.LayoutView, "app.html"},
context: context,
resource: resource,
my_resource: my_resource,
resource_name: resource_name,
schema: schema,
entry: entry,
adjustments: adjustments_list,
order_id: id
)
else
put_flash(conn, :error, "The resource you are trying to visit does not exist!")
|> redirect(
to: Kaffy.Utils.router().kaffy_resource_path(conn, :index, context, resource)
)
end
end
end
def payments(conn, %{
"context" => context,
"resource" => "payment" = resource,
"order_id" => id
}) do
my_resource = Kaffy.Utils.get_resource(conn, context, "order")
schema = my_resource[:schema]
resource_name = Kaffy.ResourceAdmin.singular_name(my_resource)
payment_resource = Kaffy.Utils.get_resource(conn, "payment", "payment")
{_filtered_count, payments_list} =
Kaffy.ResourceQuery.list_resource(conn, payment_resource, %{})
case can_proceed?(my_resource, conn) do
false ->
unauthorized_access(conn)
true ->
if entry = Kaffy.ResourceQuery.fetch_resource(conn, my_resource, id) do
render(conn, "payment_index.html",
layout: {KaffyWeb.LayoutView, "app.html"},
context: context,
resource: resource,
my_resource: my_resource,
resource_name: resource_name,
schema: schema,
entry: entry,
adjustments: payments_list,
order_id: id
)
else
put_flash(conn, :error, "The resource you are trying to visit does not exist!")
|> redirect(
to: Kaffy.Utils.router().kaffy_resource_path(conn, :index, context, resource)
)
end
end
end
def update_customer(
conn,
%{"context" => context, "resource" => resource, "order_id" => id} = params
) do
my_resource = Kaffy.Utils.get_resource(conn, context, resource)
schema = my_resource[:schema]
params = Kaffy.ResourceAdmin.customer_update_params(params)
params = Kaffy.ResourceParams.decode_map_fields(resource, schema, params)
resource_name = Kaffy.ResourceAdmin.singular_name(my_resource) |> String.capitalize()
case can_proceed?(my_resource, conn) do
false ->
unauthorized_access(conn)
true ->
entry = Kaffy.ResourceQuery.fetch_resource(conn, my_resource, id)
changes = Map.get(params, resource, %{})
case Kaffy.ResourceCallbacks.update_callbacks(conn, my_resource, entry, changes) do
{:ok, entry} ->
conn = put_flash(conn, :success, "#{resource_name} saved successfully")
save_button = Map.get(params, "submit", "Save")
case save_button do
"Save" ->
conn
|> put_flash(:success, "#{resource_name} saved successfully")
|> redirect(
to:
Kaffy.Utils.router().kaffy_order_path(
conn,
:order_customer,
context,
resource,
entry.id
)
)
end
{:error, %Ecto.Changeset{} = changeset} ->
conn =
put_flash(
conn,
:error,
"A problem occurred while trying to save this #{resource} "
)
conn
|> redirect(
to:
Kaffy.Utils.router().kaffy_order_path(
conn,
:order_customer,
context,
resource,
changeset.data.id
)
)
{:error, {_entry, error}} when is_binary(error) ->
conn = put_flash(conn, :error, error)
conn
|> redirect(
to: Kaffy.Utils.router().kaffy_order_path(conn, :order_customer, context, resource)
)
end
end
end
def order_shipment(conn, %{"context" => context, "resource" => resource, "id" => id}) do
my_resource = Kaffy.Utils.get_resource(conn, context, resource)
resource_name = Kaffy.ResourceAdmin.singular_name(my_resource)
case can_proceed?(my_resource, conn) do
false ->
unauthorized_access(conn)
true ->
if entry = Kaffy.ResourceQuery.fetch_resource(conn, my_resource, id) do
render(conn, "order_shipment.html",
layout: {KaffyWeb.LayoutView, "app.html"},
context: context,
resource: resource,
my_resource: my_resource,
resource_name: resource_name,
entry: entry
)
else
put_flash(conn, :error, "The resource you are trying to visit does not exist!")
|> redirect(
to: Kaffy.Utils.router().kaffy_resource_path(conn, :index, context, resource)
)
end
end
end
# we received actions as map so we actually use strings as keys
defp get_action_record(actions, action_key) when is_map(actions) and is_binary(action_key) do
Map.fetch!(actions, action_key)
end
defp unauthorized_access(conn) do
conn
|> put_flash(:error, "You are not authorized to access that page")
|> redirect(to: Kaffy.Utils.router().kaffy_home_path(conn, :index))
end
# we received actions as Keyword list so action_key needs to be an atom
defp get_action_record(actions, action_key) when is_list(actions) and is_binary(action_key) do
action_key = String.to_existing_atom(action_key)
[action_record] = Keyword.get_values(actions, action_key)
action_record
end
defp can_proceed?(resource, conn) do
Kaffy.ResourceAdmin.authorized?(resource, conn)
end
end
| 33.714286 | 102 | 0.590973 |
f7864d90f5c30c3e56ed26e3f77ae766b3b2e88f | 1,697 | ex | Elixir | clients/cloud_search/lib/google_api/cloud_search/v1/model/list_items_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/cloud_search/lib/google_api/cloud_search/v1/model/list_items_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/cloud_search/lib/google_api/cloud_search/v1/model/list_items_response.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.CloudSearch.V1.Model.ListItemsResponse do
@moduledoc """
## Attributes
* `items` (*type:* `list(GoogleApi.CloudSearch.V1.Model.Item.t)`, *default:* `nil`) -
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Token to retrieve the next page of results, or empty if there are no more results in the list.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:items => list(GoogleApi.CloudSearch.V1.Model.Item.t()) | nil,
:nextPageToken => String.t() | nil
}
field(:items, as: GoogleApi.CloudSearch.V1.Model.Item, type: :list)
field(:nextPageToken)
end
defimpl Poison.Decoder, for: GoogleApi.CloudSearch.V1.Model.ListItemsResponse do
def decode(value, options) do
GoogleApi.CloudSearch.V1.Model.ListItemsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudSearch.V1.Model.ListItemsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.94 | 157 | 0.726576 |
f7867e5e8cc40d2433cd9f83b33ad0f86eaed872 | 1,520 | ex | Elixir | test/support/data_case.ex | wbotelhos/crud-in-5-minutes-with-phoenix-and-elixir | f3218507d5c2ea7c23170d4316b41979beaa9aa6 | [
"MIT"
] | 2 | 2021-05-28T11:32:22.000Z | 2021-05-28T19:39:03.000Z | test/support/data_case.ex | wbotelhos/crud-in-5-minutes-with-phoenix-and-elixir | f3218507d5c2ea7c23170d4316b41979beaa9aa6 | [
"MIT"
] | null | null | null | test/support/data_case.ex | wbotelhos/crud-in-5-minutes-with-phoenix-and-elixir | f3218507d5c2ea7c23170d4316b41979beaa9aa6 | [
"MIT"
] | null | null | null | defmodule Bible.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 Bible.DataCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
alias Bible.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Bible.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Bible.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Bible.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.142857 | 77 | 0.686184 |
f786916e9fda8b70c2a8950a9ad705071cf888e3 | 530 | ex | Elixir | lib/docusign/model/chunked_upload_part.ex | gaslight/docusign_elixir | d9d88d53dd85d32a39d537bade9db28d779414e6 | [
"MIT"
] | 4 | 2020-12-21T12:50:13.000Z | 2022-01-12T16:50:43.000Z | lib/docusign/model/chunked_upload_part.ex | gaslight/docusign_elixir | d9d88d53dd85d32a39d537bade9db28d779414e6 | [
"MIT"
] | 12 | 2018-09-18T15:26:34.000Z | 2019-09-28T15:29:39.000Z | lib/docusign/model/chunked_upload_part.ex | gaslight/docusign_elixir | d9d88d53dd85d32a39d537bade9db28d779414e6 | [
"MIT"
] | 15 | 2020-04-29T21:50:16.000Z | 2022-02-11T18:01:51.000Z | # 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 DocuSign.Model.ChunkedUploadPart do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:sequence,
:size
]
@type t :: %__MODULE__{
:sequence => String.t(),
:size => String.t()
}
end
defimpl Poison.Decoder, for: DocuSign.Model.ChunkedUploadPart do
def decode(value, _options) do
value
end
end
| 19.62963 | 75 | 0.660377 |
f786b9451a17036eb085c2ce5cba64fc6e8c88ed | 2,085 | exs | Elixir | mix.exs | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 178 | 2018-04-08T17:11:56.000Z | 2022-03-25T15:36:41.000Z | mix.exs | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 21 | 2018-04-30T21:33:59.000Z | 2019-09-03T17:25:26.000Z | mix.exs | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 25 | 2018-04-21T19:41:03.000Z | 2021-07-24T22:40:40.000Z | defmodule Coxir.MixProject do
use Mix.Project
def project do
[
app: :coxir,
version: "2.0.0",
elixir: "~> 1.11",
start_permanent: Mix.env() == :prod,
deps: deps(),
docs: docs(),
package: package(),
source_url: "https://github.com/satom99/coxir"
]
end
def application do
[
mod: {Coxir, []}
]
end
defp deps do
[
{:ecto, ">= 3.0.0"},
{:jason, ">= 1.0.0"},
{:idna, ">= 6.0.0"},
{:castore, ">= 0.1.0"},
{:gun, ">= 1.3.0"},
{:tesla, ">= 1.3.0"},
{:gen_stage, ">= 0.14.0"},
{:kcl, ">= 1.0.0"},
{:porcelain, ">= 2.0.3"},
{:ex_doc, "~> 0.24.2", only: :dev}
]
end
defp docs do
[
groups_for_modules: [
Entities: [
Coxir.User,
Coxir.Channel,
Coxir.Guild,
Coxir.Invite,
Coxir.Overwrite,
Coxir.Webhook,
~r/^Coxir.Message.?/,
Coxir.Emoji,
Coxir.Reaction,
~r/^Coxir.Interaction.?/,
Coxir.Integration,
Coxir.Role,
Coxir.Ban,
Coxir.Member,
~r/^Coxir.Presence.?/,
Coxir.VoiceState
],
Gateway: [
~r/^Coxir.Gateway.?/,
~r/^Coxir.Payload.?/
],
Voice: [
~r/^Coxir.Voice.?/
],
Adapters: [
~r/^Coxir.Limiter.?/,
~r/^Coxir.Storage.?/,
~r/^Coxir.Sharder.?/,
~r/^Coxir.Player.?/
],
Model: [
~r/^Coxir.Model.?/
],
API: [
~r/^Coxir.API.?/
],
Other: ~r/(.*?)/
],
extra_section: "GUIDES",
extras: [
"guides/introduction.md",
"guides/quickstart.md",
"guides/configuration.md",
"guides/multiple-clients.md",
"guides/entities.md"
],
main: "introduction",
source_ref: "main"
]
end
defp package do
[
licenses: ["Apache-2.0"],
links: %{"GitHub" => "https://github.com/satom99/coxir"}
]
end
end
| 20.85 | 62 | 0.434532 |
f786c88ef10db449902c2c340f02b43c4038e048 | 1,309 | ex | Elixir | clients/video_intelligence/lib/google_api/video_intelligence/v1beta1/model/google_cloud_videointelligence_v1_safe_search_annotation.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_safe_search_annotation.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_safe_search_annotation.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_SafeSearchAnnotation do
@moduledoc """
Safe search annotation (based on per-frame visual signals only). If no unsafe content has been detected in a frame, no annotations are present for that frame.
"""
@derive [Poison.Encoder]
defstruct [
:"adult",
:"time"
]
end
defimpl Poison.Decoder, for: GoogleApi.VideoIntelligence.V1beta1.Model.GoogleCloudVideointelligenceV1_SafeSearchAnnotation do
def decode(value, _options) do
value
end
end
| 34.447368 | 160 | 0.767762 |
f786d28816ea27f3f6bd77087d5fdf37a7f74238 | 4,087 | exs | Elixir | test/battle_box_web/templates/breadcrumbs_test.exs | GrantJamesPowell/battle_box | 301091955b68cd4672f6513d645eca4e3c4e17d0 | [
"Apache-2.0"
] | 2 | 2020-10-17T05:48:49.000Z | 2020-11-11T02:34:15.000Z | test/battle_box_web/templates/breadcrumbs_test.exs | FlyingDutchmanGames/battle_box | 301091955b68cd4672f6513d645eca4e3c4e17d0 | [
"Apache-2.0"
] | 3 | 2020-05-18T05:52:21.000Z | 2020-06-09T07:24:14.000Z | test/battle_box_web/templates/breadcrumbs_test.exs | FlyingDutchmanGames/battle_box | 301091955b68cd4672f6513d645eca4e3c4e17d0 | [
"Apache-2.0"
] | null | null | null | defmodule BattleBoxWeb.Templates.BreadCrumbsTest do
use ExUnit.Case, async: true
alias BattleBoxWeb.PageView
alias BattleBox.{User, Arena, Bot}
@user %User{username: "example-username"}
@bot %Bot{user: @user, name: "example-bot"}
@arena %Arena{user: @user, name: "example-arena"}
test "it renders the breadcrumbs correctly" do
[
# The Basics
{[], nil, "/ ", ["/"]},
{["foo"], [], "/ foo /", ["/"]},
{[{"foo", "/to/foo"}], [], "/ foo /", ["/", "/to/foo"]},
{[], [{"foo", "/to/foo"}], "/ { foo, }", ["/", "/to/foo"]},
{[], [{"foo", "/to/foo"}, {"bar", "/to/bar"}], "/ { foo, bar, }",
["/", "/to/foo", "/to/bar"]},
{[], [{:inaccessible, "foo"}], "/ { foo, }", ["/"]},
# User
{[@user], [], "/ Users / example-username /", ["/", "/users", "/users/example-username"]},
{[{@user, :bots}], [], "/ Users / example-username / Bots /",
["/", "/users", "/users/example-username", "/users/example-username/bots"]},
{[{@user, :keys}], [], "/ Users / example-username / Keys /",
["/", "/users", "/users/example-username", "/keys"]},
{[{@user, :arenas}], [], "/ Users / example-username / Arenas /",
["/", "/users", "/users/example-username", "/users/example-username/arenas"]},
# Resources
{[@bot], [], "/ Users / example-username / Bots / example-bot /",
[
"/",
"/users",
"/users/example-username",
"/users/example-username/bots",
"/users/example-username/bots/example-bot"
]},
{[@arena], [], "/ Users / example-username / Arenas / example-arena /",
[
"/",
"/users",
"/users/example-username",
"/users/example-username/arenas",
"/users/example-username/arenas/example-arena"
]},
# No Subject handling
{[:no_subject, :no_subject, @user, :no_subject], [], "/ Users / example-username /",
["/", "/users", "/users/example-username"]},
# Admin
{[:admin], [], "/ Admin /", ["/", "/admin"]},
{[:admin, {:admin, @user}], [], "/ Admin / Users / example-username /",
["/", "/admin", "/admin/users", "/admin/users/example-username"]},
# Options
{[], [{:new, :bot}], "/ { New, }", ["/", "/bots/new"]},
{[], [{:new, :arena}], "/ { New, }", ["/", "/arenas/new"]},
{[], [{:new, :api_key}], "/ { New, }", ["/", "/keys/new"]},
{[], [{:edit, @bot}], "/ { Edit, }",
["/", "/users/example-username/bots/example-bot/edit"]},
{[], [{:edit, @arena}], "/ { Edit, }",
["/", "/users/example-username/arenas/example-arena/edit"]},
{[], [{:admin, {:edit, @user}}], "/ { Edit, }",
["/", "/admin/users/example-username/edit"]},
{[], [{:games, @bot}], "/ { Games, }",
["/", "/users/example-username/bots/example-bot/games"]},
{[], [{:games, @user}], "/ { Games, }", ["/", "/users/example-username/games"]},
{[], [{:games, @arena}], "/ { Games, }",
["/", "/users/example-username/arenas/example-arena/games"]},
{[], [{:follow, @bot}], "/ { Follow, }",
["/", "/users/example-username/bots/example-bot/follow"]},
{[], [{:follow, @user}], "/ { Follow, }", ["/", "/users/example-username/follow"]},
{[], [{:follow, @arena}], "/ { Follow, }",
["/", "/users/example-username/arenas/example-arena/follow"]}
]
|> Enum.each(fn {nav_segments, nav_options, expected, links} ->
{:safe, io_list} =
PageView.render("_bread_crumbs.html",
conn: BattleBoxWeb.Endpoint,
segments: nav_segments,
options: nav_options
)
html = IO.iodata_to_binary(io_list)
{:ok, document} = Floki.parse_document(html)
assert expected ==
document
|> Floki.text()
|> (&Regex.replace(~r/\n/, &1, "")).()
|> (&Regex.replace(~r/\s+/, &1, " ")).()
assert links ==
document
|> Floki.find("a")
|> Enum.flat_map(&Floki.attribute(&1, "href"))
end)
end
end
| 42.134021 | 96 | 0.477367 |
f786e8db0d8650a9e5a4cb1577ecb04fc84572f1 | 708 | ex | Elixir | lib/coder_ring/migration.ex | instinctscience/coder_ring | dfa3e66893e15c6e69974cfe709d3380d01bf7d1 | [
"MIT"
] | null | null | null | lib/coder_ring/migration.ex | instinctscience/coder_ring | dfa3e66893e15c6e69974cfe709d3380d01bf7d1 | [
"MIT"
] | null | null | null | lib/coder_ring/migration.ex | instinctscience/coder_ring | dfa3e66893e15c6e69974cfe709d3380d01bf7d1 | [
"MIT"
] | null | null | null | defmodule CoderRing.Migration do
@moduledoc """
Handles table migrations.
Invoke `CoderRing.Migration.change/0` in your migration's `change/0`
function.
"""
use Ecto.Migration
@spec change :: :ok
def change do
create table(:code_memos, primary_key: false) do
add(:name, :string, primary_key: true)
add(:uniquizer_num, :integer, null: false, default: 0)
add(:extra, :string, null: false, default: "")
add(:last_max_pos, :integer)
end
create table(:codes) do
add(:position, :integer, null: false)
add(:name, references(:code_memos, type: :string, column: :name), null: false)
add(:value, :string, null: false)
end
:ok
end
end
| 25.285714 | 84 | 0.646893 |
f786f122096b3c94c7a524810da3f8798f609564 | 2,228 | exs | Elixir | implementations/elixir/ockam/ockam/test/ockam/protocol/protocol_test.exs | twittner/ockam | 96eadf99da42f7c35539c6e29010a657c579ccba | [
"Apache-2.0"
] | 1,912 | 2019-01-10T14:17:00.000Z | 2022-03-30T19:16:44.000Z | implementations/elixir/ockam/ockam/test/ockam/protocol/protocol_test.exs | twittner/ockam | 96eadf99da42f7c35539c6e29010a657c579ccba | [
"Apache-2.0"
] | 1,473 | 2019-01-16T15:14:47.000Z | 2022-03-31T23:44:50.000Z | implementations/elixir/ockam/ockam/test/ockam/protocol/protocol_test.exs | twittner/ockam | 96eadf99da42f7c35539c6e29010a657c579ccba | [
"Apache-2.0"
] | 219 | 2019-01-11T03:35:13.000Z | 2022-03-31T10:25:56.000Z | defmodule Ockam.Protocol.Tests do
use ExUnit.Case, async: true
doctest Ockam.Protocol
alias Ockam.Protocol
alias Ockam.Protocol.Tests.ExampleProtocol
describe "Base message" do
test "can be encoded and decoded" do
name = "my_protocol_name"
data = "some arbitrary data"
base_message = %{protocol: name, data: data}
encoded = Protocol.base_encode(name, data)
assert is_binary(encoded)
{:ok, decoded} = Protocol.base_decode(encoded)
assert ^decoded = base_message
end
end
describe "Protocol message" do
test "can be encoded and decoded" do
struct_request = %{string_field: "I am string", int_field: 10}
data_request = "I am data request"
data_response = "I am data response"
struct_request_encoded =
Protocol.encode(ExampleProtocol, :request, {:structure, struct_request})
assert is_binary(struct_request_encoded)
assert {:ok, {:structure, ^struct_request}} =
Protocol.decode(ExampleProtocol, :request, struct_request_encoded)
data_request_encoded = Protocol.encode(ExampleProtocol, :request, {:data, data_request})
assert {:ok, {:data, ^data_request}} =
Protocol.decode(ExampleProtocol, :request, data_request_encoded)
data_response_encoded = Protocol.encode(ExampleProtocol, :response, data_response)
assert {:ok, ^data_response} =
Protocol.decode(ExampleProtocol, :response, data_response_encoded)
assert catch_error(Protocol.encode(ExampleProtocol, :response, struct_request)) ==
:cannot_encode
end
end
describe "Protocol message wrapped in the base message" do
test "can be encoded and decoded" do
struct_request = %{string_field: "I am string", int_field: 10}
struct_request_encoded =
Protocol.encode_payload(ExampleProtocol, :request, {:structure, struct_request})
assert is_binary(struct_request_encoded)
assert {:ok, %{protocol: "example_protocol"}} = Protocol.base_decode(struct_request_encoded)
assert {:ok, {:structure, ^struct_request}} =
Protocol.decode_payload(ExampleProtocol, :request, struct_request_encoded)
end
end
end
| 32.764706 | 98 | 0.694345 |
f786fd073c0dcd0720b4827d616abbdb29830742 | 71 | ex | Elixir | lib/loaded_bike/web/views/social_view.ex | GBH/pedal | a2d68c3561f186ee3017a21b4170127b1625e18d | [
"MIT"
] | 48 | 2017-04-25T16:02:08.000Z | 2021-01-23T01:57:29.000Z | lib/loaded_bike/web/views/social_view.ex | GBH/pedal | a2d68c3561f186ee3017a21b4170127b1625e18d | [
"MIT"
] | 5 | 2018-03-09T20:17:55.000Z | 2018-07-23T16:29:21.000Z | lib/loaded_bike/web/views/social_view.ex | GBH/pedal | a2d68c3561f186ee3017a21b4170127b1625e18d | [
"MIT"
] | 4 | 2017-05-21T14:38:38.000Z | 2017-12-29T11:09:54.000Z | defmodule LoadedBike.Web.SocialView do
use LoadedBike.Web, :view
end
| 17.75 | 38 | 0.802817 |
f78720eab0146abaa859ad66b890230505441009 | 139 | exs | Elixir | config/config.exs | wilk/dpc18bot | 1f68343b0929f2a6f38dde22e52d028a85418af3 | [
"MIT"
] | null | null | null | config/config.exs | wilk/dpc18bot | 1f68343b0929f2a6f38dde22e52d028a85418af3 | [
"MIT"
] | null | null | null | config/config.exs | wilk/dpc18bot | 1f68343b0929f2a6f38dde22e52d028a85418af3 | [
"MIT"
] | null | null | null | use Mix.Config
config :app,
bot_name: System.get_env("TELEGRAM_BOT_NAME")
config :nadia,
token: System.get_env("TELEGRAM_BOT_TOKEN")
| 17.375 | 47 | 0.76259 |
f7875542cacc4dd119aad16e0b0b76a992024799 | 511 | ex | Elixir | test/middleware/support/halting_router.ex | jwilger/commanded | 2d9950fd3ce76a23a3c410c99857b812f5705d66 | [
"MIT"
] | 1,220 | 2017-10-31T10:56:40.000Z | 2022-03-31T17:40:19.000Z | test/middleware/support/halting_router.ex | jwilger/commanded | 2d9950fd3ce76a23a3c410c99857b812f5705d66 | [
"MIT"
] | 294 | 2017-11-03T10:33:41.000Z | 2022-03-24T08:36:42.000Z | test/middleware/support/halting_router.ex | jwilger/commanded | 2d9950fd3ce76a23a3c410c99857b812f5705d66 | [
"MIT"
] | 208 | 2017-11-03T10:56:47.000Z | 2022-03-14T05:49:38.000Z | defmodule Commanded.HaltingRouter do
use Commanded.Commands.Router
alias Commanded.Helpers.CommandAuditMiddleware
alias Commanded.HaltingMiddleware
alias Commanded.Middleware.Commands.CommandHandler
alias Commanded.Middleware.Commands.CounterAggregateRoot
alias Commanded.Middleware.Commands.IncrementCount
middleware CommandAuditMiddleware
middleware HaltingMiddleware
dispatch IncrementCount,
to: CommandHandler,
aggregate: CounterAggregateRoot,
identity: :aggregate_uuid
end
| 28.388889 | 58 | 0.837573 |
f78755de091f744f3ad06158d55f732527be71df | 1,047 | exs | Elixir | test/farmbot_celery_script/assertion_compiler_test.exs | FarmBot/farmbot_os | 5ebdca3afd672eb6b0af5c71cfca02488b32569a | [
"MIT"
] | 843 | 2016-10-05T23:46:05.000Z | 2022-03-14T04:31:55.000Z | test/farmbot_celery_script/assertion_compiler_test.exs | FarmBot/farmbot_os | 5ebdca3afd672eb6b0af5c71cfca02488b32569a | [
"MIT"
] | 455 | 2016-10-15T08:49:16.000Z | 2022-03-15T12:23:04.000Z | test/farmbot_celery_script/assertion_compiler_test.exs | FarmBot/farmbot_os | 5ebdca3afd672eb6b0af5c71cfca02488b32569a | [
"MIT"
] | 261 | 2016-10-10T04:37:06.000Z | 2022-03-13T21:07:38.000Z | defmodule FarmbotCore.Celery.AssertionCompilerTest do
use ExUnit.Case
use Mimic
alias FarmbotCore.Celery.Compiler.{Assertion, Scope}
alias FarmbotCore.Celery.AST
test "Assertion.assertion/2" do
scope = Scope.new()
expect(FarmbotCore.Celery.SysCallGlue, :log_assertion, 1, fn ok?, t, msg ->
refute ok?
assert t == "abort"
assert msg == "[comment] failed to evaluate, aborting"
:ok
end)
expect(FarmbotCore.Celery.Compiler.Lua, :do_lua, 1, fn lua, actual_scope ->
assert lua == "return false"
assert actual_scope == scope
{:error, "intentional failure case"}
end)
{result, _} =
%{
kind: :assertion,
args: %{
lua: "return false",
assertion_type: "abort",
_then: %{kind: :nothing, args: %{}}
},
comment: "comment"
}
|> AST.decode()
|> Assertion.assertion(scope)
|> Macro.to_string()
|> Code.eval_string()
assert {:error, "intentional failure case"} == result
end
end
| 25.536585 | 79 | 0.597899 |
f7875c1f8ad8a15e0cd9f2aca49cc5062f61bee8 | 4,306 | ex | Elixir | lib/livebook/notebook/explore.ex | wojtekmach/livebook | 861fc3110bb1b9e400925c39b8b6d13a07b7c475 | [
"Apache-2.0"
] | null | null | null | lib/livebook/notebook/explore.ex | wojtekmach/livebook | 861fc3110bb1b9e400925c39b8b6d13a07b7c475 | [
"Apache-2.0"
] | null | null | null | lib/livebook/notebook/explore.ex | wojtekmach/livebook | 861fc3110bb1b9e400925c39b8b6d13a07b7c475 | [
"Apache-2.0"
] | null | null | null | defmodule Livebook.Notebook.Explore.Utils do
@moduledoc false
@doc """
Defines a module attribute `attr` with notebook info.
"""
defmacro defnotebook(attr, props) do
quote bind_quoted: [attr: attr, props: props] do
{path, notebook_info} = Livebook.Notebook.Explore.Utils.fetch_notebook!(attr, props)
@external_resource path
Module.put_attribute(__MODULE__, attr, notebook_info)
end
end
def fetch_notebook!(attr, props) do
name = Atom.to_string(attr)
path = Path.join([__DIR__, "explore", name <> ".livemd"])
markdown = File.read!(path)
# Parse the file to ensure no warnings and read the title.
# However, in the info we keep just the file contents to save on memory.
{notebook, []} = Livebook.LiveMarkdown.Import.notebook_from_markdown(markdown)
images =
props
|> Keyword.get(:image_names, [])
|> Map.new(fn image_name ->
path = Path.join([__DIR__, "explore", "images", image_name])
content = File.read!(path)
{image_name, content}
end)
notebook_info = %{
slug: String.replace(name, "_", "-"),
livemd: markdown,
title: notebook.name,
description: Keyword.fetch!(props, :description),
image_url: Keyword.fetch!(props, :image_url),
images: images
}
{path, notebook_info}
end
end
defmodule Livebook.Notebook.Explore do
@moduledoc false
defmodule NotFoundError do
@moduledoc false
defexception [:slug, plug_status: 404]
def message(%{slug: slug}) do
"could not find an example notebook matching #{inspect(slug)}"
end
end
import Livebook.Notebook.Explore.Utils
defnotebook(:intro_to_livebook,
description: "Get to know Livebook, see how it works and explore its features.",
image_url: "/images/logo.png"
)
defnotebook(:distributed_portals_with_elixir,
description:
"A fast-paced introduction to the Elixir language by building distributed data-transfer portals.",
image_url: "/images/elixir-portal.jpeg",
image_names: ["portal-drop.jpeg", "portal-list.jpeg"]
)
defnotebook(:elixir_and_livebook,
description: "Learn how to use some of Elixir and Livebook's unique features together.",
image_url: "/images/elixir.png"
)
defnotebook(:intro_to_nx,
description:
"Enter Numerical Elixir, experience the power of multi-dimensional arrays of numbers.",
image_url: "/images/nx.png"
)
defnotebook(:intro_to_axon,
description: "Build Neural Networks in Elixir using a high-level, composable API.",
image_url: "/images/axon.png"
)
defnotebook(:intro_to_vega_lite,
description: "Learn how to quickly create numerous plots for your data.",
image_url: "/images/vega_lite.png"
)
defnotebook(:vm_introspection,
description: "Extract and visualize information about a remote running node.",
image_url: "/images/vm_introspection.png"
)
defnotebook(:intro_to_kino,
description: "Display and control rich and interactive widgets in Livebook.",
image_url: "/images/kino.png"
)
@type notebook_info :: %{
slug: String.t(),
livemd: String.t(),
title: String.t(),
description: String.t(),
image_url: String.t(),
images: images()
}
@type images :: %{String.t() => binary()}
@doc """
Returns a list of example notebooks with metadata.
"""
@spec notebook_infos() :: list(notebook_info())
def notebook_infos() do
[
@intro_to_livebook,
@distributed_portals_with_elixir,
@elixir_and_livebook,
@intro_to_vega_lite,
@intro_to_kino,
@intro_to_nx,
@vm_introspection
# , @intro_to_axon
]
end
@doc """
Finds explore notebook by slug and returns the parsed data structure.
Returns the notebook along with the images it uses as preloaded binaries.
"""
@spec notebook_by_slug!(String.t()) :: {Livebook.Notebook.t(), images()}
def notebook_by_slug!(slug) do
notebook_infos()
|> Enum.find(&(&1.slug == slug))
|> case do
nil ->
raise NotFoundError, slug: slug
notebook_info ->
{notebook, []} = Livebook.LiveMarkdown.Import.notebook_from_markdown(notebook_info.livemd)
{notebook, notebook_info.images}
end
end
end
| 28.143791 | 104 | 0.66837 |
f787601cbfc9186d38d64c873aba5f482f254763 | 3,200 | ex | Elixir | clients/network_services/lib/google_api/network_services/v1/model/operation.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/network_services/lib/google_api/network_services/v1/model/operation.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/network_services/lib/google_api/network_services/v1/model/operation.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.NetworkServices.V1.Model.Operation do
@moduledoc """
This resource represents a long-running operation that is the result of a network API call.
## Attributes
* `done` (*type:* `boolean()`, *default:* `nil`) - If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.
* `error` (*type:* `GoogleApi.NetworkServices.V1.Model.Status.t`, *default:* `nil`) - The error result of the operation in case of failure or cancellation.
* `metadata` (*type:* `map()`, *default:* `nil`) - Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
* `name` (*type:* `String.t`, *default:* `nil`) - The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.
* `response` (*type:* `map()`, *default:* `nil`) - The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:done => boolean() | nil,
:error => GoogleApi.NetworkServices.V1.Model.Status.t() | nil,
:metadata => map() | nil,
:name => String.t() | nil,
:response => map() | nil
}
field(:done)
field(:error, as: GoogleApi.NetworkServices.V1.Model.Status)
field(:metadata, type: :map)
field(:name)
field(:response, type: :map)
end
defimpl Poison.Decoder, for: GoogleApi.NetworkServices.V1.Model.Operation do
def decode(value, options) do
GoogleApi.NetworkServices.V1.Model.Operation.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.NetworkServices.V1.Model.Operation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 54.237288 | 543 | 0.72375 |
f78791df6e6a84464199b22103032eb48290ec82 | 1,520 | ex | Elixir | lib/adoptoposs_web/email.ex | paulgoetze/adoptoposs | 1a143917ac5a192f12054fff4410a1ee18935353 | [
"MIT"
] | null | null | null | lib/adoptoposs_web/email.ex | paulgoetze/adoptoposs | 1a143917ac5a192f12054fff4410a1ee18935353 | [
"MIT"
] | null | null | null | lib/adoptoposs_web/email.ex | paulgoetze/adoptoposs | 1a143917ac5a192f12054fff4410a1ee18935353 | [
"MIT"
] | null | null | null | defmodule AdoptopossWeb.Email do
@moduledoc """
Defines all system emails.
"""
use Bamboo.Phoenix, view: AdoptopossWeb.EmailView
import AdoptopossWeb.Router.Helpers
alias AdoptopossWeb.Endpoint
def interest_received_email(interest) do
%{project: project, creator: creator} = interest
message_url =
live_url(Endpoint, AdoptopossWeb.MessagesLive.Interests) <> "/#p-#{project.uuid}"
base_email(:notification)
|> to(project.user.email)
|> subject("[Adoptoposs][#{project.name}] #{creator.name} wrote you a message")
|> put_header("Reply-To", creator.email)
|> assign(:interest, interest)
|> assign(:message_url, message_url)
|> render_mjml(:interest_received)
end
def project_recommendations_email(user, projects) do
base_email(:newsletter)
|> to(user.email)
|> subject("[Adoptoposs] Projects you might like to help maintain")
|> assign(:user, user)
|> assign(:projects, projects)
|> render_mjml(:project_recommendations)
end
defp base_email(layout_type) do
new_email()
|> from("Adoptoposs<notifications@#{Endpoint.host()}>")
|> put_html_layout({AdoptopossWeb.LayoutView, "email.html"})
|> put_text_layout({AdoptopossWeb.LayoutView, "email.text"})
|> assign(:layout_type, layout_type)
end
def render_mjml(email, template, assigns \\ []) do
result = render(email, template, assigns)
{:ok, html_body} = Mjml.to_html(Map.get(result, :html_body))
Map.put(result, :html_body, html_body)
end
end
| 31.020408 | 87 | 0.696053 |
f787926b1cab7ab04cc15c3083fe0beaaa12483e | 357 | exs | Elixir | shritesh+elixir/test/advent/day_11_test.exs | NashFP/advent-2020 | 3ef8736357cb1753ea6b8acf558e344e842ab247 | [
"MIT"
] | 1 | 2020-11-25T01:54:02.000Z | 2020-11-25T01:54:02.000Z | shritesh+elixir/test/advent/day_11_test.exs | NashFP/advent-2020 | 3ef8736357cb1753ea6b8acf558e344e842ab247 | [
"MIT"
] | null | null | null | shritesh+elixir/test/advent/day_11_test.exs | NashFP/advent-2020 | 3ef8736357cb1753ea6b8acf558e344e842ab247 | [
"MIT"
] | 2 | 2020-11-25T01:54:42.000Z | 2021-02-24T00:12:59.000Z | defmodule Advent.Day11Test do
use ExUnit.Case
alias Advent.Day11
@example """
L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL
"""
test "part_1" do
assert Day11.part_1(@example) == 37
end
test "part_2" do
assert Day11.part_2(@example) == 26
end
end
| 13.730769 | 39 | 0.610644 |
f787bb1842f44ffad11b4efe971a99cceced2e3f | 820 | exs | Elixir | test/ping_test.exs | rawdamedia/quoil | 8d7be55d15442e2f0cf8743d5ceb1dd5761e9356 | [
"MIT"
] | 1 | 2015-07-17T13:42:12.000Z | 2015-07-17T13:42:12.000Z | test/ping_test.exs | rawdamedia/quoil | 8d7be55d15442e2f0cf8743d5ceb1dd5761e9356 | [
"MIT"
] | 3 | 2015-07-17T07:52:30.000Z | 2016-03-16T11:34:48.000Z | test/ping_test.exs | rawdamedia/quoil | 8d7be55d15442e2f0cf8743d5ceb1dd5761e9356 | [
"MIT"
] | 1 | 2015-07-17T11:50:44.000Z | 2015-07-17T11:50:44.000Z | defmodule PingTest do
use ExUnit.Case
import String
import ExUnit.CaptureIO
# Testing run_ping function using system ping utility
test "able to run system ping function" do
test_data = capture_io(fn -> Quoil.CLI.main(["-i","1","-n","3","-s","google.com"]) end)
IO.puts test_data
assert (contains?(test_data, "\nPING statistics")) && (contains?(test_data, "google.com"))
end
# Testing gen_icmp
test "able to use gen_icmp" do
IO.puts "--==<< Testing gen_icmp >>==--"
{:ok, socket} = :gen_icmp.open()
IO.puts inspect(socket)
response = :gen_icmp.ping(socket,['www.google.com.au', 'telstra.com.au'],[])
IO.puts "["
Enum.each(response, &(IO.puts inspect(&1)))
IO.puts "]"
assert Enum.all?(response, &(elem(&1,0) == :ok))
:gen_icmp.close(socket)
end
end | 28.275862 | 94 | 0.635366 |
f787dd409c8b63eb1718dd7cbbaf132ad41b7be0 | 203 | exs | Elixir | test/first_days_web/controllers/page_controller_test.exs | TechforgoodCAST/first-steps | fa178d44d7c58a2e3fa372adcf7b5f2dc4ff6862 | [
"BSD-3-Clause"
] | 3 | 2018-01-30T09:55:29.000Z | 2018-02-01T18:48:10.000Z | test/first_days_web/controllers/page_controller_test.exs | TechforgoodCAST/first-days | fa178d44d7c58a2e3fa372adcf7b5f2dc4ff6862 | [
"BSD-3-Clause"
] | 16 | 2018-01-30T09:45:20.000Z | 2018-02-07T11:11:04.000Z | test/first_days_web/controllers/page_controller_test.exs | TechforgoodCAST/first-days | fa178d44d7c58a2e3fa372adcf7b5f2dc4ff6862 | [
"BSD-3-Clause"
] | null | null | null | defmodule FirstDaysWeb.PageControllerTest do
use FirstDaysWeb.ConnCase
test "GET /", %{conn: conn} do
conn = get conn, "/"
assert html_response(conn, 200) =~ "Welcome to Phoenix!"
end
end
| 22.555556 | 60 | 0.689655 |
f787df91bca1f1e8060c75ed1ec5a261562d8d8d | 473 | exs | Elixir | lib/p03.exs | ospatil/99problems | 4a5d3a3983ea07109f84870d82ccfd7d967858da | [
"MIT"
] | 2 | 2016-07-18T02:53:37.000Z | 2019-06-25T10:31:11.000Z | lib/p03.exs | ospatil/99problems | 4a5d3a3983ea07109f84870d82ccfd7d967858da | [
"MIT"
] | null | null | null | lib/p03.exs | ospatil/99problems | 4a5d3a3983ea07109f84870d82ccfd7d967858da | [
"MIT"
] | null | null | null | defmodule P3 do
# Find the k'th element of a list. The first element in the list is number 1.
def at(pos, list), do: do_at(pos, list, 1)
defp do_at(_, [], _), do: nil
defp do_at(pos, [head | _], counter) when pos == counter, do: head
defp do_at(pos, [_ | tail], counter), do: do_at(pos, tail, counter + 1)
end
ExUnit.start()
defmodule P3Test do
use ExUnit.Case
test "P3.at" do
assert P3.at(3, [1, 2, 3]) == 3
assert P3.at(3, []) == nil
end
end
| 22.52381 | 79 | 0.617336 |
f787f0a0a7469de32a31a911b01e90920b54d51b | 664 | exs | Elixir | test/acceptance/regressions/i002-accept-any-struct-as-option_test.exs | akash-akya/earmark_parser | de2216ca0622a9d2491ea2295d0be1bedcaf64c6 | [
"Apache-2.0"
] | null | null | null | test/acceptance/regressions/i002-accept-any-struct-as-option_test.exs | akash-akya/earmark_parser | de2216ca0622a9d2491ea2295d0be1bedcaf64c6 | [
"Apache-2.0"
] | null | null | null | test/acceptance/regressions/i002-accept-any-struct-as-option_test.exs | akash-akya/earmark_parser | de2216ca0622a9d2491ea2295d0be1bedcaf64c6 | [
"Apache-2.0"
] | null | null | null | defmodule Acceptance.Regressions.I002AcceptAnyStructAsOptionTest do
use ExUnit.Case
import EarmarkParser, only: [as_ast: 2]
defmodule MyStruct do
defstruct pure_links: false
end
describe "can parse with MyStruct" do
@markdown "see https://my.site.com"
test "pure_links deactivated" do
ast = [{"p", [], [@markdown], %{}}]
assert as_ast(@markdown, %MyStruct{}) == {:ok, ast, []}
end
test "or activated" do
ast =
[{"p", '', ["see ", {"a", [{"href", "https://my.site.com"}], ["https://my.site.com"], %{}}], %{}}]
assert as_ast(@markdown, %MyStruct{pure_links: true}) == {:ok, ast, []}
end
end
end
| 26.56 | 106 | 0.59488 |
f78809a0b284bd7c6c0ab6bd5006d255aa5fe13d | 472 | exs | Elixir | test/elixirfm_test.exs | jrichocean/Elixirfm | 5595c08c3217500bbc3fe74fe1657fe0e7bfcda8 | [
"MIT"
] | 9 | 2016-10-04T10:09:17.000Z | 2020-10-20T10:34:47.000Z | test/elixirfm_test.exs | jrichocean/Elixirfm | 5595c08c3217500bbc3fe74fe1657fe0e7bfcda8 | [
"MIT"
] | 4 | 2017-06-19T11:11:15.000Z | 2021-11-10T04:31:45.000Z | test/elixirfm_test.exs | jrichocean/Elixirfm | 5595c08c3217500bbc3fe74fe1657fe0e7bfcda8 | [
"MIT"
] | 2 | 2018-10-12T09:53:36.000Z | 2019-09-29T13:19:41.000Z | defmodule ElixirfmTest do
use ExUnit.Case
doctest Elixirfm
test "_encode_params/1 encodes types correctly" do
import Elixirfm, only: [_encode_params: 1]
assert _encode_params([{"testkey", "testval"}]) == ["&testkey=testval"]
assert _encode_params(%{"testkey" => "testval"}) == ["&testkey=testval"]
assert _encode_params(%{testkey: "testval"}) == ["&testkey=testval"]
assert _encode_params([testkey: "testval"]) == ["&testkey=testval"]
end
end
| 36.307692 | 76 | 0.686441 |
f7881a974ea374fa3aa760b947d7cd410fe9be4e | 669 | ex | Elixir | lib/memo/creators/creator_user_interest.ex | ashkan18/memo | da62914abff2f4f4c75ad6b996e3f6c3d5e9ad64 | [
"MIT"
] | null | null | null | lib/memo/creators/creator_user_interest.ex | ashkan18/memo | da62914abff2f4f4c75ad6b996e3f6c3d5e9ad64 | [
"MIT"
] | null | null | null | lib/memo/creators/creator_user_interest.ex | ashkan18/memo | da62914abff2f4f4c75ad6b996e3f6c3d5e9ad64 | [
"MIT"
] | null | null | null | defmodule Memo.Creators.CreatorUserInterest do
use Ecto.Schema
import Ecto.Changeset
schema "creator_user_interests" do
belongs_to(:user_interest, Memo.Interests.UserInterest)
belongs_to(:creator, Memo.Creators.Creator)
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(creator, attrs) do
creator
|> cast(attrs, [:user_interest_id, :creator_id])
|> validate_required([:user_interest_id, :creator_id])
|> foreign_key_constraint(:user_interest_id)
|> foreign_key_constraint(:creator_id)
|> assoc_constraint(:user_interest)
|> assoc_constraint(:creator)
end
end
| 26.76 | 59 | 0.723468 |
f7883be2dfe8ed0a2abff8b7cbb3c84a2f09e34a | 787 | ex | Elixir | server/apps/boardr/lib/boardr/stats_server.ex | AlphaHydrae/boardr | 98eed02801f88c065a24bf13051c5cf96270a5f7 | [
"MIT"
] | 1 | 2021-04-08T17:26:27.000Z | 2021-04-08T17:26:27.000Z | server/apps/boardr/lib/boardr/stats_server.ex | AlphaHydrae/boardr | 98eed02801f88c065a24bf13051c5cf96270a5f7 | [
"MIT"
] | 1 | 2022-02-13T05:50:46.000Z | 2022-02-13T05:50:46.000Z | server/apps/boardr/lib/boardr/stats_server.ex | AlphaHydrae/boardr | 98eed02801f88c065a24bf13051c5cf96270a5f7 | [
"MIT"
] | null | null | null | # TODO: use telemetry somehow
defmodule Boardr.StatsServer do
use GenServer
def start_link(_) do
GenServer.start_link(__MODULE__, nil, name: __MODULE__)
end
def stats() do
GenServer.call(__MODULE__, :stats)
end
# Server (callbacks)
@impl true
def init(_) do
{:ok, nil}
end
@impl true
def handle_call(:stats, _from, state) do
{:reply, compute_stats(), state}
end
defp compute_stats() do
%{
game_servers: count_local_game_servers(),
swarm_processes: length(Swarm.registered())
}
end
defp count_local_game_servers() do
Swarm.registered() |> Enum.map(fn {_, pid} -> pid end) |> Enum.filter(fn pid ->
try do
Process.alive?(pid)
rescue
_ -> false
end
end) |> length()
end
end
| 18.738095 | 83 | 0.632783 |
f7884af5eca7af7966d2615b70031cb33ab13444 | 5,717 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/advertiser.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/advertiser.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"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/advertiser.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.DFAReporting.V33.Model.Advertiser do
@moduledoc """
Contains properties of a Campaign Manager advertiser.
## Attributes
* `accountId` (*type:* `String.t`, *default:* `nil`) - Account ID of this advertiser.This is a read-only field that can be left blank.
* `advertiserGroupId` (*type:* `String.t`, *default:* `nil`) - ID of the advertiser group this advertiser belongs to. You can group advertisers for reporting purposes, allowing you to see aggregated information for all advertisers in each group.
* `clickThroughUrlSuffix` (*type:* `String.t`, *default:* `nil`) - Suffix added to click-through URL of ad creative associations under this advertiser. Must be less than 129 characters long.
* `defaultClickThroughEventTagId` (*type:* `String.t`, *default:* `nil`) - ID of the click-through event tag to apply by default to the landing pages of this advertiser's campaigns.
* `defaultEmail` (*type:* `String.t`, *default:* `nil`) - Default email address used in sender field for tag emails.
* `floodlightConfigurationId` (*type:* `String.t`, *default:* `nil`) - Floodlight configuration ID of this advertiser. The floodlight configuration ID will be created automatically, so on insert this field should be left blank. This field can be set to another advertiser's floodlight configuration ID in order to share that advertiser's floodlight configuration with this advertiser, so long as: - This advertiser's original floodlight configuration is not already associated with floodlight activities or floodlight activity groups. - This advertiser's original floodlight configuration is not already shared with another advertiser.
* `floodlightConfigurationIdDimensionValue` (*type:* `GoogleApi.DFAReporting.V33.Model.DimensionValue.t`, *default:* `nil`) - Dimension value for the ID of the floodlight configuration. This is a read-only, auto-generated field.
* `id` (*type:* `String.t`, *default:* `nil`) - ID of this advertiser. This is a read-only, auto-generated field.
* `idDimensionValue` (*type:* `GoogleApi.DFAReporting.V33.Model.DimensionValue.t`, *default:* `nil`) - Dimension value for the ID of this advertiser. This is a read-only, auto-generated field.
* `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#advertiser".
* `name` (*type:* `String.t`, *default:* `nil`) - Name of this advertiser. This is a required field and must be less than 256 characters long and unique among advertisers of the same account.
* `originalFloodlightConfigurationId` (*type:* `String.t`, *default:* `nil`) - Original floodlight configuration before any sharing occurred. Set the floodlightConfigurationId of this advertiser to originalFloodlightConfigurationId to unshare the advertiser's current floodlight configuration. You cannot unshare an advertiser's floodlight configuration if the shared configuration has activities associated with any campaign or placement.
* `status` (*type:* `String.t`, *default:* `nil`) - Status of this advertiser.
* `subaccountId` (*type:* `String.t`, *default:* `nil`) - Subaccount ID of this advertiser.This is a read-only field that can be left blank.
* `suspended` (*type:* `boolean()`, *default:* `nil`) - Suspension status of this advertiser.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:accountId => String.t(),
:advertiserGroupId => String.t(),
:clickThroughUrlSuffix => String.t(),
:defaultClickThroughEventTagId => String.t(),
:defaultEmail => String.t(),
:floodlightConfigurationId => String.t(),
:floodlightConfigurationIdDimensionValue =>
GoogleApi.DFAReporting.V33.Model.DimensionValue.t(),
:id => String.t(),
:idDimensionValue => GoogleApi.DFAReporting.V33.Model.DimensionValue.t(),
:kind => String.t(),
:name => String.t(),
:originalFloodlightConfigurationId => String.t(),
:status => String.t(),
:subaccountId => String.t(),
:suspended => boolean()
}
field(:accountId)
field(:advertiserGroupId)
field(:clickThroughUrlSuffix)
field(:defaultClickThroughEventTagId)
field(:defaultEmail)
field(:floodlightConfigurationId)
field(:floodlightConfigurationIdDimensionValue,
as: GoogleApi.DFAReporting.V33.Model.DimensionValue
)
field(:id)
field(:idDimensionValue, as: GoogleApi.DFAReporting.V33.Model.DimensionValue)
field(:kind)
field(:name)
field(:originalFloodlightConfigurationId)
field(:status)
field(:subaccountId)
field(:suspended)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.Advertiser do
def decode(value, options) do
GoogleApi.DFAReporting.V33.Model.Advertiser.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.Advertiser do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 60.819149 | 640 | 0.728004 |
f7885dc16600e733e133446413f9b95d49a047aa | 2,150 | ex | Elixir | lib/live_sup_web/live/team/components/team_form_component.ex | livesup-dev/livesup | eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446 | [
"Apache-2.0",
"MIT"
] | null | null | null | lib/live_sup_web/live/team/components/team_form_component.ex | livesup-dev/livesup | eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446 | [
"Apache-2.0",
"MIT"
] | 3 | 2022-02-23T15:51:48.000Z | 2022-03-14T22:52:43.000Z | lib/live_sup_web/live/team/components/team_form_component.ex | livesup-dev/livesup | eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446 | [
"Apache-2.0",
"MIT"
] | null | null | null | defmodule LiveSupWeb.Team.Components.TeamFormComponent do
use LiveSupWeb, :live_component
alias LiveSup.Core.Teams
alias LiveSup.Schemas.Team
@impl true
def update(%{team: team} = assigns, socket) do
changeset = Teams.change(team)
{:ok,
socket
|> assign(assigns)
|> assign(:changeset, changeset)
|> allow_upload(:avatar, accept: ~w(.jpg .jpeg .png), max_entries: 1)}
end
@impl true
def handle_event("validate", %{"team" => team_params}, socket) do
changeset =
socket.assigns.team
|> Teams.change(team_params)
|> Map.put(:action, :validate)
{:noreply, assign(socket, :changeset, changeset)}
end
def handle_event("save", %{"team" => team_params}, socket) do
{entries, _} = uploaded_entries(socket, :avatar)
avatar_entry = entries |> Enum.at(0)
file_path = socket |> copy_file(avatar_entry)
save_team(socket, socket.assigns.action, Map.put(team_params, "avatar_url", file_path))
end
defp copy_file(_, nil), do: nil
defp copy_file(socket, avatar_entry) do
Phoenix.LiveView.Upload.consume_uploaded_entry(socket, avatar_entry, fn %{path: path} ->
dest = Path.join("priv/static/uploads", Path.basename(path))
File.cp!(path, dest)
Routes.static_path(socket, "/uploads/#{Path.basename(dest)}")
end)
end
defp save_team(socket, :new, team_params) do
case Teams.create(team_params) do
{:ok, team} ->
{:noreply,
socket
|> put_flash(:info, "Team creted successfully")
|> push_redirect(to: Routes.members_path(socket, :index, team.id))}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :changeset, changeset)}
end
end
defp save_team(socket, :edit, team_params) do
case Teams.update(socket.assigns.team, team_params) do
{:ok, team} ->
{:noreply,
socket
|> put_flash(:info, "Team updated successfully")
|> push_redirect(to: Routes.members_path(socket, :index, team.id))}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :changeset, changeset)}
end
end
end
| 29.861111 | 92 | 0.646512 |
f788782162bd094580e13cf5ac3f66f3a173dd19 | 3,579 | ex | Elixir | day19/lib/day19.ex | carlism/aoc_2020 | 5ffdba5d41d243562fa448a92ff02900354956bb | [
"MIT"
] | null | null | null | day19/lib/day19.ex | carlism/aoc_2020 | 5ffdba5d41d243562fa448a92ff02900354956bb | [
"MIT"
] | null | null | null | day19/lib/day19.ex | carlism/aoc_2020 | 5ffdba5d41d243562fa448a92ff02900354956bb | [
"MIT"
] | null | null | null | defmodule Day19 do
@moduledoc """
Documentation for Day19.
"""
def part1 do
[rules | messages] = read_input("input.txt")
rules = Day19.parsed_rules(rules)
rex = Day19.build_rex(rules, 0)
{:ok, regex} = Regex.compile("^#{rex}$")
messages
|> Enum.map(fn msg -> Regex.match?(regex, msg) end)
|> Enum.filter(fn x -> x end)
|> Enum.count()
|> IO.puts()
end
def part2 do
[rules | messages] = read_input("input.1.txt")
rules = Day19.parsed_rules(rules)
rex = Day19.build_rex(rules, 0)
IO.inspect(String.length(rex))
{:ok, regex} = :re2.compile("^#{rex}$")
messages
|> Enum.map(fn msg -> :re2.run(msg, regex) end)
|> Enum.filter(fn
:nomatch -> false
{:match, _} -> true
end)
|> Enum.count()
|> IO.puts()
end
def read_input(filename) do
[rules | messages] =
File.stream!(filename)
|> Stream.map(&String.trim/1)
|> Stream.chunk_by(fn x -> x == "" end)
|> Stream.reject(fn x -> x == [""] end)
|> Enum.to_list()
[
rules
|> Stream.map(fn x -> x |> String.split(~r/:\s?/, parts: 2, trim: true) end)
|> Enum.reduce(%{}, fn [i, v], map ->
Map.put(map, String.to_integer(i), v)
end)
| messages |> List.flatten()
]
end
def parse_rule(rule) do
letter_result = Regex.named_captures(~r/"(?<letter>.+)"/, rule)
if letter_result do
%SingleLetter{letter: letter_result["letter"]}
else
alt_result = String.split(rule, "|")
if Enum.count(alt_result) > 1 do
%Alternation{
left: parse_rule(List.first(alt_result)),
right: parse_rule(List.last(alt_result))
}
else
rep_result = Regex.named_captures(~r/(?<thing>.+)\+/, rule)
if rep_result do
%Repeat{expr: parse_rule(rep_result["thing"])}
else
nest_result = String.split(rule, "^")
if Enum.count(nest_result) > 1 do
%Nest{
left: parse_rule(List.first(nest_result)),
right: parse_rule(List.last(nest_result))
}
else
seq_result = Regex.scan(~r/\d+/, rule)
if seq_result != [] do
%Sequence{
refs: seq_result |> Enum.map(&List.first/1) |> Enum.map(&String.to_integer/1)
}
end
end
end
end
end
end
def parsed_rules(input) do
input
|> Enum.map(fn {i, r} -> {i, parse_rule(r)} end)
|> Map.new()
end
def build_rex(rules, start, cache \\ nil) do
{:ok, cache} =
if cache == nil do
Agent.start_link(fn -> %{} end)
else
{:ok, cache}
end
if Agent.get(cache, fn map -> map[start] end) == nil do
result = rule_rex(rules, rules[start], cache)
Agent.update(cache, fn map -> Map.put(map, start, result) end)
end
Agent.get(cache, fn map -> map[start] end)
end
def rule_rex(rules, rule, c) do
case rule do
%SingleLetter{letter: l} ->
l
%Alternation{left: l, right: r} ->
"(#{rule_rex(rules, l, c)}|#{rule_rex(rules, r, c)})"
%Sequence{refs: rs} ->
Enum.map(rs, fn r -> build_rex(rules, r, c) end) |> Enum.join()
%Repeat{expr: e} ->
"(#{rule_rex(rules, e, c)})+"
%Nest{left: l, right: r} ->
left = rule_rex(rules, l, c)
right = rule_rex(rules, r, c)
2..10
|> Enum.map(fn count ->
"(#{left}{#{count}}#{right}{#{count}})"
end)
|> Enum.join("|")
end
end
end
| 25.204225 | 93 | 0.526404 |
f78882b1b516a9517cb27b6c0e61eb42be473c47 | 848 | exs | Elixir | apps/glayu/test/glayu/cli/cli_test.exs | pmartinezalvarez/glayu | 8dc30eea4d04c38f5c7999b593c066828423a3dc | [
"MIT"
] | 51 | 2017-05-21T07:27:34.000Z | 2017-11-30T04:34:17.000Z | apps/glayu/test/glayu/cli/cli_test.exs | doc22940/glayu | 8dc30eea4d04c38f5c7999b593c066828423a3dc | [
"MIT"
] | 17 | 2017-06-14T18:40:44.000Z | 2017-08-20T16:14:58.000Z | apps/glayu/test/glayu/cli/cli_test.exs | doc22940/glayu | 8dc30eea4d04c38f5c7999b593c066828423a3dc | [
"MIT"
] | 5 | 2017-06-04T19:55:56.000Z | 2017-07-29T16:18:58.000Z | defmodule Glayu.CLITest do
use ExUnit.Case
import ExUnit.CaptureIO
test "help is displayed with an unknown command" do
assert capture_io(fn -> Glayu.CLI.main(["unknown-command invalid-arg"]) end) == help_output()
end
def help_output do
"\n\e[1mGLAYU COMMANDS\n\e[0m\nglayu \e[0m\e[96minit \e[0m[\e[1mfolder\e[0m] Initializes the website.\n\nglayu \e[0m\e[96mnew \e[0m[\e[1mfolder\e[0m] <\e[1mtitle\e[0m> Creates a new post or page.\n\nglayu \e[0m\e[96mpublish \e[0m<\e[1mfilename\e[0m> Publishes a draft.\n\nglayu \e[0m\e[96mbuild \e[0m[\e[1m-chp\e[0m] [\e[1mregex\e[0m] Generates the static files.\n\nglayu \e[0m\e[96mserve \e[0m[\e[1mport\e[0m] Starts the preview server.\n\nglayu \e[0m\e[96mhelp \e[0m[\e[1mcommand\e[0m] Displays help.\n\n\e[0m\n"
end
end | 60.571429 | 583 | 0.652123 |
f788a6137d3050e03c430c77a039a2d20b2eec58 | 1,199 | ex | Elixir | RAEM/raem/lib/raem/idds/idds.ex | pedromcorreia/Rumo-ao-ensino-superior | be0b9bf417604bdf8a349fde8a8a1c0aaf4c4cdb | [
"MIT"
] | null | null | null | RAEM/raem/lib/raem/idds/idds.ex | pedromcorreia/Rumo-ao-ensino-superior | be0b9bf417604bdf8a349fde8a8a1c0aaf4c4cdb | [
"MIT"
] | null | null | null | RAEM/raem/lib/raem/idds/idds.ex | pedromcorreia/Rumo-ao-ensino-superior | be0b9bf417604bdf8a349fde8a8a1c0aaf4c4cdb | [
"MIT"
] | 2 | 2018-02-24T19:56:21.000Z | 2018-02-26T00:16:41.000Z | defmodule Raem.Idds do
@moduledoc """
The Idds context.
"""
import Ecto.Query
alias Raem.Repo
alias Raem.Idds.Idd
@doc """
Creates a idd.
## Examples
iex> create_idd(%{field: value})
{:ok, %Idd{}}
iex> create_idd(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_idd(attrs \\ %{}) do
%Idd{}
|> Idd.changeset(attrs)
|> Repo.insert()
end
@doc """
Returns the list of idds.
## Examples
iex> list_idds()
[%Idd{}, ...]
"""
def list_idds do
Repo.all(Idd)
end
@doc """
Gets a single idd.
Raises `Ecto.NoResultsError` if the Idd does not exist.
## Examples
iex> get_idd!(123)
%Idd{}
iex> get_idd!(456)
** (Ecto.NoResultsError)
"""
def get_idd!(id), do: Repo.get!(Idd, id)
def list_all_by(area_enquadramento, :area_enquadramento) do
from(i in Idd,
where: i.area_enquadramento == ^area_enquadramento,
select: %{
area_enquadramento: i.area_enquadramento,
municipio_curso: i.municipio_curso,
id: i.id,
nota_padronizada_idd: i.nota_padronizada_idd,
nome: i.nome_ies})
|> Repo.all()
end
end
| 16.652778 | 61 | 0.582986 |
f788e6831e49bcf603a9a9c28400eff30c14977f | 404 | ex | Elixir | ears/lib/events.ex | mashbytes/sentry | d4b13419694d0e30199af6ff0f8a2b68ef54fefa | [
"MIT"
] | null | null | null | ears/lib/events.ex | mashbytes/sentry | d4b13419694d0e30199af6ff0f8a2b68ef54fefa | [
"MIT"
] | 2 | 2021-03-09T20:59:23.000Z | 2021-05-10T18:01:00.000Z | ears/lib/events.ex | mashbytes/sentry | d4b13419694d0e30199af6ff0f8a2b68ef54fefa | [
"MIT"
] | null | null | null | defmodule Ears.Event do
defmacro __using__(_) do
quote do
defstruct [:node, :since]
def new(since \\ DateTime.utc_now(), node \\ Node.self()) do
%__MODULE__{ node: node, since: since }
end
end
end
end
defmodule Ears.Events.Noisy do
use Ears.Event
end
defmodule Ears.Events.Quiet do
use Ears.Event
end
defmodule Ears.Events.Offline do
use Ears.Event
end
| 14.962963 | 66 | 0.668317 |
f788ed0278b436e6319afcee08a143fa2ef3597f | 1,686 | ex | Elixir | clients/container_analysis/lib/google_api/container_analysis/v1alpha1/model/file_hashes.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/container_analysis/lib/google_api/container_analysis/v1alpha1/model/file_hashes.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/container_analysis/lib/google_api/container_analysis/v1alpha1/model/file_hashes.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.ContainerAnalysis.V1alpha1.Model.FileHashes do
@moduledoc """
Container message for hashes of byte content of files, used in Source
messages to verify integrity of source input to the build.
## Attributes
* `fileHash` (*type:* `list(GoogleApi.ContainerAnalysis.V1alpha1.Model.Hash.t)`, *default:* `nil`) - Collection of file hashes.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:fileHash => list(GoogleApi.ContainerAnalysis.V1alpha1.Model.Hash.t())
}
field(:fileHash, as: GoogleApi.ContainerAnalysis.V1alpha1.Model.Hash, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.ContainerAnalysis.V1alpha1.Model.FileHashes do
def decode(value, options) do
GoogleApi.ContainerAnalysis.V1alpha1.Model.FileHashes.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ContainerAnalysis.V1alpha1.Model.FileHashes do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.125 | 131 | 0.755042 |
f788ed237ebc74c5872cd24920be48236875fb11 | 92 | exs | Elixir | test/eliscore_chat_web/views/layout_view_test.exs | CandN/eliscore-chat | a626077bf1c46b329c15f63db9a25521b43bd61b | [
"MIT"
] | null | null | null | test/eliscore_chat_web/views/layout_view_test.exs | CandN/eliscore-chat | a626077bf1c46b329c15f63db9a25521b43bd61b | [
"MIT"
] | null | null | null | test/eliscore_chat_web/views/layout_view_test.exs | CandN/eliscore-chat | a626077bf1c46b329c15f63db9a25521b43bd61b | [
"MIT"
] | null | null | null | defmodule EliscoreChatWeb.LayoutViewTest do
use EliscoreChatWeb.ConnCase, async: true
end
| 23 | 43 | 0.847826 |
f7894306046ee334bfe0f0a7bc633084db0eb935 | 2,717 | ex | Elixir | lib/mix/lib/mix/tasks/local.hex.ex | carlosantoniodasilva/elixir | 0b7d1c9d4964cd6699b72298294844d8d7d694b5 | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/tasks/local.hex.ex | carlosantoniodasilva/elixir | 0b7d1c9d4964cd6699b72298294844d8d7d694b5 | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/tasks/local.hex.ex | carlosantoniodasilva/elixir | 0b7d1c9d4964cd6699b72298294844d8d7d694b5 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Local.Hex do
use Mix.Task
@hex_s3 "https://s3.amazonaws.com/s3.hex.pm"
@hex_list_url @hex_s3 <> "/installs/list.csv"
@hex_archive_url @hex_s3 <> "/installs/[VERSION]/hex.ez"
@hex_requirement ">= 0.5.0"
@shortdoc "Install hex locally"
@moduledoc """
Install Hex locally.
mix local.hex
## Command line options
* `--force` - forces installation without a shell prompt; primarily
intended for automation in build systems like make
"""
@spec run(OptionParser.argv) :: boolean
def run(args) do
version = get_matching_version()
url = String.replace(@hex_archive_url, "[VERSION]", version)
Mix.Tasks.Archive.Install.run [url, "--system" | args]
end
@doc false
# Returns true if Hex is loaded or installed, otherwise returns false.
@spec ensure_installed?(atom) :: boolean
def ensure_installed?(app) do
if Code.ensure_loaded?(Hex) do
true
else
shell = Mix.shell
shell.info "Could not find hex, which is needed to build dependency #{inspect app}"
if shell.yes?("Shall I install hex?") do
run ["--force"]
else
false
end
end
end
@doc false
# Returns true if have required Hex, returns false if don't and don't update,
# if update then exits.
@spec ensure_updated?() :: boolean
def ensure_updated?() do
if Code.ensure_loaded?(Hex) do
if Version.match?(Hex.version, @hex_requirement) do
true
else
Mix.shell.info "Mix requires hex #{@hex_requirement} but you have #{Hex.version}"
if Mix.shell.yes?("Shall I abort the current command and update hex?") do
run ["--force"]
exit({:shutdown, 0})
end
false
end
else
false
end
end
@doc false
def start do
try do
Hex.start
catch
kind, reason ->
stacktrace = System.stacktrace
Mix.shell.error "Could not start Hex. Try fetching a new version with " <>
"`mix local.hex` or uninstalling it with `mix archive.uninstall hex.ez`"
:erlang.raise(kind, reason, stacktrace)
end
end
defp get_matching_version do
Mix.Utils.read_path!(@hex_list_url)
|> parse_csv
|> all_eligibile_versions
|> List.last
end
defp parse_csv(body) do
:binary.split(body, "\n", [:global, :trim])
|> Enum.flat_map(fn line ->
[_hex|elixirs] = :binary.split(line, ",", [:global, :trim])
elixirs
end)
|> Enum.uniq
end
defp all_eligibile_versions(versions) do
{:ok, current_version} = Version.parse(System.version)
Enum.filter(versions, &Version.compare(&1, current_version) != :gt)
end
end
| 26.125 | 96 | 0.627898 |
f7899f0f100b92dab943afebaca9f797433aed1b | 14,812 | ex | Elixir | clients/books/lib/google_api/books/v1/api/myconfig.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/books/lib/google_api/books/v1/api/myconfig.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/books/lib/google_api/books/v1/api/myconfig.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.Books.V1.Api.Myconfig do
@moduledoc """
API calls for all endpoints tagged `Myconfig`.
"""
alias GoogleApi.Books.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets the current settings for the user.
## Parameters
* `connection` (*type:* `GoogleApi.Books.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Books.V1.Model.Usersettings{}}` on success
* `{:error, info}` on failure
"""
@spec books_myconfig_get_user_settings(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.Books.V1.Model.Usersettings.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def books_myconfig_get_user_settings(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/myconfig/getUserSettings", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Books.V1.Model.Usersettings{}])
end
@doc """
Release downloaded content access restriction.
## Parameters
* `connection` (*type:* `GoogleApi.Books.V1.Connection.t`) - Connection to server
* `volume_ids` (*type:* `list(String.t)`) - The volume(s) to release restrictions for.
* `cpksver` (*type:* `String.t`) - The device/version ID from which to release the restriction.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:locale` (*type:* `String.t`) - ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
* `:source` (*type:* `String.t`) - String to identify the originator of this request.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Books.V1.Model.DownloadAccesses{}}` on success
* `{:error, info}` on failure
"""
@spec books_myconfig_release_download_access(
Tesla.Env.client(),
list(String.t()),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Books.V1.Model.DownloadAccesses.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def books_myconfig_release_download_access(
connection,
volume_ids,
cpksver,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:locale => :query,
:source => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/myconfig/releaseDownloadAccess", %{})
|> Request.add_param(:query, :volumeIds, volume_ids)
|> Request.add_param(:query, :cpksver, cpksver)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Books.V1.Model.DownloadAccesses{}])
end
@doc """
Request concurrent and download access restrictions.
## Parameters
* `connection` (*type:* `GoogleApi.Books.V1.Connection.t`) - Connection to server
* `source` (*type:* `String.t`) - String to identify the originator of this request.
* `volume_id` (*type:* `String.t`) - The volume to request concurrent/download restrictions for.
* `nonce` (*type:* `String.t`) - The client nonce value.
* `cpksver` (*type:* `String.t`) - The device/version ID from which to request the restrictions.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:licenseTypes` (*type:* `String.t`) - The type of access license to request. If not specified, the default is BOTH.
* `:locale` (*type:* `String.t`) - ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Books.V1.Model.RequestAccess{}}` on success
* `{:error, info}` on failure
"""
@spec books_myconfig_request_access(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Books.V1.Model.RequestAccess.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def books_myconfig_request_access(
connection,
source,
volume_id,
nonce,
cpksver,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:licenseTypes => :query,
:locale => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/myconfig/requestAccess", %{})
|> Request.add_param(:query, :source, source)
|> Request.add_param(:query, :volumeId, volume_id)
|> Request.add_param(:query, :nonce, nonce)
|> Request.add_param(:query, :cpksver, cpksver)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Books.V1.Model.RequestAccess{}])
end
@doc """
Request downloaded content access for specified volumes on the My eBooks shelf.
## Parameters
* `connection` (*type:* `GoogleApi.Books.V1.Connection.t`) - Connection to server
* `source` (*type:* `String.t`) - String to identify the originator of this request.
* `nonce` (*type:* `String.t`) - The client nonce value.
* `cpksver` (*type:* `String.t`) - The device/version ID from which to release the restriction.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:features` (*type:* `list(String.t)`) - List of features supported by the client, i.e., 'RENTALS'
* `:includeNonComicsSeries` (*type:* `boolean()`) - Set to true to include non-comics series. Defaults to false.
* `:locale` (*type:* `String.t`) - ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
* `:showPreorders` (*type:* `boolean()`) - Set to true to show pre-ordered books. Defaults to false.
* `:volumeIds` (*type:* `list(String.t)`) - The volume(s) to request download restrictions for.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Books.V1.Model.Volumes{}}` on success
* `{:error, info}` on failure
"""
@spec books_myconfig_sync_volume_licenses(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Books.V1.Model.Volumes.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def books_myconfig_sync_volume_licenses(
connection,
source,
nonce,
cpksver,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:features => :query,
:includeNonComicsSeries => :query,
:locale => :query,
:showPreorders => :query,
:volumeIds => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/myconfig/syncVolumeLicenses", %{})
|> Request.add_param(:query, :source, source)
|> Request.add_param(:query, :nonce, nonce)
|> Request.add_param(:query, :cpksver, cpksver)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Books.V1.Model.Volumes{}])
end
@doc """
Sets the settings for the user. If a sub-object is specified, it will overwrite the existing sub-object stored in the server. Unspecified sub-objects will retain the existing value.
## Parameters
* `connection` (*type:* `GoogleApi.Books.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Books.V1.Model.Usersettings.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Books.V1.Model.Usersettings{}}` on success
* `{:error, info}` on failure
"""
@spec books_myconfig_update_user_settings(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.Books.V1.Model.Usersettings.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def books_myconfig_update_user_settings(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/myconfig/updateUserSettings", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Books.V1.Model.Usersettings{}])
end
end
| 42.563218 | 187 | 0.622333 |
f789a81441ec5dbb0460c5b70d503ae070df3cc9 | 1,785 | ex | Elixir | clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__disk_config.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__disk_config.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__disk_config.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_DiskConfig do
@moduledoc """
Represents the config of disk options.
## Attributes
* `bootDiskSizeGb` (*type:* `integer()`, *default:* `nil`) - Size in GB of the boot disk (default is 100GB).
* `bootDiskType` (*type:* `String.t`, *default:* `nil`) - Type of the boot disk (default is "pd-ssd"). Valid values: "pd-ssd" (Persistent Disk Solid State Drive) or "pd-standard" (Persistent Disk Hard Disk Drive).
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:bootDiskSizeGb => integer(),
:bootDiskType => String.t()
}
field(:bootDiskSizeGb)
field(:bootDiskType)
end
defimpl Poison.Decoder, for: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_DiskConfig do
def decode(value, options) do
GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_DiskConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_DiskConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.7 | 217 | 0.735014 |
f789bacd8d715d0c982045d3bfd6783b39d66f1b | 5,896 | ex | Elixir | lib/ex_oauth2_provider/oauth2/token/strategy/revoke.ex | loopsocial/ex_oauth2_provider | 59d177f1c7581e1d794823279067022b1598f5f2 | [
"MIT"
] | null | null | null | lib/ex_oauth2_provider/oauth2/token/strategy/revoke.ex | loopsocial/ex_oauth2_provider | 59d177f1c7581e1d794823279067022b1598f5f2 | [
"MIT"
] | null | null | null | lib/ex_oauth2_provider/oauth2/token/strategy/revoke.ex | loopsocial/ex_oauth2_provider | 59d177f1c7581e1d794823279067022b1598f5f2 | [
"MIT"
] | null | null | null | defmodule ExOauth2Provider.Token.Revoke do
@moduledoc """
Functions for dealing with revocation.
"""
alias ExOauth2Provider.{
AccessTokens,
Config,
Token.Utils,
Token.Utils.Response,
Utils.Error
}
@doc """
Revokes access token.
The authorization server, if applicable, first authenticates the client
and checks its ownership of the provided token.
ExOauth2Provider does not use the token_type_hint logic described in the
RFC 7009 due to the refresh token implementation that is a field in
the access token schema.
## Example confidential client
ExOauth2Provider.Token.revoke(%{
"client_id" => "Jf5rM8hQBc",
"client_secret" => "secret",
"token" => "fi3S9u"
}, otp_app: :my_app)
## Response
{:ok, %{}}
## Example public client
ExOauth2Provider.Token.revoke(%{
"token" => "fi3S9u"
}, otp_app: :my_app)
## Response
{:ok, %{}}
"""
@spec revoke(map(), keyword()) :: {:ok, map()} | {:error, map(), atom()}
def revoke(request, config \\ []) do
{:ok, %{request: request}}
|> load_client_if_presented(config)
|> return_error()
|> load_access_token(config)
|> validate_request()
|> revoke_token(config)
|> Response.revocation_response(config)
end
defp load_client_if_presented({:ok, %{request: %{"client_id" => _}} = params}, config),
do: Utils.load_client({:ok, params}, config)
defp load_client_if_presented({:ok, params}, _config), do: {:ok, params}
defp load_access_token({:error, %{error: _} = params}, _config), do: {:error, params}
defp load_access_token({:ok, %{request: %{"token" => _}} = params}, config) do
{:ok, params}
|> get_access_token(config)
|> get_refresh_token(config)
|> preload_token_associations(config)
end
defp load_access_token({:ok, params}, _config),
do: Error.add_error({:ok, params}, Error.invalid_request())
defp get_access_token({:ok, %{request: %{"token" => token}} = params}, config) do
token
|> AccessTokens.get_by_token(config)
|> case do
nil -> Error.add_error({:ok, params}, Error.invalid_request())
access_token -> {:ok, Map.put(params, :access_token, access_token)}
end
end
defp get_refresh_token({:ok, %{access_token: _} = params}, _config), do: {:ok, params}
defp get_refresh_token({:error, %{error: _} = params}, _config), do: {:error, params}
defp get_refresh_token({:ok, %{request: %{"token" => token}} = params}, config) do
token
|> AccessTokens.get_by_refresh_token(config)
|> case do
nil -> Error.add_error({:ok, params}, Error.invalid_request())
access_token -> {:ok, Map.put(params, :access_token, access_token)}
end
end
defp preload_token_associations({:error, params}, _config), do: {:error, params}
defp preload_token_associations({:ok, %{access_token: access_token} = params}, config) do
if is_nil(access_token.application_id) do
{:ok, params}
else
access_token =
case params do
%{client: application} ->
Map.put(access_token, :application, application)
_ ->
Config.repo(config).preload(access_token, :application)
end
{:ok, Map.put(params, :access_token, access_token)}
end
end
defp validate_request({:error, params}), do: {:error, params}
defp validate_request({:ok, params}) do
{:ok, params}
|> validate_permissions()
|> validate_accessible()
end
# This will verify permissions on the access token and client.
#
# OAuth 2.0 Section 2.1 defines two client types, "public" & "confidential".
# Public clients (as per RFC 7009) do not require authentication whereas
# confidential clients must be authenticated for their token revocation.
#
# Once a confidential client is authenticated, it must be authorized to
# revoke the provided access or refresh token. This ensures one client
# cannot revoke another's tokens.
#
# ExOauth2Provider determines the client type implicitly via the presence of the
# OAuth client associated with a given access or refresh token. Since public
# clients authenticate the resource owner via "password" or "implicit" grant
# types, they set the application_id as null (since the claim cannot be
# verified).
#
# https://tools.ietf.org/html/rfc6749#section-2.1
# https://tools.ietf.org/html/rfc7009
# Client is public, authentication unnecessary
defp validate_permissions({:ok, %{access_token: %{application_id: nil}} = params}),
do: {:ok, params}
# Client is confidential, therefore client authentication & authorization is required
defp validate_permissions({:ok, %{access_token: %{application_id: _id}} = params}),
do: validate_ownership({:ok, params})
defp validate_ownership(
{:ok,
%{access_token: %{application_id: application_id}, client: %{id: client_id}} = params}
)
when application_id == client_id,
do: {:ok, params}
defp validate_ownership({:ok, params}),
do: Error.add_error({:ok, params}, Error.invalid_request())
defp validate_accessible({:error, params}), do: {:error, params}
defp validate_accessible({:ok, %{access_token: access_token} = params}) do
case AccessTokens.is_accessible?(access_token) do
true -> {:ok, params}
false -> Error.add_error({:ok, params}, Error.invalid_request())
end
end
defp revoke_token({:error, params}, _config), do: {:error, params}
defp revoke_token({:ok, %{access_token: access_token} = params}, config) do
case AccessTokens.revoke(access_token, config) do
{:ok, _} -> {:ok, params}
{:error, _} -> Error.add_error({:ok, params}, Error.invalid_request())
end
end
defp return_error({:error, params}), do: {:error, Map.put(params, :should_return_error, true)}
defp return_error({:ok, params}), do: {:ok, params}
end
| 33.691429 | 96 | 0.666214 |
f789c944127420d2e4e48859d702b015d84cf708 | 197 | exs | Elixir | test/snapshots/ubuntu_1804.exs | elcritch/ExDhcp | 7c2641eaf86b1e1e0cbbaef67908a8e1829c45a8 | [
"MIT"
] | null | null | null | test/snapshots/ubuntu_1804.exs | elcritch/ExDhcp | 7c2641eaf86b1e1e0cbbaef67908a8e1829c45a8 | [
"MIT"
] | null | null | null | test/snapshots/ubuntu_1804.exs | elcritch/ExDhcp | 7c2641eaf86b1e1e0cbbaef67908a8e1829c45a8 | [
"MIT"
] | 1 | 2019-12-16T04:53:17.000Z | 2019-12-16T04:53:17.000Z | defmodule DhcpTest.Snapshot.Ubuntu1804 do
@moduledoc """
snapshot testing verifying that the DHCP server can correctly provision
DHCP addresses for "default" Ubuntu 18.04 netplan.
"""
end
| 24.625 | 73 | 0.766497 |
f789e9099f72a01f76ccc02f16e88d6b523b9e17 | 3,856 | exs | Elixir | test/lib/stats/stats_parser_test.exs | soleo/changelog.com | 621c7471b23379e1cdd4a0c960b66ed98d8d1a53 | [
"MIT"
] | null | null | null | test/lib/stats/stats_parser_test.exs | soleo/changelog.com | 621c7471b23379e1cdd4a0c960b66ed98d8d1a53 | [
"MIT"
] | null | null | null | test/lib/stats/stats_parser_test.exs | soleo/changelog.com | 621c7471b23379e1cdd4a0c960b66ed98d8d1a53 | [
"MIT"
] | null | null | null | defmodule ChangelogStatsParserTest do
use ExUnit.Case
alias Changelog.Stats.{Parser, Entry}
@log1 ~s{<134>2016-10-14T16:56:41Z cache-jfk8141 S3TheChangelog[81772]: 142.169.78.110,[14/Oct/2016:16:56:40 +0000],/uploads/podcast/145/the-changelog-145.mp3,2,206,"AppleCoreMedia/1.0.0.14A403 (iPhone; U; CPU OS 10_0_1 like Mac OS X; en_ca)",45.500,-73.583,"(null)",NA,CA,"Canada"}
@log2 ~s{<134>2016-10-13T18:09:07Z cache-fra1237 S3TheChangelog[415970]: 78.35.187.78,[13/Oct/2016:18:09:04 +0000],/uploads/podcast/219/the-changelog-219.mp3,262144,200,"Mozilla/5.0 (Linux; Android 6.0.1; HUAWEI RIO-L01 Build/HuaweiRIO-L01) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",50.933,6.950,"Köln",EU,DE,"Germany"}
@log3 ~s{<134>2016-10-14T06:21:01Z cache-bma7035 S3TheChangelog[465510]: 122.163.200.110,[14/Oct/2016:06:18:55 +0000],/uploads/podcast/204/the-changelog-204.mp3,13132042,206,""Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0"",26.850,80.917,"Lucknow",AS,IN,"India"}
@log4 ~s{<134>2016-11-03T09:06:02Z cache-cdg8721 S3TheChangelog[301760]: 149.202.170.38,[03/Nov/2016:09:06:00 +0000],/uploads/podcast/224/the-changelog-224.mp3,0,200,"<div style="display:none;">",48.867,2.333,"Paris",EU,FR,"France"}
@file1 ~s{test/fixtures/logs/2016-10-14T13:00:00.000-oe6twX9qexnc62cAAAAA.log}
@file2 ~s{test/fixtures/logs/2016-10-13T08:00:00.000-aQlu8sDqCqHgsnMAAAAA.log}
describe "parse_files" do
test "it creates a list with all the entries for the list of files given" do
entries = Parser.parse_files([@file1, @file2])
# actually 73 lines, but 26 of them have 0 byte entries
assert length(entries) == (73 - 26)
end
end
describe "parse_file" do
test "it creates a list with one entry when file has one line in it" do
entries = Parser.parse_file(@file1)
assert length(entries) == 1
end
test "it creates a list with many entries when file has many lines in it" do
entries = Parser.parse_file(@file2)
# actually 72 lines, but 26 of them have 0 byte entries
assert length(entries) == (72 - 26)
end
end
describe "parse_line" do
test "it parses log1 into a value Entry" do
assert Parser.parse_line(@log1) == %Entry{
ip: "142.169.78.110",
episode: "145",
bytes: 2,
status: 206,
agent: "AppleCoreMedia/1.0.0.14A403 (iPhone; U; CPU OS 10_0_1 like Mac OS X; en_ca)",
latitude: 45.5,
longitude: -73.583,
city_name: "Unknown",
continent_code: "NA",
country_code: "CA",
country_name: "Canada"}
end
test "it parses log2 in to a valid Entry" do
assert Parser.parse_line(@log2) == %Entry{
ip: "78.35.187.78",
episode: "219",
bytes: 262144,
status: 200,
agent: "Mozilla/5.0 (Linux; Android 6.0.1; HUAWEI RIO-L01 Build/HuaweiRIO-L01) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
latitude: 50.933,
longitude: 6.950,
city_name: "Köln",
continent_code: "EU",
country_code: "DE",
country_name: "Germany"}
end
test "it parses log3 (which contains double quotes in the user agent) in to a valid Entry" do
assert Parser.parse_line(@log3) == %Entry{
ip: "122.163.200.110",
episode: "204",
bytes: 13132042,
status: 206,
agent: "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0",
latitude: 26.850,
longitude: 80.917,
city_name: "Lucknow",
continent_code: "AS",
country_code: "IN",
country_name: "India"}
end
test "it rescues CSV parse errors and returns a 0 byte entry otherwise" do
assert Parser.parse_line(@log4) == %Entry{bytes: 0}
end
end
end
| 45.364706 | 361 | 0.653786 |
f78a04157eb8e5d5501e33deb0ba597f0ce86a9d | 2,699 | ex | Elixir | lib/ecto_job/config.ex | niku/ecto_job | 666637007c71feddec7e59cb1c0a069d33dfe947 | [
"MIT"
] | null | null | null | lib/ecto_job/config.ex | niku/ecto_job | 666637007c71feddec7e59cb1c0a069d33dfe947 | [
"MIT"
] | null | null | null | lib/ecto_job/config.ex | niku/ecto_job | 666637007c71feddec7e59cb1c0a069d33dfe947 | [
"MIT"
] | null | null | null | defmodule EctoJob.Config do
@moduledoc """
EctoJob Configuration struct.
Configuration may be provided directly to your JobQueue supervisor:
supervisor(MyApp.JobQueue, [[repo: MyApp.Repo, max_demand: 100, log_level: :debug]])
Or if the configuration should be environment-specific, use Mix config:
config :ecto_job,
repo: MyApp.Repo,
max_demand: 100,
log_level: :debug
Otherwise default values will be used.
Configurable values:
- `repo`: (Required) The `Ecto.Repo` module in your application to use for accessing the `JobQueue`
- `max_demand`: (Default `100`) The number of concurrent worker processes to use, see `ConsumerSupervisor` for more details
- `log`: (Default `true`) Enables logging using the standard Elixir `Logger` module
- `log_level`: (Default `:info`) The level used to log messages, see [Logger](https://hexdocs.pm/logger/Logger.html#module-levels)
- `poll_interval`: (Default `60_000`) Time in milliseconds between polling the `JobQueue` for scheduled jobs or jobs due to be retried
- `reservation_timeout`: (Default `60_000`) Time in ms during which a `RESERVED` job state is held while waiting for a worker to start the job. Subsequent polls will return the job to the `AVAILABLE` state for retry.
- `execution_timeout`: (Default `300_000`) Time in ms that a worker is allotted to hold a job in the `IN_PROGRESS` state before subsequent polls return a job to the `AVAILABLE` state for retry. The timeout is extended by `execution_timeout` for every retry attempt until `max_attemps` is reached for a given job.
"""
alias __MODULE__
defstruct repo: nil,
schema: nil,
max_demand: 100,
log: true,
log_level: :info,
poll_interval: 60_000,
reservation_timeout: 60_000,
execution_timeout: 300_000
@type t :: %Config{}
@doc """
Constructs a new `Config` from params, falling back to Application environment then to default values.
## Example
iex> EctoJob.Config.new(repo: MyApp.Repo, log: false)
%EctoJob.Config{
repo: MyApp.Repo,
max_demand: 100,
log: false,
log_level: :info,
poll_interval: 60_000,
reservation_timeout: 60_000,
execution_timeout: 300_000
}
"""
@spec new(Keyword.t()) :: Config.t()
def new(params \\ []) when is_list(params) do
defaults = Map.from_struct(%Config{})
Enum.reduce(defaults, %Config{}, fn {key, default}, config ->
default = Application.get_env(:ecto_job, key, default)
value = Keyword.get(params, key, default)
Map.put(config, key, value)
end)
end
end
| 39.115942 | 316 | 0.677288 |
f78a2510ac5417c97bf8923404b53d69b01dfbbd | 2,063 | exs | Elixir | apps/re_integrations/test/google/calendars/calendars_test.exs | ruby2elixir/emcasa-backend | 70d7f4f233555417941ffa6ada84cf8740c21dd2 | [
"MIT"
] | 4 | 2019-11-01T16:29:31.000Z | 2020-10-10T21:20:12.000Z | apps/re_integrations/test/google/calendars/calendars_test.exs | eduardomartines/emcasa-backend | 70d7f4f233555417941ffa6ada84cf8740c21dd2 | [
"MIT"
] | null | null | null | apps/re_integrations/test/google/calendars/calendars_test.exs | eduardomartines/emcasa-backend | 70d7f4f233555417941ffa6ada84cf8740c21dd2 | [
"MIT"
] | 5 | 2019-11-04T21:25:45.000Z | 2020-02-13T23:49:36.000Z | defmodule ReIntegrations.Google.CalendarsTest do
@moduledoc false
use ReIntegrations.ModelCase
alias GoogleApi.Calendar.V3.Model
alias ReIntegrations.Google.Calendars
import Tesla.Mock
import Re.Factory
@calendar_id "calendar123"
@calendar_response """
{
"id": "#{@calendar_id}",
"kind": "calendar#calendar"
}
"""
@acl_response """
{
"kind": "calendar#acl"
}
"""
@event_response """
{
"kind": "calendar#event"
}
"""
describe "insert/2" do
setup do
mock(fn
%{method: :post, url: "https://www.googleapis.com/calendar/v3/calendars"} ->
%Tesla.Env{status: 200, body: @calendar_response}
%{
method: :post,
url: "https://www.googleapis.com/calendar/v3/calendars/#{@calendar_id}/acl"
} ->
%Tesla.Env{status: 200, body: @acl_response}
end)
:ok
end
test "creates a google calendar and inserts it to the database" do
address = insert(:address)
assert {:ok, calendar = %Re.Calendars.Calendar{}} =
Calendars.insert(%{
name: "test",
speed: "slow",
shift_start: ~T[10:00:00],
shift_end: ~T[12:00:00],
address_uuid: address.uuid
})
assert ~T[10:00:00] == calendar.shift_start
assert ~T[12:00:00] == calendar.shift_end
assert address.uuid == calendar.address_uuid
end
end
describe "insert_event/2" do
setup do
mock(fn
%{
method: :post,
url: "https://www.googleapis.com/calendar/v3/calendars/#{@calendar_id}/events"
} ->
%Tesla.Env{status: 200, body: @event_response}
end)
:ok
end
test "inserts an event into a google calendar" do
calendar = insert(:calendar, external_id: @calendar_id)
{:ok, start_time} = DateTime.now("Etc/UTC")
assert {:ok, %Model.Event{}} =
Calendars.insert_event(calendar, summary: "test", start: start_time)
end
end
end
| 22.67033 | 88 | 0.572467 |
f78a492e42eeff56184be764a4815814ad616ada | 13,716 | ex | Elixir | clients/admin/lib/google_api/admin/directory_v1/api/role_assignments.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/admin/lib/google_api/admin/directory_v1/api/role_assignments.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/admin/lib/google_api/admin/directory_v1/api/role_assignments.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.Admin.Directory_v1.Api.RoleAssignments do
@moduledoc """
API calls for all endpoints tagged `RoleAssignments`.
"""
alias GoogleApi.Admin.Directory_v1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Deletes a role assignment.
## Parameters
* `connection` (*type:* `GoogleApi.Admin.Directory_v1.Connection.t`) - Connection to server
* `customer` (*type:* `String.t`) - Immutable ID of the Google Workspace account.
* `role_assignment_id` (*type:* `String.t`) - Immutable ID of the role assignment.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %{}}` on success
* `{:error, info}` on failure
"""
@spec directory_role_assignments_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()}
def directory_role_assignments_delete(
connection,
customer,
role_assignment_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/admin/directory/v1/customer/{customer}/roleassignments/{roleAssignmentId}",
%{
"customer" => URI.encode(customer, &URI.char_unreserved?/1),
"roleAssignmentId" =>
URI.encode(role_assignment_id, &(URI.char_unreserved?(&1) || &1 == ?/))
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
@doc """
Retrieves a role assignment.
## Parameters
* `connection` (*type:* `GoogleApi.Admin.Directory_v1.Connection.t`) - Connection to server
* `customer` (*type:* `String.t`) - Immutable ID of the Google Workspace account.
* `role_assignment_id` (*type:* `String.t`) - Immutable ID of the role assignment.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Admin.Directory_v1.Model.RoleAssignment{}}` on success
* `{:error, info}` on failure
"""
@spec directory_role_assignments_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Admin.Directory_v1.Model.RoleAssignment.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def directory_role_assignments_get(
connection,
customer,
role_assignment_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/admin/directory/v1/customer/{customer}/roleassignments/{roleAssignmentId}",
%{
"customer" => URI.encode(customer, &URI.char_unreserved?/1),
"roleAssignmentId" =>
URI.encode(role_assignment_id, &(URI.char_unreserved?(&1) || &1 == ?/))
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Admin.Directory_v1.Model.RoleAssignment{}])
end
@doc """
Creates a role assignment.
## Parameters
* `connection` (*type:* `GoogleApi.Admin.Directory_v1.Connection.t`) - Connection to server
* `customer` (*type:* `String.t`) - Immutable ID of the Google Workspace account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.Admin.Directory_v1.Model.RoleAssignment.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Admin.Directory_v1.Model.RoleAssignment{}}` on success
* `{:error, info}` on failure
"""
@spec directory_role_assignments_insert(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Admin.Directory_v1.Model.RoleAssignment.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def directory_role_assignments_insert(connection, customer, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/admin/directory/v1/customer/{customer}/roleassignments", %{
"customer" => URI.encode(customer, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Admin.Directory_v1.Model.RoleAssignment{}])
end
@doc """
Retrieves a paginated list of all roleAssignments.
## Parameters
* `connection` (*type:* `GoogleApi.Admin.Directory_v1.Connection.t`) - Connection to server
* `customer` (*type:* `String.t`) - Immutable ID of the Google Workspace account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:maxResults` (*type:* `integer()`) - Maximum number of results to return.
* `:pageToken` (*type:* `String.t`) - Token to specify the next page in the list.
* `:roleId` (*type:* `String.t`) - Immutable ID of a role. If included in the request, returns only role assignments containing this role ID.
* `:userKey` (*type:* `String.t`) - The user's primary email address, alias email address, or unique user ID. If included in the request, returns role assignments only for this user.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Admin.Directory_v1.Model.RoleAssignments{}}` on success
* `{:error, info}` on failure
"""
@spec directory_role_assignments_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Admin.Directory_v1.Model.RoleAssignments.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def directory_role_assignments_list(connection, customer, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:maxResults => :query,
:pageToken => :query,
:roleId => :query,
:userKey => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/admin/directory/v1/customer/{customer}/roleassignments", %{
"customer" => URI.encode(customer, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Admin.Directory_v1.Model.RoleAssignments{}])
end
end
| 44.245161 | 196 | 0.617381 |
f78a504ffa0c93af6c74ff7992c1b36201dd875f | 3,442 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/scheduling.ex | jamesvl/elixir-google-api | 6c87fb31d996f08fb42ce6066317e9d652a87acc | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/scheduling.ex | jamesvl/elixir-google-api | 6c87fb31d996f08fb42ce6066317e9d652a87acc | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/compute/lib/google_api/compute/v1/model/scheduling.ex | myskoach/elixir-google-api | 4f8cbc2fc38f70ffc120fd7ec48e27e46807b563 | [
"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.Scheduling do
@moduledoc """
Sets the scheduling options for an Instance. NextID: 13
## Attributes
* `automaticRestart` (*type:* `boolean()`, *default:* `nil`) - Specifies whether the instance should be automatically restarted if it is terminated by Compute Engine (not terminated by a user). You can only set the automatic restart option for standard instances. Preemptible instances cannot be automatically restarted.
By default, this is set to true so an instance is automatically restarted if it is terminated by Compute Engine.
* `locationHint` (*type:* `String.t`, *default:* `nil`) - An opaque location hint used to place the instance close to other resources. This field is for use by internal tools that use the public API.
* `minNodeCpus` (*type:* `integer()`, *default:* `nil`) - The minimum number of virtual CPUs this instance will consume when running on a sole-tenant node.
* `nodeAffinities` (*type:* `list(GoogleApi.Compute.V1.Model.SchedulingNodeAffinity.t)`, *default:* `nil`) - A set of node affinity and anti-affinity configurations. Refer to Configuring node affinity for more information. Overrides reservationAffinity.
* `onHostMaintenance` (*type:* `String.t`, *default:* `nil`) - Defines the maintenance behavior for this instance. For standard instances, the default behavior is MIGRATE. For preemptible instances, the default and only possible behavior is TERMINATE. For more information, see Setting Instance Scheduling Options.
* `preemptible` (*type:* `boolean()`, *default:* `nil`) - Defines whether the instance is preemptible. This can only be set during instance creation or while the instance is stopped and therefore, in a `TERMINATED` state. See Instance Life Cycle for more information on the possible instance states.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:automaticRestart => boolean(),
:locationHint => String.t(),
:minNodeCpus => integer(),
:nodeAffinities => list(GoogleApi.Compute.V1.Model.SchedulingNodeAffinity.t()),
:onHostMaintenance => String.t(),
:preemptible => boolean()
}
field(:automaticRestart)
field(:locationHint)
field(:minNodeCpus)
field(:nodeAffinities, as: GoogleApi.Compute.V1.Model.SchedulingNodeAffinity, type: :list)
field(:onHostMaintenance)
field(:preemptible)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.Scheduling do
def decode(value, options) do
GoogleApi.Compute.V1.Model.Scheduling.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.Scheduling do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 53.78125 | 324 | 0.740848 |
f78a54d4bce09f8bfada971836994b28319e7273 | 4,748 | ex | Elixir | lib/arkecosystem/crypto/transactions/serializer.ex | whitehat/elixir-crypto | 6347868ee15c7b79676df58bef54376a8dc6fd02 | [
"MIT"
] | null | null | null | lib/arkecosystem/crypto/transactions/serializer.ex | whitehat/elixir-crypto | 6347868ee15c7b79676df58bef54376a8dc6fd02 | [
"MIT"
] | null | null | null | lib/arkecosystem/crypto/transactions/serializer.ex | whitehat/elixir-crypto | 6347868ee15c7b79676df58bef54376a8dc6fd02 | [
"MIT"
] | null | null | null | defmodule ArkEcosystem.Crypto.Transactions.Serializer do
alias ArkEcosystem.Crypto.Enums.Types
alias ArkEcosystem.Crypto.Helpers.MapKeyTransformer
alias ArkEcosystem.Crypto.Configuration.Network
alias ArkEcosystem.Crypto.Transactions.Serializers.Transfer
alias ArkEcosystem.Crypto.Transactions.Serializers.SecondSignatureRegistration
alias ArkEcosystem.Crypto.Transactions.Serializers.DelegateRegistration
alias ArkEcosystem.Crypto.Transactions.Serializers.Vote
alias ArkEcosystem.Crypto.Transactions.Serializers.MultiSignatureRegistration
alias ArkEcosystem.Crypto.Transactions.Serializers.IPFS
alias ArkEcosystem.Crypto.Transactions.Serializers.TimelockTransfer
alias ArkEcosystem.Crypto.Transactions.Serializers.MultiPayment
alias ArkEcosystem.Crypto.Transactions.Serializers.DelegateResignation
@transfer Types.transfer()
@second_signature_registration Types.second_signature_registration()
@delegate_registration Types.delegate_registration()
@vote Types.vote()
@multi_signature_registration Types.multi_signature_registration()
@ipfs Types.ipfs()
@timelock_transfer Types.timelock_transfer()
@multi_payment Types.multi_payment()
@delegate_resignation Types.delegate_resignation()
def serialize(transaction, %{underscore: underscore}) when is_map(transaction) do
if(underscore, do: MapKeyTransformer.underscore(transaction), else: transaction)
|> serialize
end
def serialize(transaction) when is_map(transaction) do
transaction
|> serialize_header
|> serialize_vendor_field(transaction)
|> serialize_type(transaction)
|> serialize_signatures(transaction)
|> Base.encode16(case: :lower)
end
defp serialize_header(transaction) do
header = <<255::little-unsigned-integer-size(8)>>
version =
if Map.has_key?(transaction, :version) do
<<transaction.version::little-unsigned-integer-size(8)>>
else
<<1::little-unsigned-integer-size(8)>>
end
network =
if Map.has_key?(transaction, :network) do
<<transaction.network::little-unsigned-integer-size(8)>>
else
Network.version()
end
type = <<transaction.type::little-unsigned-integer-size(8)>>
timestamp = <<transaction.timestamp::little-unsigned-integer-size(32)>>
sender_public_key =
transaction.sender_public_key
|> Base.decode16!(case: :lower)
fee = <<transaction.fee::little-unsigned-integer-size(64)>>
header <> version <> network <> type <> timestamp <> sender_public_key <> fee
end
defp serialize_vendor_field(bytes, transaction) do
bytes <>
cond do
Map.has_key?(transaction, :vendor_field) ->
length = byte_size(transaction.vendor_field)
<<length::little-unsigned-integer-size(length)>> <> transaction.vendor_field
Map.has_key?(transaction, :vendor_field_hex) ->
length = byte_size(transaction.vendor_field_hex)
<<length::little-unsigned-integer-size(8)>> <> transaction.vendor_field_hex
true ->
<<0::little-unsigned-integer-size(8)>>
end
end
defp serialize_type(bytes, transaction) do
case transaction.type do
@transfer -> Transfer.serialize(bytes, transaction)
@second_signature_registration -> SecondSignatureRegistration.serialize(bytes, transaction)
@delegate_registration -> DelegateRegistration.serialize(bytes, transaction)
@vote -> Vote.serialize(bytes, transaction)
@multi_signature_registration -> MultiSignatureRegistration.serialize(bytes, transaction)
@ipfs -> IPFS.serialize(bytes, transaction)
@timelock_transfer -> TimelockTransfer.serialize(bytes, transaction)
@multi_payment -> MultiPayment.serialize(bytes, transaction)
@delegate_resignation -> DelegateResignation.serialize(bytes, transaction)
end
end
defp serialize_signatures(bytes, transaction) do
signature =
if Map.has_key?(transaction, :signature) do
transaction.signature
|> Base.decode16!(case: :lower)
else
<<>>
end
second_signature =
cond do
Map.has_key?(transaction, :second_signature) ->
transaction.second_signature
|> Base.decode16!(case: :lower)
Map.has_key?(transaction, :sign_signature) ->
transaction.sign_signature
|> Base.decode16!(case: :lower)
true ->
<<>>
end
signatures =
if Map.has_key?(transaction, :signatures) do
<<255::little-unsigned-integer-size(8)>> <>
(transaction.signatures
|> Enum.join()
|> Base.decode16!(case: :lower))
else
<<>>
end
bytes <> signature <> second_signature <> signatures
end
end
| 35.17037 | 97 | 0.711457 |
f78a6a64e3cbc46218f6cb172c1c3fa5556fe66e | 1,557 | ex | Elixir | lib/commodity/application.ex | akdilsiz/commodity-cloud | 08c366c9fc95fbb3565131672db4cc52f8b870c9 | [
"Apache-2.0"
] | 7 | 2019-04-11T21:12:49.000Z | 2021-04-14T12:56:42.000Z | lib/commodity/application.ex | akdilsiz/commodity-cloud | 08c366c9fc95fbb3565131672db4cc52f8b870c9 | [
"Apache-2.0"
] | null | null | null | lib/commodity/application.ex | akdilsiz/commodity-cloud | 08c366c9fc95fbb3565131672db4cc52f8b870c9 | [
"Apache-2.0"
] | 2 | 2019-06-06T18:05:33.000Z | 2019-07-16T08:49:45.000Z | ##
# Copyright 2018 Abdulkadir DILSIZ
#
# 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 Commodity.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
# Start the Ecto repository
Commodity.Repo,
# Start the endpoint when the application starts
Commodity.Endpoint
# Starts a worker by calling: Commodity.Worker.start_link(arg)
# {Commodity.Worker, arg},
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Commodity.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
Commodity.Endpoint.config_change(changed, removed)
:ok
end
end
| 33.12766 | 77 | 0.717405 |
f78a74f74630afcfb7bca3aa911c5e462d6132cc | 2,517 | ex | Elixir | clients/dns/lib/google_api/dns/v1/model/policies_list_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dns/lib/google_api/dns/v1/model/policies_list_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dns/lib/google_api/dns/v1/model/policies_list_response.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.DNS.V1.Model.PoliciesListResponse do
@moduledoc """
## Attributes
* `header` (*type:* `GoogleApi.DNS.V1.Model.ResponseHeader.t`, *default:* `nil`) -
* `kind` (*type:* `String.t`, *default:* `dns#policiesListResponse`) - Type of resource.
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The presence of this field indicates that there exist more results following your last page of results in pagination order. To fetch them, make another list request using this value as your page token. This lets you the complete contents of even very large collections one page at a time. However, if the contents of the collection change between the first and last paginated list request, the set of all elements returned are an inconsistent view of the collection. You cannot retrieve a consistent snapshot of a collection larger than the maximum page size.
* `policies` (*type:* `list(GoogleApi.DNS.V1.Model.Policy.t)`, *default:* `nil`) - The policy resources.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:header => GoogleApi.DNS.V1.Model.ResponseHeader.t() | nil,
:kind => String.t() | nil,
:nextPageToken => String.t() | nil,
:policies => list(GoogleApi.DNS.V1.Model.Policy.t()) | nil
}
field(:header, as: GoogleApi.DNS.V1.Model.ResponseHeader)
field(:kind)
field(:nextPageToken)
field(:policies, as: GoogleApi.DNS.V1.Model.Policy, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.DNS.V1.Model.PoliciesListResponse do
def decode(value, options) do
GoogleApi.DNS.V1.Model.PoliciesListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DNS.V1.Model.PoliciesListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.946429 | 622 | 0.727453 |
f78a99fc503bc8692802416db69fd0b569ef1bae | 890 | ex | Elixir | clients/text_to_speech/lib/google_api/text_to_speech/v1/metadata.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/text_to_speech/lib/google_api/text_to_speech/v1/metadata.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/text_to_speech/lib/google_api/text_to_speech/v1/metadata.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2020 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.TextToSpeech.V1 do
@moduledoc """
API client metadata for GoogleApi.TextToSpeech.V1.
"""
@discovery_revision "20200814"
def discovery_revision(), do: @discovery_revision
end
| 32.962963 | 74 | 0.760674 |
f78aa50b2a9c69e09b2eea37db392dd5c1c11784 | 10,578 | ex | Elixir | lib/mix/lib/mix/dep/loader.ex | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | 1 | 2021-05-20T13:08:37.000Z | 2021-05-20T13:08:37.000Z | lib/mix/lib/mix/dep/loader.ex | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/dep/loader.ex | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | null | null | null | # This module is responsible for loading dependencies
# of the current project. This module and its functions
# are private to Mix.
defmodule Mix.Dep.Loader do
@moduledoc false
import Mix.Dep, only: [ok?: 1, mix?: 1, rebar?: 1, make?: 1]
@doc """
Gets all direct children of the current `Mix.Project`
as a `Mix.Dep` struct. Umbrella project dependencies
are included as children.
By default, it will filter all dependencies that does not match
current environment, behaviour can be overridden via options.
"""
def children() do
mix_children([]) ++ Mix.Dep.Umbrella.unloaded()
end
@doc """
Partitions loaded dependencies by environment.
"""
def partition_by_env(deps, nil), do: {deps, []}
def partition_by_env(deps, env), do: Enum.split_with(deps, &(not skip?(&1, env)))
@doc """
Checks if a dependency must be skipped according to the environment.
"""
def skip?(_dep, nil), do: false
def skip?(%Mix.Dep{status: {:divergedonly, _}}, _), do: false
def skip?(%Mix.Dep{opts: opts}, env) do
only = opts[:only]
validate_only!(only)
only != nil and env not in List.wrap(only)
end
def with_system_env(%Mix.Dep{system_env: []}, callback), do: callback.()
def with_system_env(%Mix.Dep{system_env: new_env}, callback) do
old_env =
for {key, _} <- new_env do
{key, System.get_env(key)}
end
try do
System.put_env(new_env)
callback.()
after
for {key, value} <- old_env do
if value do
System.put_env(key, value)
else
System.delete_env(key)
end
end
end
end
@doc """
Loads the given dependency information, including its
latest status and children.
"""
def load(%Mix.Dep{manager: manager, scm: scm, opts: opts} = dep, children) do
manager = scm_manager(scm, opts) || manager || infer_manager(opts[:dest])
dep = %{dep | manager: manager, status: scm_status(scm, opts)}
{dep, children} =
cond do
not ok?(dep) ->
{dep, []}
mix?(dep) ->
mix_dep(dep, children)
# If not an explicit Rebar or Mix dependency
# but came from Rebar, assume to be a Rebar dep.
rebar?(dep) ->
rebar_dep(dep, children, manager)
make?(dep) ->
make_dep(dep)
true ->
{dep, []}
end
%{validate_app(dep) | deps: attach_only(children, opts)}
end
@doc """
Checks if a requirement from a dependency matches
the given version.
"""
def vsn_match(nil, _actual, _app), do: {:ok, true}
def vsn_match(req, actual, app) do
if Regex.regex?(req) do
{:ok, actual =~ req}
else
case Version.parse(actual) do
{:ok, version} ->
case Version.parse_requirement(req) do
{:ok, req} ->
{:ok, Version.match?(version, req)}
:error ->
Mix.raise("Invalid requirement #{req} for app #{app}")
end
:error ->
{:error, :nosemver}
end
end
end
## Helpers
def to_dep(tuple, from, manager \\ nil) do
%{opts: opts} = dep = with_scm_and_app(tuple)
%{dep | from: from, manager: opts[:manager] || manager}
end
defp with_scm_and_app({app, opts} = original) when is_atom(app) and is_list(opts) do
with_scm_and_app(app, nil, opts, original)
end
defp with_scm_and_app({app, req} = original) when is_atom(app) do
if is_binary(req) or Regex.regex?(req) do
with_scm_and_app(app, req, [], original)
else
invalid_dep_format(original)
end
end
defp with_scm_and_app({app, req, opts} = original) when is_atom(app) and is_list(opts) do
if is_binary(req) or Regex.regex?(req) do
with_scm_and_app(app, req, opts, original)
else
invalid_dep_format(original)
end
end
defp with_scm_and_app(original) do
invalid_dep_format(original)
end
defp with_scm_and_app(app, req, opts, original) do
unless Keyword.keyword?(opts) do
invalid_dep_format(original)
end
bin_app = Atom.to_string(app)
dest = Path.join(Mix.Project.deps_path(), bin_app)
build = Path.join([Mix.Project.build_path(), "lib", bin_app])
opts =
opts
|> Keyword.put(:dest, dest)
|> Keyword.put(:build, build)
{system_env, opts} = Keyword.pop(opts, :system_env, [])
{scm, opts} = get_scm(app, opts)
{scm, opts} =
if !scm && Mix.Hex.ensure_installed?(app) do
_ = Mix.Hex.start()
get_scm(app, opts)
else
{scm, opts}
end
unless scm do
Mix.raise(
"Could not find an SCM for dependency #{inspect(app)} from #{inspect(Mix.Project.get())}"
)
end
%Mix.Dep{
scm: scm,
app: app,
requirement: req,
status: scm_status(scm, opts),
opts: Keyword.put_new(opts, :env, :prod),
system_env: system_env
}
end
defp get_scm(app, opts) do
Enum.find_value(Mix.SCM.available(), {nil, opts}, fn scm ->
(new = scm.accepts_options(app, opts)) && {scm, new}
end)
end
# Notice we ignore Make dependencies because the
# file based heuristic will always figure it out.
@scm_managers ~w(mix rebar rebar3)a
defp scm_manager(scm, opts) do
managers = scm.managers(opts)
Enum.find(@scm_managers, &(&1 in managers))
end
defp scm_status(scm, opts) do
if scm.checked_out?(opts) do
{:ok, nil}
else
{:unavailable, opts[:dest]}
end
end
defp infer_manager(dest) do
cond do
any_of?(dest, ["mix.exs"]) ->
:mix
any_of?(dest, ["rebar", "rebar.config", "rebar.config.script", "rebar.lock"]) ->
:rebar3
any_of?(dest, ["Makefile", "Makefile.win"]) ->
:make
true ->
nil
end
end
defp any_of?(dest, files) do
Enum.any?(files, &File.regular?(Path.join(dest, &1)))
end
defp invalid_dep_format(dep) do
Mix.raise("""
Dependency specified in the wrong format:
#{inspect(dep)}
Expected:
{app, opts} | {app, requirement} | {app, requirement, opts}
Where:
app :: atom
requirement :: String.t | Regex.t
opts :: keyword
If you want to skip the requirement (not recommended), use ">= 0.0.0".
""")
end
## Fetching
# We need to override the dependencies so they mirror
# the :only requirement in the parent.
defp attach_only(deps, opts) do
if only = opts[:only] do
Enum.map(deps, fn %{opts: opts} = dep ->
%{dep | opts: Keyword.put_new(opts, :only, only)}
end)
else
deps
end
end
defp mix_dep(%Mix.Dep{opts: opts} = dep, nil) do
Mix.Dep.in_dependency(dep, fn _ ->
opts =
if Mix.Project.umbrella?() do
Keyword.put_new(opts, :app, false)
else
opts
end
child_opts =
if opts[:from_umbrella] do
[]
else
[env: Keyword.fetch!(opts, :env)]
end
deps = mix_children(child_opts) ++ Mix.Dep.Umbrella.unloaded()
{%{dep | opts: opts}, deps}
end)
end
# If we have a Mix dependency that came from a remote converger,
# we just use the dependencies given by the remote converger,
# we don't need to load the mix.exs at all. We can only do this
# because umbrella projects are not supported in remotes.
defp mix_dep(%Mix.Dep{opts: opts} = dep, children) do
from = Path.join(opts[:dest], "mix.exs")
deps = Enum.map(children, &to_dep(&1, from))
{dep, deps}
end
defp rebar_dep(%Mix.Dep{app: app, opts: opts, extra: overrides} = dep, children, manager) do
config = File.cd!(opts[:dest], fn -> Mix.Rebar.load_config(".") end)
config = Mix.Rebar.apply_overrides(app, config, overrides)
deps =
if children do
from = Path.join(opts[:dest], "rebar.config")
# Pass the manager because deps of a Rebar project need
# to default to Rebar if we cannot chose a manager from
# files in the dependency
Enum.map(children, &to_dep(&1, from, manager))
else
rebar_children(config, manager, opts[:dest])
end
{%{dep | extra: config}, deps}
end
defp make_dep(dep) do
{dep, []}
end
defp validate_only!(only) do
for entry <- List.wrap(only), not is_atom(entry) do
Mix.raise(
"Expected :only in dependency to be an atom or a list of atoms, got: #{inspect(only)}"
)
end
only
end
defp mix_children(opts) do
from = Path.absname("mix.exs")
(Mix.Project.config()[:deps] || [])
|> Enum.map(&to_dep(&1, from))
|> partition_by_env(opts[:env])
|> elem(0)
end
defp rebar_children(root_config, manager, dest) do
from = Path.absname(Path.join(dest, "rebar.config"))
Mix.Rebar.recur(root_config, fn config ->
overrides = overrides(manager, config)
config
|> Mix.Rebar.deps()
|> Enum.map(fn dep -> %{to_dep(dep, from, manager) | extra: overrides} end)
end)
|> Enum.concat()
end
defp overrides(:rebar3, config), do: config[:overrides] || []
defp overrides(_, _config), do: []
defp validate_app(%Mix.Dep{opts: opts, requirement: req, app: app} = dep) do
opts_app = opts[:app]
cond do
not ok?(dep) ->
dep
recently_fetched?(dep) ->
%{dep | status: :compile}
opts_app == false ->
dep
true ->
path = if is_binary(opts_app), do: opts_app, else: "ebin/#{app}.app"
path = Path.expand(path, opts[:build])
%{dep | status: app_status(path, app, req)}
end
end
defp recently_fetched?(%Mix.Dep{opts: opts, scm: scm}) do
scm.fetchable? &&
Mix.Utils.stale?(
join_stale(opts, :dest, ".fetch"),
join_stale(opts, :build, ".compile.fetch")
)
end
defp join_stale(opts, key, file) do
[Path.join(opts[key], file)]
end
defp app_status(app_path, app, req) do
case :file.consult(app_path) do
{:ok, [{:application, ^app, config}]} ->
case List.keyfind(config, :vsn, 0) do
{:vsn, actual} when is_list(actual) ->
actual = IO.iodata_to_binary(actual)
case vsn_match(req, actual, app) do
{:ok, true} -> {:ok, actual}
{:ok, false} -> {:nomatchvsn, actual}
{:error, error} -> {error, actual}
end
{:vsn, actual} ->
{:invalidvsn, actual}
nil ->
{:invalidvsn, nil}
end
{:ok, _} ->
{:invalidapp, app_path}
{:error, _} ->
{:noappfile, app_path}
end
end
end
| 25.30622 | 97 | 0.593023 |
f78ab836cf07c57a02605e50d59850ef90405420 | 3,547 | ex | Elixir | clients/cloud_identity/lib/google_api/cloud_identity/v1/model/google_apps_cloudidentity_devices_v1_device_user.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/cloud_identity/lib/google_api/cloud_identity/v1/model/google_apps_cloudidentity_devices_v1_device_user.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/cloud_identity/lib/google_api/cloud_identity/v1/model/google_apps_cloudidentity_devices_v1_device_user.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.CloudIdentity.V1.Model.GoogleAppsCloudidentityDevicesV1DeviceUser do
@moduledoc """
Represents a user's use of a Device in the Cloud Identity Devices API. A DeviceUser is a resource representing a user's use of a Device
## Attributes
* `compromisedState` (*type:* `String.t`, *default:* `nil`) - Compromised State of the DeviceUser object
* `createTime` (*type:* `DateTime.t`, *default:* `nil`) - When the user first signed in to the device
* `firstSyncTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. Most recent time when user registered with this service.
* `languageCode` (*type:* `String.t`, *default:* `nil`) - Output only. Default locale used on device, in IETF BCP-47 format.
* `lastSyncTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. Last time when user synced with policies.
* `managementState` (*type:* `String.t`, *default:* `nil`) - Output only. Management state of the user on the device.
* `name` (*type:* `String.t`, *default:* `nil`) - Output only. [Resource name](https://cloud.google.com/apis/design/resource_names) of the DeviceUser in format: `devices/{device}/deviceUsers/{device_user}`, where `device_user` uniquely identifies a user's use of a device.
* `passwordState` (*type:* `String.t`, *default:* `nil`) - Password state of the DeviceUser object
* `userAgent` (*type:* `String.t`, *default:* `nil`) - Output only. User agent on the device for this specific user
* `userEmail` (*type:* `String.t`, *default:* `nil`) - Email address of the user registered on the device.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:compromisedState => String.t() | nil,
:createTime => DateTime.t() | nil,
:firstSyncTime => DateTime.t() | nil,
:languageCode => String.t() | nil,
:lastSyncTime => DateTime.t() | nil,
:managementState => String.t() | nil,
:name => String.t() | nil,
:passwordState => String.t() | nil,
:userAgent => String.t() | nil,
:userEmail => String.t() | nil
}
field(:compromisedState)
field(:createTime, as: DateTime)
field(:firstSyncTime, as: DateTime)
field(:languageCode)
field(:lastSyncTime, as: DateTime)
field(:managementState)
field(:name)
field(:passwordState)
field(:userAgent)
field(:userEmail)
end
defimpl Poison.Decoder,
for: GoogleApi.CloudIdentity.V1.Model.GoogleAppsCloudidentityDevicesV1DeviceUser do
def decode(value, options) do
GoogleApi.CloudIdentity.V1.Model.GoogleAppsCloudidentityDevicesV1DeviceUser.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.CloudIdentity.V1.Model.GoogleAppsCloudidentityDevicesV1DeviceUser do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.898734 | 276 | 0.693826 |
f78ab89b2f140cf3cfca35f08eda6a439911f157 | 1,646 | ex | Elixir | bleacher_fire/lib/bleacher_fire_web/controllers/reactions_controller.ex | nyolamike/bleacher_fire | 4ec43b01d06b44c3e39200248f709400a1d60b70 | [
"Apache-2.0"
] | null | null | null | bleacher_fire/lib/bleacher_fire_web/controllers/reactions_controller.ex | nyolamike/bleacher_fire | 4ec43b01d06b44c3e39200248f709400a1d60b70 | [
"Apache-2.0"
] | 1 | 2021-03-10T05:45:29.000Z | 2021-03-10T05:45:29.000Z | bleacher_fire/lib/bleacher_fire_web/controllers/reactions_controller.ex | nyolamike/bleacher_fire | 4ec43b01d06b44c3e39200248f709400a1d60b70 | [
"Apache-2.0"
] | null | null | null | defmodule BleacherFireWeb.ReactionsController do
use BleacherFireWeb, :controller
def details(conn, %{"user_name" => user_id, "id" => selected_content_id} = _params) do
contents = get_bleacher_content()
#get this users reactions to the content to be rendered
user_reactions = Enum.reduce(contents, %{}, fn {content_id, _content}, acc ->
user_reacted = UsersServer.UsersAgent.has_reaction(:users_agent_process,user_id,content_id)
Map.put(acc, content_id, user_reacted )
end)
conn
|>render("details.html", selected_post: contents[selected_content_id], posts: contents, reactions: user_reactions, user_id: user_id, selected_content_id: selected_content_id )
end
def index(conn, %{"user_name" => user_id} = _params) do
contents = get_bleacher_content()
#get this users reactions to the content to be rendered
user_reactions = Enum.reduce(contents, %{}, fn {content_id, _content}, acc ->
user_reacted = UsersServer.UsersAgent.has_reaction(:users_agent_process,user_id,content_id)
Map.put(acc, content_id, user_reacted )
end)
conn
|>render("index.html", posts: contents, reactions: user_reactions, user_id: user_id )
end
def index(conn, _params) do
contents = get_bleacher_content()
user_reactions = Enum.reduce(contents, %{}, fn {content_id, _content}, acc ->
Map.put(acc, content_id, false )
end)
conn
|> put_flash(:error, "Please Sign in, to load your reactions state from the <Users Server> micro service")
|>render("index.html", posts: contents, reactions: user_reactions, user_id: "" )
end
end | 40.146341 | 181 | 0.704131 |
f78acec06f78bc7e4333793c29769e941c54dd07 | 22,595 | ex | Elixir | lib/grizzly/command_class/mappings.ex | pragdave/grizzly | bcd7b46ab2cff1797dac04bc3cd12a36209dd579 | [
"Apache-2.0"
] | null | null | null | lib/grizzly/command_class/mappings.ex | pragdave/grizzly | bcd7b46ab2cff1797dac04bc3cd12a36209dd579 | [
"Apache-2.0"
] | null | null | null | lib/grizzly/command_class/mappings.ex | pragdave/grizzly | bcd7b46ab2cff1797dac04bc3cd12a36209dd579 | [
"Apache-2.0"
] | null | null | null | defmodule Grizzly.CommandClass.Mappings do
@type command_class_name :: atom
@type command_class_type :: :raw | :network | :application | :management
@type command_class_byte :: byte()
@type command_class_unk :: {:unk, byte}
@type specific_cmd_class_unk :: {:unk, byte, byte}
@known_network_command_classes [0x34]
require Logger
@spec from_byte(byte) :: command_class_name | command_class_unk
def from_byte(0x02), do: :zensor_net
def from_byte(0x20), do: :basic
def from_byte(0x21), do: :controller_replication
def from_byte(0x22), do: :application_status
def from_byte(0x23), do: :zip
def from_byte(0x24), do: :security_panel_mode
def from_byte(0x25), do: :switch_binary
def from_byte(0x26), do: :switch_multilevel
def from_byte(0x27), do: :switch_all
def from_byte(0x28), do: :switch_toggle_binary
def from_byte(0x2A), do: :chimney_fan
def from_byte(0x2B), do: :scene_activation
def from_byte(0x2C), do: :scene_actuator_conf
def from_byte(0x2D), do: :scene_controller_conf
def from_byte(0x2E), do: :security_panel_zone
def from_byte(0x2F), do: :security_panel_zone_sensor
def from_byte(0x30), do: :sensor_binary
def from_byte(0x31), do: :sensor_multilevel
def from_byte(0x32), do: :meter
def from_byte(0x33), do: :switch_color
def from_byte(0x34), do: :network_management_inclusion
def from_byte(0x35), do: :meter_pulse
def from_byte(0x36), do: :basic_tariff_info
def from_byte(0x37), do: :hrv_status
def from_byte(0x38), do: :thermostat_heating
def from_byte(0x39), do: :hrv_control
def from_byte(0x3A), do: :dcp_config
def from_byte(0x3B), do: :dcp_monitor
def from_byte(0x3C), do: :meter_tbl_config
def from_byte(0x3D), do: :meter_tbl_monitor
def from_byte(0x3E), do: :meter_tbl_push
def from_byte(0x3F), do: :prepayment
def from_byte(0x40), do: :thermostat_mode
def from_byte(0x41), do: :prepayment_encapsulation
def from_byte(0x42), do: :operating_state
def from_byte(0x43), do: :thermostat_setpoint
def from_byte(0x44), do: :thermostat_fan_mode
def from_byte(0x45), do: :thermostat_fan_state
def from_byte(0x46), do: :climate_control_schedule
def from_byte(0x47), do: :thermostat_setback
def from_byte(0x48), do: :rate_tbl_config
def from_byte(0x49), do: :rate_tbl_monitor
def from_byte(0x4A), do: :tariff_config
def from_byte(0x4B), do: :tariff_tbl_monitor
def from_byte(0x4C), do: :door_lock_logging
def from_byte(0x4D), do: :network_management_basic
def from_byte(0x4E), do: :schedule_entry_lock
def from_byte(0x4F), do: :zip_6lowpan
def from_byte(0x50), do: :basic_window_covering
def from_byte(0x51), do: :mtp_window_covering
def from_byte(0x52), do: :network_management_proxy
def from_byte(0x53), do: :schedule
def from_byte(0x54), do: :network_management_primary
def from_byte(0x55), do: :transport_service
def from_byte(0x56), do: :crc_16_encap
def from_byte(0x57), do: :application_capability
def from_byte(0x58), do: :zip_nd
def from_byte(0x59), do: :association_group_info
def from_byte(0x5A), do: :device_rest_locally
def from_byte(0x5B), do: :central_scene
def from_byte(0x5C), do: :ip_association
def from_byte(0x5D), do: :antitheft
def from_byte(0x5E), do: :zwaveplus_info
def from_byte(0x5F), do: :zip_gateway
def from_byte(0x61), do: :zip_portal
def from_byte(0x62), do: :door_lock
def from_byte(0x63), do: :user_code
def from_byte(0x64), do: :humidity_control_setpoint
def from_byte(0x65), do: :dmx
def from_byte(0x66), do: :barrier_operator
def from_byte(0x67), do: :network_management_installation_maintenance
def from_byte(0x68), do: :zip_naming
def from_byte(0x69), do: :mailbox
def from_byte(0x6A), do: :window_covering
def from_byte(0x6B), do: :irrigation
def from_byte(0x6C), do: :supervision
def from_byte(0x6D), do: :humidity_control_mode
def from_byte(0x6E), do: :humidity_control_operating_state
def from_byte(0x6F), do: :entry_control
def from_byte(0x70), do: :configuration
def from_byte(0x71), do: :alarm
def from_byte(0x72), do: :manufacturer_specific
def from_byte(0x73), do: :powerlevel
def from_byte(0x74), do: :inclusion_controller
def from_byte(0x75), do: :protection
def from_byte(0x76), do: :lock
def from_byte(0x77), do: :node_naming
def from_byte(0x78), do: :node_provisioning
def from_byte(0x7A), do: :firmware_update_md
def from_byte(0x7B), do: :grouping_name
def from_byte(0x7C), do: :remote_association_activate
def from_byte(0x7D), do: :remote_association
def from_byte(0x80), do: :battery
def from_byte(0x81), do: :clock
def from_byte(0x82), do: :hail
def from_byte(0x84), do: :wake_up
def from_byte(0x85), do: :association
def from_byte(0x86), do: :command_class_version
def from_byte(0x87), do: :indicator
def from_byte(0x88), do: :proprietary
def from_byte(0x89), do: :language
def from_byte(0x8A), do: :time
def from_byte(0x8B), do: :time_parameters
def from_byte(0x8C), do: :geographic_location
def from_byte(0x8E), do: :multi_channel_association
def from_byte(0x8F), do: :multi_cmd
def from_byte(0x90), do: :energy_production
def from_byte(0x91), do: :manufacturer_proprietary
def from_byte(0x92), do: :screen_md
def from_byte(0x93), do: :screen_attributes
def from_byte(0x94), do: :simple_av_control
def from_byte(0x95), do: :av_content_directory_md
def from_byte(0x96), do: :av_content_renderer_status
def from_byte(0x97), do: :av_content_search_md
def from_byte(0x98), do: :security
def from_byte(0x99), do: :av_tagging_md
def from_byte(0x9A), do: :ip_configuration
def from_byte(0x9B), do: :association_command_configuration
def from_byte(0x9C), do: :sensor_alarm
def from_byte(0x9D), do: :silence_alarm
def from_byte(0x9E), do: :sensor_configuration
def from_byte(0x9F), do: :security_2
def from_byte(0xEF), do: :mark
def from_byte(0xF0), do: :non_interoperable
def from_byte(byte) do
_ = Logger.warn("Unknown command class byte #{Integer.to_string(byte, 16)}")
{:unk, byte}
end
@spec to_byte(command_class_name) :: command_class_byte() | command_class_unk()
def to_byte(:zensor_net), do: 0x02
def to_byte(:basic), do: 0x20
def to_byte(:controller_replication), do: 0x21
def to_byte(:application_status), do: 0x22
def to_byte(:zip), do: 0x23
def to_byte(:security_panel_mode), do: 0x24
def to_byte(:switch_binary), do: 0x25
def to_byte(:switch_multilevel), do: 0x26
def to_byte(:switch_all), do: 0x27
def to_byte(:switch_toggle_binary), do: 0x28
def to_byte(:chimney_fan), do: 0x2A
def to_byte(:scene_activation), do: 0x2B
def to_byte(:scene_actuator_conf), do: 0x2C
def to_byte(:scene_controller_conf), do: 0x2D
def to_byte(:security_panel_zone), do: 0x2E
def to_byte(:security_panel_zone_sensor), do: 0x2F
def to_byte(:sensor_binary), do: 0x30
def to_byte(:sensor_multilevel), do: 0x31
def to_byte(:meter), do: 0x32
def to_byte(:switch_color), do: 0x33
def to_byte(:network_management_inclusion), do: 0x34
def to_byte(:meter_pulse), do: 0x35
def to_byte(:basic_tariff_info), do: 0x36
def to_byte(:hrv_status), do: 0x37
def to_byte(:thermostat_heating), do: 0x38
def to_byte(:hrv_control), do: 0x39
def to_byte(:dcp_config), do: 0x3A
def to_byte(:dcp_monitor), do: 0x3B
def to_byte(:meter_tbl_config), do: 0x3C
def to_byte(:meter_tbl_monitor), do: 0x3D
def to_byte(:meter_tbl_push), do: 0x3E
def to_byte(:prepayment), do: 0x3F
def to_byte(:thermostat_mode), do: 0x40
def to_byte(:prepayment_encapsulation), do: 0x41
def to_byte(:operating_state), do: 0x42
def to_byte(:thermostat_setpoint), do: 0x43
def to_byte(:thermostat_fan_mode), do: 0x44
def to_byte(:thermostat_fan_state), do: 0x45
def to_byte(:climate_control_schedule), do: 0x46
def to_byte(:thermostat_setback), do: 0x47
def to_byte(:rate_tbl_config), do: 0x48
def to_byte(:rate_tbl_monitor), do: 0x49
def to_byte(:tariff_config), do: 0x4A
def to_byte(:tariff_tbl_monitor), do: 0x4B
def to_byte(:door_lock_logging), do: 0x4C
def to_byte(:network_management_basic), do: 0x4D
def to_byte(:schedule_entry_lock), do: 0x4E
def to_byte(:zip_6lowpan), do: 0x4F
def to_byte(:basic_window_covering), do: 0x50
def to_byte(:mtp_window_covering), do: 0x51
def to_byte(:network_management_proxy), do: 0x52
def to_byte(:schedule), do: 0x53
def to_byte(:network_management_primary), do: 0x54
def to_byte(:transport_service), do: 0x55
def to_byte(:crc_16_encap), do: 0x56
def to_byte(:application_capability), do: 0x57
def to_byte(:zip_nd), do: 0x58
def to_byte(:association_group_info), do: 0x59
def to_byte(:device_rest_locally), do: 0x5A
def to_byte(:central_scene), do: 0x5B
def to_byte(:ip_association), do: 0x5C
def to_byte(:antitheft), do: 0x5D
def to_byte(:zwaveplus_info), do: 0x5E
def to_byte(:zip_gateway), do: 0x5F
def to_byte(:zip_portal), do: 0x61
def to_byte(:door_lock), do: 0x62
def to_byte(:user_code), do: 0x63
def to_byte(:humidity_control_setpoint), do: 0x64
def to_byte(:dmx), do: 0x65
def to_byte(:barrier_operator), do: 0x66
def to_byte(:network_management_installation_maintenance), do: 0x67
def to_byte(:zip_naming), do: 0x68
def to_byte(:mailbox), do: 0x69
def to_byte(:window_covering), do: 0x6A
def to_byte(:irrigation), do: 0x6B
def to_byte(:supervision), do: 0x6C
def to_byte(:humidity_control_mode), do: 0x6D
def to_byte(:humidity_control_operating_state), do: 0x6E
def to_byte(:entry_control), do: 0x6F
def to_byte(:configuration), do: 0x70
def to_byte(:alarm), do: 0x71
def to_byte(:manufacturer_specific), do: 0x72
def to_byte(:powerlevel), do: 0x73
def to_byte(:inclusion_controller), do: 0x74
def to_byte(:protection), do: 0x75
def to_byte(:lock), do: 0x76
def to_byte(:node_naming), do: 0x77
def to_byte(:node_provisioning), do: 0x78
def to_byte(:firmware_update_md), do: 0x7A
def to_byte(:grouping_name), do: 0x7B
def to_byte(:remote_association_activate), do: 0x7C
def to_byte(:remote_association), do: 0x7D
def to_byte(:battery), do: 0x80
def to_byte(:clock), do: 0x81
def to_byte(:hail), do: 0x82
def to_byte(:wake_up), do: 0x84
def to_byte(:association), do: 0x85
def to_byte(:command_class_version), do: 0x86
def to_byte(:indicator), do: 0x87
def to_byte(:proprietary), do: 0x88
def to_byte(:language), do: 0x89
def to_byte(:time), do: 0x8A
def to_byte(:time_parameters), do: 0x8B
def to_byte(:geographic_location), do: 0x8C
def to_byte(:multi_channel_association), do: 0x8E
def to_byte(:multi_cmd), do: 0x8F
def to_byte(:energy_production), do: 0x90
def to_byte(:manufacturer_proprietary), do: 0x91
def to_byte(:screen_md), do: 0x92
def to_byte(:screen_attributes), do: 0x93
def to_byte(:simple_av_control), do: 0x94
def to_byte(:av_content_directory_md), do: 0x95
def to_byte(:av_content_renderer_status), do: 0x96
def to_byte(:av_content_search_md), do: 0x97
def to_byte(:security), do: 0x98
def to_byte(:av_tagging_md), do: 0x99
def to_byte(:ip_configuration), do: 0x9A
def to_byte(:association_command_configuration), do: 0x9B
def to_byte(:sensor_alarm), do: 0x9C
def to_byte(:silence_alarm), do: 0x9D
def to_byte(:sensor_configuration), do: 0x9E
def to_byte(:security_2), do: 0x9F
def to_byte(:mark), do: 0xEF
def to_byte(:non_interoperable), do: 0xF0
def to_byte(command_class) do
_ = Logger.warn("Unknown command class name #{inspect(command_class)}")
{:unk, command_class}
end
@spec command_from_byte(command_class :: byte, command :: byte) ::
command_class_name() | command_class_unk()
def command_from_byte(0x25, 0x01), do: :set
def command_from_byte(0x25, 0x02), do: :get
def command_from_byte(0x25, 0x03), do: :switch_binary_report
def command_from_byte(0x31, 0x05), do: :sensor_multilevel_report
def command_from_byte(0x32, 0x02), do: :meter_report
def command_from_byte(0x34, 0x02), do: :node_add_status
def command_from_byte(0x34, 0x04), do: :node_remove_status
def command_from_byte(0x43, 0x03), do: :thermostat_setpoint_report
def command_from_byte(0x52, 0x01), do: :node_list_get
def command_from_byte(0x52, 0x03), do: :node_info_cache
def command_from_byte(0x5A, 0x01), do: :device_rest_locally_notification
def command_from_byte(0x69, 0x03), do: :mailbox_configuration_report
def command_from_byte(0x71, 0x05), do: :zwave_alarm_event
def command_from_byte(0x72, 0x04), do: :manufacturer_specific_get
def command_from_byte(0x72, 0x05), do: :manufacturer_specific_report
def command_from_byte(0x80, 0x02), do: :get
def command_from_byte(0x84, 0x05), do: :interval_get
def command_from_byte(0x84, 0x06), do: :interval_report
def command_from_byte(0x84, 0x0A), do: :interval_capabilities_report
def command_from_byte(0x85, 0x01), do: :set
def command_from_byte(0x85, 0x03), do: :report
def command_from_byte(command_class_byte, byte) do
_ =
Logger.warn(
"Unknown command from byte #{Integer.to_string(byte, 16)} for command class byte #{
Integer.to_string(command_class_byte, 16)
}"
)
{:unk, byte}
end
@spec byte_to_basic_class(byte) :: command_class_name() | command_class_unk()
def byte_to_basic_class(0x01), do: :controller
def byte_to_basic_class(0x02), do: :static_controller
def byte_to_basic_class(0x03), do: :slave
def byte_to_basic_class(0x04), do: :routing_slave
def byte_to_basic_class(byte) do
_ = Logger.warn("Unknown basic class #{Integer.to_string(byte, 16)}")
{:unk, byte}
end
@spec byte_to_generic_class(byte) :: command_class_name() | command_class_unk()
def byte_to_generic_class(0x01), do: :generic_controller
def byte_to_generic_class(0x02), do: :static_controller
def byte_to_generic_class(0x03), do: :av_control_point
def byte_to_generic_class(0x04), do: :display
def byte_to_generic_class(0x05), do: :network_extender
def byte_to_generic_class(0x06), do: :appliance
def byte_to_generic_class(0x07), do: :sensor_notification
def byte_to_generic_class(0x08), do: :thermostat
def byte_to_generic_class(0x09), do: :window_covering
def byte_to_generic_class(0x0F), do: :repeater_slave
def byte_to_generic_class(0x10), do: :switch_binary
def byte_to_generic_class(0x11), do: :switch_multilevel
def byte_to_generic_class(0x12), do: :switch_remote
def byte_to_generic_class(0x13), do: :switch_toggle
def byte_to_generic_class(0x15), do: :zip_node
def byte_to_generic_class(0x16), do: :ventilation
def byte_to_generic_class(0x17), do: :security_panel
def byte_to_generic_class(0x18), do: :wall_controller
def byte_to_generic_class(0x20), do: :sensor_binary
def byte_to_generic_class(0x21), do: :sensor_multilevel
def byte_to_generic_class(0x30), do: :meter_pulse
def byte_to_generic_class(0x31), do: :meter
def byte_to_generic_class(0x40), do: :entry_control
def byte_to_generic_class(0x50), do: :semi_interoperable
def byte_to_generic_class(0xA1), do: :sensor_alarm
def byte_to_generic_class(0xFF), do: :non_interoperable
def byte_to_generic_class(byte) do
_ = Logger.warn("Unknown generic class #{Integer.to_string(byte, 16)}")
{:unk, byte}
end
@spec byte_to_specific_class(byte, byte) :: command_class_name() | specific_cmd_class_unk()
def byte_to_specific_class(0x01, 0x00), do: :not_used
def byte_to_specific_class(0x01, 0x01), do: :portable_remote_controller
def byte_to_specific_class(0x01, 0x02), do: :portable_scene_controller
def byte_to_specific_class(0x01, 0x03), do: :installer_tool
def byte_to_specific_class(0x01, 0x04), do: :remote_control_av
def byte_to_specific_class(0x01, 0x06), do: :remote_control_simple
def byte_to_specific_class(0x02, 0x00), do: :not_used
def byte_to_specific_class(0x02, 0x01), do: :pc_controller
def byte_to_specific_class(0x02, 0x02), do: :scene_controller
def byte_to_specific_class(0x02, 0x03), do: :static_installer_tool
def byte_to_specific_class(0x02, 0x04), do: :set_top_box
def byte_to_specific_class(0x02, 0x05), do: :sub_system_controller
def byte_to_specific_class(0x02, 0x06), do: :tv
def byte_to_specific_class(0x02, 0x07), do: :gateway
def byte_to_specific_class(0x03, 0x00), do: :not_used
def byte_to_specific_class(0x03, 0x04), do: :satellite_receiver
def byte_to_specific_class(0x03, 0x11), do: :satellite_receiver_v2
def byte_to_specific_class(0x03, 0x12), do: :doorbell
def byte_to_specific_class(0x04, 0x00), do: :not_used
def byte_to_specific_class(0x04, 0x01), do: :simple_display
def byte_to_specific_class(0x05, 0x00), do: :not_used
def byte_to_specific_class(0x05, 0x01), do: :secure_extender
def byte_to_specific_class(0x06, 0x00), do: :not_used
def byte_to_specific_class(0x06, 0x01), do: :general_appliance
def byte_to_specific_class(0x06, 0x02), do: :kitchen_appliance
def byte_to_specific_class(0x06, 0x03), do: :laundry_appliance
def byte_to_specific_class(0x07, 0x00), do: :not_used
def byte_to_specific_class(0x07, 0x01), do: :notification_sensor
def byte_to_specific_class(0x08, 0x00), do: :not_used
def byte_to_specific_class(0x08, 0x01), do: :thermostat_heating
def byte_to_specific_class(0x08, 0x02), do: :thermostat_general
def byte_to_specific_class(0x08, 0x03), do: :setback_schedule_thermostat
def byte_to_specific_class(0x08, 0x04), do: :setpoint_thermostat
def byte_to_specific_class(0x08, 0x05), do: :setback_thermostat
def byte_to_specific_class(0x08, 0x06), do: :thermostat_general_v2
def byte_to_specific_class(0x09, 0x00), do: :not_used
def byte_to_specific_class(0x09, 0x01), do: :simple_window_covering
def byte_to_specific_class(0x10, 0x00), do: :not_used
def byte_to_specific_class(0x10, 0x01), do: :power_switch_binary
def byte_to_specific_class(0x10, 0x02), do: :color_tunable_binary
def byte_to_specific_class(0x10, 0x03), do: :scene_switch_binary
def byte_to_specific_class(0x10, 0x04), do: :power_strip
def byte_to_specific_class(0x10, 0x05), do: :siren
def byte_to_specific_class(0x10, 0x06), do: :valve_open_close
def byte_to_specific_class(0x10, 0x07), do: :irrigation_controller
def byte_to_specific_class(0x11, 0x00), do: :not_used
def byte_to_specific_class(0x11, 0x01), do: :power_switch_multilevel
def byte_to_specific_class(0x11, 0x02), do: :color_tunable_multilevel
def byte_to_specific_class(0x11, 0x03), do: :motor_multipositions
def byte_to_specific_class(0x11, 0x04), do: :scene_switch_multilevel
def byte_to_specific_class(0x11, 0x05), do: :class_a_motor_control
def byte_to_specific_class(0x11, 0x06), do: :class_b_motor_control
def byte_to_specific_class(0x11, 0x07), do: :class_c_motor_control
def byte_to_specific_class(0x11, 0x08), do: :fan_switch
def byte_to_specific_class(0x12, 0x00), do: :not_used
def byte_to_specific_class(0x12, 0x01), do: :switch_remote_binary
def byte_to_specific_class(0x12, 0x02), do: :switch_remote_multilevel
def byte_to_specific_class(0x12, 0x03), do: :switch_remote_toggle_binary
def byte_to_specific_class(0x12, 0x04), do: :switch_remote_toggle_multilevel
def byte_to_specific_class(0x13, 0x00), do: :not_used
def byte_to_specific_class(0x13, 0x01), do: :switch_toggle_binary
def byte_to_specific_class(0x13, 0x02), do: :switch_toggle_multilevel
def byte_to_specific_class(0x15, 0x00), do: :not_used
def byte_to_specific_class(0x15, 0x01), do: :zip_adv_node
def byte_to_specific_class(0x15, 0x02), do: :zip_tun_node
def byte_to_specific_class(0x17, 0x00), do: :not_used
def byte_to_specific_class(0x17, 0x01), do: :zoned_security_panel
def byte_to_specific_class(0x18, 0x00), do: :not_used
def byte_to_specific_class(0x18, 0x01), do: :basic_wall_controller
def byte_to_specific_class(0x20, 0x00), do: :not_used
def byte_to_specific_class(0x20, 0x01), do: :routing_sensor_binary
def byte_to_specific_class(0x21, 0x00), do: :not_used
def byte_to_specific_class(0x21, 0x01), do: :routing_sensor_multilevel
def byte_to_specific_class(0x21, 0x02), do: :chimney_fan
def byte_to_specific_class(0x30, 0x00), do: :not_used
def byte_to_specific_class(0x31, 0x00), do: :not_used
def byte_to_specific_class(0x31, 0x01), do: :simple_meter
def byte_to_specific_class(0x31, 0x02), do: :adv_energy_control
def byte_to_specific_class(0x31, 0x03), do: :whole_home_meter_simple
def byte_to_specific_class(0x40, 0x00), do: :not_used
def byte_to_specific_class(0x40, 0x01), do: :door_lock
def byte_to_specific_class(0x40, 0x02), do: :advanced_door_lock
def byte_to_specific_class(0x40, 0x03), do: :secure_keypad_door_lock
def byte_to_specific_class(0x40, 0x04), do: :secure_keypad_door_lock_deadbolt
def byte_to_specific_class(0x40, 0x05), do: :secure_door
def byte_to_specific_class(0x40, 0x06), do: :secure_gate
def byte_to_specific_class(0x40, 0x07), do: :secure_barrier_addon
def byte_to_specific_class(0x40, 0x08), do: :secure_barrier_open_only
def byte_to_specific_class(0x40, 0x09), do: :secure_barrier_close_only
def byte_to_specific_class(0x40, 0x0A), do: :secure_lockbox
def byte_to_specific_class(0x40, 0x0B), do: :secure_keypad
def byte_to_specific_class(0x50, 0x00), do: :not_used
def byte_to_specific_class(0x50, 0x01), do: :energy_production
def byte_to_specific_class(0xA1, 0x00), do: :not_used
def byte_to_specific_class(0xA1, 0x01), do: :basic_routing_alarm_sensor
def byte_to_specific_class(0xA1, 0x02), do: :routing_alarm_sensor
def byte_to_specific_class(0xA1, 0x03), do: :basic_zensor_net_alarm_sensor
def byte_to_specific_class(0xA1, 0x04), do: :zensor_net_alarm_sensor
def byte_to_specific_class(0xA1, 0x05), do: :adv_zensor_net_alarm_sensor
def byte_to_specific_class(0xA1, 0x06), do: :basic_routing_smoke_sensor
def byte_to_specific_class(0xA1, 0x07), do: :routing_smoke_sensor
def byte_to_specific_class(0xA1, 0x08), do: :basic_zensor_net_smoke_sensor
def byte_to_specific_class(0xA1, 0x09), do: :zensor_net_smoke_sensor
def byte_to_specific_class(0xA1, 0x0A), do: :adv_zensor_net_smoke_sensor
def byte_to_specific_class(0xA1, 0x0B), do: :alarm_sensor
def byte_to_specific_class(0xFF, 0x00), do: :not_used
def byte_to_specific_class(gen_byte, spec_byte) do
_ =
Logger.warn(
"Unknown specific class #{Integer.to_string(spec_byte, 16)} for generic class #{
Integer.to_string(gen_byte, 16)
}"
)
{:unk, gen_byte, spec_byte}
end
@spec is_network_command_class(byte) :: boolean
def is_network_command_class(byte) when byte in @known_network_command_classes, do: true
def is_network_command_class(_), do: false
end
| 45.0998 | 93 | 0.76185 |
f78af5c32f37c12c09226703fd09d26b6eedffab | 191 | exs | Elixir | priv/repo/migrations/20180928054123_create_types.exs | the-mikedavis/doc_gen | efcc884ea65bba5748f41c5601abd00db2777ec4 | [
"BSD-3-Clause"
] | null | null | null | priv/repo/migrations/20180928054123_create_types.exs | the-mikedavis/doc_gen | efcc884ea65bba5748f41c5601abd00db2777ec4 | [
"BSD-3-Clause"
] | 27 | 2018-10-29T18:34:44.000Z | 2019-03-11T18:43:12.000Z | priv/repo/migrations/20180928054123_create_types.exs | the-mikedavis/doc_gen | efcc884ea65bba5748f41c5601abd00db2777ec4 | [
"BSD-3-Clause"
] | null | null | null | defmodule DocGen.Repo.Migrations.CreateTypes do
use Ecto.Migration
def change do
create table(:types) do
add(:name, :string, null: false)
timestamps()
end
end
end
| 15.916667 | 47 | 0.670157 |
f78b06ee7068da56a41e0fc135bae4d95dd0655d | 380 | ex | Elixir | lib/bifroest/web/views/error_view.ex | theSuess/bifroest-web | fc25d4e827546b2e1a08719962f0e161d622eded | [
"BSD-3-Clause"
] | 1 | 2017-03-29T06:48:06.000Z | 2017-03-29T06:48:06.000Z | lib/bifroest/web/views/error_view.ex | theSuess/bifroest-web | fc25d4e827546b2e1a08719962f0e161d622eded | [
"BSD-3-Clause"
] | null | null | null | lib/bifroest/web/views/error_view.ex | theSuess/bifroest-web | fc25d4e827546b2e1a08719962f0e161d622eded | [
"BSD-3-Clause"
] | null | null | null | defmodule Bifroest.Web.ErrorView do
use Bifroest.Web, :view
def render("404.html", _assigns) do
"Page not found"
end
def render("500.html", _assigns) do
"Internal server error"
end
# In case no render clause matches or no
# template is found, let's render it as 500
def template_not_found(_template, assigns) do
render "500.html", assigns
end
end
| 21.111111 | 47 | 0.7 |
f78b36ca30a7414a8e25d4d9c5d1ea0384599a27 | 1,822 | exs | Elixir | elixir/config/prod.exs | VitorFirmino/NLW-7 | 16d3319c6bcf2308ef6ea5fdf8257be78887a190 | [
"MIT"
] | null | null | null | elixir/config/prod.exs | VitorFirmino/NLW-7 | 16d3319c6bcf2308ef6ea5fdf8257be78887a190 | [
"MIT"
] | null | null | null | elixir/config/prod.exs | VitorFirmino/NLW-7 | 16d3319c6bcf2308ef6ea5fdf8257be78887a190 | [
"MIT"
] | null | null | null | import Config
# For production, don't forget to configure the url host
# to something meaningful, Phoenix uses this information
# when generating URLs.
#
# Note we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the `mix phx.digest` task,
# which you should run after static files are built and
# before starting your production server.
config :elixer, ElixerWeb.Endpoint,
url: [host: "example.com", port: 80],
cache_static_manifest: "priv/static/cache_manifest.json"
# Do not print debug messages in production
config :logger, level: :info
# ## 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 :elixer, ElixerWeb.Endpoint,
# ...,
# url: [host: "example.com", port: 443],
# https: [
# ...,
# port: 443,
# cipher_suite: :strong,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")
# ]
#
# The `cipher_suite` is set to `:strong` to support only the
# latest and more secure SSL ciphers. This means old browsers
# and clients may not be supported. You can set it to
# `:compatible` for wider support.
#
# `:keyfile` and `:certfile` expect an absolute path to the key
# and cert in disk or a relative path inside priv, for example
# "priv/ssl/server.key". For all supported SSL configuration
# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1
#
# We also recommend setting `force_ssl` in your endpoint, ensuring
# no data is ever sent via http, always redirecting to https:
#
# config :elixer, ElixerWeb.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
| 35.038462 | 66 | 0.703074 |
f78b47e5f0a649b163bca780566034ba309c8923 | 176 | exs | Elixir | mix.exs | knoxcarey/kmitr | b8e08dc7708631b2c5beb031a0ed96fdd4cc0ab6 | [
"0BSD"
] | null | null | null | mix.exs | knoxcarey/kmitr | b8e08dc7708631b2c5beb031a0ed96fdd4cc0ab6 | [
"0BSD"
] | null | null | null | mix.exs | knoxcarey/kmitr | b8e08dc7708631b2c5beb031a0ed96fdd4cc0ab6 | [
"0BSD"
] | null | null | null | defmodule Kmitr.Mixfile do
use Mix.Project
def project do
[apps_path: "apps",
deps: deps]
end
defp deps do
[
{:exrm, "~> 0.14.16"}
]
end
end
| 11.733333 | 27 | 0.551136 |
f78b5075dfc02ba0eaf7d7c62bb7f339dd79b6f9 | 2,411 | ex | Elixir | rtp/lib/membrane_demo_rtp/receive_pipeline.ex | membraneframework/videoroom_advanced | d5bfbcec7558bb7ddd4f74742c0d842e5d759b21 | [
"Apache-2.0"
] | 84 | 2020-08-01T14:57:29.000Z | 2022-03-27T13:28:23.000Z | rtp/lib/membrane_demo_rtp/receive_pipeline.ex | membraneframework/videoroom_advanced | d5bfbcec7558bb7ddd4f74742c0d842e5d759b21 | [
"Apache-2.0"
] | 75 | 2020-08-24T08:01:53.000Z | 2022-03-17T10:41:22.000Z | rtp/lib/membrane_demo_rtp/receive_pipeline.ex | membraneframework/videoroom_advanced | d5bfbcec7558bb7ddd4f74742c0d842e5d759b21 | [
"Apache-2.0"
] | 17 | 2020-09-15T21:04:23.000Z | 2022-03-31T07:43:48.000Z | defmodule Membrane.Demo.RTP.ReceivePipeline do
use Membrane.Pipeline
alias Membrane.RTP
@impl true
def handle_init(opts) do
%{secure?: secure?, audio_port: audio_port, video_port: video_port} = opts
spec = %ParentSpec{
children: [
video_src: %Membrane.Element.UDP.Source{
local_port_no: video_port,
local_address: {127, 0, 0, 1}
},
audio_src: %Membrane.Element.UDP.Source{
local_port_no: audio_port,
local_address: {127, 0, 0, 1}
},
rtp: %RTP.SessionBin{
secure?: secure?,
srtp_policies: [
%ExLibSRTP.Policy{
ssrc: :any_inbound,
key: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
]
}
],
links: [
link(:video_src) |> via_in(:rtp_input) |> to(:rtp),
link(:audio_src) |> via_in(:rtp_input) |> to(:rtp)
]
}
{{:ok, spec: spec}, %{}}
end
@impl true
def handle_notification({:new_rtp_stream, ssrc, 96}, :rtp, _ctx, state) do
state = Map.put(state, :video, ssrc)
actions = handle_stream(state)
{{:ok, actions}, state}
end
@impl true
def handle_notification({:new_rtp_stream, ssrc, 120}, :rtp, _ctx, state) do
state = Map.put(state, :audio, ssrc)
actions = handle_stream(state)
{{:ok, actions}, state}
end
@impl true
def handle_notification({:new_rtp_stream, _ssrc, encoding_name}, :rtp, _ctx, _state) do
raise "Unsupported encoding: #{inspect(encoding_name)}"
end
@impl true
def handle_notification(_, _, _ctx, state) do
{:ok, state}
end
defp handle_stream(%{audio: audio_ssrc, video: video_ssrc}) do
spec = %ParentSpec{
children: %{
audio_decoder: Membrane.Opus.Decoder,
audio_player: Membrane.PortAudio.Sink,
video_parser: %Membrane.H264.FFmpeg.Parser{framerate: {30, 1}},
video_decoder: Membrane.H264.FFmpeg.Decoder,
video_player: Membrane.SDL.Player
},
links: [
link(:rtp)
|> via_out(Pad.ref(:output, audio_ssrc))
|> to(:audio_decoder)
|> to(:audio_player),
link(:rtp)
|> via_out(Pad.ref(:output, video_ssrc))
|> to(:video_parser)
|> to(:video_decoder)
|> to(:video_player)
],
stream_sync: :sinks
}
[spec: spec]
end
defp handle_stream(_state) do
[]
end
end
| 25.924731 | 89 | 0.588138 |
f78b95898e6c88748ff4160092e0f07151ea4f80 | 566 | ex | Elixir | lib/cookbook_web/live/geolocation_live.ex | joerichsen/live_view_cookbook | a211e6bcfaa872df120f186b3d65e0672f410365 | [
"MIT"
] | null | null | null | lib/cookbook_web/live/geolocation_live.ex | joerichsen/live_view_cookbook | a211e6bcfaa872df120f186b3d65e0672f410365 | [
"MIT"
] | 11 | 2021-12-19T09:07:30.000Z | 2022-01-01T17:54:43.000Z | lib/cookbook_web/live/geolocation_live.ex | joerichsen/live_view_cookbook | a211e6bcfaa872df120f186b3d65e0672f410365 | [
"MIT"
] | null | null | null | defmodule CookbookWeb.GeolocationLive do
use CookbookWeb, :live_view
def render(assigns) do
~H"""
<div id="geolocation-demo" phx-hook="GetGeolocation">
<%= if @address do %>
<h1>Your address is:</h1>
<%= @address %>
<% end %>
</div>
"""
end
def mount(_params, _session, socket) do
{:ok, socket |> assign(address: nil)}
end
def handle_event("position", %{"lat" => lat, "long" => long}, socket) do
info = LibLatLon.lookup({lat, long})
{:noreply, socket |> assign(address: info.address)}
end
end
| 23.583333 | 74 | 0.59364 |
f78b9aac6a388f4a469e759808344d0463c63ba7 | 711 | ex | Elixir | lib/exkubed_web/gettext.ex | nilenso/exkubed | 84586ab75ebc417cf5a5bed5323d9032b23ea2ec | [
"MIT"
] | 1 | 2019-08-29T20:35:54.000Z | 2019-08-29T20:35:54.000Z | lib/exkubed_web/gettext.ex | nilenso/exkubed | 84586ab75ebc417cf5a5bed5323d9032b23ea2ec | [
"MIT"
] | null | null | null | lib/exkubed_web/gettext.ex | nilenso/exkubed | 84586ab75ebc417cf5a5bed5323d9032b23ea2ec | [
"MIT"
] | null | null | null | defmodule ExkubedWeb.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 ExkubedWeb.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: :exkubed
end
| 28.44 | 72 | 0.677918 |
f78ba71910f51203eb49d625e87b7157651d3ba7 | 1,151 | exs | Elixir | test/wallaby/phantom/log_store_test.exs | alecho/wallaby | 90c34245e6340d49a2976f3f60b810c4435c19f8 | [
"MIT"
] | 1 | 2020-05-15T20:41:00.000Z | 2020-05-15T20:41:00.000Z | test/wallaby/phantom/log_store_test.exs | aarongraham/wallaby | 37a4dc379a83b64540c8763e7205752b43bd811e | [
"MIT"
] | null | null | null | test/wallaby/phantom/log_store_test.exs | aarongraham/wallaby | 37a4dc379a83b64540c8763e7205752b43bd811e | [
"MIT"
] | null | null | null | defmodule Wallaby.Driver.LogStoreTest do
use ExUnit.Case, async: true
alias Wallaby.Driver.LogStore
@l1 %{"level" => "INFO", "message" => "l1 (:)", "timestamp" => 1_470_795_015_152}
@l2 %{"level" => "INFO", "message" => "l2 (:)", "timestamp" => 1_470_795_015_290}
@l3 %{"level" => "WARNING", "message" => "l3 (:)", "timestamp" => 1_470_795_015_345}
@session "123abc"
setup do
{:ok, log_store} = start_supervised({LogStore, name: :test})
[log_store: log_store]
end
describe "append_logs/2" do
test "only appends new logs", %{log_store: log_store} do
assert LogStore.append_logs(@session, [@l1, @l2], log_store) == [@l1, @l2]
assert LogStore.append_logs(@session, [@l2, @l3], log_store) == [@l3]
assert LogStore.get_logs(@session, log_store) == [@l1, @l2, @l3]
end
test "wraps logs in a list if they are not already in one", %{log_store: log_store} do
assert LogStore.append_logs(@session, [@l1, @l2], log_store) == [@l1, @l2]
assert LogStore.append_logs(@session, @l3, log_store) == [@l3]
assert LogStore.get_logs(@session, log_store) == [@l1, @l2, @l3]
end
end
end
| 37.129032 | 90 | 0.631625 |
f78bb916431bc024b368d2f77de42bb5fc18738c | 9,391 | exs | Elixir | test/cadet/accounts/notification_test.exs | seanlowjk/cadet | 52b55cc0f777cb0d55a78fe1693f762085ab36c2 | [
"Apache-2.0"
] | null | null | null | test/cadet/accounts/notification_test.exs | seanlowjk/cadet | 52b55cc0f777cb0d55a78fe1693f762085ab36c2 | [
"Apache-2.0"
] | null | null | null | test/cadet/accounts/notification_test.exs | seanlowjk/cadet | 52b55cc0f777cb0d55a78fe1693f762085ab36c2 | [
"Apache-2.0"
] | null | null | null | defmodule Cadet.Accounts.NotificationTest do
alias Cadet.Accounts.{Notification, Notifications}
use Cadet.ChangesetCase, entity: Notification
@required_fields ~w(type role user_id)a
setup do
assessment = insert(:assessment, %{is_published: true})
avenger = insert(:user, %{role: :staff})
student = insert(:user, %{role: :student})
submission = insert(:submission, %{student: student, assessment: assessment})
valid_params_for_student = %{
type: :new,
read: false,
role: student.role,
user_id: student.id,
assessment_id: assessment.id
}
valid_params_for_avenger = %{
type: :submitted,
read: false,
role: avenger.role,
user_id: avenger.id,
assessment_id: assessment.id,
submission_id: submission.id
}
{:ok,
%{
assessment: assessment,
avenger: avenger,
student: student,
submission: submission,
valid_params_for_student: valid_params_for_student,
valid_params_for_avenger: valid_params_for_avenger
}}
end
describe "changeset" do
test "valid notification params for student", %{valid_params_for_student: params} do
assert_changeset(params, :valid)
end
test "valid notification params for avenger", %{valid_params_for_avenger: params} do
assert_changeset(params, :valid)
end
test "invalid changeset missing required params for student", %{
valid_params_for_student: params
} do
for field <- @required_fields ++ [:assessment_id] do
params_missing_field = Map.delete(params, field)
assert_changeset(params_missing_field, :invalid)
end
end
test "invalid changeset missing required params for avenger", %{
valid_params_for_avenger: params
} do
for field <- @required_fields ++ [:submission_id] do
params_missing_field = Map.delete(params, field)
assert_changeset(params_missing_field, :invalid)
end
end
test "invalid role", %{valid_params_for_avenger: params} do
params = Map.put(params, :role, :admin)
assert_changeset(params, :invalid)
end
end
describe "repo" do
test "fetch notifications when there are none", %{avenger: avenger, student: student} do
{:ok, notifications_avenger} = Notifications.fetch(avenger)
{:ok, notifications_student} = Notifications.fetch(student)
assert notifications_avenger == []
assert notifications_student == []
end
test "fetch notifications when all unread", %{assessment: assessment, student: student} do
notifications =
insert_list(3, :notification, %{
read: false,
assessment_id: assessment.id,
assessment: assessment,
user_id: student.id
})
expected = Enum.sort(notifications, &(&1.id < &2.id))
{:ok, notifications_db} = Notifications.fetch(student)
results = Enum.sort(notifications_db, &(&1.id < &2.id))
assert results == expected
end
test "fetch notifications when all read", %{assessment: assessment, student: student} do
insert_list(3, :notification, %{
read: true,
assessment_id: assessment.id,
user_id: student.id
})
{:ok, notifications_db} = Notifications.fetch(student)
assert notifications_db == []
end
test "write notification valid params", %{
assessment: assessment,
avenger: avenger,
student: student,
submission: submission
} do
params_student = %{
type: :new,
read: false,
role: student.role,
user_id: student.id,
assessment_id: assessment.id
}
params_avenger = %{
type: :submitted,
read: false,
role: avenger.role,
user_id: avenger.id,
assessment_id: assessment.id,
submission_id: submission.id
}
assert {:ok, _} = Notifications.write(params_student)
assert {:ok, _} = Notifications.write(params_avenger)
end
test "write notification and ensure no duplicates", %{
assessment: assessment,
avenger: avenger,
student: student,
submission: submission
} do
params_student = %{
type: :new,
read: false,
role: student.role,
user_id: student.id,
assessment_id: assessment.id
}
params_avenger = %{
type: :submitted,
read: false,
role: avenger.role,
user_id: avenger.id,
assessment_id: assessment.id,
submission_id: submission.id
}
Notifications.write(params_student)
Notifications.write(params_student)
assert Repo.one(
from(n in Notification,
where:
n.type == ^:new and n.user_id == ^student.id and
n.assessment_id == ^assessment.id
)
)
Notifications.write(params_avenger)
Notifications.write(params_avenger)
assert Repo.one(
from(n in Notification,
where:
n.type == ^:submitted and n.user_id == ^avenger.id and
n.submission_id == ^submission.id
)
)
end
test "write notification missing params", %{
assessment: assessment,
student: student
} do
params_student = %{
type: :new,
read: false,
role: student.role,
user_id: student.id,
assessment_id: assessment.id
}
for field <- @required_fields do
params = Map.delete(params_student, field)
{:error, changeset} = Notifications.write(params)
assert changeset.valid? == false
end
end
test "acknowledge notification valid user", %{
assessment: assessment,
student: student
} do
notification =
insert(:notification, %{
read: false,
assessment_id: assessment.id,
user_id: student.id
})
Notifications.acknowledge([notification.id], student)
notification_db = Repo.get_by(Notification, id: notification.id)
assert %{read: true} = notification_db
end
test "acknowledge multiple notifications valid user", %{
assessment: assessment,
student: student
} do
notifications =
insert_list(3, :notification, %{
read: false,
assessment_id: assessment.id,
user_id: student.id
})
notifications
|> Enum.map(& &1.id)
|> Notifications.acknowledge(student)
for n <- notifications do
assert %{read: true} = Repo.get_by(Notification, id: n.id)
end
end
test "acknowledge notification invalid user", %{
assessment: assessment,
avenger: avenger,
student: student
} do
notification =
insert(:notification, %{
read: false,
assessment_id: assessment.id,
user_id: student.id
})
assert {:error, _} = Notifications.acknowledge(notification.id, avenger)
end
test "handle unsubmit works properly", %{
assessment: assessment,
student: student
} do
{:ok, notification_db} = Notifications.handle_unsubmit_notifications(assessment.id, student)
assert %{type: :unsubmitted} = notification_db
end
test "receives notification when submitted" do
assessment = insert(:assessment, %{is_published: true})
avenger = insert(:user, %{role: :staff})
group = insert(:group, %{leader: avenger})
student = insert(:user, %{role: :student, group: group})
submission = insert(:submission, %{student: student, assessment: assessment})
Notifications.write_notification_when_student_submits(submission)
notification =
Repo.get_by(Notification,
user_id: avenger.id,
type: :submitted,
submission_id: submission.id
)
assert %{type: :submitted} = notification
end
test "receives notification when autograded", %{
assessment: assessment,
student: student,
submission: submission
} do
Notifications.write_notification_when_graded(submission.id, :autograded)
notification =
Repo.get_by(Notification,
user_id: student.id,
type: :autograded,
assessment_id: assessment.id
)
assert %{type: :autograded} = notification
end
test "receives notification when manually graded", %{
assessment: assessment,
student: student,
submission: submission
} do
Notifications.write_notification_when_graded(submission.id, :graded)
notification =
Repo.get_by(Notification, user_id: student.id, type: :graded, assessment_id: assessment.id)
assert %{type: :graded} = notification
end
test "every student receives notifications when a new assessment is published", %{
assessment: assessment,
student: student
} do
students = [student | insert_list(3, :user, %{role: :student})]
Notifications.write_notification_for_new_assessment(assessment.id)
for student <- students do
notification =
Repo.get_by(Notification, user_id: student.id, type: :new, assessment_id: assessment.id)
assert %{type: :new} = notification
end
end
end
end
| 27.702065 | 99 | 0.621233 |
f78be4600eaae9bb7e0f45878d24d6340f6bdbc4 | 1,735 | exs | Elixir | test/crawlie/pqueue_wrapper_test.exs | kianmeng/crawlie | 19883f17a208107927ba14d15312f5a908d5e8ea | [
"MIT"
] | 91 | 2016-12-29T12:31:14.000Z | 2021-09-25T23:09:34.000Z | test/crawlie/pqueue_wrapper_test.exs | kianmeng/crawlie | 19883f17a208107927ba14d15312f5a908d5e8ea | [
"MIT"
] | 40 | 2016-12-14T00:55:52.000Z | 2022-01-29T08:46:03.000Z | test/crawlie/pqueue_wrapper_test.exs | kianmeng/crawlie | 19883f17a208107927ba14d15312f5a908d5e8ea | [
"MIT"
] | 10 | 2017-04-06T11:18:10.000Z | 2021-10-30T00:04:09.000Z | defmodule PqueueWrapperTest do
@pqueue_modules [:pqueue, :pqueue2, :pqueue3, :pqueue4]
use ExUnit.Case
alias Crawlie.Page
alias Crawlie.PqueueWrapper, as: PW
test "constructor" do
Enum.each(@pqueue_modules, fn(m) ->
empty = PW.new(m)
assert %PW{module: ^m, data: data} = empty
assert data != nil
assert data == m.new
end)
end
test "get_priority for :pqueue" do
empty = PW.new(:pqueue)
assert PW.get_priority(empty, 0) == 20
assert PW.get_priority(empty, 40) == -20
end
test "get_priority for :pqueue4" do
empty = PW.new(:pqueue4)
assert PW.get_priority(empty, 0) == 128
assert PW.get_priority(empty, 256) == -128
end
test "get_priority for :pqueue2 and :pqueue3" do
Enum.each([:pqueue2, :pqueue3], fn(m) ->
empty = PW.new(m)
assert PW.get_priority(empty, 0) == 0
assert PW.get_priority(empty, 13) == -13
assert PW.get_priority(empty, 256) == -256
end)
end
test "all/1" do
pages = [p1, p2, p3] = ["foo", "bar", "baz"] |> Enum.map(&Page.new(&1))
empty = PW.new(:pqueue)
q =
empty
|> PW.add_page(p1)
|> PW.add_page(p2)
|> PW.add_page(p3)
assert Enum.sort(pages) == Enum.sort(PW.all(q))
end
test "works in a sample scenario" do
p0 = Page.new("foo", 0)
p1 = Page.new("bar", 1)
p2 = Page.new("bar", 2)
Enum.each(@pqueue_modules, fn(m) ->
q = PW.new(m)
q = PW.add_page(q, p1)
q = PW.add_page(q, p0)
q = PW.add_page(q, p2)
assert PW.len(q) == 3
assert {q, ^p2} = PW.take(q)
assert {q, ^p1} = PW.take(q)
assert {q, ^p0} = PW.take(q)
assert PW.empty?(q)
assert PW.len(q) == 0
end)
end
end
| 22.828947 | 75 | 0.574063 |
f78bfb34e3a958002327bc3be769cb742e5fcb43 | 201 | ex | Elixir | lib/phone/lr.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | lib/phone/lr.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | lib/phone/lr.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | defmodule Phone.LR do
@moduledoc false
use Helper.Country
def regex, do: ~r/^(231)()(.{7,9})/
def country, do: "Liberia"
def a2, do: "LR"
def a3, do: "LBR"
matcher :regex, ["231"]
end
| 15.461538 | 37 | 0.597015 |
f78c06823932361875a283a2eade80fa1fed2f55 | 2,017 | ex | Elixir | lib/tmdb/keywords/keywords.ex | DonHansDampf/elixir-tmdb | 7a79350dfb0eeb5a37384be4ca9fac0570a3020e | [
"MIT"
] | 13 | 2016-07-30T05:10:50.000Z | 2019-04-25T05:08:11.000Z | lib/tmdb/keywords/keywords.ex | DonHansDampf/elixir-tmdb | 7a79350dfb0eeb5a37384be4ca9fac0570a3020e | [
"MIT"
] | 3 | 2016-08-04T00:44:01.000Z | 2017-07-18T17:27:05.000Z | lib/tmdb/keywords/keywords.ex | DonHansDampf/elixir-tmdb | 7a79350dfb0eeb5a37384be4ca9fac0570a3020e | [
"MIT"
] | 12 | 2016-07-30T23:59:26.000Z | 2021-06-25T05:53:57.000Z | defmodule Tmdb.Keywords do
@moduledoc """
Keywords Endpoint
## Available functions for keywords
Tmdb.Keywords.find(1721) # Find a keyword and its name by keyword id
Tmdb.Keywords.search("fight") # Search for keywords by text
Tmdb.Keywords.movies(1721) # find movies by a keyword ID
"""
use Tmdb.Base
@doc ~S"""
Get the basic information for a specific keyword id.
## Required Parameters
api_key
## Examples
iex> Tmdb.Keywords.find(1721)
%{"id" => 1721, "name" => "fight"}
"""
def find(id) do
get!("keyword/#{id}?").body
end
@doc ~S"""
Search for keywords by text
## Required Parameters
api_key
query: CGI escaped string
## Optional Parameters
page: minimum 1, maximum 1000.
## Examples
iex(2)> Tmdb.Keywords.search("fight") %{"page" => 1,
"results" => [%{"id" => 1721, "name" => "fight"},
%{"id" => 9725, "name" => "sword fight"},
%{"id" => 5380, "name" => "virtual fight"},
%{"id" => 14696, "name" => "bloody fight"},
%{"id" => 14949, "name" => "stick fight"},
%{"id" => 18109, "name" => "knife fight"},
%{"id" => 18110, "name" => "gist fight"},
%{"id" => 1527, "name" => "gladiator fight"},
%{"id" => 156808, "name" => "hospital fight"},
%{"id" => 156854, "name" => "cat fight"},
%{"id" => 156479, "name" => "inheritance fight"},
%{"id" => 68643, "name" => "food fight"},
%{"id" => 157201, "name" => "women fight"},
%{"id" => 186727, "name" => "nude fight"},
%{"id" => 186150, "name" => "street fight"},
%{"id" => 187928, "name" => "prison fight"},
%{"id" => 187292, "name" => "fixed fight"},
%{"id" => 187368, "name" => "pillow fight"},
%{"id" => 188933, "name" => "bar fight"},
%{"id" => 189274, "name" => "hotel fight"}], "total_pages" => 6,
"total_results" => 109}
"""
def movies(id) do
get!("keyword/#{id}/movies?").body
end
end
| 33.616667 | 94 | 0.517105 |
f78c27947d73384b669f32501005e36d969c7c98 | 1,050 | ex | Elixir | apps/artemis/lib/artemis/contexts/cloud/delete_cloud.ex | artemis-platform/artemis_dashboard | 5ab3f5ac4c5255478bbebf76f0e43b44992e3cab | [
"MIT"
] | 9 | 2019-08-19T19:56:34.000Z | 2022-03-22T17:56:38.000Z | apps/artemis/lib/artemis/contexts/cloud/delete_cloud.ex | chrislaskey/atlas_dashboard | 9009ef5aac8fefba126fa7d3e3b82d1b610ee6fe | [
"MIT"
] | 7 | 2019-07-12T21:41:01.000Z | 2020-08-17T21:29:22.000Z | apps/artemis/lib/artemis/contexts/cloud/delete_cloud.ex | chrislaskey/atlas_dashboard | 9009ef5aac8fefba126fa7d3e3b82d1b610ee6fe | [
"MIT"
] | 2 | 2019-07-05T22:51:47.000Z | 2019-08-19T19:56:37.000Z | defmodule Artemis.DeleteCloud do
use Artemis.Context
alias Artemis.DeleteManyAssociatedComments
alias Artemis.GetCloud
alias Artemis.Repo
def call!(id, params \\ %{}, user) do
case call(id, params, user) do
{:error, _} -> raise(Artemis.Context.Error, "Error deleting cloud")
{:ok, result} -> result
end
end
def call(id, params \\ %{}, user) do
with_transaction(fn ->
id
|> get_record(user)
|> delete_associated_comments(user)
|> delete_record
|> Event.broadcast("cloud:deleted", params, user)
end)
end
def get_record(%{id: id}, user), do: get_record(id, user)
def get_record(id, user), do: GetCloud.call(id, user)
defp delete_associated_comments(record, user) do
resource_type = "Cloud"
resource_id = record.id
{:ok, _} = DeleteManyAssociatedComments.call(resource_type, resource_id, user)
record
rescue
_ -> record
end
defp delete_record(nil), do: {:error, "Record not found"}
defp delete_record(record), do: Repo.delete(record)
end
| 25 | 82 | 0.666667 |
f78c30bc24bf49aeecf0c364a738fbbcd17597bf | 31 | ex | Elixir | testData/org/elixir_lang/parser_definition/matched_dot_operation_parsing_test_case/CharListHeredoc.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 1,668 | 2015-01-03T05:54:27.000Z | 2022-03-25T08:01:20.000Z | testData/org/elixir_lang/parser_definition/matched_dot_operation_parsing_test_case/CharListHeredoc.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 2,018 | 2015-01-01T22:43:39.000Z | 2022-03-31T20:13:08.000Z | testData/org/elixir_lang/parser_definition/matched_dot_operation_parsing_test_case/CharListHeredoc.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | '''
One
'''.'''
Two
''' | 6.2 | 7 | 0.193548 |
f78c61bb87275149410d100da84f880428859c41 | 7,965 | ex | Elixir | lib/type.ex | prithvihv/tarams | 45396934d91aa624da6e3ef233d8e26236eeed2c | [
"MIT"
] | null | null | null | lib/type.ex | prithvihv/tarams | 45396934d91aa624da6e3ef233d8e26236eeed2c | [
"MIT"
] | null | null | null | lib/type.ex | prithvihv/tarams | 45396934d91aa624da6e3ef233d8e26236eeed2c | [
"MIT"
] | null | null | null | defmodule Tarams.Type do
@moduledoc """
Cast data to target type.
Much code of this module is borrowed from `Ecto.Type`
"""
# @base ~w(
# integer float decimal boolean string map binary id binary_id any
# datetime utc_datetime naive_datetime date time
# )a
def cast({:embed, mod, params}, value), do: mod.cast(value, params)
def cast(type, value) do
cast_fun(type).(value)
end
def cast!(type, value) do
with {:ok, data} <- cast(type, value) do
data
else
_ ->
raise "invalid #{inspect(type)}"
end
end
# def is_base_type(type) do
# type in @base
# end
defp cast_fun(:boolean), do: &cast_boolean/1
defp cast_fun(:integer), do: &cast_integer/1
defp cast_fun(:float), do: &cast_float/1
defp cast_fun(:string), do: &cast_binary/1
defp cast_fun(:binary), do: &cast_binary/1
defp cast_fun(:any), do: &{:ok, &1}
defp cast_fun(:date), do: &cast_date/1
defp cast_fun(:time), do: &maybe_truncate_usec(cast_time(&1))
defp cast_fun(:datetime), do: &maybe_truncate_usec(cast_utc_datetime(&1))
defp cast_fun(:naive_datetime), do: &maybe_truncate_usec(cast_naive_datetime(&1))
defp cast_fun(:utc_datetime), do: &maybe_truncate_usec(cast_utc_datetime(&1))
defp cast_fun(:map), do: &cast_map/1
defp cast_fun(:decimal), do: &cast_decimal/1
defp cast_fun(mod) when is_atom(mod), do: &maybe_cast_custom_type(mod, &1)
defp same_decimal(term) when is_integer(term), do: {:ok, Decimal.new(term)}
defp same_decimal(term) when is_float(term), do: {:ok, Decimal.from_float(term)}
defp same_decimal(%Decimal{} = term), do: check_decimal(term, true)
defp same_decimal(_), do: :error
defp check_decimal(%Decimal{coef: coef} = decimal, _) when is_integer(coef), do: {:ok, decimal}
defp check_decimal(_decimal, false), do: :error
defp check_decimal(decimal, true) do
raise ArgumentError, """
#{inspect(decimal)} is not allowed for type :decimal
`+Infinity`, `-Infinity`, and `NaN` values are not supported, even though the `Decimal` library handles them. \
To support them, you can create a custom type.
"""
end
defp cast_decimal(term) when is_binary(term) do
case Decimal.parse(term) do
{:ok, decimal} -> check_decimal(decimal, false)
# The following two clauses exist to support earlier versions of Decimal.
{decimal, ""} -> check_decimal(decimal, false)
{_, remainder} when is_binary(remainder) and byte_size(remainder) > 0 -> :error
:error -> :error
end
end
defp cast_decimal(term), do: same_decimal(term)
defp cast_fun({:array, {:embed, _, _} = type}) do
fun = fn value -> cast(type, value) end
&array(&1, fun, true, [])
end
defp cast_fun({:array, type}) do
fun = cast_fun(type)
&array(&1, fun, true, [])
end
defp cast_boolean(term) when term in ~w(true 1), do: {:ok, true}
defp cast_boolean(term) when term in ~w(false 0), do: {:ok, false}
defp cast_boolean(term) when is_boolean(term), do: {:ok, term}
defp cast_boolean(_), do: :error
defp cast_integer(term) when is_binary(term) do
case Integer.parse(term) do
{integer, ""} -> {:ok, integer}
_ -> :error
end
end
defp cast_integer(term) when is_integer(term), do: {:ok, term}
defp cast_integer(_), do: :error
defp cast_float(term) when is_binary(term) do
case Float.parse(term) do
{float, ""} -> {:ok, float}
_ -> :error
end
end
defp cast_float(term) when is_float(term), do: {:ok, term}
defp cast_float(term) when is_integer(term), do: {:ok, :erlang.float(term)}
defp cast_float(_), do: :error
defp cast_binary(term) when is_binary(term), do: {:ok, term}
defp cast_binary(_), do: :error
## Date
defp cast_date(binary) when is_binary(binary) do
case Date.from_iso8601(binary) do
{:ok, _} = ok ->
ok
{:error, _} ->
case NaiveDateTime.from_iso8601(binary) do
{:ok, naive_datetime} -> {:ok, NaiveDateTime.to_date(naive_datetime)}
{:error, _} -> :error
end
end
end
defp cast_date(%Date{} = date), do: {:ok, date}
defp cast_date(%DateTime{} = date), do: {:ok, DateTime.to_date(date)}
defp cast_date(%NaiveDateTime{} = date), do: {:ok, NaiveDateTime.to_date(date)}
defp cast_date(%{year: year, month: month, day: day})
when is_integer(year) and is_integer(month) and is_integer(day),
do: Date.new(year, month, day)
defp cast_date(_), do: :error
## Time
defp cast_time(binary) when is_binary(binary) do
case Time.from_iso8601(binary) do
{:ok, _} = ok -> ok
{:error, _} -> :error
end
end
defp cast_time(%Time{} = time), do: {:ok, time}
defp cast_time(%DateTime{} = date), do: {:ok, DateTime.to_time(date)}
defp cast_time(%NaiveDateTime{} = date), do: {:ok, NaiveDateTime.to_time(date)}
defp cast_time(%{hour: hour, minute: minute, second: second})
when is_integer(hour) and is_integer(minute) and is_integer(second),
do: Time.new(hour, minute, second)
defp cast_time(_), do: :error
## Naive datetime
defp cast_naive_datetime("-" <> rest) do
with {:ok, datetime} <- cast_naive_datetime(rest) do
{:ok, %{datetime | year: datetime.year * -1}}
end
end
defp cast_naive_datetime(binary) when is_binary(binary) do
case NaiveDateTime.from_iso8601(binary) do
{:ok, _} = ok -> ok
{:error, _} -> :error
end
end
defp cast_naive_datetime(%{
year: empty,
month: empty,
day: empty,
hour: empty,
minute: empty,
second: empty
})
when empty in ["", nil],
do: {:ok, nil}
defp cast_naive_datetime(%{} = map) do
with {:ok, %Date{} = date} <- cast_date(map),
{:ok, %Time{} = time} <- cast_time(map) do
NaiveDateTime.new(date, time)
else
_ -> :error
end
end
defp cast_naive_datetime(_) do
:error
end
## UTC datetime
defp cast_utc_datetime("-" <> rest) do
with {:ok, utc_datetime} <- cast_utc_datetime(rest) do
{:ok, %{utc_datetime | year: utc_datetime.year * -1}}
end
end
defp cast_utc_datetime(binary) when is_binary(binary) do
case DateTime.from_iso8601(binary) do
{:ok, datetime, _offset} ->
{:ok, datetime}
{:error, :missing_offset} ->
case NaiveDateTime.from_iso8601(binary) do
{:ok, naive_datetime} -> {:ok, DateTime.from_naive!(naive_datetime, "Etc/UTC")}
{:error, _} -> :error
end
{:error, _} ->
:error
end
end
defp cast_utc_datetime(%DateTime{time_zone: "Etc/UTC"} = datetime), do: {:ok, datetime}
defp cast_utc_datetime(%DateTime{} = datetime) do
case datetime |> DateTime.to_unix(:microsecond) |> DateTime.from_unix(:microsecond) do
{:ok, _} = ok -> ok
{:error, _} -> :error
end
end
defp cast_utc_datetime(value) do
case cast_naive_datetime(value) do
{:ok, %NaiveDateTime{} = naive_datetime} ->
{:ok, DateTime.from_naive!(naive_datetime, "Etc/UTC")}
{:ok, _} = ok ->
ok
:error ->
:error
end
end
defp cast_map(term) when is_map(term), do: {:ok, term}
defp cast_map(_), do: :error
defp maybe_cast_custom_type(mod, value) do
mod.cast(value)
end
defp array(term, _, _, _) when not is_list(term) do
:error
end
defp array([nil | t], fun, true, acc) do
array(t, fun, true, [nil | acc])
end
defp array([h | t], fun, skip_nil?, acc) do
case fun.(h) do
{:ok, h} -> array(t, fun, skip_nil?, [h | acc])
_error -> :error
end
end
defp array([], _fun, _skip_nil?, acc) do
{:ok, Enum.reverse(acc)}
end
defp maybe_truncate_usec({:ok, struct}), do: {:ok, truncate_usec(struct)}
defp maybe_truncate_usec(:error), do: :error
defp truncate_usec(nil), do: nil
defp truncate_usec(%{microsecond: {0, 0}} = struct), do: struct
defp truncate_usec(struct), do: %{struct | microsecond: {0, 0}}
end
| 29.069343 | 115 | 0.632141 |
f78c6f43e41251cedd79806f23d31273054b3f91 | 947 | exs | Elixir | config/config.exs | bcoop713/rumbl | 831982b86f8f4e6540b6d481e36e2e3c3470b5b1 | [
"MIT"
] | null | null | null | config/config.exs | bcoop713/rumbl | 831982b86f8f4e6540b6d481e36e2e3c3470b5b1 | [
"MIT"
] | null | null | null | config/config.exs | bcoop713/rumbl | 831982b86f8f4e6540b6d481e36e2e3c3470b5b1 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# Configures the endpoint
config :rumbl, Rumbl.Endpoint,
url: [host: "localhost"],
root: Path.dirname(__DIR__),
secret_key_base: "TyTvCco55h90jFNVBAONDT30pEZqGb0Vzt1l0VQUInbngKYXzwekYAG7yKQKEkjb",
render_errors: [accepts: ~w(html json)],
pubsub: [name: Rumbl.PubSub,
adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
# Configure phoenix generators
config :phoenix, :generators,
migration: true,
binary_id: false
| 31.566667 | 86 | 0.757128 |
f78c739c510f62b426b9429e7ccbc0ea40498939 | 1,201 | exs | Elixir | test/test_helper.exs | Rutaba/stripity_stripe | 12c525301c781f9c8c7e578cc0d933f5d35183d5 | [
"BSD-3-Clause"
] | 2 | 2019-05-02T10:42:09.000Z | 2019-12-02T21:29:17.000Z | test/test_helper.exs | Rutaba/stripity_stripe | 12c525301c781f9c8c7e578cc0d933f5d35183d5 | [
"BSD-3-Clause"
] | 1 | 2020-05-20T21:04:19.000Z | 2020-05-20T21:04:19.000Z | test/test_helper.exs | Rutaba/stripity_stripe | 12c525301c781f9c8c7e578cc0d933f5d35183d5 | [
"BSD-3-Clause"
] | 1 | 2019-07-18T11:44:35.000Z | 2019-07-18T11:44:35.000Z | ExUnit.start()
# Stripe.start
Application.ensure_all_started(:erlexec)
Application.ensure_all_started(:exexec)
Application.ensure_all_started(:mox)
ExUnit.configure(exclude: [disabled: true], seed: 0)
Logger.configure(level: :info)
{:ok, pid} = Stripe.StripeMock.start_link(port: 12123, global: true)
Application.put_env(:stripity_stripe, :api_base_url, "http://localhost:12123/v1/")
Application.put_env(:stripity_stripe, :api_upload_url, "http://localhost:12123/v1/")
Application.put_env(:stripity_stripe, :api_key, "sk_test_123")
Application.put_env(:stripity_stripe, :log_level, :debug)
Mox.defmock(Stripe.Connect.OAuthMock, for: Stripe.Connect.OAuth)
Mox.defmock(Stripe.APIMock, for: Stripe.API)
defmodule Helper do
@fixture_path "./test/fixtures/"
def load_fixture(filename) do
File.read!(@fixture_path <> filename) |> Stripe.API.json_library().decode!()
end
def wait_until_stripe_mock_launch() do
case Stripe.Charge.list() do
{:error, %Stripe.Error{code: :network_error}} ->
# It might be connection refused.
Process.sleep(250)
wait_until_stripe_mock_launch()
_ ->
true
end
end
end
Helper.wait_until_stripe_mock_launch()
| 30.025 | 84 | 0.739384 |
f78c793f4ebd378936fbc977736e4639cf387a3b | 2,333 | ex | Elixir | lib/easypost/request.ex | winestyr/ex_easypost | a8563ccbff429ad181280c438efeea65383ff852 | [
"MIT"
] | 6 | 2017-09-21T13:19:56.000Z | 2021-01-07T18:31:42.000Z | lib/easypost/request.ex | winestyr/ex_easypost | a8563ccbff429ad181280c438efeea65383ff852 | [
"MIT"
] | null | null | null | lib/easypost/request.ex | winestyr/ex_easypost | a8563ccbff429ad181280c438efeea65383ff852 | [
"MIT"
] | 2 | 2018-07-11T07:12:08.000Z | 2020-06-29T02:04:48.000Z | defmodule EasyPost.Request do
alias EasyPost.{ Helpers, Response }
@type t ::
%__MODULE__{
attempt: integer,
body: binary,
headers: EasyPost.http_headers_t(),
method: EasyPost.http_method_t(),
result: any,
url: String.t()
}
defstruct attempt: 0,
body: nil,
headers: nil,
method: nil,
result: nil,
url: nil
@spec send(EasyPost.Operation.t(), EasyPost.Config.t()) :: EasyPost.response_t()
def send(operation, config) do
body = Helpers.Body.encode!(operation, config)
headers = []
headers = headers ++ [{ "authorization", "Bearer #{config.api_key}" }]
headers = headers ++ [{ "content-type", "application/json" }]
method = operation.method
url = Helpers.URL.to_string(operation, config)
request = %__MODULE__{}
request = Map.put(request, :body, body)
request = Map.put(request, :headers, headers)
request = Map.put(request, :method, method)
request = Map.put(request, :url, url)
request
|> dispatch(config)
|> retry(config)
|> finish(config)
end
defp dispatch(request, config) do
http_client = config.http_client
result = http_client.request(request.method, request.url, request.headers, request.body, config.http_client_opts)
request = Map.put(request, :attempt, request.attempt + 1)
request = Map.put(request, :result, result)
request
end
defp retry(request, config) do
max_attempts = Keyword.get(config.retry_opts, :max_attempts, 3)
if config.retry && max_attempts > request.attempt do
case request.result do
{ :ok, %{ status_code: status_code } } when status_code >= 500 ->
dispatch(request, config)
{ :error, _reason } ->
dispatch(request, config)
_otherwise ->
request
end
else
request
end
end
defp finish(request, config) do
case request.result do
{ :ok, %{ status_code: status_code } = response } when status_code >= 400 ->
{ :error, Response.new(response, config) }
{ :ok, %{ status_code: status_code } = response } when status_code >= 200 ->
{ :ok, Response.new(response, config) }
otherwise ->
otherwise
end
end
end
| 27.77381 | 117 | 0.603943 |
f78c8958c45acebabb33b16cfecfdcf91f8b5223 | 758 | ex | Elixir | lib/xeroxero/core_api/models/tracking_categories/tracking_category/options/option.ex | scottmessinger/elixero | 4e62c4d80d221639ba2347a563002511e8d4a6c6 | [
"MIT"
] | 1 | 2021-12-01T18:21:31.000Z | 2021-12-01T18:21:31.000Z | lib/xeroxero/core_api/models/tracking_categories/tracking_category/options/option.ex | scottmessinger/elixero | 4e62c4d80d221639ba2347a563002511e8d4a6c6 | [
"MIT"
] | null | null | null | lib/xeroxero/core_api/models/tracking_categories/tracking_category/options/option.ex | scottmessinger/elixero | 4e62c4d80d221639ba2347a563002511e8d4a6c6 | [
"MIT"
] | 1 | 2021-10-01T12:09:46.000Z | 2021-10-01T12:09:46.000Z | defmodule XeroXero.CoreApi.Models.TrackingCategories.TrackingCategory.Options.Option do
use Ecto.Schema
import Ecto.Changeset
@derive {Jason.Encoder, except: [:__meta__, :id]}
schema "options" do
field :TrackingOptionID, Ecto.UUID
field :Name, :string
field :Status, :string
embeds_many :ValidationErrors, XeroXero.CoreApi.Models.Common.Error
embeds_many :Warnings, XeroXero.CoreApi.Models.Common.Warning
field :StatusAttributeString, :string
end
def changeset(struct, data) do
struct
|> cast(data, [:TrackingOptionID, :Name, :Status, :StatusAttributeString])
|> cast_embed(:ValidationErrors)
|> cast_embed(:Warnings)
end
end
| 32.956522 | 88 | 0.663588 |
f78c8ce8183851dc0ce4c02d8ef186c7e03933b7 | 1,398 | ex | Elixir | test/support/data_case.ex | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | test/support/data_case.ex | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | test/support/data_case.ex | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | defmodule ElixirBlog.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,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
alias ElixirBlog.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import ElixirBlog.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(ElixirBlog.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(ElixirBlog.Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transform changeset errors to 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} ->
Enum.reduce(opts, message, fn {key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end)
end
end
| 25.888889 | 77 | 0.683119 |
f78c962e85ac63543efa1aff70f1f10e5f12655f | 865 | ex | Elixir | exercism/elixir/space-age/lib/space_age.ex | Tyyagoo/studies | f8fcc3a539cfb6d04a149174c88bf2208e220b96 | [
"Unlicense"
] | null | null | null | exercism/elixir/space-age/lib/space_age.ex | Tyyagoo/studies | f8fcc3a539cfb6d04a149174c88bf2208e220b96 | [
"Unlicense"
] | null | null | null | exercism/elixir/space-age/lib/space_age.ex | Tyyagoo/studies | f8fcc3a539cfb6d04a149174c88bf2208e220b96 | [
"Unlicense"
] | null | null | null | defmodule SpaceAge do
@type planet ::
:mercury
| :venus
| :earth
| :mars
| :jupiter
| :saturn
| :uranus
| :neptune
@planets %{
mercury: 0.2408467,
venus: 0.61519726,
mars: 1.8808158,
jupiter: 11.862615,
saturn: 29.447498,
uranus: 84.016846,
neptune: 164.79132
}
@doc """
Return the number of years a person that has lived for 'seconds' seconds is
aged on 'planet'.
"""
@spec age_on(planet, pos_integer) :: {:ok, float()} | {:error, String.t()}
def age_on(:earth, seconds), do: {:ok, seconds / 31_557_600}
def age_on(planet, seconds) do
{:ok, age_on_earth} = age_on(:earth, seconds)
case Map.fetch(@planets, planet) do
{:ok, rate} -> {:ok, age_on_earth / rate}
:error -> {:error, "not a planet"}
end
end
end
| 22.763158 | 77 | 0.556069 |
f78ca1e7883406d1688a21e876613de10ef3430f | 1,249 | ex | Elixir | lib/mongo/pool/monitor.ex | Talkdesk/mongodb | d6c240c4faf2f73d408b24a028e96f0b30fcb031 | [
"Apache-2.0"
] | null | null | null | lib/mongo/pool/monitor.ex | Talkdesk/mongodb | d6c240c4faf2f73d408b24a028e96f0b30fcb031 | [
"Apache-2.0"
] | null | null | null | lib/mongo/pool/monitor.ex | Talkdesk/mongodb | d6c240c4faf2f73d408b24a028e96f0b30fcb031 | [
"Apache-2.0"
] | null | null | null | defmodule Mongo.Pool.Monitor do
@moduledoc false
use GenServer
alias Mongo.Connection
def start_link(name, ets, opts) do
GenServer.start_link(__MODULE__, [ets, opts], name: name)
end
def version(name, ets, timeout) do
case :ets.lookup(ets, :wire_version) do
[] ->
GenServer.call(name, :version, timeout)
[{:wire_version, version}] ->
version
end
end
def init([ets, opts]) do
:ets.new(ets, [:named_table, read_concurrency: true])
{:ok, conn} = Connection.start_link([on_connect: self] ++ opts)
state = %{ets: ets, conn: conn, waiting: []}
{:ok, state}
end
def handle_call(:version, _from, %{ets: ets, waiting: nil} = state) do
[{:wire_version, version}] = :ets.lookup(ets, :wire_version)
{:reply, version, state}
end
def handle_call(:version, from, %{waiting: waiting} = state) do
{:noreply, %{state | waiting: [from|waiting]}}
end
def handle_info({Connection, :on_connect, conn},
%{ets: ets, conn: conn, waiting: waiting} = state) do
version = Connection.wire_version(conn)
:ets.insert(ets, {:wire_version, version})
Enum.each(waiting, &GenServer.reply(&1, version))
{:noreply, %{state | waiting: nil}}
end
end
| 29.046512 | 72 | 0.635709 |
f78cbad87e85da7a3eff60cf241c62d3abe7f33f | 8,958 | ex | Elixir | clients/elixir/generated/lib/cloud_manager_api/api/environments.ex | shinesolutions/cloudmanager-api-clients | d73a25878f6cc57af954362ba8dccc90d54e6131 | [
"Apache-2.0"
] | 3 | 2020-06-23T05:31:52.000Z | 2020-11-26T05:34:57.000Z | clients/elixir/generated/lib/cloud_manager_api/api/environments.ex | shinesolutions/cloudmanager-api-clients | d73a25878f6cc57af954362ba8dccc90d54e6131 | [
"Apache-2.0"
] | 2 | 2021-01-21T01:19:54.000Z | 2021-12-09T22:30:22.000Z | clients/elixir/generated/lib/cloud_manager_api/api/environments.ex | shinesolutions/cloudmanager-api-clients | d73a25878f6cc57af954362ba8dccc90d54e6131 | [
"Apache-2.0"
] | 1 | 2020-11-18T11:48:13.000Z | 2020-11-18T11:48:13.000Z | # NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
# https://openapi-generator.tech
# Do not edit the class manually.
defmodule CloudManagerAPI.Api.Environments do
@moduledoc """
API calls for all endpoints tagged `Environments`.
"""
alias CloudManagerAPI.Connection
import CloudManagerAPI.RequestBuilder
@doc """
DeleteEnvironment
Delete environment
## Parameters
- connection (CloudManagerAPI.Connection): Connection to server
- program_id (String.t): Identifier of the application
- environment_id (String.t): Identifier of the environment
- x_gw_ims_org_id (String.t): IMS organization ID that the request is being made under.
- authorization (String.t): Bearer [token] - An access token for the technical account created through integration with Adobe IO
- x_api_key (String.t): IMS Client ID (API Key) which is subscribed to consume services on console.adobe.io
- opts (KeywordList): [optional] Optional parameters
## Returns
{:ok, %CloudManagerAPI.Model.Environment{}} on success
{:error, info} on failure
"""
@spec delete_environment(Tesla.Env.client, String.t, String.t, String.t, String.t, String.t, keyword()) :: {:ok, CloudManagerAPI.Model.Environment.t} | {:error, Tesla.Env.t}
def delete_environment(connection, program_id, environment_id, x_gw_ims_org_id, authorization, x_api_key, _opts \\ []) do
%{}
|> method(:delete)
|> url("/api/program/#{program_id}/environment/#{environment_id}")
|> add_param(:headers, :"x-gw-ims-org-id", x_gw_ims_org_id)
|> add_param(:headers, :"Authorization", authorization)
|> add_param(:headers, :"x-api-key", x_api_key)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> evaluate_response([
{ 201, %CloudManagerAPI.Model.Environment{}},
{ 400, %CloudManagerAPI.Model.BadRequestError{}},
{ 404, false}
])
end
@doc """
Download Logs
Download environment logs
## Parameters
- connection (CloudManagerAPI.Connection): Connection to server
- program_id (String.t): Identifier of the program
- environment_id (String.t): Identifier of the environment
- service (String.t): Name of service
- name (String.t): Name of log
- date (String.t): date for which log is required
- x_gw_ims_org_id (String.t): IMS organization ID that the request is being made under.
- authorization (String.t): Bearer [token] - An access token for the technical account created through integration with Adobe IO
- x_api_key (String.t): IMS Client ID (API Key) which is subscribed to consume services on console.adobe.io
- opts (KeywordList): [optional] Optional parameters
- :accept (String.t): Specify application/json in this header to receive a JSON response. Otherwise, a 307 response code will be returned with a Location header.
## Returns
{:ok, %{}} on success
{:error, info} on failure
"""
@spec download_logs(Tesla.Env.client, String.t, String.t, String.t, String.t, String.t, String.t, String.t, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t}
def download_logs(connection, program_id, environment_id, service, name, date, x_gw_ims_org_id, authorization, x_api_key, opts \\ []) do
optional_params = %{
:"Accept" => :headers
}
%{}
|> method(:get)
|> url("/api/program/#{program_id}/environment/#{environment_id}/logs/download")
|> add_param(:query, :"service", service)
|> add_param(:query, :"name", name)
|> add_param(:query, :"date", date)
|> add_param(:headers, :"x-gw-ims-org-id", x_gw_ims_org_id)
|> add_param(:headers, :"Authorization", authorization)
|> add_param(:headers, :"x-api-key", x_api_key)
|> add_optional_params(optional_params, opts)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> evaluate_response([
{ 200, false},
{ 400, %CloudManagerAPI.Model.BadRequestError{}},
{ 404, false}
])
end
@doc """
Get Environment
Returns an environment by its id
## Parameters
- connection (CloudManagerAPI.Connection): Connection to server
- program_id (String.t): Identifier of the program
- environment_id (String.t): Identifier of the environment
- x_gw_ims_org_id (String.t): IMS organization ID that the request is being made under.
- authorization (String.t): Bearer [token] - An access token for the technical account created through integration with Adobe IO
- x_api_key (String.t): IMS Client ID (API Key) which is subscribed to consume services on console.adobe.io
- opts (KeywordList): [optional] Optional parameters
## Returns
{:ok, %CloudManagerAPI.Model.Environment{}} on success
{:error, info} on failure
"""
@spec get_environment(Tesla.Env.client, String.t, String.t, String.t, String.t, String.t, keyword()) :: {:ok, CloudManagerAPI.Model.Environment.t} | {:error, Tesla.Env.t}
def get_environment(connection, program_id, environment_id, x_gw_ims_org_id, authorization, x_api_key, _opts \\ []) do
%{}
|> method(:get)
|> url("/api/program/#{program_id}/environment/#{environment_id}")
|> add_param(:headers, :"x-gw-ims-org-id", x_gw_ims_org_id)
|> add_param(:headers, :"Authorization", authorization)
|> add_param(:headers, :"x-api-key", x_api_key)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> evaluate_response([
{ 200, %CloudManagerAPI.Model.Environment{}}
])
end
@doc """
Get Environment Logs
List all logs available in environment
## Parameters
- connection (CloudManagerAPI.Connection): Connection to server
- program_id (String.t): Identifier of the program
- environment_id (String.t): Identifier of the environment
- days (integer()): number of days for which logs are required
- x_gw_ims_org_id (String.t): IMS organization ID that the request is being made under.
- authorization (String.t): Bearer [token] - An access token for the technical account created through integration with Adobe IO
- x_api_key (String.t): IMS Client ID (API Key) which is subscribed to consume services on console.adobe.io
- opts (KeywordList): [optional] Optional parameters
- :service ([String.t]): Names of services
- :name ([String.t]): Names of log
## Returns
{:ok, %CloudManagerAPI.Model.EnvironmentLogs{}} on success
{:error, info} on failure
"""
@spec get_environment_logs(Tesla.Env.client, String.t, String.t, integer(), String.t, String.t, String.t, keyword()) :: {:ok, CloudManagerAPI.Model.EnvironmentLogs.t} | {:error, Tesla.Env.t}
def get_environment_logs(connection, program_id, environment_id, days, x_gw_ims_org_id, authorization, x_api_key, opts \\ []) do
optional_params = %{
:"service" => :query,
:"name" => :query
}
%{}
|> method(:get)
|> url("/api/program/#{program_id}/environment/#{environment_id}/logs")
|> add_param(:query, :"days", days)
|> add_param(:headers, :"x-gw-ims-org-id", x_gw_ims_org_id)
|> add_param(:headers, :"Authorization", authorization)
|> add_param(:headers, :"x-api-key", x_api_key)
|> add_optional_params(optional_params, opts)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> evaluate_response([
{ 200, %CloudManagerAPI.Model.EnvironmentLogs{}},
{ 400, %CloudManagerAPI.Model.BadRequestError{}},
{ 404, false}
])
end
@doc """
List Environments
Lists all environments in an program
## Parameters
- connection (CloudManagerAPI.Connection): Connection to server
- program_id (String.t): Identifier of the program
- x_gw_ims_org_id (String.t): IMS organization ID that the request is being made under.
- authorization (String.t): Bearer [token] - An access token for the technical account created through integration with Adobe IO
- x_api_key (String.t): IMS Client ID (API Key) which is subscribed to consume services on console.adobe.io
- opts (KeywordList): [optional] Optional parameters
- :type (String.t): Type of the environment
## Returns
{:ok, %CloudManagerAPI.Model.EnvironmentList{}} on success
{:error, info} on failure
"""
@spec get_environments(Tesla.Env.client, String.t, String.t, String.t, String.t, keyword()) :: {:ok, CloudManagerAPI.Model.EnvironmentList.t} | {:error, Tesla.Env.t}
def get_environments(connection, program_id, x_gw_ims_org_id, authorization, x_api_key, opts \\ []) do
optional_params = %{
:"type" => :query
}
%{}
|> method(:get)
|> url("/api/program/#{program_id}/environments")
|> add_param(:headers, :"x-gw-ims-org-id", x_gw_ims_org_id)
|> add_param(:headers, :"Authorization", authorization)
|> add_param(:headers, :"x-api-key", x_api_key)
|> add_optional_params(optional_params, opts)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> evaluate_response([
{ 200, %CloudManagerAPI.Model.EnvironmentList{}},
{ 404, false}
])
end
end
| 42.657143 | 192 | 0.690444 |
f78cc682ba598cce30a82011b671625978b62707 | 1,708 | exs | Elixir | test/honeybadger/plug_test.exs | blitzstudios/honeybadger-elixir | 81ec81c8e7303847de784c2fb7a189b8521c296c | [
"MIT"
] | 175 | 2015-07-04T16:01:53.000Z | 2022-03-30T10:18:03.000Z | test/honeybadger/plug_test.exs | blitzstudios/honeybadger-elixir | 81ec81c8e7303847de784c2fb7a189b8521c296c | [
"MIT"
] | 225 | 2015-07-03T22:08:58.000Z | 2022-02-03T14:16:20.000Z | test/honeybadger/plug_test.exs | blitzstudios/honeybadger-elixir | 81ec81c8e7303847de784c2fb7a189b8521c296c | [
"MIT"
] | 69 | 2015-09-17T13:56:28.000Z | 2022-03-20T17:49:17.000Z | defmodule Honeybadger.PlugTest do
use Honeybadger.Case
use Plug.Test
alias Plug.Conn.WrapperError
defmodule CustomNotFound do
defexception [:message]
end
defimpl Plug.Exception, for: CustomNotFound do
def actions(_), do: []
def status(_), do: 404
end
defmodule PlugApp do
use Plug.Router
use Honeybadger.Plug
alias Honeybadger.PlugTest.CustomNotFound
plug(:match)
plug(:dispatch)
get "/bang" do
_ = conn
raise RuntimeError, "Oops"
end
get "/404_exception" do
_ = conn
raise CustomNotFound, "Oops"
end
end
describe "handle_errors/2" do
setup do
{:ok, _} = Honeybadger.API.start(self())
on_exit(&Honeybadger.API.stop/0)
restart_with_config(exclude_envs: [], breadcrumbs_enabled: true)
end
test "errors are reported" do
conn = conn(:get, "/bang")
assert %WrapperError{reason: reason} = catch_error(PlugApp.call(conn, []))
assert %RuntimeError{message: "Oops"} = reason
assert_receive {:api_request, %{"breadcrumbs" => breadcrumbs}}
assert List.first(breadcrumbs["trail"])["metadata"]["message"] == "Oops"
end
test "not found errors for plug are ignored" do
conn = conn(:get, "/not_found")
assert :function_clause == catch_error(PlugApp.call(conn, []))
refute_receive {:api_request, _}
end
test "exceptions that implement Plug.Exception and return a 404 are ignored" do
conn = conn(:get, "/404_exception")
assert %WrapperError{reason: reason} = catch_error(PlugApp.call(conn, []))
assert %CustomNotFound{message: "Oops"} = reason
refute_receive {:api_request, _}
end
end
end
| 23.081081 | 83 | 0.654567 |
f78cd6354cf5e07c6c043ddf41b703e0626e301e | 849 | ex | Elixir | lib/mail/encoders/base64.ex | sam701/elixir-mail | 5771a8b8808c26f7d6adc3a44859f2c140c994e1 | [
"MIT"
] | 387 | 2016-02-09T23:17:51.000Z | 2022-03-31T13:57:05.000Z | lib/mail/encoders/base64.ex | sam701/elixir-mail | 5771a8b8808c26f7d6adc3a44859f2c140c994e1 | [
"MIT"
] | 84 | 2016-02-09T21:20:11.000Z | 2022-03-10T09:58:43.000Z | lib/mail/encoders/base64.ex | sam701/elixir-mail | 5771a8b8808c26f7d6adc3a44859f2c140c994e1 | [
"MIT"
] | 70 | 2016-02-10T15:21:44.000Z | 2021-12-08T18:20:25.000Z | defmodule Mail.Encoders.Base64 do
@moduledoc """
Encodes/decodes base64 strings according to RFC 2045 which requires line
lengths of less than 76 characters and illegal characters to be removed
during parsing.
See the following links for reference:
- <https://www.ietf.org/rfc/rfc2045.txt>
- <https://stackoverflow.com/questions/25710599/content-transfer-encoding-7bit-or-8-bit>
- <https://stackoverflow.com/questions/13301708/base64-encode-length-parameter>
"""
def encode(string),
do:
string
|> Base.encode64()
|> add_line_breaks()
|> List.flatten()
|> Enum.join()
def decode(string),
do: :base64.mime_decode(string)
defp add_line_breaks(<<head::binary-size(76), tail::binary>>),
do: [head, "\r\n" | add_line_breaks(tail)]
defp add_line_breaks(tail), do: [tail, "\r\n"]
end
| 29.275862 | 90 | 0.687868 |
f78cee22891463f41c8a74424ba5f299e517f4d7 | 812 | ex | Elixir | lib/uro_web/uploaders/user_content_preview.ex | V-Sekai/uro | 0b23da65d5c7e459efcd6b2c3d9bdf91c533b737 | [
"MIT"
] | 1 | 2022-01-11T04:05:39.000Z | 2022-01-11T04:05:39.000Z | lib/uro_web/uploaders/user_content_preview.ex | V-Sekai/uro | 0b23da65d5c7e459efcd6b2c3d9bdf91c533b737 | [
"MIT"
] | 35 | 2021-02-10T08:18:57.000Z | 2021-05-06T17:19:50.000Z | lib/uro_web/uploaders/user_content_preview.ex | V-Sekai/uro | 0b23da65d5c7e459efcd6b2c3d9bdf91c533b737 | [
"MIT"
] | null | null | null | defmodule Uro.Uploaders.UserContentPreview do
use Waffle.Definition
use Waffle.Ecto.Definition
@versions [:original, :thumb]
@extension_whitelist ~w(.jpg .jpeg .gif .png)
# Override the bucket on a per definition basis:
# def bucket do
# :custom_bucket_name
# end
# Whitelist file extensions:
def validate({file, _}) do
file_extension = file.file_name |> Path.extname() |> String.downcase()
Enum.member?(@extension_whitelist, file_extension)
end
# Override the persisted filenames:
def filename(version, {_file, scope}) do
"#{scope.id}_preview_#{version}"
end
# Override the storage directory:
def storage_dir(_version, {_file, _scope}) do
"uploads/"
end
def default_url(version, _scope) do
"/images/user_content/default_#{version}.png"
end
end
| 24.606061 | 74 | 0.706897 |
f78cfb2e2ce6bd12ca9282e7fc9a50a986df3049 | 2,602 | ex | Elixir | kousa/lib/kousa/auth.ex | dqnk/dogehouse | e6bb60429575e664f5ed1a1b667a55f0ea95fc4c | [
"MIT"
] | null | null | null | kousa/lib/kousa/auth.ex | dqnk/dogehouse | e6bb60429575e664f5ed1a1b667a55f0ea95fc4c | [
"MIT"
] | null | null | null | kousa/lib/kousa/auth.ex | dqnk/dogehouse | e6bb60429575e664f5ed1a1b667a55f0ea95fc4c | [
"MIT"
] | null | null | null | defmodule Kousa.Auth do
alias Onion.PubSub
alias Kousa.Utils.TokenUtils
@spec authenticate(Broth.Message.Auth.Request.t(), IP.addr()) ::
{:ok, Beef.Schemas.User.t()} | {:error, term}
def authenticate(request, ip) do
case TokenUtils.tokens_to_user_id(request.accessToken, request.refreshToken) do
nil ->
{:error, "invalid_authentication"}
{:existing_claim, user_id} ->
do_auth(Beef.Users.get(user_id), nil, request, ip)
# TODO: streamline this since we're duplicating user_id and user.
{:new_tokens, _user_id, tokens, user} ->
do_auth(user, tokens, request, ip)
end
end
defp do_auth(user, tokens, request, ip) do
alias Onion.UserSession
alias Onion.RoomSession
alias Beef.Rooms
if user do
# note that this will start the session and will be ignored if the
# session is already running.
UserSession.start_supervised(
user_id: user.id,
ip: ip,
username: user.username,
avatar_url: user.avatarUrl,
banner_url: user.bannerUrl,
display_name: user.displayName,
current_room_id: user.currentRoomId,
muted: request.muted,
deafened: request.deafened,
bot_owner_id: user.botOwnerId
)
if user.ip != ip do
Beef.Users.set_ip(user.id, ip)
end
# currently we only allow one active websocket connection per-user
# at some point soon we're going to make this multi-connection, and we
# won't have to do this.
UserSession.set_active_ws(user.id, self())
if tokens do
UserSession.new_tokens(user.id, tokens)
end
roomIdFromFrontend = request.currentRoomId
cond do
user.currentRoomId ->
# TODO: move toroom business logic
room = Rooms.get_room_by_id(user.currentRoomId)
RoomSession.start_supervised(
room_id: user.currentRoomId,
voice_server_id: room.voiceServerId
)
RoomSession.join_room(room.id, user.id, request.muted, request.deafened)
if request.reconnectToVoice == true do
Kousa.Room.join_vc_room(user.id, room)
end
roomIdFromFrontend ->
Kousa.Room.join_room(user.id, roomIdFromFrontend)
true ->
:ok
end
# subscribe to chats directed to oneself.
PubSub.subscribe("chat:" <> user.id)
# subscribe to user updates
PubSub.subscribe("user:update:" <> user.id)
{:ok, user}
else
{:close, 4001, "invalid_authentication"}
end
end
end
| 28.282609 | 83 | 0.632206 |
f78d1d44e9ede91bf74e2cff926e2f8865c2aa9a | 30 | exs | Elixir | test/test_helper.exs | serokell/fsentry | 8b1fef9867c6f761e3a894d3019199e73999bad6 | [
"CC0-1.0"
] | 1 | 2019-10-11T18:48:34.000Z | 2019-10-11T18:48:34.000Z | test/test_helper.exs | serokell/fsentry | 8b1fef9867c6f761e3a894d3019199e73999bad6 | [
"CC0-1.0"
] | null | null | null | test/test_helper.exs | serokell/fsentry | 8b1fef9867c6f761e3a894d3019199e73999bad6 | [
"CC0-1.0"
] | null | null | null | FSentry.load()
ExUnit.start()
| 10 | 14 | 0.733333 |
f78d242ffb10cefc10127e1068f57fc3528db9c1 | 1,293 | ex | Elixir | clients/translate/lib/google_api/translate/v3/connection.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/translate/lib/google_api/translate/v3/connection.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/translate/lib/google_api/translate/v3/connection.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Translate.V3.Connection do
@moduledoc """
Handle Tesla connections for GoogleApi.Translate.V3.
"""
@type t :: Tesla.Env.client()
use GoogleApi.Gax.Connection,
scopes: [
# See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
"https://www.googleapis.com/auth/cloud-platform",
# Translate text from one language to another using Google Translate
"https://www.googleapis.com/auth/cloud-translation"
],
otp_app: :google_api_translate,
base_url: "https://translation.googleapis.com/"
end
| 35.916667 | 114 | 0.737819 |
f78d61dae35c7765a55e0cc3f6206d544e6068cd | 1,930 | exs | Elixir | test/backoff_server_test.exs | bougueil/kitto | a2b5fb10e632e9ee05dce2644193fd35eaa1938e | [
"MIT"
] | 1,047 | 2016-05-11T16:09:29.000Z | 2022-03-29T17:17:26.000Z | test/backoff_server_test.exs | bougueil/kitto | a2b5fb10e632e9ee05dce2644193fd35eaa1938e | [
"MIT"
] | 132 | 2016-10-28T19:44:26.000Z | 2020-12-06T21:16:53.000Z | test/backoff_server_test.exs | bougueil/kitto | a2b5fb10e632e9ee05dce2644193fd35eaa1938e | [
"MIT"
] | 70 | 2016-10-26T00:11:05.000Z | 2022-01-02T21:43:06.000Z | defmodule Kitto.BackoffServerTest do
use ExUnit.Case, async: true
alias Kitto.BackoffServer, as: Subject
@min 1
setup do
Subject.reset
on_exit fn ->
Application.delete_env :kitto, :job_min_backoff
Application.delete_env :kitto, :job_max_backoff
end
end
test "#succeed resets to 0 the backoff for a job" do
Subject.succeed :italian_job
assert Subject.get(:italian_job) == 0
end
test "#reset resets the state of the server to an empty map" do
Subject.fail :failjob
Subject.fail :otherjob
Subject.succeed :successjob
Subject.reset
assert is_nil(Subject.get(:failjob))
assert is_nil(Subject.get(:otherjob))
assert is_nil(Subject.get(:successjob))
end
test "#fail increases the backoff value exponentially (power of 2)" do
Subject.fail :failjob
val = Subject.get :failjob
Subject.fail :failjob
assert Subject.get(:failjob) == val * 2
Subject.fail :failjob
assert Subject.get(:failjob) == val * 4
end
test "#backoff! puts the current process to sleep for backoff time" do
maxval = 100
Application.put_env :kitto, :job_mix_backoff, 64
Application.put_env :kitto, :job_max_backoff, maxval
Subject.fail :failjob
{time, _} = :timer.tc fn -> Subject.backoff! :failjob end
assert_in_delta time / 1000, maxval, 5
end
describe "when :job_min_backoff is configured" do
setup [:set_job_min_backoff]
test "#fail initializes the backoff to the min value" do
Subject.fail :failjob
assert Subject.get(:failjob) == @min
end
end
describe "when :job_min_backoff is not configured" do
test "#fail initializes the backoff to the default min value" do
Subject.fail :failjob
assert Subject.get(:failjob) == Kitto.Time.mseconds(:second)
end
end
defp set_job_min_backoff(_context) do
Application.put_env :kitto, :job_min_backoff, @min
end
end
| 24.125 | 72 | 0.696373 |
f78d63d1a0830a7796e27bc2a5932dd7baa3e8d4 | 59 | exs | Elixir | episode25/todo/test/todo_test.exs | paulfioravanti/learn_elixir | 8424b1a7a89cb9fd1dacb85bcca487601958b8fa | [
"MIT"
] | 1 | 2021-11-17T23:50:24.000Z | 2021-11-17T23:50:24.000Z | episode25/todo/test/todo_test.exs | paulfioravanti/learn_elixir | 8424b1a7a89cb9fd1dacb85bcca487601958b8fa | [
"MIT"
] | 1 | 2022-03-15T01:11:52.000Z | 2022-03-15T01:11:52.000Z | episode25/todo/test/todo_test.exs | paulfioravanti/learn_elixir | 8424b1a7a89cb9fd1dacb85bcca487601958b8fa | [
"MIT"
] | null | null | null | defmodule TodoTest do
use ExUnit.Case
doctest Todo
end
| 11.8 | 21 | 0.779661 |
f78d6df57b9382347d03c2c8079608265a64a623 | 210 | exs | Elixir | tests/dummy/priv/repo/migrations/2016041605594815_create_batches.exs | autoxjs/autox-phoenix | 6446f4487e3af28955f6560973cff6add34be4d4 | [
"MIT"
] | null | null | null | tests/dummy/priv/repo/migrations/2016041605594815_create_batches.exs | autoxjs/autox-phoenix | 6446f4487e3af28955f6560973cff6add34be4d4 | [
"MIT"
] | 20 | 2016-04-05T06:28:58.000Z | 2016-05-12T15:45:37.000Z | tests/dummy/priv/repo/migrations/2016041605594815_create_batches.exs | foxnewsnetwork/autox | 66ea3f0f7ba8b3f9e910984a2ed3cdf0ef5ef29a | [
"MIT"
] | null | null | null | defmodule Dummy.Repo.Migrations.CreateBatches do
use Ecto.Migration
def change do
create table(:batches) do
add :material, :string
add :weight, :integer
timestamps
end
end
end | 16.153846 | 48 | 0.67619 |
f78dbaf781d8d0a7b4d385af6e957f60ec13b231 | 171 | ex | Elixir | apps/panacea_beacon/lib/panacea_beacon_web/router.ex | timjp87/panacea | 5edddfa12a8f18b040248b9b186479b9ec8aed51 | [
"MIT"
] | null | null | null | apps/panacea_beacon/lib/panacea_beacon_web/router.ex | timjp87/panacea | 5edddfa12a8f18b040248b9b186479b9ec8aed51 | [
"MIT"
] | null | null | null | apps/panacea_beacon/lib/panacea_beacon_web/router.ex | timjp87/panacea | 5edddfa12a8f18b040248b9b186479b9ec8aed51 | [
"MIT"
] | null | null | null | defmodule BeaconWeb.Router do
use BeaconWeb, :router
pipeline :api do
plug :accepts, ["json"]
end
scope "/api", BeaconWeb do
pipe_through :api
end
end
| 14.25 | 29 | 0.672515 |
f78dd339121739cc416a32669798290328564065 | 1,714 | exs | Elixir | test/cforum/jobs/archiver_job_test.exs | jrieger/cforum_ex | 61f6ce84708cb55bd0feedf69853dae64146a7a0 | [
"MIT"
] | 16 | 2019-04-04T06:33:33.000Z | 2021-08-16T19:34:31.000Z | test/cforum/jobs/archiver_job_test.exs | jrieger/cforum_ex | 61f6ce84708cb55bd0feedf69853dae64146a7a0 | [
"MIT"
] | 294 | 2019-02-10T11:10:27.000Z | 2022-03-30T04:52:53.000Z | test/cforum/jobs/archiver_job_test.exs | jrieger/cforum_ex | 61f6ce84708cb55bd0feedf69853dae64146a7a0 | [
"MIT"
] | 10 | 2019-02-10T10:39:24.000Z | 2021-07-06T11:46:05.000Z | defmodule Cforum.Jobs.ArchiverJobTest do
use Cforum.DataCase
alias Cforum.Threads
alias Cforum.Jobs.ArchiverJob
setup do
forum = insert(:forum)
thread = insert(:thread, forum: forum)
message = insert(:message, thread: thread, forum: forum)
{:ok, message: message, thread: thread, forum: forum}
end
test "archive/0 archives a thread because it has to many messages", %{thread: thread, forum: forum} do
insert(:setting, options: %{"max_messages_per_thread" => 1})
insert(:message, thread: thread, forum: forum)
ArchiverJob.new(%{}) |> Oban.insert!()
assert %{success: 1, failure: 0} == Oban.drain_queue(queue: :background)
thread = Threads.get_thread!(thread.thread_id)
assert thread.archived == true
end
test "archive/0 archives a thread because there are to many threads", %{forum: forum, thread: old_thread} do
insert(:setting, options: %{"max_threads" => 1})
thread = insert(:thread, forum: forum)
insert(:message, thread: thread, forum: forum)
ArchiverJob.new(%{}) |> Oban.insert!()
assert %{success: 1, failure: 0} == Oban.drain_queue(queue: :background)
thread = Threads.get_thread!(old_thread.thread_id)
assert thread.archived == true
end
test "archive/0 deletes a thread set to no-archive", %{thread: thread, forum: forum} do
insert(:setting, options: %{"max_messages_per_thread" => 1})
insert(:message, thread: thread, forum: forum)
Threads.flag_thread_no_archive(nil, thread)
ArchiverJob.new(%{}) |> Oban.insert!()
assert %{success: 1, failure: 0} == Oban.drain_queue(queue: :background)
assert_raise Ecto.NoResultsError, fn -> Threads.get_thread!(thread.thread_id) end
end
end
| 34.28 | 110 | 0.689032 |
f78de0f5648531f4f266d72de59b084f3e402ee3 | 589 | ex | Elixir | lib/staff_notes_web/controllers/member_controller.ex | lee-dohm/staff-notes | 07186e8407f1955876fa2dee2dbbfd0bbac91333 | [
"MIT"
] | 1 | 2020-01-26T18:08:40.000Z | 2020-01-26T18:08:40.000Z | lib/staff_notes_web/controllers/member_controller.ex | lee-dohm/staff-notes | 07186e8407f1955876fa2dee2dbbfd0bbac91333 | [
"MIT"
] | 36 | 2017-12-23T20:22:07.000Z | 2018-05-10T09:16:59.000Z | lib/staff_notes_web/controllers/member_controller.ex | lee-dohm/staff-notes | 07186e8407f1955876fa2dee2dbbfd0bbac91333 | [
"MIT"
] | null | null | null | defmodule StaffNotesWeb.MemberController do
@moduledoc """
Handles requests for `StaffNotes.Notes.Member` records.
"""
use StaffNotesWeb, :controller
alias StaffNotes.Accounts
alias StaffNotes.Notes
alias StaffNotes.Repo
def index(conn, %{"organization_name" => name}) do
org = Accounts.get_org!(name, with: [members: [:organization]])
render(conn, "index.html", org: org)
end
def show(conn, %{"id" => id}) do
member =
id
|> Notes.get_member!()
|> Repo.preload([:organization])
render(conn, "show.html", member: member)
end
end
| 22.653846 | 67 | 0.662139 |
f78df09cea2706278b0012b6b7d50060159f4366 | 824 | exs | Elixir | apps/ewallet_db/priv/repo/migrations/20180629050719_add_failure_reason_to_consumption.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 322 | 2018-02-28T07:38:44.000Z | 2020-05-27T23:09:55.000Z | apps/ewallet_db/priv/repo/migrations/20180629050719_add_failure_reason_to_consumption.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 643 | 2018-02-28T12:05:20.000Z | 2020-05-22T08:34:38.000Z | apps/ewallet_db/priv/repo/migrations/20180629050719_add_failure_reason_to_consumption.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 63 | 2018-02-28T10:57:06.000Z | 2020-05-27T23:10:38.000Z | # Copyright 2018-2019 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule EWalletDB.Repo.Migrations.AddFailureReasonToConsumption do
use Ecto.Migration
def change do
alter table(:transaction_consumption) do
add :error_code, :string
add :error_description, :string
end
end
end
| 32.96 | 74 | 0.758495 |
f78df8ecc6582ed05f3117ff6954077b3837d470 | 394 | exs | Elixir | server/cardinal/priv/repo/migrations/20210315223123_create_user_table.exs | llucasreis/cardinal | 714d89d37ef0fa305d78622ff7228864bf382035 | [
"MIT"
] | null | null | null | server/cardinal/priv/repo/migrations/20210315223123_create_user_table.exs | llucasreis/cardinal | 714d89d37ef0fa305d78622ff7228864bf382035 | [
"MIT"
] | null | null | null | server/cardinal/priv/repo/migrations/20210315223123_create_user_table.exs | llucasreis/cardinal | 714d89d37ef0fa305d78622ff7228864bf382035 | [
"MIT"
] | null | null | null | defmodule Cardinal.Repo.Migrations.CreateUserTable do
use Ecto.Migration
def change do
create table(:users, primary_key: false) do
add :id, :uuid, primary_key: true
add :username, :string
add :email, :string
add :password_hash, :string
timestamps()
end
create unique_index(:users, [:username])
create unique_index(:users, [:email])
end
end
| 23.176471 | 53 | 0.670051 |
f78e032ae08f486c0f8d6d693b83582f7de49e1a | 1,222 | ex | Elixir | src/auth_service/lib/auth_service_web/views/error_helpers.ex | wbpascal/statuswebsite | 7a81e530a9176c53abeab0582cb710113101b716 | [
"MIT"
] | 1 | 2021-04-18T20:21:03.000Z | 2021-04-18T20:21:03.000Z | src/auth_service/lib/auth_service_web/views/error_helpers.ex | wbpascal/statuswebsite | 7a81e530a9176c53abeab0582cb710113101b716 | [
"MIT"
] | null | null | null | src/auth_service/lib/auth_service_web/views/error_helpers.ex | wbpascal/statuswebsite | 7a81e530a9176c53abeab0582cb710113101b716 | [
"MIT"
] | 1 | 2021-04-18T20:21:08.000Z | 2021-04-18T20:21:08.000Z | defmodule AuthServiceWeb.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# When using gettext, we typically pass the strings we want
# to translate as a static argument:
#
# # Translate "is invalid" in the "errors" domain
# dgettext("errors", "is invalid")
#
# # Translate the number of files with plural rules
# dngettext("errors", "1 file", "%{count} files", count)
#
# Because the error messages we show in our forms and APIs
# are defined inside Ecto, we need to translate them dynamically.
# This requires us to call the Gettext module passing our gettext
# backend as first argument.
#
# Note we use the "errors" domain, which means translations
# should be written to the errors.po file. The :count option is
# set by Ecto and indicates we should also apply plural rules.
if count = opts[:count] do
Gettext.dngettext(AuthServiceWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(AuthServiceWeb.Gettext, "errors", msg, opts)
end
end
end
| 35.941176 | 80 | 0.674304 |
f78e140ab7da5dbee17ea67f3086995b380a32e6 | 3,788 | ex | Elixir | lib/koans/13_functions.ex | mingyar/elixir-koans | d9e05081f862a351323bf5a02fff574164bef889 | [
"MIT"
] | null | null | null | lib/koans/13_functions.ex | mingyar/elixir-koans | d9e05081f862a351323bf5a02fff574164bef889 | [
"MIT"
] | null | null | null | lib/koans/13_functions.ex | mingyar/elixir-koans | d9e05081f862a351323bf5a02fff574164bef889 | [
"MIT"
] | null | null | null | defmodule Functions do
use Koans
@intro "Functions"
def greet(name) do
"Hello, #{name}!"
end
koan "Functions map arguments to outputs" do
assert greet("World") == "Hello, World!"
end
def multiply(a, b), do: a * b
koan "Single line functions are cool, but mind the comma and the colon!" do
assert 6 == multiply(2, 3)
end
def first(foo, bar), do: "#{foo} and #{bar}"
def first(foo), do: "Only #{foo}"
koan "Functions with the same name are distinguished by the number of arguments they take" do
assert first("One", "Two") == "One and Two"
assert first("One") == "Only One"
end
def repeat_again(message, times \\ 5) do
String.duplicate(message, times)
end
koan "Functions can have default argument values" do
assert repeat_again("Hello ") == "Hello Hello Hello Hello Hello "
assert repeat_again("Hello ", 2) == "Hello Hello "
end
def sum_up(thing) when is_list(thing), do: :entire_list
def sum_up(_thing), do: :single_thing
koan "Functions can have guard expressions" do
assert sum_up([1, 2, 3]) == :entire_list
assert sum_up(1) == :single_thing
end
def bigger(a, b) when a > b, do: "#{a} is bigger than #{b}"
def bigger(a, b) when a <= b, do: "#{a} is not bigger than #{b}"
koan "Intricate guards are possible, but be mindful of the reader" do
assert bigger(10, 5) == "10 is bigger than 5"
assert bigger(4, 27) == "4 is not bigger than 27"
end
def get_number(0), do: "The number was zero"
def get_number(number), do: "The number was #{number}"
koan "For simpler cases, pattern matching is effective" do
assert get_number(0) == "The number was zero"
assert get_number(5) == "The number was 5"
end
koan "Little anonymous functions are common, and called with a dot" do
multiply = fn a, b -> a * b end
assert multiply.(2, 3) == 6
end
koan "You can even go shorter, by using capture syntax `&()` and positional arguments" do
multiply = &(&1 * &2)
assert multiply.(2, 3) == 6
end
koan "Prefix a string with & to build a simple anonymous greet function" do
greet = &"Hi, #{&1}!"
assert greet.("Foo") == "Hi, Foo!"
end
koan "You can build anonymous functions out of any elixir expression by prefixing it with &" do
three_times = &[&1, &1, &1]
assert three_times.("foo") == ["foo", "foo", "foo"]
end
koan "You can use pattern matching to define multiple cases for anonymous functions" do
inspirational_quote = fn
{:ok, result} -> "Success is #{result}"
{:error, reason} -> "You just lost #{reason}"
end
assert inspirational_quote.({:ok, "no accident"}) == "Success is no accident"
assert inspirational_quote.({:error, "the game"}) == "You just lost the game"
end
def times_five_and_then(number, fun), do: fun.(number * 5)
def square(number), do: number * number
koan "You can pass functions around as arguments. Place an '&' before the name and state the arity" do
assert times_five_and_then(3, &square/1) == 225
end
koan "The '&' operation is not needed for anonymous functions" do
cube = fn number -> number * number * number end
assert times_five_and_then(2, cube) == 1000
end
koan "The result of a function can be piped into another function as its first argument" do
result =
"full-name"
|> String.split("-")
|> Enum.map(&String.capitalize/1)
|> Enum.join(" ")
assert result == "Full Name"
end
koan "Conveniently keyword lists can be used for function options" do
transform = fn str, opts ->
if opts[:upcase] do
String.upcase(str)
else
str
end
end
assert transform.("good", upcase: true) == "GOOD"
assert transform.("good", upcase: false) == "good"
end
end
| 30.063492 | 104 | 0.643875 |
f78e3d7efb352acd2eb5ff176267f7efb6ae4b93 | 778 | ex | Elixir | lib/test/gear_log_helper.ex | sylph01/antikythera | 47a93f3d4c70975f7296725c9bde2ea823867436 | [
"Apache-2.0"
] | 144 | 2018-04-27T07:24:49.000Z | 2022-03-15T05:19:37.000Z | lib/test/gear_log_helper.ex | sylph01/antikythera | 47a93f3d4c70975f7296725c9bde2ea823867436 | [
"Apache-2.0"
] | 123 | 2018-05-01T02:54:43.000Z | 2022-01-28T01:30:52.000Z | lib/test/gear_log_helper.ex | sylph01/antikythera | 47a93f3d4c70975f7296725c9bde2ea823867436 | [
"Apache-2.0"
] | 14 | 2018-05-01T02:30:47.000Z | 2022-02-21T04:38:56.000Z | # Copyright(c) 2015-2021 ACCESS CO., LTD. All rights reserved.
use Croma
defmodule Antikythera.Test.GearLogHelper do
@moduledoc """
Helpers to work with gear logs within tests.
"""
alias Antikythera.{Context, Conn}
alias Antikythera.Test.ConnHelper
alias AntikytheraCore.GearLog.ContextHelper
@doc """
Sets a context ID (which is included in gear logs) to process dictionary so that logs can be emitted during test executions.
If no argument is given, generates a new context ID and sets it.
"""
defun set_context_id(conn_or_context_or_nil :: nil | Context.t() | Conn.t() \\ nil) :: :ok do
nil -> set_context_id(ConnHelper.make_conn())
%Context{} = context -> ContextHelper.set(context)
%Conn{} = conn -> ContextHelper.set(conn)
end
end
| 31.12 | 126 | 0.718509 |
f78e4eeabdce659648e755b3c4845279603cddd2 | 1,563 | exs | Elixir | 1_lists/15_replicate.exs | leesharma/99_elixir_problems | 6f284d94e07c24a73b06d0c36ba88c73e74cb841 | [
"MIT"
] | null | null | null | 1_lists/15_replicate.exs | leesharma/99_elixir_problems | 6f284d94e07c24a73b06d0c36ba88c73e74cb841 | [
"MIT"
] | null | null | null | 1_lists/15_replicate.exs | leesharma/99_elixir_problems | 6f284d94e07c24a73b06d0c36ba88c73e74cb841 | [
"MIT"
] | null | null | null | ExUnit.start
defmodule Problem15Test do
use ExUnit.Case, async: true
test "replicate basic list" do
assert [1, 1, 1, 2, 2, 2, 2, 2, 2] == Problem15.replicate([1, 2, 2], 3)
end
test "replicate char list" do
assert 'aaabbbccccccddd' == Problem15.replicate 'abccd', 3
end
test "very long list" do
# Use List.replicate/2 for testing long lists
list = [1 | List.duplicate(0, 500_000)]
assert [1, 1 | List.duplicate(0, 1_000_000)] ==
Problem15.replicate(list, 2)
end
test "many replications" do
assert List.duplicate(0, 1_000_000) ==
Problem15.replicate([0], 1_000_000)
end
test "an empty list returns itself" do
assert [] == Problem15.replicate([], 5)
end
test "replicating 0 times returns an empty list" do
assert [] == Problem15.replicate([1, 2, 3], 0)
end
end
defmodule Problem15 do
@moduledoc false
@vsn 0.1
@doc """
(**) Replicate the elements of a list a given number of times.
This is part of Ninety-Nine Haskell Problems, based on Ninety-Nine Prolog
Problems and Ninety-Nine Lisp Problems.
"""
@spec replicate([elem], number) :: [elem] when elem: var
def replicate(list, times) when times >= 0 do
do_replicate([], list, times, times)
end
defp do_replicate(result, [], _, _), do: Enum.reverse(result)
defp do_replicate(acc, [_ | tail], times, 0) do
acc
|> do_replicate(tail, times, times)
end
defp do_replicate(acc, [head | _] = list, times, current_count) do
[head | acc]
|> do_replicate(list, times, current_count - 1)
end
end
| 25.622951 | 75 | 0.65771 |
f78e8b476e27498e4ddb82bde51853ae6ed7ba7c | 589 | ex | Elixir | lib/controller/controller_supervisor.ex | derekchiang/Elixir-MapReduce | 87e3b5f2caba2b8f5050ace818e5061278fb49da | [
"WTFPL"
] | 6 | 2015-06-24T20:09:08.000Z | 2019-12-04T21:29:47.000Z | lib/controller/controller_supervisor.ex | derekchiang/Elixir-MapReduce | 87e3b5f2caba2b8f5050ace818e5061278fb49da | [
"WTFPL"
] | null | null | null | lib/controller/controller_supervisor.ex | derekchiang/Elixir-MapReduce | 87e3b5f2caba2b8f5050ace818e5061278fb49da | [
"WTFPL"
] | null | null | null | defmodule Controller.Supervisor do
use Supervisor.Behaviour
def start_link(args) do
:supervisor.start_link(__MODULE__, args)
end
def init([]) do
children = [
# Define workers and child supervisors to be supervised
# worker(MapReduce.Worker, [])
]
# See http://elixir-lang.org/docs/stable/Supervisor.Behaviour.html
# for other strategies and supported options
supervise(children, strategy: :one_for_one)
end
def init([path]) do
children = [ worker(Controller.Server, [path]) ]
supervise children, strategy: :one_for_one
end
end
| 24.541667 | 70 | 0.697793 |
f78e8c7c617bf211b73422706a15a58ca457eca6 | 507 | ex | Elixir | test/support/data_case.ex | straw-hat-team/straw_hat_review | 342dbbfac0ac96287111babd59b5321efdd8728d | [
"MIT"
] | 11 | 2018-04-09T06:32:02.000Z | 2019-09-11T14:18:21.000Z | test/support/data_case.ex | straw-hat-labs/straw_hat_review | 342dbbfac0ac96287111babd59b5321efdd8728d | [
"MIT"
] | 64 | 2018-03-30T06:21:49.000Z | 2019-11-01T13:57:34.000Z | test/support/data_case.ex | straw-hat-labs/straw_hat_review | 342dbbfac0ac96287111babd59b5321efdd8728d | [
"MIT"
] | 1 | 2018-06-21T23:00:00.000Z | 2018-06-21T23:00:00.000Z | defmodule StrawHat.Review.Test.DataCase do
@moduledoc false
use ExUnit.CaseTemplate
using do
quote do
import Ecto
import Ecto.Query
import StrawHat.Review.Test.DataCase
import StrawHat.Review.Test.Factory
alias StrawHat.Review.Repo
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(StrawHat.Review.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(StrawHat.Review.Repo, {:shared, self()})
end
:ok
end
end
| 18.107143 | 77 | 0.682446 |
f78ea204e47a9561e517715b177c317b8fba1ec7 | 54 | exs | Elixir | test/ex_permissions_test.exs | mtwilliams/ex_permissions | 1842f27f41b5d404d2e2409ad3c421de08970843 | [
"Unlicense"
] | null | null | null | test/ex_permissions_test.exs | mtwilliams/ex_permissions | 1842f27f41b5d404d2e2409ad3c421de08970843 | [
"Unlicense"
] | 3 | 2015-05-03T05:15:56.000Z | 2015-05-03T05:20:02.000Z | test/ex_permissions_test.exs | mtwilliams/ex_permissions | 1842f27f41b5d404d2e2409ad3c421de08970843 | [
"Unlicense"
] | null | null | null | defmodule ExPermissions.Test do
use ExUnit.Case
end
| 13.5 | 31 | 0.814815 |
f78ed11012a3d94b9ddd113ad33e0ef5e99f6f86 | 1,133 | exs | Elixir | strain/strain.exs | RamanBut-Husaim/exercism.elixir | 683bb3b5700945dbbebcedf26d37208d4201ef49 | [
"MIT"
] | null | null | null | strain/strain.exs | RamanBut-Husaim/exercism.elixir | 683bb3b5700945dbbebcedf26d37208d4201ef49 | [
"MIT"
] | null | null | null | strain/strain.exs | RamanBut-Husaim/exercism.elixir | 683bb3b5700945dbbebcedf26d37208d4201ef49 | [
"MIT"
] | null | null | null | defmodule Strain do
@doc """
Given a `list` of items and a function `fun`, return the list of items where
`fun` returns true.
Do not use `Enum.filter`.
"""
@spec keep(list :: list(any), fun :: ((any) -> boolean)) :: list(any)
def keep(list, fun) do
keep([], list, fun)
end
defp keep(accum, [], _fun) do
Enum.reverse(accum)
end
defp keep(accum, [head | tail], fun) do
applyResult = Kernel.apply(fun, [head])
case applyResult do
true -> keep([head | accum], tail, fun)
_ -> keep(accum, tail, fun)
end
end
@doc """
Given a `list` of items and a function `fun`, return the list of items where
`fun` returns false.
Do not use `Enum.reject`.
"""
@spec discard(list :: list(any), fun :: ((any) -> boolean)) :: list(any)
def discard(list, fun) do
discard([], list, fun)
end
defp discard(accum, [], _fun) do
Enum.reverse(accum)
end
defp discard(accum, [head | tail], fun) do
applyResult = Kernel.apply(fun, [head])
case applyResult do
true -> discard(accum, tail, fun)
_ -> discard([head | accum], tail, fun)
end
end
end
| 22.66 | 78 | 0.598411 |
f78f3086cb81e998a37cd3b780ed1f31a663e272 | 814 | exs | Elixir | year_2019/test/day_11/robot_test.exs | bschmeck/advent_of_code | cbec98019c6c00444e0f4c7e15e01b1ed9ae6145 | [
"MIT"
] | null | null | null | year_2019/test/day_11/robot_test.exs | bschmeck/advent_of_code | cbec98019c6c00444e0f4c7e15e01b1ed9ae6145 | [
"MIT"
] | null | null | null | year_2019/test/day_11/robot_test.exs | bschmeck/advent_of_code | cbec98019c6c00444e0f4c7e15e01b1ed9ae6145 | [
"MIT"
] | null | null | null | defmodule Day11.RobotTest do
use ExUnit.Case
test "it moves left" do
robot = %Day11.Robot{}
robot = Day11.Robot.move(robot, :left)
assert robot.location == {-1, 0}
robot = Day11.Robot.move(robot, :left)
assert robot.location == {-1, -1}
robot = Day11.Robot.move(robot, :left)
assert robot.location == {0, -1}
robot = Day11.Robot.move(robot, :left)
assert robot.location == {0, 0}
end
test "it moves right" do
robot = %Day11.Robot{}
robot = Day11.Robot.move(robot, :right)
assert robot.location == {1, 0}
robot = Day11.Robot.move(robot, :right)
assert robot.location == {1, -1}
robot = Day11.Robot.move(robot, :right)
assert robot.location == {0, -1}
robot = Day11.Robot.move(robot, :right)
assert robot.location == {0, 0}
end
end
| 29.071429 | 43 | 0.624079 |
f78f336237cff84608b5c8d4fb03661a90de8a70 | 1,125 | ex | Elixir | exex_producer/lib/exex_producer/worker.ex | StephenWeber/elixir-kafka-example | 963698b451b01eb0f5c2415d79a87c53950e38f9 | [
"MIT"
] | null | null | null | exex_producer/lib/exex_producer/worker.ex | StephenWeber/elixir-kafka-example | 963698b451b01eb0f5c2415d79a87c53950e38f9 | [
"MIT"
] | null | null | null | exex_producer/lib/exex_producer/worker.ex | StephenWeber/elixir-kafka-example | 963698b451b01eb0f5c2415d79a87c53950e38f9 | [
"MIT"
] | null | null | null | defmodule ExexProducer.Worker do
use GenServer
def start_link(args) do
GenServer.start_link(__MODULE__, args, name: __MODULE__)
end
def init(state) do
schedule_stock_fetch()
{:ok, state}
end
def handle_info(:stock_fetch, state) do
info = stock_info("FB")
bid = info["bid"]
ask = info["ask"]
rmp = info["regularMarketPrice"]
spread = abs(ask - bid)
IO.inspect("Current value FB: $#{rmp} spread $#{spread} -- $#{ask} $#{bid}")
schedule_stock_fetch()
produce_data(rmp, spread)
s = Map.put(state, :spread, spread)
{:noreply, s}
end
defp stock_info(symbol) do
YahooFinance.custom_quote(symbol, [:regularMarketPrice, :bid, :ask])
|> elem(1)
|> elem(1)
|> Jason.decode!()
|> Map.get("quoteResponse")
|> Map.get("result")
|> hd
end
def schedule_stock_fetch do
Process.send_after(self(), :stock_fetch, 5_000)
end
defp produce_data(price, spread) do
price_s = Float.to_string(price)
Kaffe.Producer.produce_sync("price", "price", price_s)
#Kaffe.Producer.produce_sync("spread", [{"spread", spread}])
end
end
| 24.456522 | 80 | 0.645333 |
f78f3dcdf3c66e6a059fa52df1f4a81fb08393cd | 669 | ex | Elixir | lib/swagger/client/connection.ex | CordBoard/ostip-exari | a7a40e438c9a2ab358c28c164cec445a0345d15e | [
"Apache-2.0"
] | null | null | null | lib/swagger/client/connection.ex | CordBoard/ostip-exari | a7a40e438c9a2ab358c28c164cec445a0345d15e | [
"Apache-2.0"
] | null | null | null | lib/swagger/client/connection.ex | CordBoard/ostip-exari | a7a40e438c9a2ab358c28c164cec445a0345d15e | [
"Apache-2.0"
] | 1 | 2018-10-27T07:10:02.000Z | 2018-10-27T07:10:02.000Z | # 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 Swagger.Client.Connection do
@moduledoc """
Handle Tesla connections for Swagger.Client.
"""
use Tesla
# Add any middleware here (authentication)
plug Tesla.Middleware.BaseUrl, "http://192.168.64.2:8088/ari"
plug Tesla.Middleware.Headers, %{"User-Agent" => "Elixir"}
plug Tesla.Middleware.EncodeJson
@doc """
Configure an authless client connection
# Returns
Tesla.Env.client
"""
@spec new() :: Tesla.Env.client
def new do
Tesla.build_client([])
end
end
| 23.068966 | 75 | 0.71151 |
f78f6aece89065cd3d98a8d065ad649e2c4f3c78 | 291 | exs | Elixir | priv/repo/migrations/20160821032913_students.exs | Calvyn82/grades | 4f8f43283cf9380dc48a4bc999dd46c66a1ad7ee | [
"MIT"
] | null | null | null | priv/repo/migrations/20160821032913_students.exs | Calvyn82/grades | 4f8f43283cf9380dc48a4bc999dd46c66a1ad7ee | [
"MIT"
] | null | null | null | priv/repo/migrations/20160821032913_students.exs | Calvyn82/grades | 4f8f43283cf9380dc48a4bc999dd46c66a1ad7ee | [
"MIT"
] | null | null | null | defmodule Grades.Repo.Migrations.Students do
use Ecto.Migration
def change do
create table(:students) do
add :first_name, :string
add :student_id, :integer, unique: true
add :hour, :integer
add :grade, :integer
timestamps
end
end
end
| 19.4 | 45 | 0.632302 |