hexsha stringlengths 40 40 | size int64 2 991k | ext stringclasses 2 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 208 | max_stars_repo_name stringlengths 6 106 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses list | max_stars_count int64 1 33.5k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 208 | max_issues_repo_name stringlengths 6 106 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses list | max_issues_count int64 1 16.3k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 208 | max_forks_repo_name stringlengths 6 106 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses list | max_forks_count int64 1 6.91k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 991k | avg_line_length float64 1 36k | max_line_length int64 1 977k | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
03f1f8d07c0fedfb851feed60cb5a9658f4a8811 | 1,577 | ex | Elixir | lib/arango_phx_web.ex | SquashConsulting/ArangoPhx | 4b7e55710e9f7e6afbcae07e96e1de9c46b7c935 | [
"BSD-3-Clause"
] | 5 | 2020-01-30T07:11:33.000Z | 2021-05-07T12:52:41.000Z | lib/arango_phx_web.ex | rasjonell/ArangoPhx | 4b7e55710e9f7e6afbcae07e96e1de9c46b7c935 | [
"BSD-3-Clause"
] | 5 | 2019-12-04T12:41:50.000Z | 2019-12-05T13:21:50.000Z | lib/arango_phx_web.ex | SquashConsulting/ArangoPhx | 4b7e55710e9f7e6afbcae07e96e1de9c46b7c935 | [
"BSD-3-Clause"
] | null | null | null | defmodule ArangoPhxWeb do
@moduledoc """
The entrypoint for defining your web interface, such
as controllers, views, channels and so on.
This can be used in your application as:
use ArangoPhxWeb, :controller
use ArangoPhxWeb, :view
The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below. Instead, define any helper function in modules
and import those modules here.
"""
def controller do
quote do
use Phoenix.Controller, namespace: ArangoPhxWeb
import Plug.Conn
import ArangoPhxWeb.Gettext
alias ArangoPhxWeb.Router.Helpers, as: Routes
end
end
def view do
quote do
use Phoenix.View,
root: "lib/arango_phx_web/templates",
namespace: ArangoPhxWeb
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1]
import ArangoPhxWeb.ErrorHelpers
import ArangoPhxWeb.Gettext
alias ArangoPhxWeb.Router.Helpers, as: Routes
end
end
def router do
quote do
use Phoenix.Router
import Plug.Conn
import Phoenix.Controller
end
end
def channel do
quote do
use Phoenix.Channel
import ArangoPhxWeb.Gettext
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
| 23.537313 | 83 | 0.696893 |
03f21902013c5371c3762c99f39392093150438f | 676 | ex | Elixir | lib/docusign/model/permission_profile_information.ex | gaslight/docusign_elixir | d9d88d53dd85d32a39d537bade9db28d779414e6 | [
"MIT"
] | 4 | 2020-12-21T12:50:13.000Z | 2022-01-12T16:50:43.000Z | lib/docusign/model/permission_profile_information.ex | gaslight/docusign_elixir | d9d88d53dd85d32a39d537bade9db28d779414e6 | [
"MIT"
] | 12 | 2018-09-18T15:26:34.000Z | 2019-09-28T15:29:39.000Z | lib/docusign/model/permission_profile_information.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.PermissionProfileInformation do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:permissionProfiles
]
@type t :: %__MODULE__{
:permissionProfiles => [AccountPermissionProfiles]
}
end
defimpl Poison.Decoder, for: DocuSign.Model.PermissionProfileInformation do
import DocuSign.Deserializer
def decode(value, options) do
value
|> deserialize(:permissionProfiles, :list, DocuSign.Model.AccountPermissionProfiles, options)
end
end
| 24.142857 | 97 | 0.736686 |
03f22aa09ff105add4cd8fe0de6da4cd2eb7f4ed | 1,429 | ex | Elixir | test/support/data_case.ex | oryono/banking | 0a49ebae5ebf93a6db0c24476a1c86c60bb72733 | [
"MIT"
] | null | null | null | test/support/data_case.ex | oryono/banking | 0a49ebae5ebf93a6db0c24476a1c86c60bb72733 | [
"MIT"
] | null | null | null | test/support/data_case.ex | oryono/banking | 0a49ebae5ebf93a6db0c24476a1c86c60bb72733 | [
"MIT"
] | null | null | null | defmodule BankingGraph.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 BankingGraph.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import BankingGraph.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(BankingGraph.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(BankingGraph.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
| 26.462963 | 77 | 0.685094 |
03f22d88b1f94eb0e1150765a039d83795580e73 | 1,797 | ex | Elixir | lib/absinthe/subscription/local.ex | dmarkow/absinthe | 707690bf06189b3a4b13959908a2eb52a3951179 | [
"MIT"
] | null | null | null | lib/absinthe/subscription/local.ex | dmarkow/absinthe | 707690bf06189b3a4b13959908a2eb52a3951179 | [
"MIT"
] | null | null | null | lib/absinthe/subscription/local.ex | dmarkow/absinthe | 707690bf06189b3a4b13959908a2eb52a3951179 | [
"MIT"
] | null | null | null | defmodule Absinthe.Subscription.Local do
@moduledoc false
require Logger
alias Absinthe.Pipeline.BatchResolver
# This module handles running and broadcasting documents that are local to this
# node.
def publish_mutation(pubsub, mutation_result, subscribed_fields) do
docs_and_topics =
for {field, key_strategy} <- subscribed_fields,
{topic, doc} <- get_docs(pubsub, field, mutation_result, key_strategy) do
{{topic, {field, key_strategy}}, put_in(doc.execution.root_value, mutation_result)}
end
if Enum.any?(docs_and_topics) do
{topics, docs} = Enum.unzip(docs_and_topics)
docs = BatchResolver.run(docs, schema: hd(docs).schema, abort_on_error: false)
pipeline = [
Absinthe.Phase.Document.Result
]
for {doc, {topic, key_strategy}} <- Enum.zip(docs, topics), doc != :error do
try do
{:ok, %{result: data}, _} = Absinthe.Pipeline.run(doc, pipeline)
Logger.debug("""
Absinthe Subscription Publication
Field Topic: #{inspect(key_strategy)}
Subscription id: #{inspect(topic)}
Data: #{inspect(data)}
""")
:ok = pubsub.publish_subscription(topic, data)
rescue
e ->
BatchResolver.pipeline_error(e)
end
end
end
end
defp get_docs(pubsub, field, mutation_result, topic: topic_fun)
when is_function(topic_fun, 1) do
do_get_docs(pubsub, field, topic_fun.(mutation_result))
end
defp get_docs(pubsub, field, _mutation_result, key) do
do_get_docs(pubsub, field, key)
end
defp do_get_docs(pubsub, field, keys) do
keys
|> List.wrap()
|> Enum.map(&to_string/1)
|> Enum.flat_map(&Absinthe.Subscription.get(pubsub, {field, &1}))
end
end
| 28.983871 | 91 | 0.648859 |
03f231c068c40455ecec6b8c78c27106a6af7164 | 66 | exs | Elixir | test/data_storage/data_storage_test.exs | nkyian/auctoritas | 24480b8d38fccdbadf588b110cdee061b6286f0c | [
"MIT"
] | 1 | 2019-01-18T10:37:40.000Z | 2019-01-18T10:37:40.000Z | test/data_storage/data_storage_test.exs | nkyian/auctoritas | 24480b8d38fccdbadf588b110cdee061b6286f0c | [
"MIT"
] | 6 | 2019-04-20T18:32:37.000Z | 2019-04-20T19:41:29.000Z | test/data_storage/data_storage_test.exs | nkyian/auctoritas | 24480b8d38fccdbadf588b110cdee061b6286f0c | [
"MIT"
] | null | null | null | defmodule AuctoritasTest.DataStorageTest do
use ExUnit.Case
end
| 16.5 | 43 | 0.848485 |
03f232ae4a25041290893c0b2507f1f46106a6f7 | 341 | exs | Elixir | app/test/app_web/views/page_view_test.exs | kljensen/yale-class-chat | b03e72deed967249a64404bff68b1cf22e7e1e6a | [
"Unlicense"
] | 1 | 2020-02-10T21:35:17.000Z | 2020-02-10T21:35:17.000Z | app/test/app_web/views/page_view_test.exs | kljensen/yale-class-chat | b03e72deed967249a64404bff68b1cf22e7e1e6a | [
"Unlicense"
] | 86 | 2020-01-24T14:53:27.000Z | 2021-05-18T19:16:30.000Z | app/test/app_web/views/page_view_test.exs | kljensen/yale-class-chat | b03e72deed967249a64404bff68b1cf22e7e1e6a | [
"Unlicense"
] | null | null | null | defmodule AppWeb.PageViewTest do
use AppWeb.ConnCase, async: true
import Phoenix.View
test "renders index.html", %{conn: conn} do
content = render_to_string(
AppWeb.PageView,
"index.html",
conn: conn,
current_user: nil,
is_faculty: false)
assert String.contains?(content, "WELCOME")
end
end
| 18.944444 | 47 | 0.662757 |
03f2633efc09835fead7c4a42c9ec1c159f5b3a5 | 864 | exs | Elixir | backend/test/caffe/accounts/use_cases/authenticate_test.exs | eeng/caffe | d85d0dd56a8204c715052ddaf3d990e47c5df0e9 | [
"MIT"
] | 7 | 2020-03-27T08:26:52.000Z | 2021-08-29T09:50:31.000Z | backend/test/caffe/accounts/use_cases/authenticate_test.exs | eeng/caffe | d85d0dd56a8204c715052ddaf3d990e47c5df0e9 | [
"MIT"
] | null | null | null | backend/test/caffe/accounts/use_cases/authenticate_test.exs | eeng/caffe | d85d0dd56a8204c715052ddaf3d990e47c5df0e9 | [
"MIT"
] | null | null | null | defmodule Caffe.Accounts.UseCases.AuthenticateTest do
use Caffe.UseCaseCase, async: true
alias Caffe.Accounts.UseCases.Authenticate
alias Caffe.Accounts.User
describe "execute" do
setup do
[user: insert!(:user, email: "alice@acme.com", password: "secret123")]
end
test "valid credentials" do
assert {:ok, %User{email: "alice@acme.com"}} = authenticate("alice@acme.com", "secret123")
end
test "invalid credentials" do
assert {:error, :invalid_credentials} = authenticate("alice@acme.com", "Secret123")
assert {:error, :invalid_credentials} = authenticate("bob@acme.com", "secret123")
assert {:error, :invalid_credentials} = authenticate("alice@acme.com", "")
end
def authenticate(email, password) do
%Authenticate{email: email, password: password} |> Mediator.dispatch()
end
end
end
| 33.230769 | 96 | 0.689815 |
03f269369eed7236025ae7cb0289eded01beb694 | 212 | exs | Elixir | apps/core/priv/repo/migrations/20180214161617_add_person_type_to_registers.exs | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 8 | 2019-06-14T11:34:49.000Z | 2021-08-05T19:14:24.000Z | apps/core/priv/repo/migrations/20180214161617_add_person_type_to_registers.exs | edenlabllc/ehealth.api.public | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 1 | 2019-07-08T15:20:22.000Z | 2019-07-08T15:20:22.000Z | apps/core/priv/repo/migrations/20180214161617_add_person_type_to_registers.exs | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 6 | 2018-05-11T13:59:32.000Z | 2022-01-19T20:15:22.000Z | defmodule Core.Repo.Migrations.AddPersonTypeToRegisters do
use Ecto.Migration
def change do
alter table(:registers) do
add(:person_type, :string, null: false, default: "patient")
end
end
end
| 21.2 | 65 | 0.721698 |
03f27401934225d9a0de83dfd3bbcfdf25f5fa3f | 1,058 | ex | Elixir | lib/banking_graph/application.ex | oryono/banking | 0a49ebae5ebf93a6db0c24476a1c86c60bb72733 | [
"MIT"
] | null | null | null | lib/banking_graph/application.ex | oryono/banking | 0a49ebae5ebf93a6db0c24476a1c86c60bb72733 | [
"MIT"
] | null | null | null | lib/banking_graph/application.ex | oryono/banking | 0a49ebae5ebf93a6db0c24476a1c86c60bb72733 | [
"MIT"
] | null | null | null | defmodule BankingGraph.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
BankingGraph.Repo,
# Start the endpoint when the application starts
BankingGraphWeb.Endpoint,
# Starts a worker by calling: BankingGraph.Worker.start_link(arg)
# {BankingGraph.Worker, arg},
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: BankingGraph.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
BankingGraphWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 33.0625 | 77 | 0.660681 |
03f2a99161de4380fc95e7ec303048e518b78315 | 596 | exs | Elixir | priv/repo/migrations/20190405115947_create_authentications.exs | hammoc-app/hammoc-elixir | 00cd24e2170cc3dee65c7848868ea3d1096ac25c | [
"MIT"
] | 5 | 2019-07-13T22:20:50.000Z | 2020-07-13T05:05:43.000Z | priv/repo/migrations/20190405115947_create_authentications.exs | hammoc-app/hammoc-elixir | 00cd24e2170cc3dee65c7848868ea3d1096ac25c | [
"MIT"
] | 33 | 2019-08-01T03:48:23.000Z | 2021-07-28T03:29:40.000Z | priv/repo/migrations/20190405115947_create_authentications.exs | hammoc-app/hammoc-elixir | 00cd24e2170cc3dee65c7848868ea3d1096ac25c | [
"MIT"
] | 2 | 2019-09-03T22:45:11.000Z | 2020-01-01T23:56:58.000Z | defmodule Hammoc.Repo.Migrations.CreateAuthentications do
use Ecto.Migration
def up do
create table(:authentications) do
add :provider, :string
add :uid, :binary
add :uid_hash, :binary
add :access_token, :binary
add :access_token_secret, :binary
add :name, :binary
add :first_name, :binary
add :last_name, :binary
add :nickname, :binary
add :image_url, :binary
timestamps()
end
create index(:authentications, [:provider, :uid_hash], unique: true)
end
def down do
drop table(:authentications)
end
end
| 22.074074 | 72 | 0.654362 |
03f2e9d26b2609a9025a43141ef32eb38b5dc922 | 3,587 | ex | Elixir | web/controllers/session_controller.ex | ClubNix/academy | 962be0defc1d8eedc5d19ac0a65e931c794c6538 | [
"MIT"
] | 3 | 2016-06-18T17:46:14.000Z | 2020-01-21T03:19:41.000Z | web/controllers/session_controller.ex | ClubNix/academy | 962be0defc1d8eedc5d19ac0a65e931c794c6538 | [
"MIT"
] | 18 | 2016-06-18T18:05:43.000Z | 2018-03-06T08:19:41.000Z | web/controllers/session_controller.ex | ClubNix/academy | 962be0defc1d8eedc5d19ac0a65e931c794c6538 | [
"MIT"
] | 3 | 2016-10-26T19:51:06.000Z | 2018-09-18T09:06:14.000Z | defmodule Academy.SessionController do
@moduledoc ~S"""
Module controlling user sessions.
"""
use Academy.Web, :controller
alias Academy.UserController
require Logger
@doc ~S"""
Render the login page if the user is not logged in
"""
def new(conn, _params) do
if logged_in?(conn) do
conn
|> put_flash(:warn, "You already are logged in")
|> redirect(to: user_path(conn, :index))
else
render conn, "login.html"
end
end
@doc ~S"""
Check the credentials and log the given user.
See the `login/1` function and `Academy.Endpoint.LDAP` module.
"""
def create(conn, %{"session" => session_params}) do
if logged_in?(conn) do
conn
|> put_flash(:warn, "You already are logged in")
|> redirect(to: user_path(conn, :index))
else
case login(session_params) do
{:ok, username} ->
handle_login(conn, username)
{:error, reason} ->
handle_error(conn, reason)
end
end
end
@doc ~S"""
Log out the current user
"""
def delete(conn, _) do
if logged_in?(conn) do
conn
|> logout
|> put_flash(:info, "Logged out")
|> redirect(to: user_path(conn, :index))
else
conn
|> put_flash(:error, "You are not logged in")
|> redirect(to: user_path(conn, :index))
end
end
@doc ~S"""
Function called after a successful credentials verification.
Log the user using the `Guardian` module and return it, creating it if it
does not exists. This function also generates an avatar for the newly created
user.
"""
defp handle_login(conn, username) do
user = UserController.get_or_create(username)
conn
|> Guardian.Plug.sign_in(user)
|> put_flash(:info, "You are now logged in as #{String.capitalize user.name}")
|> redirect(to: user_path(conn, :index))
end
@doc ~S"""
Function called on authentication failure.
"""
defp handle_error(conn, error) do
conn = case error do
:missing_field ->
put_flash(conn, :error, "Please ensure all required fields are filled")
:invalid_credentials ->
put_flash(conn, :error, "Wrong username or password")
_ ->
put_flash(conn, :error, "Internal error. Please try again.")
end
render conn, "login.html"
end
@doc ~S"""
Check the given credentials using the `Academy.Endpoint.LDAP` module.
Returns `{:ok, username}` on success and `{:error, error_msg}` on failure.
"""
def login(%{"username" => username, "password" => password}) when username != "" and password != "" do
case Academy.Endpoint.LDAP.check_credentials(username, password) do
:ok ->
Logger.info("User #{username} successfully authenticated to LDAP")
{:ok, username}
{:error, :invalid_credentials} ->
Logger.info("User #{username} failed to authenticate to LDAP: Wrong login/password.")
{:error, :invalid_credentials}
{:error, error_msg} ->
Logger.warn("User #{username} failed to authenticate to LDAP: #{error_msg}")
{:error, error_msg}
end
end
def login(_params), do: {:error, :missing_field}
@doc ~S"""
Log out the given user using the `Guardian` module
"""
def logout(conn) do
Guardian.Plug.sign_out(conn)
end
@doc ~S"""
Return the currently logged user
"""
def current_user(conn) do
Guardian.Plug.current_resource(conn)
end
@doc ~S"""
Return true if a user is logged in for the current connection, false otherwise
"""
def logged_in?(conn) do
!!current_user(conn)
end
end
| 26.969925 | 104 | 0.637023 |
03f33c690d17eded15c2275984a5a22d3f4f31ef | 2,150 | ex | Elixir | clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remoteworkers_v1test2_directory_metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remoteworkers_v1test2_directory_metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remoteworkers_v1test2_directory_metadata.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.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2DirectoryMetadata do
@moduledoc """
The metadata for a directory. Similar to the equivalent message in the Remote Execution API.
## Attributes
* `digest` (*type:* `GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Digest.t`, *default:* `nil`) - A pointer to the contents of the directory, in the form of a marshalled Directory message.
* `path` (*type:* `String.t`, *default:* `nil`) - The path of the directory, as in FileMetadata.path.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:digest =>
GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Digest.t()
| nil,
:path => String.t() | nil
}
field(:digest,
as: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Digest
)
field(:path)
end
defimpl Poison.Decoder,
for: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2DirectoryMetadata do
def decode(value, options) do
GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2DirectoryMetadata.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2DirectoryMetadata do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.833333 | 220 | 0.751628 |
03f34a67de93c6b945efc09157e62fee81430698 | 179 | exs | Elixir | test/modules/handler_missing.exs | kianmeng/unsafe | 76951b0b9e4f8b82e32fbb5a91e67de8963898e8 | [
"MIT"
] | 11 | 2017-11-09T05:58:25.000Z | 2020-01-23T02:12:27.000Z | test/modules/handler_missing.exs | kianmeng/unsafe | 76951b0b9e4f8b82e32fbb5a91e67de8963898e8 | [
"MIT"
] | 3 | 2017-11-09T09:23:41.000Z | 2018-07-30T16:21:48.000Z | test/modules/handler_missing.exs | kianmeng/unsafe | 76951b0b9e4f8b82e32fbb5a91e67de8963898e8 | [
"MIT"
] | 2 | 2018-07-30T02:59:14.000Z | 2021-11-27T13:05:58.000Z | defmodule UnsafeTest.MissingHandle do
use Unsafe.Generator
@unsafe [ { :test, 1 } ]
def test(true),
do: { :ok, true }
def test(false),
do: { :error, false }
end
| 16.272727 | 37 | 0.608939 |
03f34ec75f08af197311081864cc2c5aea68dfd2 | 829 | ex | Elixir | lib/sprint_poker/operations/ticket_operations.ex | elpassion/sprint-poker | 5c9b34bb264c7a30ff48f0aeac40821b67310ff8 | [
"MIT"
] | 199 | 2015-10-22T16:20:09.000Z | 2021-11-08T11:20:45.000Z | lib/sprint_poker/operations/ticket_operations.ex | elpassion/sprint-poker | 5c9b34bb264c7a30ff48f0aeac40821b67310ff8 | [
"MIT"
] | 4 | 2015-10-24T20:43:29.000Z | 2016-03-03T21:09:06.000Z | lib/sprint_poker/operations/ticket_operations.ex | elpassion/sprint-poker | 5c9b34bb264c7a30ff48f0aeac40821b67310ff8 | [
"MIT"
] | 34 | 2015-10-23T06:38:43.000Z | 2019-08-13T23:49:24.000Z | defmodule SprintPoker.TicketOperations do
@moduledoc """
Ticket related operations
"""
alias SprintPoker.Repo
alias SprintPoker.Repo.Ticket
def create(params, game) do
changeset = Ticket.changeset(%Ticket{}, %{
name: params["name"],
game_id: game.id
})
case changeset do
{:error, errors} ->
raise errors
_ ->
changeset |> Repo.insert!
end
end
def delete(params) do
case Repo.get(Ticket, params["id"]) do
nil -> :nothing
ticket -> ticket |> Repo.delete!
end
end
def update(ticket, params) do
changeset = Ticket.changeset(ticket, params)
case changeset do
{:error, errors} ->
raise errors
_ ->
changeset |> Repo.update!
end
end
def get_by_id(id) do
Repo.get!(Ticket, id)
end
end
| 18.840909 | 48 | 0.600724 |
03f37a573bf5bdf23ee0192ba1523a1c6b2712d9 | 1,657 | exs | Elixir | elixir/word-count/word_count_test.exs | tiagoefmoraes/exercism | 9855b4b75a6a3f7cfe13bfb459e04bcb11f3279b | [
"MIT"
] | null | null | null | elixir/word-count/word_count_test.exs | tiagoefmoraes/exercism | 9855b4b75a6a3f7cfe13bfb459e04bcb11f3279b | [
"MIT"
] | null | null | null | elixir/word-count/word_count_test.exs | tiagoefmoraes/exercism | 9855b4b75a6a3f7cfe13bfb459e04bcb11f3279b | [
"MIT"
] | null | null | null | if !System.get_env("EXERCISM_TEST_EXAMPLES") do
Code.load_file("word_count.exs", __DIR__)
end
ExUnit.start
ExUnit.configure exclude: :pending, trace: true
defmodule WordsTest do
use ExUnit.Case
test "count one word" do
assert Words.count("word") == %{ "word" => 1 }
end
# @tag :pending
test "count one of each" do
expected = %{ "one" => 1 , "of" => 1 , "each" => 1 }
assert Words.count("one of each") == expected
end
# @tag :pending
test "count multiple occurrences" do
expected = %{ "one" => 1 , "fish" => 4 , "two" => 1 , "red" => 1 , "blue" => 1 }
assert Words.count("one fish two fish red fish blue fish") == expected
end
# @tag :pending
test "ignore punctuation" do
expected = %{"car" => 1, "carpet" => 1, "as" => 1, "java" => 1, "javascript" => 1}
assert Words.count("car : carpet as java : javascript!!&@$%^&") == expected
end
# @tag :pending
test "include numbers" do
expected = %{"testing" => 2, "1" => 1, "2" => 1}
assert Words.count("testing, 1, 2 testing") == expected
end
# @tag :pending
test "hyphens" do
expected = %{"co-operative" => 1}
assert Words.count("co-operative") == expected
end
# @tag :pending
test "ignore underscores" do
expected = %{"two" => 1, "words" => 1}
assert Words.count("two_words") == expected
end
# @tag :pending
test "normalize case" do
expected = %{"go" => 3}
assert Words.count("go Go GO") == expected
end
# @tag :pending
test "German" do
expected = %{"götterfunken" => 1, "schöner" => 1, "freude" => 1}
assert Words.count("Freude schöner Götterfunken") == expected
end
end
| 26.301587 | 88 | 0.594448 |
03f3b53bc4b39c14aec4d3c4643706a03d6220c1 | 285 | ex | Elixir | lib/portmidi/input.ex | bwanab/ex-portmidi | 9e10a5ff007ebef81c5212dbfb65b4bd90e49daa | [
"MIT"
] | 36 | 2016-03-28T15:01:18.000Z | 2021-09-11T02:41:31.000Z | lib/portmidi/input.ex | bwanab/ex-portmidi | 9e10a5ff007ebef81c5212dbfb65b4bd90e49daa | [
"MIT"
] | 15 | 2016-05-29T13:01:33.000Z | 2021-11-18T18:24:23.000Z | lib/portmidi/input.ex | bwanab/ex-portmidi | 9e10a5ff007ebef81c5212dbfb65b4bd90e49daa | [
"MIT"
] | 11 | 2016-05-19T15:37:49.000Z | 2020-12-13T21:34:07.000Z | defmodule PortMidi.Input do
alias PortMidi.Input.Server
alias PortMidi.Listeners
def start_link(device_name) do
Server.start_link device_name
end
def listen(input, pid) do
Listeners.register(input, pid)
end
def stop(input) do
Server.stop(input)
end
end
| 15.833333 | 34 | 0.729825 |
03f3b97bcccc111d1aee3a61348b4eeaf77e9213 | 9,294 | ex | Elixir | lib/ex_kpl.ex | sneako/ex_kpl | 71e17dd21f3c35e9bae9c05132468278ad327be7 | [
"MIT"
] | 10 | 2018-01-31T15:29:27.000Z | 2020-12-30T20:33:30.000Z | lib/ex_kpl.ex | sneako/ex_kpl | 71e17dd21f3c35e9bae9c05132468278ad327be7 | [
"MIT"
] | null | null | null | lib/ex_kpl.ex | sneako/ex_kpl | 71e17dd21f3c35e9bae9c05132468278ad327be7 | [
"MIT"
] | null | null | null | defmodule ExKpl do
@moduledoc """
Elixir implementation of the Kinesis Producer Library record aggregator.
This is a port of the Erlang implementation included in [adroll/erlmld](https://github.com/AdRoll/erlmld)
## Basic usage:
iex> {_, aggregator} = ExKpl.add(ExKpl.new(), {"partition_key", "data"})
...> ExKpl.finish(aggregator)
{{"partition_key", <<243, 137, 154, 194, 10, 13, 112, 97, 114, 116, 105, 116, 105, 111, 110, 95, 107, 101, 121, 26, 8, 8, 0, 26, 4, 100, 97, 116, 97, 208, 54, 153, 218, 90, 34, 47, 163, 33, 8, 173, 27, 217, 85, 161, 78>>, nil}, %ExKpl{agg_explicit_hash_key: nil, agg_partition_key: nil, agg_size_bytes: 0, explicit_hash_keyset: %ExKpl.Keyset{key_to_index: %{}, rev_keys: []}, num_user_records: 0, partition_keyset: %ExKpl.Keyset{key_to_index: %{}, rev_keys: []}, rev_records: []}}
Typically you will use it like:
case ExKpl.add(aggregator, {partition_key, data}) do
{nil, aggregator} ->
aggregator
{full_record, aggregator} ->
send_record_to_kinesis(full_record)
aggregator
end
You can force the current records to be aggregated with `finish/1,2`
"""
use Bitwise
alias ExKpl.{Proto, Keyset}
require Logger
@type key :: binary() | nil
@type raw_data :: binary()
@type serialized_data :: binary()
@type user_record :: {key(), raw_data(), key()}
@type aggregated_record :: {key(), serialized_data(), key()}
@type new_opts :: [{:max_bytes_per_record, pos_integer()}]
@magic <<243, 137, 154, 194>>
@magic_deflated <<244, 137, 154, 194>>
@max_bytes_per_record bsl(1, 20)
@md5_digest_bytes 16
@empty_record_size %Proto.AggregatedRecord{}
|> Protox.Encode.encode!()
|> IO.iodata_to_binary()
|> byte_size()
defstruct num_user_records: 0,
agg_size_bytes: 0,
agg_partition_key: nil,
agg_explicit_hash_key: nil,
partition_keyset: %Keyset{},
explicit_hash_keyset: %Keyset{},
rev_records: [],
max_bytes_per_record: @max_bytes_per_record
@type t :: %__MODULE__{
num_user_records: non_neg_integer(),
agg_size_bytes: non_neg_integer(),
agg_partition_key: key(),
agg_explicit_hash_key: key(),
partition_keyset: Keyset.t(),
explicit_hash_keyset: Keyset.t(),
rev_records: [binary()],
max_bytes_per_record: pos_integer()
}
@spec new(new_opts()) :: t()
def new(opts \\ []) do
max = Keyword.get(opts, :max_bytes_per_record, @max_bytes_per_record)
%__MODULE__{
max_bytes_per_record: min(max, @max_bytes_per_record)
}
end
@spec count(t()) :: non_neg_integer()
def count(%__MODULE__{num_user_records: count}), do: count
@spec size_bytes(t()) :: non_neg_integer()
def size_bytes(%__MODULE__{agg_size_bytes: size, agg_partition_key: pk}) do
byte_size(@magic) + size + pk_size(pk) + @md5_digest_bytes + @empty_record_size
end
@spec finish(t()) :: {aggregated_record() | nil, t()}
def finish(%__MODULE__{num_user_records: 0} = agg, _), do: {nil, agg}
def finish(
%__MODULE__{agg_partition_key: agg_pk, agg_explicit_hash_key: agg_ehk} = agg,
should_deflate?
) do
agg_record = {agg_pk, serialize_data(agg, should_deflate?), agg_ehk}
{agg_record, new(max_bytes_per_record: agg.max_bytes_per_record)}
end
def finish(agg), do: finish(agg, false)
@spec add(t(), {key(), binary()} | {key(), binary(), key()}) ::
{aggregated_record() | nil, t()}
def add(agg, {partition_key, data}) do
add(agg, {partition_key, data, create_explicit_hash_key(partition_key)})
end
def add(%{max_bytes_per_record: max} = agg, {partition_key, data, explicit_hash_key}) do
case {calc_record_size(agg, partition_key, data, explicit_hash_key), size_bytes(agg)} do
{rec_size, _} when rec_size > max ->
Logger.error(fn -> "input record too large to fit in a single Kinesis record" end)
{nil, agg}
{rec_size, cur_size} when rec_size + cur_size > max ->
{full_record, agg1} = finish(agg)
agg2 = add_record(agg1, partition_key, data, explicit_hash_key, rec_size)
{full_record, agg2}
{rec_size, _} ->
agg1 = add_record(agg, partition_key, data, explicit_hash_key, rec_size)
# FIXME make size calculations more accurate
case size_bytes(agg1) > max - 64 do
true ->
{full_record, agg2} = finish(agg)
agg3 = add_record(agg2, partition_key, data, explicit_hash_key, rec_size)
{full_record, agg3}
false ->
{nil, agg1}
end
end
end
@spec add_all(t(), [user_record()]) :: {[aggregated_record()], t()}
def add_all(agg, records) do
{rev_agg_records, new_agg} =
List.foldl(records, {[], agg}, fn record, {rev_agg_records, agg} ->
case add(agg, record) do
{nil, new_agg} -> {rev_agg_records, new_agg}
{agg_record, new_agg} -> {[agg_record | rev_agg_records], new_agg}
end
end)
{Enum.reverse(rev_agg_records), new_agg}
end
defp add_record(
%__MODULE__{
partition_keyset: pkset,
explicit_hash_keyset: ehkset,
rev_records: rev_records,
num_user_records: num_user_records,
agg_size_bytes: agg_size,
agg_partition_key: agg_pk,
agg_explicit_hash_key: agg_ehk,
max_bytes_per_record: max_bytes_per_record
},
partition_key,
data,
explicit_hash_key,
new_record_size
) do
{pk_index, new_pk_set} = Keyset.get_or_add_key(partition_key, pkset)
{ehk_index, new_ehk_set} = Keyset.get_or_add_key(explicit_hash_key, ehkset)
new_record = %Proto.Record{
partition_key_index: pk_index,
explicit_hash_key_index: ehk_index,
data: data
}
%__MODULE__{
partition_keyset: new_pk_set,
explicit_hash_keyset: new_ehk_set,
rev_records: [new_record | rev_records],
num_user_records: 1 + num_user_records,
agg_size_bytes: new_record_size + agg_size,
agg_partition_key: first_defined(agg_pk, partition_key),
agg_explicit_hash_key: first_defined(agg_ehk, explicit_hash_key),
max_bytes_per_record: max_bytes_per_record
}
end
defp first_defined(nil, second), do: second
defp first_defined(first, _), do: first
defp calc_record_size(
%__MODULE__{partition_keyset: pkset, explicit_hash_keyset: ehkset},
partition_key,
data,
explicit_hash_key
) do
pk_length = byte_size(partition_key)
pk_size =
case Keyset.key?(partition_key, pkset) do
true -> 0
false -> 1 + varint_size(pk_length) + pk_length
end
ehk_size =
case explicit_hash_key do
nil ->
0
_ ->
ehk_length = byte_size(explicit_hash_key)
case Keyset.key?(explicit_hash_key, ehkset) do
true -> 0
false -> 1 + varint_size(ehk_length) + ehk_length
end
end
pk_index_size = 1 + varint_size(Keyset.potential_index(partition_key, pkset))
ehk_index_size =
case explicit_hash_key do
nil -> 0
_ -> 1 + varint_size(Keyset.potential_index(explicit_hash_key, ehkset))
end
data_length = byte_size(data)
data_size = 1 + varint_size(data_length) + data_length
inner_size = pk_index_size + ehk_index_size + data_size
pk_size + ehk_size + 1 + varint_size(inner_size) + inner_size
end
defp varint_size(int) when int >= 0 do
bits = max(num_bits(int, 0), 1)
div(bits + 6, 7)
end
defp num_bits(0, acc), do: acc
defp num_bits(int, acc) when int >= 0 do
num_bits(bsr(int, 1), acc + 1)
end
# Calculate a new explicit hash key based on the input partition key
# (following the algorithm from the original KPL).
# create_explicit_hash_key(_PartitionKey) ->
# Their python implementation [1] is broken compared to the C++
# implementation [2]. But we don't care about EHKs anyway.
# [1] https://github.com/awslabs/kinesis-aggregation/blob/db92620e435ad9924356cda7d096e3c888f0f72f/python/aws_kinesis_agg/aggregator.py#L447-L458
# [2] https://github.com/awslabs/amazon-kinesis-producer/blob/ea1e49218e1a11f1b462662a1db4cc06ddad39bb/aws/kinesis/core/user_record.cc#L36-L45
# FIXME: Implement the actual algorithm from KPL.
defp create_explicit_hash_key(_), do: nil
defp serialize_data(
%__MODULE__{
partition_keyset: pkset,
explicit_hash_keyset: ehkset,
rev_records: records
},
should_deflate?
) do
serialized =
%Proto.AggregatedRecord{
partition_key_table: Keyset.key_list(pkset),
explicit_hash_key_table: Keyset.key_list(ehkset),
records: Enum.reverse(records)
}
|> Protox.Encode.encode!()
|> IO.iodata_to_binary()
data = serialized <> :crypto.hash(:md5, serialized)
case should_deflate? do
true ->
@magic_deflated <> :zlib.compress(data)
false ->
@magic <> data
end
end
defp pk_size(nil), do: 0
defp pk_size(pk), do: byte_size(pk)
end
| 33.311828 | 486 | 0.643533 |
03f3bc3e735423e3d3a72985fddbf82844fde995 | 640 | ex | Elixir | lib/mail_slurp_api/model/bounced_recipient_dto.ex | mailslurp/mailslurp-client-elixir | 5b98b91bb327de5216e873cd45b4fbb3c1b55c90 | [
"MIT"
] | 1 | 2021-06-17T18:07:49.000Z | 2021-06-17T18:07:49.000Z | lib/mail_slurp_api/model/bounced_recipient_dto.ex | mailslurp/mailslurp-client-elixir | 5b98b91bb327de5216e873cd45b4fbb3c1b55c90 | [
"MIT"
] | null | null | null | lib/mail_slurp_api/model/bounced_recipient_dto.ex | mailslurp/mailslurp-client-elixir | 5b98b91bb327de5216e873cd45b4fbb3c1b55c90 | [
"MIT"
] | 1 | 2021-03-16T18:55:56.000Z | 2021-03-16T18:55:56.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 MailSlurpAPI.Model.BouncedRecipientDto do
@moduledoc """
Bounced recipient
"""
@derive [Poison.Encoder]
defstruct [
:"createdAt",
:"id",
:"recipient",
:"userId"
]
@type t :: %__MODULE__{
:"createdAt" => DateTime.t,
:"id" => String.t | nil,
:"recipient" => String.t,
:"userId" => String.t
}
end
defimpl Poison.Decoder, for: MailSlurpAPI.Model.BouncedRecipientDto do
def decode(value, _options) do
value
end
end
| 20 | 91 | 0.65625 |
03f3bea2e6c758edfc5ae39d07004610c6c7feb9 | 8,736 | ex | Elixir | lib/nys_etl/engines/e5/processor.ex | RatioPBC/epi-viaduct-nys | 99fb637785ea207aee5449fa01fa59dd18ec8bf2 | [
"MIT"
] | 2 | 2021-06-22T21:01:49.000Z | 2021-11-04T18:36:48.000Z | lib/nys_etl/engines/e5/processor.ex | RatioPBC/epi-viaduct-nys | 99fb637785ea207aee5449fa01fa59dd18ec8bf2 | [
"MIT"
] | null | null | null | lib/nys_etl/engines/e5/processor.ex | RatioPBC/epi-viaduct-nys | 99fb637785ea207aee5449fa01fa59dd18ec8bf2 | [
"MIT"
] | null | null | null | defmodule NYSETL.Engines.E5.Processor do
@moduledoc """
Run for each patient case extracted from CommCare.
* case_id already present in our DB:
* update it with changes from CommCare (but ignore any new lab results)
* case_id does not exist, Person exists and can be matched by dob | last_name | first_name:
* create an IndexCase and LabResult record(s)
* case_id does not exist, Person cannot be matched:
* create a Person, IndexCase and LabResult record(s)
"""
alias Euclid.Exists
alias Euclid.Extra
alias NYSETL.Commcare
require Logger
def process(case: patient_case, county: county) do
with {:error, :not_found} <- find_and_update_index_case(patient_case, county),
{_case_id, patient_key, dob, lab_results} <- extract_case_data(patient_case),
{:ok, person, finder} <- find_person(patient_case, dob, patient_key) || create_person(patient_case) do
{:ok, index_case} = create_index_case(patient_case, person, county)
index_case |> create_lab_results(lab_results, county)
{:ok, index_case, finder}
else
{:ok, %Commcare.IndexCase{} = index_case} ->
{:ok, index_case, :already_exists}
{:error, %Ecto.Changeset{} = changeset} ->
{:error, changeset.errors}
{:error, reason} ->
{:error, reason}
end
end
def extract_case_data(%{"closed" => true}), do: {:error, :closed}
def extract_case_data(%{"properties" => %{"final_disposition" => final_disposition}})
when final_disposition in ["registered_in_error", "duplicate", "not_a_case"],
do: {:error, :final_disposition}
def extract_case_data(%{"properties" => %{"patient_type" => "pui", "current_status" => "closed"}}), do: {:error, :closed}
def extract_case_data(%{"properties" => %{"stub" => "yes"}}), do: {:error, :stub}
def extract_case_data(%{"properties" => %{"transfer_status" => transfer_status}})
when transfer_status in ["pending", "sent"],
do: {:error, :transfer_status}
def extract_case_data(patient_case) do
case_id = patient_case["case_id"]
lab_results = lab_results(patient_case)
patient_key = find_patient_key(patient_case, lab_results)
dob = parse_dob(patient_case)
{case_id, patient_key, dob, lab_results}
end
def create_person(%{"properties" => properties} = patient_case) do
Logger.debug("[#{__MODULE__}] trying to create a person matching index_case case_id=#{patient_case.case_id}")
first_name = properties["first_name"] && String.upcase(properties["first_name"])
last_name = properties["last_name"] && String.upcase(properties["last_name"])
dob = properties["dob"]
%{
data: %{},
patient_keys: [],
name_last: last_name,
name_first: first_name,
dob: dob
}
|> Commcare.create_person()
|> case do
{:ok, person} -> {:ok, person, :new_person}
other -> other
end
end
def create_index_case(case, %Commcare.Person{} = person, county) do
case_id = case["case_id"]
{:ok, index_case} =
%{
case_id: case_id,
data: case["properties"],
county_id: county.fips,
person_id: person.id
}
|> Commcare.create_index_case()
:telemetry.execute([:extractor, :commcare, :index_case, :created], %{count: 1})
Logger.info("[#{__MODULE__}] created index_case case_id=#{case_id} for person_id=#{person.id}, county=#{county.domain}")
index_case |> Commcare.save_event("retrieved_from_commcare")
{:ok, index_case}
end
def create_lab_results(%Commcare.IndexCase{} = index_case, [], _county), do: index_case
def create_lab_results(%Commcare.IndexCase{} = index_case, lab_results, county) do
lab_results
|> Enum.each(fn commcare_lab_result ->
%{
case_id: commcare_lab_result["case_id"],
data: commcare_lab_result["properties"],
index_case_id: index_case.id,
accession_number: commcare_lab_result["properties"]["accession_number"]
}
|> Commcare.create_lab_result()
|> case do
{:ok, lab_result} ->
:telemetry.execute([:extractor, :commcare, :lab_result, :created], %{count: 1})
Logger.info("[#{__MODULE__}] created lab_result=#{lab_result.case_id} for index_case case_id=#{index_case.case_id} county=#{county.domain}")
{:ok, lab_result}
error ->
throw(error)
end
end)
end
def find_and_update_index_case(patient_case, county) do
Commcare.get_index_case(case_id: patient_case["case_id"], county_id: county.fips)
|> case do
{:error, :not_found} ->
{:error, :not_found}
{:ok, index_case} ->
Commcare.update_index_case_from_commcare_data(index_case, patient_case)
|> case do
{:ok, ^index_case} ->
Logger.info(
"[#{__MODULE__}] not modified index_case case_id=#{index_case.case_id} for person_id=#{index_case.person_id}, county=#{county.domain}"
)
{:ok, index_case}
{:ok, index_case} ->
:telemetry.execute([:extractor, :commcare, :index_case, :already_exists], %{count: 1})
Logger.info(
"[#{__MODULE__}] updated index_case case_id=#{index_case.case_id} for person_id=#{index_case.person_id}, county=#{county.domain}"
)
index_case |> Commcare.save_event("updated_from_commcare")
{:ok, index_case}
end
end
end
def find_person(patient_case, dob, patient_key) do
Logger.debug("[#{__MODULE__}] trying to find a person matching index_case case_id=#{patient_case.case_id}")
find_person(patient_key: patient_key) || find_person(patient_case, dob: dob)
end
def find_person(patient_key: patient_key) do
Commcare.get_person(patient_key: patient_key)
|> case do
{:ok, person} -> {:ok, person, :patient_key}
{:error, :not_found} -> nil
end
end
def find_person(_case, dob: nil), do: nil
def find_person(%{"properties" => %{"first_name" => first_name, "last_name" => last_name}}, dob: dob)
when is_binary(first_name) and is_binary(last_name) do
Commcare.get_person(
dob: dob,
name_first: first_name |> String.upcase(),
name_last: last_name |> String.upcase()
)
|> case do
{:ok, person} -> {:ok, person, :dob}
{:error, :not_found} -> nil
end
end
def find_person(%{"properties" => %{"full_name" => full_name}}, dob: dob)
when is_binary(full_name) do
Commcare.get_person(
dob: dob,
full_name: full_name
)
|> case do
{:ok, person} -> {:ok, person, :full_name}
{:error, :not_found} -> nil
end
end
def find_patient_key(case, lab_results) do
patient_key_from_external_id(case["properties"]["external_id"]) ||
patient_key_from_name_and_id(case["properties"]["name_and_id"]) ||
patient_key_from_lab_result(lab_results)
end
def parse_dob(%{"properties" => %{"dob" => <<year::binary-size(4), "-", month::binary-size(2), "-", day::binary-size(2)>>}}),
do: Date.from_erl!({String.to_integer(year), String.to_integer(month), String.to_integer(day)})
def parse_dob(_), do: nil
def patient_key_from_external_id(nil), do: nil
def patient_key_from_external_id(""), do: nil
def patient_key_from_external_id(binary) when is_binary(binary) do
binary
|> String.split("#")
|> Enum.at(1)
end
def patient_key_from_lab_result([]), do: nil
def patient_key_from_lab_result(lab_results) do
lab_results
|> Extra.Enum.pluck("properties")
|> Extra.Enum.pluck("external_id")
|> Extra.Enum.compact()
|> List.first()
|> case do
nil ->
nil
value ->
value
|> String.split("#")
|> Enum.at(1)
end
end
def patient_key_from_name_and_id(nil), do: nil
def patient_key_from_name_and_id(binary) when is_binary(binary) do
Regex.named_captures(~r|.+\(.+#(?<patient_key>\d+)\)|, binary)
|> case do
%{"patient_key" => patient_key} -> patient_key
_ -> nil
end
end
defp lab_results(case) do
case["child_cases"]
|> Map.values()
|> Enum.filter(fn child_cases ->
child_cases["properties"]["case_type"] == "lab_result" &&
Exists.present?(child_cases["properties"]["accession_number"])
end)
end
def case_is_a_stub?(%{"properties" => %{"stub" => "yes"}}), do: true
def case_is_a_stub?(_), do: false
def case_has_lab_result?(%{"child_cases" => child_cases}),
do: child_cases |> Map.values() |> Enum.any?(&case_is_a_lab_result?/1)
def case_has_lab_result?(_), do: false
def case_is_a_lab_result?(%{"properties" => %{"case_type" => "lab_result"}}), do: true
def case_is_a_lab_result?(_), do: false
end
| 32.842105 | 150 | 0.64652 |
03f3f018588a9e7dce678b864998818700a4a8f2 | 3,199 | ex | Elixir | clients/android_enterprise/lib/google_api/android_enterprise/v1/api/permissions.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/android_enterprise/lib/google_api/android_enterprise/v1/api/permissions.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/android_enterprise/lib/google_api/android_enterprise/v1/api/permissions.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.AndroidEnterprise.V1.Api.Permissions do
@moduledoc """
API calls for all endpoints tagged `Permissions`.
"""
alias GoogleApi.AndroidEnterprise.V1.Connection
import GoogleApi.AndroidEnterprise.V1.RequestBuilder
@doc """
Retrieves details of an Android app permission for display to an enterprise admin.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- permission_id (String): The ID of the permission.
- opts (KeywordList): [optional] Optional parameters
- :alt (String): Data format for the response.
- :fields (String): Selector specifying which fields to include in a partial response.
- :key (String): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String): OAuth 2.0 token for the current user.
- :pretty_print (Boolean): Returns response with indentations and line breaks.
- :quota_user (String): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
- :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits.
- :language (String): The BCP47 tag for the user's preferred language (e.g. \"en-US\", \"de\")
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.Permission{}} on success
{:error, info} on failure
"""
@spec androidenterprise_permissions_get(Tesla.Env.client, String.t, keyword()) :: {:ok, GoogleApi.AndroidEnterprise.V1.Model.Permission.t} | {:error, Tesla.Env.t}
def androidenterprise_permissions_get(connection, permission_id, opts \\ []) do
optional_params = %{
:"alt" => :query,
:"fields" => :query,
:"key" => :query,
:"oauth_token" => :query,
:"prettyPrint" => :query,
:"quotaUser" => :query,
:"userIp" => :query,
:"language" => :query
}
%{}
|> method(:get)
|> url("/permissions/{permissionId}", %{
"permissionId" => URI.encode_www_form(permission_id)
})
|> add_optional_params(optional_params, opts)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> decode(%GoogleApi.AndroidEnterprise.V1.Model.Permission{})
end
end
| 43.22973 | 217 | 0.709284 |
03f3f392fd2eaa1a7765cf29d12d2958776a9f5e | 900 | ex | Elixir | lib/httpoison.ex | SkAZi/httpoison | 730506caa1abd05e7a40c006061639badc351311 | [
"MIT"
] | null | null | null | lib/httpoison.ex | SkAZi/httpoison | 730506caa1abd05e7a40c006061639badc351311 | [
"MIT"
] | null | null | null | lib/httpoison.ex | SkAZi/httpoison | 730506caa1abd05e7a40c006061639badc351311 | [
"MIT"
] | null | null | null | defmodule HTTPoison do
@moduledoc """
The HTTP client for Elixir.
"""
defmodule Response do
defstruct status_code: nil, body: nil, headers: %{}
@type t :: %Response{status_code: integer, body: binary, headers: map}
end
defmodule AsyncResponse do
defstruct id: nil
@type t :: %AsyncResponse{id: reference}
end
defmodule AsyncStatus do
defstruct id: nil, code: nil
@type t :: %AsyncStatus{id: reference, code: integer}
end
defmodule AsyncHeaders do
defstruct id: nil, headers: %{}
@type t :: %AsyncHeaders{id: reference, headers: map}
end
defmodule AsyncChunk do
defstruct id: nil, chunk: nil
@type t :: %AsyncChunk{id: reference, chunk: binary}
end
defmodule AsyncEnd do
defstruct id: nil
@type t :: %AsyncEnd{id: reference}
end
defmodule HTTPError do
defexception message: nil
end
use HTTPoison.Base
end
| 21.428571 | 74 | 0.674444 |
03f41248655872124893dfa741eea1c2486ca5af | 2,812 | exs | Elixir | mix.exs | Annopaolo/astarte-device-sdk-elixir | fbd0c214f3e2e1d3040fa70d6c2a0d35dab0a495 | [
"Apache-2.0"
] | 3 | 2020-02-10T07:12:49.000Z | 2020-09-19T02:56:40.000Z | mix.exs | Annopaolo/astarte-device-sdk-elixir | fbd0c214f3e2e1d3040fa70d6c2a0d35dab0a495 | [
"Apache-2.0"
] | 9 | 2019-11-18T16:51:13.000Z | 2021-02-24T17:43:03.000Z | mix.exs | Annopaolo/astarte-device-sdk-elixir | fbd0c214f3e2e1d3040fa70d6c2a0d35dab0a495 | [
"Apache-2.0"
] | 5 | 2020-01-25T12:14:15.000Z | 2021-06-18T08:33:40.000Z | #
# This file is part of Astarte.
#
# Copyright 2018-2021 Ispirata Srl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
defmodule Astarte.Device.MixProject do
use Mix.Project
def project do
[
app: :astarte_device,
version: "1.1.0-dev",
elixir: "~> 1.11",
start_permanent: Mix.env() == :prod,
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
deps: deps(),
package: package(),
elixirc_paths: elixirc_paths(Mix.env()),
dialyzer_ignored_warnings: dialyzer_ignored_warnings()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
mod: {Astarte.Device.Application, []},
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:astarte_core, github: "astarte-platform/astarte_core"},
{:certifi, "~> 2.5"},
{:hackney, "~> 1.15"},
{:jason, "~> 1.1"},
{:tesla, "~> 1.2"},
{:tortoise, "~> 0.9"},
{:x509, "~> 0.5"},
{:excoveralls, "~> 0.11.1", only: :test},
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:mox, "~> 0.5", only: :test},
{:dialyzex, "~> 1.2.0", only: :dev}
]
end
defp elixirc_paths(:test), do: ["test/support", "lib"]
defp elixirc_paths(_), do: ["lib"]
defp dialyzer_ignored_warnings do
[
{:warn_matching, {'lib/astarte_device/handler.ex', 82},
{:pattern_match, ['pattern {\'error\', __@7}', '{\'ok\',\'nil\'}']}},
# Remove when this https://github.com/gausby/tortoise/pull/110 gets merged
{:warn_matching, {'lib/astarte_device/impl.ex', :_},
{:pattern_match,
[
'pattern {\'ok\', _pid@1}',
'{\'error\',\'invalid_args\' | \'invalid_certificate\' | \'invalid_private_key\'}'
]}}
]
end
defp package do
[
description: "Astarte Elixir device SDK",
maintainers: ["Riccardo Binetti"],
licenses: ["Apache-2.0"],
links: %{
"GitHub" => "https://github.com/astarte-platform/astarte-device-sdk-elixir",
"Documentation" => "http://hexdocs.pm/astarte_device"
}
]
end
end
| 29.291667 | 92 | 0.601351 |
03f419976269a5244501feb19321118ad8d13e4e | 1,247 | ex | Elixir | lib/alchemy_book_web/views/error_helpers.ex | moviedo/alchemy-book | e1a60cad85838a4ae3a7d8506be532ed45b8a716 | [
"MIT"
] | null | null | null | lib/alchemy_book_web/views/error_helpers.ex | moviedo/alchemy-book | e1a60cad85838a4ae3a7d8506be532ed45b8a716 | [
"MIT"
] | null | null | null | lib/alchemy_book_web/views/error_helpers.ex | moviedo/alchemy-book | e1a60cad85838a4ae3a7d8506be532ed45b8a716 | [
"MIT"
] | null | null | null | defmodule AlchemyBookWeb.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
if error = form.errors[field] do
content_tag :span, translate_error(error), class: "help-block"
end
end
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# Because error messages were defined within Ecto, we must
# call the Gettext module passing our Gettext backend. We
# also use the "errors" domain as translations are placed
# in the errors.po file.
# Ecto will pass the :count keyword if the error message is
# meant to be pluralized.
# On your own code and templates, depending on whether you
# need the message to be pluralized or not, this could be
# written simply as:
#
# dngettext "errors", "1 file", "%{count} files", count
# dgettext "errors", "is invalid"
#
if count = opts[:count] do
Gettext.dngettext(AlchemyBookWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(AlchemyBookWeb.Gettext, "errors", msg, opts)
end
end
end
| 30.414634 | 80 | 0.672815 |
03f41de86b7a382fde36e51e0f383fc183dfb1b0 | 1,736 | ex | Elixir | clients/content/lib/google_api/content/v21/model/link_service.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v21/model/link_service.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v21/model/link_service.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.Content.V21.Model.LinkService do
@moduledoc """
## Attributes
* `service` (*type:* `String.t`, *default:* `nil`) - Service provided to or by the linked account.
Acceptable values are:
- "`shoppingActionsOrderManagement`"
- "`shoppingActionsProductManagement`"
- "`shoppingAdsProductManagement`"
* `status` (*type:* `String.t`, *default:* `nil`) - Status of the link
Acceptable values are:
- "`active`"
- "`inactive`"
- "`pending`"
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:service => String.t(),
:status => String.t()
}
field(:service)
field(:status)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.LinkService do
def decode(value, options) do
GoogleApi.Content.V21.Model.LinkService.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.LinkService do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 28.933333 | 102 | 0.693548 |
03f41e3c7cfdd099c3a97b5727828f94bf36c6f0 | 3,800 | ex | Elixir | clients/admin/lib/google_api/admin/directory_v1/api/privileges.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/admin/lib/google_api/admin/directory_v1/api/privileges.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/admin/lib/google_api/admin/directory_v1/api/privileges.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.Admin.Directory_v1.Api.Privileges do
@moduledoc """
API calls for all endpoints tagged `Privileges`.
"""
alias GoogleApi.Admin.Directory_v1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Retrieves a paginated list of all privileges for a customer.
## Parameters
* `connection` (*type:* `GoogleApi.Admin.Directory_v1.Connection.t`) - Connection to server
* `customer` (*type:* `String.t`) - Immutable ID of the G Suite 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").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Admin.Directory_v1.Model.Privileges{}}` on success
* `{:error, info}` on failure
"""
@spec directory_privileges_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Admin.Directory_v1.Model.Privileges.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def directory_privileges_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
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/admin/directory/v1/customer/{customer}/roles/ALL/privileges", %{
"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.Privileges{}])
end
end
| 43.678161 | 196 | 0.655526 |
03f44614082ca67aabb8dc71b980dff982a8aad7 | 79 | ex | Elixir | socket_remotedata/web/views/layout_view.ex | mikeonslow/elm-socket-remotedata | 8b5ee678f7f954c6b289f96b559d8ff5d648d474 | [
"MIT"
] | 1 | 2020-02-09T20:20:23.000Z | 2020-02-09T20:20:23.000Z | socket_remotedata/web/views/layout_view.ex | mikeonslow/elm-socket-remotedata | 8b5ee678f7f954c6b289f96b559d8ff5d648d474 | [
"MIT"
] | null | null | null | socket_remotedata/web/views/layout_view.ex | mikeonslow/elm-socket-remotedata | 8b5ee678f7f954c6b289f96b559d8ff5d648d474 | [
"MIT"
] | null | null | null | defmodule SocketRemotedata.LayoutView do
use SocketRemotedata.Web, :view
end
| 19.75 | 40 | 0.835443 |
03f448bc4684a65eed47cc81c515a9581373441a | 1,706 | ex | Elixir | lib/shadowsocks/event.ex | feng19/shadowsocks-ex | 33aa06349e877b4395e27c182f0dbf71a8e51165 | [
"BSD-3-Clause"
] | null | null | null | lib/shadowsocks/event.ex | feng19/shadowsocks-ex | 33aa06349e877b4395e27c182f0dbf71a8e51165 | [
"BSD-3-Clause"
] | null | null | null | lib/shadowsocks/event.ex | feng19/shadowsocks-ex | 33aa06349e877b4395e27c182f0dbf71a8e51165 | [
"BSD-3-Clause"
] | null | null | null | defmodule Shadowsocks.Event do
require Logger
def child_spec(_) do
%{
id: __MODULE__,
start: {:gen_event, :start_link, [local: Shadowsocks.Event]},
modules: :dynamic
}
end
defmacro start_listener(port) do
quote do
:gen_event.notify(Shadowsocks.Event, {:port, :open, unquote(port)})
end
end
defmacro open_conn(port, pid, addr) do
quote do
:gen_event.notify(
Shadowsocks.Event,
{:conn, :open, {unquote(port), unquote(pid), unquote(addr)}}
)
end
end
defmacro close_conn(port, pid, reason, flow) do
quote do
:gen_event.notify(
Shadowsocks.Event,
{:conn, :close, {unquote(port), unquote(pid), unquote(reason), unquote(flow)}}
)
end
end
defmacro bad_request(port, addr) do
quote do
:gen_event.notify(Shadowsocks.Event, {:bad_request, unquote(port), unquote(addr)})
end
end
defmacro connect(port, pid, info) do
quote do
Logger.debug("#{inspect(unquote(info))}")
:gen_event.notify(
Shadowsocks.Event,
{:conn, :connect, {unquote(port), unquote(pid), unquote(info)}}
)
end
end
defmacro flow(port, down, up) do
quote do
:gen_event.notify(
Shadowsocks.Event,
{:port, :flow, {unquote(port), unquote(down), unquote(up)}}
)
end
end
defmacro sync_flow(port, down, up) do
quote do
:gen_event.sync_notify(
Shadowsocks.Event,
{:port, :flow, {unquote(port), unquote(down), unquote(up)}}
)
end
end
defmacro dynamic_blocked(addr) do
quote do
:gen_event.notify(Shadowsocks.Event, {:dynamic_blocked, unquote(addr)})
end
end
end
| 22.155844 | 88 | 0.61313 |
03f495f0bcf5f0c9162a4d485f10693b92ca1566 | 1,078 | ex | Elixir | clients/deployment_manager/lib/google_api/deployment_manager/v2/model/deployment_label_entry.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/deployment_manager/lib/google_api/deployment_manager/v2/model/deployment_label_entry.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/deployment_manager/lib/google_api/deployment_manager/v2/model/deployment_label_entry.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.DeploymentManager.V2.Model.DeploymentLabelEntry do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:"key",
:"value"
]
end
defimpl Poison.Decoder, for: GoogleApi.DeploymentManager.V2.Model.DeploymentLabelEntry do
def decode(value, _options) do
value
end
end
| 28.368421 | 89 | 0.746753 |
03f49727ef6ba7bc79521c00d9e47c36e1f17e90 | 3,417 | exs | Elixir | test/annex_test.exs | arpieb/annex | 6f472a30361bf0a1646e256d6dfe478706427f64 | [
"MIT"
] | 1 | 2020-10-23T13:41:07.000Z | 2020-10-23T13:41:07.000Z | test/annex_test.exs | arpieb/annex | 6f472a30361bf0a1646e256d6dfe478706427f64 | [
"MIT"
] | null | null | null | test/annex_test.exs | arpieb/annex | 6f472a30361bf0a1646e256d6dfe478706427f64 | [
"MIT"
] | null | null | null | defmodule AnnexTest do
use ExUnit.Case
doctest Annex
alias Annex.{
Data.DMatrix,
Layer.Activation,
Layer.Dense,
Layer.Dropout,
Layer.Sequence,
LayerConfig
}
describe "sequence/1" do
test "works" do
assert Annex.sequence([
Annex.dense(1, 1)
]) == %LayerConfig{
module: Sequence,
details: %{
layers: [
%LayerConfig{
module: Dense,
details: %{
rows: 1,
columns: 1
}
}
]
}
}
end
end
describe "dropout/1" do
test "works" do
assert Annex.dropout(0.4) == %LayerConfig{
module: Dropout,
details: %{
frequency: 0.4
}
}
end
end
describe "dense/4" do
test "works" do
weights = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
biases = [0.1, 0.1, 0.1]
assert Annex.dense(2, 3, weights, biases) == %LayerConfig{
module: Dense,
details: %{
rows: 2,
columns: 3,
weights: weights,
biases: biases
}
}
end
end
describe "dense/2" do
test "works" do
assert Annex.dense(2, 3) == %LayerConfig{
module: Dense,
details: %{
rows: 2,
columns: 3
}
}
end
end
describe "activation/1" do
test "works" do
assert Annex.activation(:relu) == %LayerConfig{
module: Activation,
details: %{
name: :relu
}
}
end
end
describe "train/2" do
test "works" do
weights = [0.1, 0.15, 0.17, 0.2, 0.24, 0.28]
biases = [0.1, 0.1]
dataset = [
{[1.0, 0.4, 1.4], [1.0, 0.0]}
]
assert {seq, training_output} =
[
Annex.dense(2, 3, weights, biases),
Annex.activation(:relu)
]
|> Annex.sequence()
|> Annex.train(dataset, halt_condition: {:epochs, 1})
assert %Sequence{layers: %{0 => dense, 1 => activation}} = seq
assert dense == %Dense{
rows: 2,
columns: 3,
data_type: DMatrix,
biases: DMatrix.build([[0.12510000000000002], [0.0606]]),
weights:
DMatrix.build([
[0.12510000000000002, 0.16004, 0.20514000000000002],
[0.16060000000000002, 0.22424, 0.22484000000000004]
])
}
assert %Activation{name: :relu} = activation
end
end
describe "predict/2" do
test "works" do
weights = [0.1, 0.15, 0.17, 0.2, 0.24, 0.28]
biases = [0.1, 0.1]
dataset = [
{[1.0, 0.4, 1.4], [1.0, 0.0]}
]
assert {seq, training_output} =
[
Annex.dense(2, 3, weights, biases),
Annex.activation(:relu)
]
|> Annex.sequence()
|> Annex.train(dataset, halt_condition: {:epochs, 1})
assert Annex.predict(seq, [1.0, 0.4, 1.4]) == [0.6014120000000001, 0.625672]
end
end
end
| 24.06338 | 82 | 0.425812 |
03f4bcfae21ee76d624b73019f6fc3006340b3a5 | 1,898 | ex | Elixir | clients/sheets/lib/google_api/sheets/v4/model/editors.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/sheets/lib/google_api/sheets/v4/model/editors.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/sheets/lib/google_api/sheets/v4/model/editors.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.Sheets.V4.Model.Editors do
@moduledoc """
The editors of a protected range.
## Attributes
* `domainUsersCanEdit` (*type:* `boolean()`, *default:* `nil`) - True if anyone in the document's domain has edit access to the protected range. Domain protection is only supported on documents within a domain.
* `groups` (*type:* `list(String.t)`, *default:* `nil`) - The email addresses of groups with edit access to the protected range.
* `users` (*type:* `list(String.t)`, *default:* `nil`) - The email addresses of users with edit access to the protected range.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:domainUsersCanEdit => boolean(),
:groups => list(String.t()),
:users => list(String.t())
}
field(:domainUsersCanEdit)
field(:groups, type: :list)
field(:users, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.Editors do
def decode(value, options) do
GoogleApi.Sheets.V4.Model.Editors.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.Editors do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.811321 | 214 | 0.712856 |
03f4d37fdfe4474817f3fe20234cee9eba119649 | 2,511 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/creative_rotation.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/creative_rotation.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/creative_rotation.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V33.Model.CreativeRotation do
@moduledoc """
Creative Rotation.
## Attributes
* `creativeAssignments` (*type:* `list(GoogleApi.DFAReporting.V33.Model.CreativeAssignment.t)`, *default:* `nil`) - Creative assignments in this creative rotation.
* `creativeOptimizationConfigurationId` (*type:* `String.t`, *default:* `nil`) - Creative optimization configuration that is used by this ad. It should refer to one of the existing optimization configurations in the ad's campaign. If it is unset or set to 0, then the campaign's default optimization configuration will be used for this ad.
* `type` (*type:* `String.t`, *default:* `nil`) - Type of creative rotation. Can be used to specify whether to use sequential or random rotation.
* `weightCalculationStrategy` (*type:* `String.t`, *default:* `nil`) - Strategy for calculating weights. Used with CREATIVE_ROTATION_TYPE_RANDOM.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:creativeAssignments => list(GoogleApi.DFAReporting.V33.Model.CreativeAssignment.t()),
:creativeOptimizationConfigurationId => String.t(),
:type => String.t(),
:weightCalculationStrategy => String.t()
}
field(:creativeAssignments, as: GoogleApi.DFAReporting.V33.Model.CreativeAssignment, type: :list)
field(:creativeOptimizationConfigurationId)
field(:type)
field(:weightCalculationStrategy)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.CreativeRotation do
def decode(value, options) do
GoogleApi.DFAReporting.V33.Model.CreativeRotation.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.CreativeRotation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.052632 | 343 | 0.747511 |
03f51b2b5f1089a07840a46726574946740fb2ee | 39,550 | ex | Elixir | deps/nimble_parsec/lib/nimble_parsec.ex | BandanaPandey/nary_tree | fb1eeb69e38e43c9f9ffb54297cef52dff5c928d | [
"MIT"
] | 13 | 2018-09-19T21:03:29.000Z | 2022-01-27T04:06:32.000Z | deps/nimble_parsec/lib/nimble_parsec.ex | BandanaPandey/nary_tree | fb1eeb69e38e43c9f9ffb54297cef52dff5c928d | [
"MIT"
] | 1 | 2020-05-26T04:16:57.000Z | 2020-05-26T04:16:57.000Z | deps/nimble_parsec/lib/nimble_parsec.ex | BandanaPandey/nary_tree | fb1eeb69e38e43c9f9ffb54297cef52dff5c928d | [
"MIT"
] | 3 | 2020-05-21T04:32:08.000Z | 2021-07-28T05:14:01.000Z | defmodule NimbleParsec do
@moduledoc "README.md"
|> File.read!()
|> String.split("<!-- MDOC !-->")
|> Enum.fetch!(1)
defmacrop is_combinator(combinator) do
quote do
is_list(unquote(combinator))
end
end
@doc """
Defines a public parser `combinator` with the given `name` and `opts`.
## Beware!
`defparsec/3` is executed during compilation. This means you can't
invoke a function defined in the same module. The following will error
because the `date` function has not yet been defined:
defmodule MyParser do
import NimbleParsec
def date do
integer(4)
|> ignore(string("-"))
|> integer(2)
|> ignore(string("-"))
|> integer(2)
end
defparsec :date, date()
end
This can be solved in different ways. You may define `date` in another
module and then invoke it. You can also store the parsec in a variable
or a module attribute and use that instead. For example:
defmodule MyParser do
import NimbleParsec
date =
integer(4)
|> ignore(string("-"))
|> integer(2)
|> ignore(string("-"))
|> integer(2)
defparsec :date, date
end
## Options
* `:inline` - when true, inlines clauses that work as redirection for
other clauses. It is disabled by default because of a bug in Elixir
v1.5 and v1.6 where unused functions that are inlined cause a
compilation error
* `:debug` - when true, writes generated clauses to `:stderr` for debugging
"""
defmacro defparsec(name, combinator, opts \\ []) do
{doc, spec, {name, args, guards, body}} = NimbleParsec.Compiler.entry_point(name)
quote do
@doc unquote(doc)
@spec unquote(spec)
def unquote(name)(unquote_splicing(args)) when unquote(guards) do
unquote(body)
end
unquote(compile(name, combinator, opts))
end
end
@doc """
Defines a private parser combinator.
It cannot be invoked directly, only via `parsec/2`.
Receives the same options as `defparsec/3`.
"""
defmacro defparsecp(name, combinator, opts \\ []) do
compile(name, combinator, opts)
end
defp compile(name, combinator, opts) do
quote bind_quoted: [name: name, combinator: combinator, opts: opts] do
{defs, inline} = NimbleParsec.Compiler.compile(name, combinator, opts)
if inline != [] do
@compile {:inline, inline}
end
for {name, args, guards, body} <- defs do
defp unquote(name)(unquote_splicing(args)) when unquote(guards), do: unquote(body)
end
:ok
end
end
@type t :: [combinator]
@type bin_modifiers :: :integer | :utf8 | :utf16 | :utf32
@type range :: inclusive_range | exclusive_range
@type inclusive_range :: Range.t() | char()
@type exclusive_range :: {:not, Range.t()} | {:not, char()}
@type min_and_max :: {:min, non_neg_integer()} | {:max, pos_integer()}
@type call :: mfargs | fargs | atom
@type mfargs :: {module, atom, args :: [term]}
@type fargs :: {atom, args :: [term]}
# Steps to add a new combinator:
#
# 1. Update the combinator type below
# 2. Update the compiler with combinator
# 3. Update the compiler with label step
#
@typep combinator :: bound_combinator | maybe_bound_combinator | unbound_combinator
@typep bound_combinator ::
{:bin_segment, [inclusive_range], [exclusive_range], [bin_modifiers]}
| {:string, binary}
@typep maybe_bound_combinator ::
{:label, t, binary}
| {:traverse, t, constant? :: boolean, [mfargs]}
@typep unbound_combinator ::
{:choice, [t]}
| {:parsec, atom}
| {:repeat, t, mfargs}
| {:times, t, min :: non_neg_integer, pos_integer}
@cont_context {__MODULE__, :__cont_context__, []}
@doc ~S"""
Returns an empty combinator.
An empty combinator cannot be compiled on its own.
"""
def empty() do
[]
end
@doc """
Invokes an already compiled parsec with name `name` in the
same module.
It is useful to implement recursive definitions.
It can also be used to exchange compilation time by runtime
performance. If you have a parser used over and over again,
you can compile it using `defparsecp` and rely on it via
this function. The tree size built at compile time will be
reduce although runtime performance is degraded as every time
this function is invoked it introduces a stacktrace entry.
"""
def parsec(combinator \\ empty(), name) when is_combinator(combinator) and is_atom(name) do
[{:parsec, name} | combinator]
end
@doc ~S"""
Defines a single ascii codepoint in the given ranges.
`ranges` is a list containing one of:
* a `min..max` range expressing supported codepoints
* a `codepoint` integer expressing a supported codepoint
* `{:not, min..max}` expressing not supported codepoints
* `{:not, codepoint}` expressing a not supported codepoint
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :digit_and_lowercase,
empty()
|> ascii_char([?0..?9])
|> ascii_char([?a..?z])
end
MyParser.digit_and_lowercase("1a")
#=> {:ok, [?1, ?a], "", %{}, {1, 0}, 2}
MyParser.digit_and_lowercase("a1")
#=> {:error, "expected a byte in the range ?0..?9, followed by a byte in the range ?a..?z", "a1", %{}, 1, 1}
"""
@spec ascii_char(t, [range]) :: t
def ascii_char(combinator \\ empty(), ranges)
when is_combinator(combinator) and is_list(ranges) do
{inclusive, exclusive} = split_ranges!(ranges, "ascii_char")
bin_segment(combinator, inclusive, exclusive, [:integer])
end
@doc ~S"""
Defines a single utf8 codepoint in the given ranges.
`ranges` is a list containing one of:
* a `min..max` range expressing supported codepoints
* a `codepoint` integer expressing a supported codepoint
* `{:not, min..max}` expressing not supported codepoints
* `{:not, codepoint}` expressing a not supported codepoint
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :digit_and_utf8,
empty()
|> utf8_char([?0..?9])
|> utf8_char([])
end
MyParser.digit_and_utf8("1é")
#=> {:ok, [?1, ?é], "", %{}, {1, 0}, 2}
MyParser.digit_and_utf8("a1")
#=> {:error, "expected a utf8 codepoint in the range ?0..?9, followed by a utf8 codepoint", "a1", %{}, {1, 0}, 0}
"""
@spec utf8_char(t, [range]) :: t
def utf8_char(combinator \\ empty(), ranges)
when is_combinator(combinator) and is_list(ranges) do
{inclusive, exclusive} = split_ranges!(ranges, "utf8_char")
bin_segment(combinator, inclusive, exclusive, [:utf8])
end
@doc ~S"""
Adds a label to the combinator to be used in error reports.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :digit_and_lowercase,
empty()
|> ascii_char([?0..?9])
|> ascii_char([?a..?z])
|> label("digit followed by lowercase letter")
end
MyParser.digit_and_lowercase("1a")
#=> {:ok, [?1, ?a], "", %{}, {1, 0}, 2}
MyParser.digit_and_lowercase("a1")
#=> {:error, "expected a digit followed by lowercase letter", "a1", %{}, {1, 0}, 0}
"""
def label(combinator \\ empty(), to_label, label)
when is_combinator(combinator) and is_combinator(to_label) and is_binary(label) do
non_empty!(to_label, "label")
[{:label, Enum.reverse(to_label), label} | combinator]
end
@doc ~S"""
Defines an integer combinator with of exact length or `min` and `max`
length.
If you want an integer of unknown size, use `integer(min: 1)`.
This combinator does not parse the sign and is always on base 10.
## Examples
With exact length:
defmodule MyParser do
import NimbleParsec
defparsec :two_digits_integer, integer(2)
end
MyParser.two_digits_integer("123")
#=> {:ok, [12], "3", %{}, {1, 0}, 2}
MyParser.two_digits_integer("1a3")
#=> {:error, "expected a two digits integer", "1a3", %{}, {1, 0}, 0}
With min and max:
defmodule MyParser do
import NimbleParsec
defparsec :two_digits_integer, integer(min: 2, max: 4)
end
MyParser.two_digits_integer("123")
#=> {:ok, [123], "", %{}, {1, 0}, 2}
MyParser.two_digits_integer("1a3")
#=> {:error, "expected a two digits integer", "1a3", %{}, {1, 0}, 0}
"""
@spec integer(t, pos_integer | [min_and_max]) :: t
def integer(combinator \\ empty(), count_or_opts)
when is_combinator(combinator) and (is_integer(count_or_opts) or is_list(count_or_opts)) do
min_max_compile_runtime_chars(
combinator,
ascii_char([?0..?9]),
count_or_opts,
:__compile_integer__,
:__runtime_integer__,
[]
)
end
@doc ~S"""
Defines an ascii string combinator with of exact length or `min` and `max`
length.
The `ranges` specify the allowed characters in the ascii string.
See `ascii_char/2` for more information.
If you want a string of unknown size, use `ascii_string(ranges, min: 1)`.
If you want a literal string, use `string/2`.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :two_lowercase_letters, ascii_string([?a..?z], 2)
end
MyParser.two_lowercase_letters("abc")
#=> {:ok, ["ab"], "c", %{}, {1, 0}, 2}
"""
@spec ascii_string(t, [range], pos_integer | [min_and_max]) :: t
def ascii_string(combinator \\ empty(), range, count_or_opts)
when is_combinator(combinator) and is_list(range) and
(is_integer(count_or_opts) or is_list(count_or_opts)) do
min_max_compile_runtime_chars(
combinator,
ascii_char(range),
count_or_opts,
:__compile_string__,
:__runtime_string__,
[quote(do: integer)]
)
end
@doc ~S"""
Defines an ascii string combinator with of exact length or `min` and `max`
codepoint length.
The `ranges` specify the allowed characters in the ascii string.
See `ascii_char/2` for more information.
If you want a string of unknown size, use `utf8_string(ranges, min: 1)`.
If you want a literal string, use `string/2`.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :two_letters, utf8_string([], 2)
end
MyParser.two_letters("áé")
#=> {:ok, ["áé"], "", %{}, {1, 0}, 3}
"""
@spec utf8_string(t, [range], pos_integer | [min_and_max]) :: t
def utf8_string(combinator \\ empty(), range, count_or_opts)
when is_combinator(combinator) and is_list(range) and
(is_integer(count_or_opts) or is_list(count_or_opts)) do
min_max_compile_runtime_chars(
combinator,
utf8_char(range),
count_or_opts,
:__compile_string__,
:__runtime_string__,
[quote(do: utf8)]
)
end
@doc ~S"""
Concatenates two combinators.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :digit_upper_lower_plus,
concat(
concat(ascii_char([?0..?9]), ascii_char([?A..?Z])),
concat(ascii_char([?a..?z]), ascii_char([?+..?+]))
)
end
MyParser.digit_upper_lower_plus("1Az+")
#=> {:ok, [?1, ?A, ?z, ?+], "", %{}, {1, 0}, 4}
"""
@spec concat(t, t) :: t
def concat(left, right) when is_combinator(left) and is_combinator(right) do
right ++ left
end
@doc """
Duplicates the combinator `to_duplicate` `n` times.
"""
@spec duplicate(t, t, non_neg_integer) :: t
def duplicate(combinator \\ empty(), to_duplicate, n)
def duplicate(combinator, to_duplicate, 0)
when is_combinator(combinator) and is_combinator(to_duplicate) do
empty()
end
def duplicate(combinator, to_duplicate, n)
when is_combinator(combinator) and is_combinator(to_duplicate) and is_integer(n) and n >= 1 do
Enum.reduce(1..n, combinator, fn _, acc -> to_duplicate ++ acc end)
end
@doc """
Puts the result of the given combinator as the first element
of a tuple with the `byte_offset` as second element.
`byte_offset` is a non-negative integer.
"""
@spec byte_offset(t, t) :: t
def byte_offset(combinator \\ empty(), to_wrap)
when is_combinator(combinator) and is_combinator(to_wrap) do
quoted_traverse(combinator, to_wrap, {__MODULE__, :__byte_offset__, []})
end
@doc """
Puts the result of the given combinator as the first element
of a tuple with the `line` as second element.
`line` is a tuple where the first element is the current line
and the second element is the byte offset immediately after
the newline.
"""
@spec line(t, t) :: t
def line(combinator \\ empty(), to_wrap)
when is_combinator(combinator) and is_combinator(to_wrap) do
quoted_traverse(combinator, to_wrap, {__MODULE__, :__line__, []})
end
@doc ~S"""
Traverses the combinator results with the remote or local function `call`.
`call` is either a `{module, function, args}` representing
a remote call, a `{function, args}` representing a local call
or an atom `function` representing `{function, []}`.
The function given in `call` will receive 5 additional arguments.
The rest of the parsed binary, the parser results to be traversed,
the parser context, the current line and the current offset will
be prepended to the given `args`. The `args` will be injected at
the compile site and therefore must be escapable via `Macro.escape/1`.
The `call` must return a tuple `{acc, context}` with list of results
to be added to the accumulator as first argument and a context as
second argument. It may also return `{:error, reason}` to stop
processing. Notice the received results are in reverse order and
must be returned in reverse order too.
The number of elements returned does not need to be
the same as the number of elements given.
This is a low-level function for changing the parsed result.
On top of this function, other functions are built, such as
`map/3` if you want to map over each individual element and
not worry about ordering, `reduce/3` to reduce all elements
into a single one, `replace/3` if you want to replace the
parsed result by a single value and `ignore/3` if you want to
ignore the parsed result.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :letters_to_chars,
ascii_char([?a..?z])
|> ascii_char([?a..?z])
|> ascii_char([?a..?z])
|> traverse({:join_and_wrap, ["-"]})
defp join_and_wrap(_rest, args, context, _line, _offset, joiner) do
{args |> Enum.join(joiner) |> List.wrap(), context}
end
end
MyParser.letters_to_chars("abc")
#=> {:ok, ["99-98-97"], "", %{}, {1, 0}, 3}
"""
@spec traverse(t, t, call) :: t
def traverse(combinator \\ empty(), to_traverse, call)
when is_combinator(combinator) and is_combinator(to_traverse) do
compile_call!([], call, "traverse")
quoted_traverse(combinator, to_traverse, {__MODULE__, :__traverse__, [call]})
end
@doc ~S"""
Looks ahead the rest of the binary to be parsed alongside the context.
`call` is either a `{module, function, args}` representing
a remote call, a `{function, args}` representing a local call
or an atom `function` representing `{function, []}`.
The function given in `call` will receive 4 additional arguments.
The rest of the parsed binary, the parser context, the current line
and the current offset will be prepended to the given `args`.
The `args` will be injected at the compile site and therefore must
be escapable via `Macro.escape/1`.
The `call` must return a tuple `{acc, context}` with list of results
to be added to the accumulator in reverse order as first argument
and a context as second argument. It may also return `{:error, reason}`
to stop processing.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :letters_no_zero,
ascii_char([?a..?z])
|> times(min: 3)
|> lookahead(:error_when_next_is_0)
defp error_when_next_is_0(<<?0, _::binary>>, context, _line, _offset) do
{:error, "next is 0"}
end
defp error_when_next_is_0(_rest, context, _line, _offset) do
{[], context}
end
end
MyParser.letters_no_zero("abc")
#=> {:ok, ["99-98-97"], "", %{}, {1, 0}, 3}
MyParser.letters_no_zero("abc1")
#=> {:ok, ["99-98-97"], "1", %{}, {1, 0}, 3}
MyParser.letters_no_zero("abc0")
#=> {:error, "next is zero", "0", %{}, {1, 0}, 3}
"""
@spec lookahead(t, call) :: t
def lookahead(combinator \\ empty(), call) when is_combinator(combinator) do
compile_call!([], call, "lookahead")
quoted_traverse(combinator, [], {__MODULE__, :__lookahead__, [call]})
end
@doc """
Invokes `call` to emit the AST that traverses the `to_traverse`
combinator results.
`call` is a `{module, function, args}` and it will receive 5
additional arguments. The AST representation of the rest of the
parsed binary, the parser results, context, line and offset will
be prepended to `args`. `call` is invoked at compile time and is
useful in combinators that avoid injecting runtime dependencies.
The `call` must return a list of results to be added to
the accumulator. Notice the received results are in reverse
order and must be returned in reverse order too.
The number of elements returned does not need to be
the same as the number of elements given.
"""
@spec quoted_traverse(t, t, mfargs) :: t
def quoted_traverse(combinator, to_traverse, {_, _, _} = call)
when is_combinator(combinator) and is_combinator(to_traverse) do
quoted_traverse(combinator, to_traverse, false, call)
end
@doc ~S"""
Maps over the combinator results with the remote or local function in `call`.
`call` is either a `{module, function, args}` representing
a remote call, a `{function, args}` representing a local call
or an atom `function` representing `{function, []}`.
Each parser result will be invoked individually for the `call`.
Each result be prepended to the given `args`. The `args` will
be injected at the compile site and therefore must be escapable
via `Macro.escape/1`.
See `traverse/3` for a low level version of this function.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :letters_to_string_chars,
ascii_char([?a..?z])
|> ascii_char([?a..?z])
|> ascii_char([?a..?z])
|> map({Integer, :to_string, []})
end
MyParser.letters_to_string_chars("abc")
#=> {:ok, ["97", "98", "99"], "", %{}, {1, 0}, 3}
"""
@spec map(t, t, call) :: t
def map(combinator \\ empty(), to_map, call)
when is_combinator(combinator) and is_combinator(to_map) do
var = Macro.var(:var, __MODULE__)
call = compile_call!([var], call, "map")
quoted_traverse(combinator, to_map, {__MODULE__, :__map__, [var, call]})
end
@doc ~S"""
Reduces over the combinator results with the remote or local function in `call`.
`call` is either a `{module, function, args}` representing
a remote call, a `{function, args}` representing a local call
or an atom `function` representing `{function, []}`.
The parser results to be reduced will be prepended to the
given `args`. The `args` will be injected at the compile site
and therefore must be escapable via `Macro.escape/1`.
See `traverse/3` for a low level version of this function.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :letters_to_reduced_chars,
ascii_char([?a..?z])
|> ascii_char([?a..?z])
|> ascii_char([?a..?z])
|> reduce({Enum, :join, ["-"]})
end
MyParser.letters_to_reduced_chars("abc")
#=> {:ok, ["97-98-99"], "", %{}, {1, 0}, 3}
"""
@spec reduce(t, t, call) :: t
def reduce(combinator \\ empty(), to_reduce, call)
when is_combinator(combinator) and is_combinator(to_reduce) do
compile_call!([], call, "reduce")
quoted_traverse(combinator, to_reduce, {__MODULE__, :__reduce__, [call]})
end
@doc """
Wraps the results of the given combinator in `to_wrap` in a list.
"""
@spec wrap(t, t) :: t
def wrap(combinator \\ empty(), to_wrap)
when is_combinator(combinator) and is_combinator(to_wrap) do
quoted_traverse(combinator, to_wrap, {__MODULE__, :__wrap__, []})
end
@doc """
Tags the result of the given combinator in `to_tag` in a tuple with
`tag` as first element.
"""
@spec tag(t, t) :: t
def tag(combinator \\ empty(), to_tag, tag)
when is_combinator(combinator) and is_combinator(to_tag) do
quoted_traverse(combinator, to_tag, {__MODULE__, :__tag__, [Macro.escape(tag)]})
end
@doc """
Inspects the combinator state given to `to_debug` with the given `opts`.
"""
@spec debug(t, t) :: t
def debug(combinator \\ empty(), to_debug)
when is_combinator(combinator) and is_combinator(to_debug) do
quoted_traverse(combinator, to_debug, {__MODULE__, :__debug__, []})
end
@doc ~S"""
Defines a string binary value.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :string_t, string("T")
end
MyParser.string_t("T")
#=> {:ok, ["T"], "", %{}, {1, 0}, 1}
MyParser.string_t("not T")
#=> {:error, "expected a string \"T\"", "not T", %{}, {1, 0}, 0}
"""
@spec string(t, binary) :: t
def string(combinator \\ empty(), binary)
when is_combinator(combinator) and is_binary(binary) do
[{:string, binary} | combinator]
end
@doc """
Ignores the output of combinator given in `to_ignore`.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :ignorable, string("T") |> ignore() |> integer(2, 2)
end
MyParser.ignorable("T12")
#=> {:ok, [12], "", %{}, {1, 0}, 2}
"""
@spec ignore(t, t) :: t
def ignore(combinator \\ empty(), to_ignore)
when is_combinator(combinator) and is_combinator(to_ignore) do
if to_ignore == empty() do
to_ignore
else
quoted_traverse(combinator, to_ignore, true, {__MODULE__, :__constant__, [[]]})
end
end
@doc """
Replaces the output of combinator given in `to_replace` by a single value.
The `value` will be injected at the compile site
and therefore must be escapable via `Macro.escape/1`.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :replaceable, string("T") |> replace("OTHER") |> integer(2, 2)
end
MyParser.replaceable("T12")
#=> {:ok, ["OTHER", 12], "", %{}, {1, 0}, 2}
"""
@spec replace(t, t, term) :: t
def replace(combinator \\ empty(), to_replace, value)
when is_combinator(combinator) and is_combinator(to_replace) do
value = Macro.escape(value)
quoted_traverse(combinator, to_replace, true, {__MODULE__, :__constant__, [[value]]})
end
@doc """
Allow the combinator given on `to_repeat` to appear zero or more times.
Beware! Since `repeat/2` allows zero entries, it cannot be used inside
`choice/2`, because it will always succeed and may lead to unused function
warnings since any further choice won't ever be attempted. For example,
because `repeat/2` always succeeds, the `string/2` combinator below it
won't ever run:
choice([
repeat(ascii_char([?a..?z])),
string("OK")
])
Instead of `repeat/2`, you may want to use `times/3` with the flags `:min`
and `:max`.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :repeat_lower, repeat(ascii_char([?a..?z]))
end
MyParser.repeat_lower("abcd")
#=> {:ok, [?a, ?b, ?c, ?d], "", %{}, {1, 0}, 4}
MyParser.repeat_lower("1234")
#=> {:ok, [], "1234", %{}, {1, 0}, 0}
"""
@spec repeat(t, t) :: t
def repeat(combinator \\ empty(), to_repeat)
when is_combinator(combinator) and is_combinator(to_repeat) do
non_empty!(to_repeat, "repeat")
quoted_repeat_while(combinator, to_repeat, {__MODULE__, :__cont_context__, []})
end
@doc ~S"""
Repeats while the given remote or local function `while` returns
`{:cont, context}`.
In case repetition should stop, `while` must return `{:halt, context}`.
`while` is either a `{module, function, args}` representing
a remote call, a `{function, args}` representing a local call
or an atom `function` representing `{function, []}`.
The function given in `while` will receive 4 additional arguments.
The `rest` of the binary to be parsed, the parser context, the
current line and the current offset will be prepended to the
given `args`. The `args` will be injected at the compile site
and therefore must be escapable via `Macro.escape/1`.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :string_with_quotes,
ascii_char([?"])
|> repeat_while(
choice([
~S(\") |> string() |> replace(?"),
utf8_char([])
]),
{:not_quote, []}
)
|> ascii_char([?"])
|> reduce({List, :to_string, []})
defp not_quote(<<?", _::binary>>, context, _, _), do: {:halt, context}
defp not_quote(_, context, _, _), do: {:cont, context}
end
MyParser.string_with_quotes(~S("string with quotes \" inside"))
{:ok, ["\"string with quotes \" inside\""], "", %{}, {1, 0}, 30}
"""
@spec repeat_while(t, t, call) :: t
def repeat_while(combinator \\ empty(), to_repeat, while)
when is_combinator(combinator) and is_combinator(to_repeat) do
non_empty!(to_repeat, "repeat_while")
compile_call!([], while, "repeat_while")
quoted_repeat_while(combinator, to_repeat, {__MODULE__, :__repeat_while__, [while]})
end
@doc ~S"""
Repeats `to_repeat` until one of the combinators in `choices` match.
Each of the combinators given in choice must be optimizable into
a single pattern, otherwise this function will refuse to compile.
Use `repeat_while/3` for a general mechanism for repeating.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :string_with_quotes,
ascii_char([?"])
|> repeat_until(
choice([
~S(\") |> string() |> replace(?"),
utf8_char([])
]),
[ascii_char([?"])]
)
|> ascii_char([?"])
|> reduce({List, :to_string, []})
end
MyParser.string_with_quotes(~S("string with quotes \" inside"))
{:ok, ["\"string with quotes \" inside\""], "", %{}, {1, 0}, 30}
"""
@spec repeat_until(t, t, [t]) :: t
def repeat_until(combinator \\ empty(), to_repeat, [_ | _] = choices)
when is_combinator(combinator) and is_combinator(to_repeat) and is_list(choices) do
non_empty!(to_repeat, "repeat_until")
clauses = check_until_choices!(choices)
quoted_repeat_while(combinator, to_repeat, {__MODULE__, :__repeat_until__, [clauses]})
end
@doc """
Invokes `while` to emit the AST that will repeat `to_repeat`
while the AST code returns `{:cont, context}`.
In case repetition should stop, `while` must return `{:halt, context}`.
`while` is a `{module, function, args}` and it will receive 4
additional arguments. The AST representations of the binary to be
parsed, context, line and offset will be prended to `args`. `while`
is invoked at compile time and is useful in combinators that avoid
injecting runtime dependencies.
"""
@spec quoted_repeat_while(t, t, mfargs) :: t
def quoted_repeat_while(combinator \\ empty(), to_repeat, {_, _, _} = while)
when is_combinator(combinator) and is_combinator(to_repeat) do
non_empty!(to_repeat, "quoted_repeat_while")
[{:repeat, Enum.reverse(to_repeat), while} | combinator]
end
@doc """
Allow the combinator given on `to_repeat` to appear at least, at most
or exactly a given amout of times.
## Examples
defmodule MyParser do
import NimbleParsec
defparsec :minimum_lower, times(ascii_char([?a..?z]), min: 2)
end
MyParser.minimum_lower("abcd")
#=> {:ok, [?a, ?b, ?c, ?d], "", %{}, {1, 0}, 4}
MyParser.minimum_lower("ab12")
#=> {:ok, [?a, ?b], "12", %{}, {1, 0}, 2}
MyParser.minimum_lower("a123")
#=> {:ok, [], "a123", %{}, {1, 0}, 0}
"""
@spec times(t, t, pos_integer | [min_and_max]) :: t
def times(combinator \\ empty(), to_repeat, count_or_min_max)
def times(combinator, to_repeat, n)
when is_combinator(combinator) and is_combinator(to_repeat) and is_integer(n) and n >= 1 do
non_empty!(to_repeat, "times")
duplicate(combinator, to_repeat, n)
end
def times(combinator, to_repeat, opts)
when is_combinator(combinator) and is_combinator(to_repeat) and is_list(opts) do
{min, max} = validate_min_and_max!(opts)
non_empty!(to_repeat, "times")
combinator =
if min > 0 do
duplicate(combinator, to_repeat, min)
else
combinator
end
to_repeat = Enum.reverse(to_repeat)
combinator =
if max do
[{:times, to_repeat, 0, max - min} | combinator]
else
[{:repeat, to_repeat, @cont_context} | combinator]
end
combinator
end
@doc """
Chooses one of the given combinators.
Expects at leasts two choices.
## Beware! Char combinators
Note both `utf8_char/2` and `ascii_char/2` allow multiple ranges to
be given. Therefore, instead this:
choice([
ascii_char([?a..?z]),
ascii_char([?A..?Z]),
])
One should simply prefer:
ascii_char([?a..?z, ?A..?Z])
As the latter is compiled more efficiently by `NimbleParser`.
## Beware! Always successful combinators
If a combinator that always succeeds is given as a choice, that choice
will always succeed which may lead to unused function warnings since
any further choice won't ever be attempted. For example, because `repeat/2`
always succeeds, the `string/2` combinator below it won't ever run:
choice([
repeat(ascii_char([?0..?9])),
string("OK")
])
Instead of `repeat/2`, you may want to use `times/3` with the flags `:min`
and `:max`.
"""
@spec choice(t, t) :: t
def choice(combinator \\ empty(), [_, _ | _] = choices) when is_combinator(combinator) do
choices = Enum.map(choices, &Enum.reverse/1)
[{:choice, choices} | combinator]
end
@doc """
Marks the given combinator as `optional`.
It is equivalent to `choice([optional, empty()])`.
"""
@spec optional(t, t) :: t
def optional(combinator \\ empty(), optional) do
choice(combinator, [optional, empty()])
end
## Helpers
defp validate_min_and_max!(opts) do
min = opts[:min]
max = opts[:max]
cond do
min && max ->
validate_min_or_max!(:min, min)
validate_min_or_max!(:max, max)
max <= min and
raise ArgumentError,
"expected :max to be strictly more than :min, got: #{min} and #{max}"
min ->
validate_min_or_max!(:min, min)
max ->
validate_min_or_max!(:max, max)
true ->
raise ArgumentError, "expected :min or :max to be given"
end
{min || 0, max}
end
defp validate_min_or_max!(kind, value) do
unless is_integer(value) and value >= 1 do
raise ArgumentError, "expected #{kind} to be an integer more than 1, got: #{inspect(value)}"
end
end
defp split_ranges!(ranges, context) do
Enum.split_with(ranges, &split_range!(&1, context))
end
defp split_range!(x, _context) when is_integer(x), do: true
defp split_range!(_.._, _context), do: true
defp split_range!({:not, x}, _context) when is_integer(x), do: false
defp split_range!({:not, _.._}, _context), do: false
defp split_range!(range, context) do
raise ArgumentError, "unknown range #{inspect(range)} given to #{context}"
end
defp compile_call!(extra, {module, function, args}, _context)
when is_atom(module) and is_atom(function) and is_list(args) do
quote do
unquote(module).unquote(function)(
unquote_splicing(extra),
unquote_splicing(Macro.escape(args))
)
end
end
defp compile_call!(extra, {function, args}, _context)
when is_atom(function) and is_list(args) do
quote do
unquote(function)(unquote_splicing(extra), unquote_splicing(Macro.escape(args)))
end
end
defp compile_call!(extra, function, _context) when is_atom(function) do
quote do
unquote(function)(unquote_splicing(extra))
end
end
defp compile_call!(_args, unknown, context) do
raise ArgumentError, "unknown call given to #{context}, got: #{inspect(unknown)}"
end
defp non_empty!([], action),
do: raise(ArgumentError, "cannot call #{action} on empty combinator")
defp non_empty!(combinator, _action), do: combinator
defp check_until_choices!(choices) do
for choice <- choices do
if choice == [] do
raise "cannot pass empty combinator as choice in repeat_until"
end
case NimbleParsec.Compiler.compile_pattern(choice) do
{_inputs, _guards} = pair -> pair
:error -> raise "cannot compile combinator as choice given in repeat_until"
end
end
end
## Inner combinators
defp quoted_traverse(combinator, to_traverse, constant?, call) do
case to_traverse do
[{:traverse, inner_traverse, inner_constant?, inner_call}] ->
constant? = inner_constant? and constant?
[{:traverse, inner_traverse, constant?, [call | inner_call]} | combinator]
_ ->
[{:traverse, Enum.reverse(to_traverse), constant?, [call]} | combinator]
end
end
defp bin_segment(combinator, inclusive, exclusive, [_ | _] = modifiers) do
[{:bin_segment, inclusive, exclusive, modifiers} | combinator]
end
## Traverse callbacks
@doc false
def __traverse__(rest, acc, context, line, offset, call) do
compile_call!([rest, acc, context, line, offset], call, "traverse")
end
@doc false
def __lookahead__(rest, _acc, context, line, offset, call) do
compile_call!([rest, context, line, offset], call, "lookahead")
end
@doc false
def __wrap__(_rest, acc, context, _line, _offset) do
{[reverse_now_or_later(acc)], context}
end
@doc false
def __tag__(_rest, acc, context, _line, _offset, tag) do
{[{tag, reverse_now_or_later(acc)}], context}
end
@doc false
def __debug__(rest, acc, context, line, offset) do
quote bind_quoted: [rest: rest, acc: acc, context: context, line: line, offset: offset] do
IO.puts("""
== DEBUG ==
Bin: #{inspect(rest)}
Acc: #{inspect(:lists.reverse(acc))}
Ctx: #{inspect(context)}
Lin: #{inspect(line)}
Off: #{inspect(offset)}
""")
{acc, context}
end
end
@doc false
def __constant__(_rest, _acc, context, _line, _offset, constant) do
{constant, context}
end
@doc false
def __line__(_rest, acc, context, line, _offset) do
{[{reverse_now_or_later(acc), line}], context}
end
@doc false
def __byte_offset__(_rest, acc, context, _line, offset) do
{[{reverse_now_or_later(acc), offset}], context}
end
@doc false
def __map__(_rest, acc, context, _line, _offset, var, call) do
ast =
quote do
Enum.map(unquote(acc), fn unquote(var) -> unquote(call) end)
end
{ast, context}
end
@doc false
def __reduce__(_rest, acc, context, _line, _offset, call) do
{[compile_call!([reverse_now_or_later(acc)], call, "reduce")], context}
end
## Repeat callbacks
@doc false
def __cont_context__(_rest, context, _line, _offset) do
{:cont, context}
end
@doc false
def __repeat_while__(quoted, context, line, offset, call) do
compile_call!([quoted, context, line, offset], call, "repeat_while")
end
@doc false
def __repeat_until__(rest, context, _line, _offset, clauses) do
clauses =
for {inputs, guards} <- clauses do
hd(
quote do
<<unquote_splicing(inputs), _::binary>> when unquote(guards) ->
{:halt, unquote(context)}
end
)
end
clauses = clauses ++ quote(do: (_ -> {:cont, unquote(context)}))
quote do
case unquote(rest), do: unquote(clauses)
end
end
## Chars callbacks
defp min_max_compile_runtime_chars(combinator, to_repeat, count, compile, _runtime, args)
when is_integer(count) and count > 0 do
chars = duplicate(to_repeat, count)
quoted_traverse(combinator, chars, {__MODULE__, compile, [count | args]})
end
defp min_max_compile_runtime_chars(combinator, to_repeat, opts, compile, runtime, args)
when is_list(opts) do
{min, max} = validate_min_and_max!(opts)
chars =
if min > 0 do
min_max_compile_runtime_chars(empty(), to_repeat, min, compile, runtime, args)
else
empty()
end
chars =
if max do
times(chars, to_repeat, max: max - min)
else
repeat(chars, to_repeat)
end
quoted_traverse(combinator, chars, {__MODULE__, runtime, [min, max | args]})
end
@doc false
def __runtime_string__(_rest, acc, context, _line, _offset, _min, _max, _type) do
ast = quote(do: List.to_string(unquote(reverse_now_or_later(acc))))
{[ast], context}
end
@doc false
def __compile_string__(_rest, acc, context, _line, _offset, _count, type) when is_list(acc) do
acc =
for entry <- :lists.reverse(acc) do
{:::, [], [entry, type]}
end
{[{:<<>>, [], acc}], context}
end
@doc false
def __runtime_integer__(_rest, acc, context, _line, _offset, min, _max)
when is_integer(min) and min > 0 do
ast =
quote do
[head | tail] = unquote(reverse_now_or_later(acc))
[:lists.foldl(fn x, acc -> x - ?0 + acc * 10 end, head, tail)]
end
{ast, context}
end
def __runtime_integer__(_rest, acc, context, _line, _offset, _min, _max) do
ast =
quote do
[head | tail] = unquote(reverse_now_or_later(acc))
[:lists.foldl(fn x, acc -> x - ?0 + acc * 10 end, head - ?0, tail)]
end
{ast, context}
end
@doc false
def __compile_integer__(_rest, acc, context, _line, _offset, _count) when is_list(acc) do
ast =
acc
|> quoted_ascii_to_integer(1)
|> Enum.reduce(&{:+, [], [&2, &1]})
{[ast], context}
end
defp reverse_now_or_later(list) when is_list(list), do: :lists.reverse(list)
defp reverse_now_or_later(expr), do: quote(do: :lists.reverse(unquote(expr)))
defp quoted_ascii_to_integer([var | vars], index) do
[quote(do: (unquote(var) - ?0) * unquote(index)) | quoted_ascii_to_integer(vars, index * 10)]
end
defp quoted_ascii_to_integer([], _index) do
[]
end
end
| 30.260138 | 119 | 0.630847 |
03f5357b2f83876cb9efa64a3a000ba12e9c58bd | 650 | ex | Elixir | lib/azure_functions_base.ex | imahiro-t/azure_functions_base | 27afa5573ba0c35570c921d8193a3980e2655c07 | [
"MIT"
] | null | null | null | lib/azure_functions_base.ex | imahiro-t/azure_functions_base | 27afa5573ba0c35570c921d8193a3980e2655c07 | [
"MIT"
] | null | null | null | lib/azure_functions_base.ex | imahiro-t/azure_functions_base | 27afa5573ba0c35570c921d8193a3980e2655c07 | [
"MIT"
] | null | null | null | defmodule AzureFunctionsBase do
@moduledoc """
This is azure functions base.
Use AzureFunctionsBase and implement `handle(request, event, context)` function
"""
alias AzureFunctionsBase.Request
alias AzureFunctionsBase.Response
@doc """
Azure runtime call init function.
"""
@callback init(context :: map()) :: :ok
@doc """
Azure runtime call handle function.
"""
@callback handle(request :: Request.t, event :: map(), context :: map()) :: {:ok, Response.t} | {:ok, String.t} | {:error, Response.t} | {:error, String.t}
defmacro __using__(_opts) do
quote do
@behaviour AzureFunctionsBase
end
end
end
| 25 | 157 | 0.672308 |
03f53e1fb833a50d181874d600fede37b80505d8 | 643 | exs | Elixir | config/test.exs | drdean/jelly | 44ca6d90e0c7ce62ccd458795f54dac4d10e8cfc | [
"MIT"
] | null | null | null | config/test.exs | drdean/jelly | 44ca6d90e0c7ce62ccd458795f54dac4d10e8cfc | [
"MIT"
] | null | null | null | config/test.exs | drdean/jelly | 44ca6d90e0c7ce62ccd458795f54dac4d10e8cfc | [
"MIT"
] | null | null | null | use Mix.Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :jelly_board, JellyBoard.Endpoint,
http: [port: 4001],
server: true
# Print only warnings and errors during test
config :logger, level: :warn
# Configure your database
config :jelly_board, JellyBoard.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
database: "jelly_board_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
# Guardian configuration
config :guardian, Guardian,
secret_key: "W9cDv9fjPtsYv2gItOcFb5PzmRzqGkrOsJGmby0KpBOlHJIlhxMKFmIlcCG9PVFQ"
| 26.791667 | 80 | 0.768274 |
03f5645f59088213f42cd975917132731d4fd566 | 7,360 | ex | Elixir | apps/massa_proxy/lib/massa_proxy/server/grpc_server.ex | eigr/massa | 508a2694905a74e0e613552241a578e70ba356a0 | [
"Apache-2.0"
] | 20 | 2021-06-28T12:03:49.000Z | 2022-03-28T22:35:56.000Z | apps/massa_proxy/lib/massa_proxy/server/grpc_server.ex | eigr/massa | 508a2694905a74e0e613552241a578e70ba356a0 | [
"Apache-2.0"
] | 48 | 2021-03-19T12:01:38.000Z | 2022-03-29T21:19:26.000Z | apps/massa_proxy/lib/massa_proxy/server/grpc_server.ex | eigr/massa | 508a2694905a74e0e613552241a578e70ba356a0 | [
"Apache-2.0"
] | 5 | 2021-03-18T21:46:10.000Z | 2021-10-01T17:39:05.000Z | defmodule MassaProxy.Server.GrpcServer do
@moduledoc false
require Logger
alias MassaProxy.{Util, Infra.Cache, Server.HttpRouter}
alias MassaProxy.Infra.Cache.Distributed
def start(descriptors, entities) do
case Cache.get(:cached_servers, :grpc) do
nil -> start_grpc(descriptors, entities)
_ -> Logger.debug("gRPC Server already started")
end
end
defp start_grpc(descriptors, entities) do
{u_secs, _} =
:timer.tc(fn ->
with {:ok, descriptors} <- descriptors |> compile(),
{:ok, _} <- generate_services(entities),
{:ok, _} <- generate_endpoints(entities) do
start_proxy(descriptors, entities)
else
_ -> Logger.error("Error during gRPC Server initialization")
end
:ok
end)
Logger.info("Started gRPC Server in #{u_secs / 1_000_000}ms")
end
defp compile(descriptors) do
files =
descriptors
|> MassaProxy.Reflection.prepare()
for {name, file} <- files do
if has_compiled?(file) do
Logger.debug("Getting cached file: #{name}")
modules =
file
|> get_hash()
|> Distributed.get()
Enum.map(modules, fn mod ->
case :code.load_binary(mod.module, String.to_charlist(mod.file_name), mod.bytecode) do
{:module, module} ->
Logger.debug("Module #{module} loaded from cache")
{:module, module}
{:error, cause} ->
Logger.error("Failed to load module #{mod.module} from cache. #{inspect(cause)}")
{:error, cause}
end
end)
else
case Util.compile(file) do
modules when is_list(modules) ->
Logger.debug("Caching file: #{name}")
modules
|> do_cache(name, file)
_ ->
Logger.debug("Fail to compile service")
end
end
end
{:ok, descriptors}
end
defp has_compiled?(file) do
file
|> get_hash()
|> Distributed.has_key?()
end
defp get_hash(file),
do:
:md5
|> :crypto.hash(file)
|> Base.encode16()
defp do_cache(modules, name, file) do
list =
Stream.map(modules, fn {mod_name, bytecode} ->
%{module: mod_name, bytecode: bytecode, file_name: name}
end)
|> Enum.to_list()
file
|> get_hash()
|> Distributed.put(list)
end
defp generate_services(entities) do
root_template_path =
Application.get_env(
:massa_proxy,
:proxy_root_template_path,
:code.priv_dir(:massa_proxy)
)
grpc_template_path =
Path.expand(
"./templates/grpc_service.ex.eex",
root_template_path
)
for entity <- entities do
name = Enum.join([Util.normalize_service_name(entity.service_name), "Service"], ".")
Stream.map(entity.services, fn service ->
methods =
service.methods
|> Flow.from_enumerable()
|> Flow.map(&Util.normalize_method_name(&1.name))
|> Enum.to_list()
Logger.info("Generating Service #{name} with Methods: #{inspect(methods)}")
original_methods = get_method_names(service)
input_types = get_input_type(service)
output_types = get_output_type(service)
request_types = get_request_type(service)
mod =
Util.get_module(
grpc_template_path,
mod_name: name,
name: name,
methods: methods,
original_methods: original_methods,
handler: "MassaProxy.Runtime.Grpc.Server.Dispatcher",
entity_type: entity.entity_type,
persistence_id: entity.persistence_id,
service_name: entity.service_name,
input_types: input_types,
output_types: output_types,
request_types: request_types
)
Logger.debug("Service Definition:\n#{mod}")
Util.compile(mod)
Logger.debug("Service compilation finish!")
end)
|> Stream.run()
end
{:ok, entities}
end
defp generate_endpoints(entities) do
root_template_path =
Application.get_env(
:massa_proxy,
:proxy_root_template_path,
:code.priv_dir(:massa_proxy)
)
grpc_endpoint_template_path =
Path.expand(
"./templates/grpc_endpoint.ex.eex",
root_template_path
)
services =
entities
|> Flow.from_enumerable()
|> Flow.map(
&Enum.join([Util.normalize_service_name(&1.service_name), "Service.ProxyService"], ".")
)
|> Enum.to_list()
mod =
Util.get_module(
grpc_endpoint_template_path,
service_names: services
)
Logger.debug("Endpoint Definition:\n#{mod}")
Util.compile(mod)
Logger.debug("Endpoint compilation finish!")
{:ok, entities}
end
defp start_proxy(descriptors, entities) do
Logger.info("Starting gRPC Server...")
Application.put_env(:grpc, :start_server, true, persistent: true)
opts = get_grpc_options()
grpc_spec = {GRPC.Server.Supervisor, opts}
http_spec = HttpRouter.child_spec(entities)
reflection_spec = MassaProxy.Reflection.Server.child_spec(descriptors)
with {:ok, _} <- DynamicSupervisor.start_child(MassaProxy.LocalSupervisor, grpc_spec),
{:ok, _} <- DynamicSupervisor.start_child(MassaProxy.LocalSupervisor, http_spec),
{:ok, _} <- DynamicSupervisor.start_child(MassaProxy.LocalSupervisor, reflection_spec) do
Cache.put(:cached_servers, :grpc, true)
end
end
defp get_grpc_options() do
port = Application.get_env(:massa_proxy, :proxy_port)
if Application.get_env(:massa_proxy, :tls) do
cert_path = Application.get_env(:massa_proxy, :tls_cert_path)
key_path = Application.get_env(:massa_proxy, :tls_key_path)
cred = GRPC.Credential.new(ssl: [certfile: cert_path, keyfile: key_path])
{Massa.Server.Grpc.ProxyEndpoint, port, cred: cred}
else
{Massa.Server.Grpc.ProxyEndpoint, port}
end
end
defp get_method_names(services),
do:
Enum.reduce(services.methods, %{}, fn method, acc ->
Map.put(
acc,
Util.normalize_method_name(method.name),
method.name
)
end)
defp get_input_type(services),
do:
Enum.reduce(services.methods, %{}, fn method, acc ->
Map.put(
acc,
Util.normalize_method_name(method.name),
String.replace_leading(Util.normalize_service_name(method.input_type), ".", "")
)
end)
defp get_output_type(services),
do:
Enum.reduce(services.methods, %{}, fn method, acc ->
Map.put(
acc,
Util.normalize_method_name(method.name),
String.replace_leading(Util.normalize_service_name(method.output_type), ".", "")
)
end)
defp get_request_type(services),
do:
Enum.reduce(services.methods, %{}, fn method, acc ->
Map.put(acc, Util.normalize_method_name(method.name), get_type(method))
end)
defp get_type(method) do
type =
cond do
method.unary == true -> "unary"
method.streamed == true -> "streamed"
method.stream_in == true -> "stream_in"
method.stream_out == true -> "stream_out"
end
type
end
end
| 27.462687 | 98 | 0.609103 |
03f565b7eaaafd368b22e27df0a07a8af665ca18 | 1,176 | exs | Elixir | config/config.exs | DrPandemic/expressive-broker | 66a8da94ede2c101db9e1841e17898b5bae5df49 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | null | null | null | config/config.exs | DrPandemic/expressive-broker | 66a8da94ede2c101db9e1841e17898b5bae5df49 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | null | null | null | config/config.exs | DrPandemic/expressive-broker | 66a8da94ede2c101db9e1841e17898b5bae5df49 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
# General application configuration
use Mix.Config
config :wow,
ecto_repos: [Wow.Repo]
# Configures the endpoint
config :wow, WowWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "WaBt9EuHBtPYSt/1vNGqf8msGO/aYFs0gwHyX/fQXpxjXPcB4YHXtkTtEDVKhRuW",
render_errors: [view: WowWeb.ErrorView, accepts: ~w(html json)],
pubsub: [name: Wow.PubSub, adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"
# Tesla
config :tesla, :adapter, Tesla.Adapter.Hackney
# Quantum
config :wow, Wow.Scheduler,
jobs: [
# Every minute
{"0 * * * *", fn -> Wow.Jobs.Scheduler.schedule() end},
]
| 28.682927 | 86 | 0.735544 |
03f58d676e84ab0e584579d7f489a6b4a07963d2 | 336 | exs | Elixir | apps/alert_processor/priv/repo/migrations/20170426151933_add_timeframe_info_to_subscriptions.exs | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | null | null | null | apps/alert_processor/priv/repo/migrations/20170426151933_add_timeframe_info_to_subscriptions.exs | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | 21 | 2021-03-12T17:05:30.000Z | 2022-02-16T21:48:35.000Z | apps/alert_processor/priv/repo/migrations/20170426151933_add_timeframe_info_to_subscriptions.exs | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | 1 | 2021-12-09T15:09:53.000Z | 2021-12-09T15:09:53.000Z | defmodule MbtaServer.Repo.Migrations.AddTimeframeInfoToSubscriptions do
use Ecto.Migration
def change do
alter table(:subscriptions, primary_key: false) do
add :relevant_days, {:array, :string}, null: false, default: []
add :start_time, :time, null: false
add :end_time, :time, null: false
end
end
end
| 25.846154 | 71 | 0.702381 |
03f5b972a495305d43a2e20cf36fcc77ceafa652 | 1,029 | ex | Elixir | lib/widget_saas/endpoint.ex | Dania02525/widget_saas | 17b853f07be08a851c3e355863c18e15755cb7cb | [
"MIT"
] | 12 | 2016-01-27T01:30:42.000Z | 2019-12-07T20:31:01.000Z | lib/widget_saas/endpoint.ex | Dania02525/widget_saas | 17b853f07be08a851c3e355863c18e15755cb7cb | [
"MIT"
] | 3 | 2016-11-22T12:22:59.000Z | 2017-08-01T17:26:40.000Z | lib/widget_saas/endpoint.ex | Dania02525/widget_saas | 17b853f07be08a851c3e355863c18e15755cb7cb | [
"MIT"
] | 5 | 2016-07-11T18:39:02.000Z | 2019-10-23T03:22:49.000Z | defmodule WidgetSaas.Endpoint do
use Phoenix.Endpoint, otp_app: :widget_saas
socket "/socket", WidgetSaas.UserSocket
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phoenix.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/", from: :widget_saas, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session,
store: :cookie,
key: "_widget_saas_key",
signing_salt: "LVh8Ee+X"
plug WidgetSaas.Router
end
| 25.725 | 69 | 0.714286 |
03f5c03cffaca7a06cfdfb790999a365fc2e847f | 23,527 | ex | Elixir | test/support/factory.ex | cmschuetz/dwolla-elixir | 5087ace13341881d293a6ac87e82dfad9880d8c4 | [
"MIT"
] | null | null | null | test/support/factory.ex | cmschuetz/dwolla-elixir | 5087ace13341881d293a6ac87e82dfad9880d8c4 | [
"MIT"
] | null | null | null | test/support/factory.ex | cmschuetz/dwolla-elixir | 5087ace13341881d293a6ac87e82dfad9880d8c4 | [
"MIT"
] | null | null | null | defmodule Dwolla.Factory do
@moduledoc false
def http_response_body(:token) do
%{
access_token: "0l6Vijvre4ICDV9SltG3KbekbtrGOPoQcP5XITsEKWH5L5me0S",
token_type: "bearer",
expires_in: 3601
}
end
def http_response_body(:error) do
%{
code: "ValidationError",
message: "Validation error(s) present. See embedded errors list for more details.",
_embedded: %{
errors: [
%{
code: "Required",
message: "FirstName is required.",
path: "/firstName",
}
]
}
}
end
def http_response_body(:customer, :update) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/customers/b2cf497a-b315-497e-95b7-d1238288f8cb\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"receive\":{\"href\":\"https://api-sandbox.dwolla.com/transfers\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"},\"edit-form\":{\"href\":\"https://api-sandbox.dwolla.com/customers/b2cf497a-b315-497e-95b7-d1238288f8cb\",\"type\":\"application/vnd.dwolla.v1.hal+json; profile=\\\"https://github.com/dwolla/hal-forms\\\"\",\"resource-type\":\"customer\"},\"edit\":{\"href\":\"https://api-sandbox.dwolla.com/customers/b2cf497a-b315-497e-95b7-d1238288f8cb\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"funding-sources\":{\"href\":\"https://api-sandbox.dwolla.com/customers/b2cf497a-b315-497e-95b7-d1238288f8cb/funding-sources\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"},\"transfers\":{\"href\":\"https://api-sandbox.dwolla.com/customers/b2cf497a-b315-497e-95b7-d1238288f8cb/transfers\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"},\"send\":{\"href\":\"https://api-sandbox.dwolla.com/transfers\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"}},\"id\":\"b2cf497a-b315-497e-95b7-d1238288f8cb\",\"firstName\":\"Will\",\"lastName\":\"Gilman\",\"email\":\"will@example.com\",\"type\":\"personal\",\"status\":\"verified\",\"created\":\"2017-03-15T20:46:33.330Z\",\"address1\":\"2340 Chicago St\",\"address2\":\"Apt 3\",\"city\":\"Bodega Bay\",\"state\":\"CA\",\"postalCode\":\"94923\",\"phone\":\"0987654321\"}"
end
def http_response_body(:customer, :suspend) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/customers/e5101b1f-f582-4162-b0bd-c2c464f4e741\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"}},\"id\":\"e5101b1f-f582-4162-b0bd-c2c464f4e741\",\"firstName\":\"Bob\",\"lastName\":\"Costco\",\"email\":\"bob@costco.com\",\"type\":\"unverified\",\"status\":\"suspended\",\"created\":\"2016-10-10T20:31:59.820Z\"}"
end
def http_response_body(:customer, :get) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"receive\":{\"href\":\"https://api-sandbox.dwolla.com/transfers\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"},\"edit-form\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json; profile=\\\"https://github.com/dwolla/hal-forms\\\"\",\"resource-type\":\"customer\"},\"edit\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"funding-sources\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44/funding-sources\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"},\"transfers\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44/transfers\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"},\"send\":{\"href\":\"https://api-sandbox.dwolla.com/transfers\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"}},\"id\":\"a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"firstName\":\"Ben\",\"lastName\":\"Franklin\",\"email\":\"ben.franklin@usaog.com\",\"type\":\"personal\",\"status\":\"verified\",\"created\":\"2016-10-10T21:12:03.577Z\",\"address1\":\"99-99 33rd St\",\"city\":\"some city\",\"state\":\"NY\",\"postalCode\":\"11101\",\"phone\":\"8008881776\"}"
end
def http_response_body(:customer, :search) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/customers?search=ben.franklin@usaog.com\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"first\":{\"href\":\"https://api-sandbox.dwolla.com/customers?search=ben.franklin@usaog.com&limit=25&offset=0\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"last\":{\"href\":\"https://api-sandbox.dwolla.com/customers?search=ben.franklin@usaog.com&limit=25&offset=0\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"}},\"_embedded\":{\"customers\":[{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"receive\":{\"href\":\"https://api-sandbox.dwolla.com/transfers\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"},\"edit-form\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json; profile=\\\"https://github.com/dwolla/hal-forms\\\"\",\"resource-type\":\"customer\"},\"edit\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"funding-sources\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44/funding-sources\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"},\"transfers\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44/transfers\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"},\"send\":{\"href\":\"https://api-sandbox.dwolla.com/transfers\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"}},\"id\":\"a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"firstName\":\"Ben\",\"lastName\":\"Franklin\",\"email\":\"ben.franklin@usaog.com\",\"type\":\"personal\",\"status\":\"verified\",\"created\":\"2016-10-10T21:12:03.577Z\",\"address1\":\"99-99 33rd St\",\"city\":\"some city\",\"state\":\"NY\",\"postalCode\":\"11101\",\"phone\":\"8008881776\"}]},\"total\":1}"
end
def http_response_body(:funding_source, :list) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44/funding-sources\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"},\"customer\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"}},\"_embedded\":{\"funding-sources\":[{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/53720cfa-1088-4aee-8fd6-d98e4617732f\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"},\"customer\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"initiate-micro-deposits\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/53720cfa-1088-4aee-8fd6-d98e4617732f/micro-deposits\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"micro-deposits\"}},\"id\":\"53720cfa-1088-4aee-8fd6-d98e4617732f\",\"status\":\"unverified\",\"type\":\"bank\",\"name\":\"My name 7\",\"created\":\"2016-11-07T03:39:46.000Z\",\"removed\":false,\"channels\":[\"ach\"],\"bankName\":\"SANDBOX TEST BANK\"},{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/e8b4d511-805d-4e91-bfb4-670cd9583a18\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"},\"customer\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"initiate-micro-deposits\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/e8b4d511-805d-4e91-bfb4-670cd9583a18/micro-deposits\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"micro-deposits\"}},\"id\":\"e8b4d511-805d-4e91-bfb4-670cd9583a18\",\"status\":\"unverified\",\"type\":\"bank\",\"name\":\"Big Ben's Checking Account\",\"created\":\"2017-03-15T22:27:51.000Z\",\"removed\":false,\"channels\":[\"ach\"],\"bankName\":\"SANDBOX TEST BANK\"},{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/f049fbc5-7162-474a-b30a-85cd8e90fbd0\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"},\"customer\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"initiate-micro-deposits\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/f049fbc5-7162-474a-b30a-85cd8e90fbd0/micro-deposits\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"micro-deposits\"}},\"id\":\"f049fbc5-7162-474a-b30a-85cd8e90fbd0\",\"status\":\"unverified\",\"type\":\"bank\",\"name\":\"My Balance\",\"created\":\"2016-10-10T21:15:27.000Z\",\"removed\":true,\"channels\":[\"ach\"]},{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/2c824e50-1c23-4adc-8935-9d1fa1bb21a4\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"},\"customer\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"with-available-balance\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/2c824e50-1c23-4adc-8935-9d1fa1bb21a4\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"},\"balance\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/2c824e50-1c23-4adc-8935-9d1fa1bb21a4/balance\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"balance\"}},\"id\":\"2c824e50-1c23-4adc-8935-9d1fa1bb21a4\",\"status\":\"verified\",\"type\":\"balance\",\"name\":\"Balance\",\"created\":\"2016-10-10T21:12:09.000Z\",\"removed\":false,\"channels\":[]}]}}"
end
def http_response_body(:transfer, :search) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44/transfers\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"},\"first\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44/transfers?&limit=25&offset=0\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"},\"last\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44/transfers?&limit=25&offset=0\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"}},\"_embedded\":{\"transfers\":[]},\"total\":0}"
end
def http_response_body(:funding_source, :get) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/f049fbc5-7162-474a-b30a-85cd8e90fbd0\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"},\"customer\":{\"href\":\"https://api-sandbox.dwolla.com/customers/a131acb0-9fad-4fe6-9ccd-3a5c4facaf44\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"initiate-micro-deposits\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/f049fbc5-7162-474a-b30a-85cd8e90fbd0/micro-deposits\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"micro-deposits\"}},\"id\":\"f049fbc5-7162-474a-b30a-85cd8e90fbd0\",\"status\":\"unverified\",\"type\":\"bank\",\"name\":\"My Balance\",\"created\":\"2016-10-10T21:15:27.000Z\",\"removed\":true,\"channels\":[\"ach\"],\"bankName\":\"SANDBOX TEST BANK\"}"
end
def http_response_body(:balance, :get) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/c18945d3-101e-4aee-8eb4-f33887222935/balance\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"balance\"},\"funding-source\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/c18945d3-101e-4aee-8eb4-f33887222935\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"}},\"balance\":{\"value\":\"0.00\",\"currency\":\"USD\"},\"lastUpdated\":\"2017-04-03T21:41:10.283Z\"}"
end
def http_response_body(:transfer, :get) do
"{\"_links\":{\"cancel\":{\"href\":\"https://api-sandbox.dwolla.com/transfers/8f669079-b036-e611-80e3-0aa34a9b2388\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"},\"source\":{\"href\":\"https://api-sandbox.dwolla.com/accounts/fc81fee0-1520-4949-bc2d-73e4e11fddd9\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"account\"},\"funding-transfer\":{\"href\":\"https://api-sandbox.dwolla.com/transfers/8e669079-b036-e611-80e3-0aa34a9b2388\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"},\"self\":{\"href\":\"https://api-sandbox.dwolla.com/transfers/8f669079-b036-e611-80e3-0aa34a9b2388\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"transfer\"},\"source-funding-source\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/70c99528-285d-4de5-9ece-6d9b8f5cb1a4\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"},\"destination\":{\"href\":\"https://api-sandbox.dwolla.com/customers/df1eb2aa-3d75-48a1-b882-425b579a85dc\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"customer\"},\"destination-funding-source\":{\"href\":\"https://api-sandbox.dwolla.com/funding-sources/500f8e0e-dfd5-431b-83e0-cd6632e63fcb\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"funding-source\"}},\"id\":\"8f669079-b036-e611-80e3-0aa34a9b2388\",\"status\":\"pending\",\"amount\":{\"value\":\"55.00\",\"currency\":\"usd\"},\"created\":\"2016-06-20T06:30:27.243Z\",\"metadata\":{\"notes\":\"First test transfer!\",\"customerId\":\"1234\"},\"clearing\":{\"source\": \"standard\"},\"correlationId\":\"4293d107-fa46-4188-91b1-e60bb9621bea\",\"individualAchId\":\"IWOBPWJZ\"}"
end
def http_response_body(:transfer, :failure) do
"{\"_links\": {\"self\": {\"href\": \"https://api-sandbox.dwolla.com/transfers/E6D9A950-AC9E-E511-80DC-0AA34A9B2388/failure\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"failure\"}},\"code\":\"R1\",\"description\":\"Insufficient Funds\"}"
end
def http_response_body(:event, :list) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/events\"},\"first\":{\"href\":\"https://api-sandbox.dwolla.com/events?limit=25&offset=0\"},\"last\":{\"href\":\"https://api-sandbox.dwolla.com/events?limit=25&offset=150\"},\"next\":{\"href\":\"https://api-sandbox.dwolla.com/events?limit=25&offset=25\"}},\"_embedded\":{\"events\":[{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/events/78e57644-56e4-4da2-b743-059479f2e80f\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"event\"},\"resource\":{\"href\":\"https://api-sandbox.dwolla.com/transfers/47CFDDB4-1E74-E511-80DB-0AA34A9B2388\"},\"account\":{\"href\":\"https://api-sandbox.dwolla.com/accounts/ca32853c-48fa-40be-ae75-77b37504581b\"}},\"id\":\"78e57644-56e4-4da2-b743-059479f2e80f\",\"created\":\"2015-10-16T15:58:18.000Z\",\"topic\":\"bank_transfer_created\",\"resourceId\":\"47CFDDB4-1E74-E511-80DB-0AA34A9B2388\"},{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/events/f8e70f48-b7ff-47d0-9d3d-62a099363a76\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"event\"},\"resource\":{\"href\":\"https://api-sandbox.dwolla.com/transfers/48CFDDB4-1E74-E511-80DB-0AA34A9B2388\"},\"account\":{\"href\":\"https://api-sandbox.dwolla.com/accounts/ca32853c-48fa-40be-ae75-77b37504581b\"}},\"id\":\"f8e70f48-b7ff-47d0-9d3d-62a099363a76\",\"created\":\"2015-10-16T15:58:15.000Z\",\"topic\":\"transfer_created\",\"resourceId\":\"48CFDDB4-1E74-E511-80DB-0AA34A9B2388\"}]},\"total\": 2}"
end
def http_response_body(:event, :get) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/events/81f6e13c-557c-4449-9331-da5c65e61095\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"event\"},\"resource\":{\"href\":\"https://api-sandbox.dwolla.com/transfers/09A166BC-1B74-E511-80DB-0AA34A9B2388\"},\"account\":{\"href\":\"https://api-sandbox.dwolla.com/accounts/ca32853c-48fa-40be-ae75-77b37504581b\"},\"customer\":{\"href\":\"https://api-sandbox.dwolla.com/customers/07d59716-ef22-4fe6-98e8-f3190233dfb8\"}},\"id\":\"81f6e13c-557c-4449-9331-da5c65e61095\",\"created\":\"2015-10-16T15:37:02.000Z\",\"topic\":\"customer_transfer_created\",\"resourceId\":\"09A166BC-1B74-E511-80DB-0AA34A9B2388\"}"
end
def http_response_body(:webhook_subscription, :get) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/webhook-subscriptions/4c63f8c2-6599-4e7d-9594-be5e0c25a8c7\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"webhook-subscription\"},\"webhooks\":{\"href\":\"https://api-sandbox.dwolla.com/webhook-subscriptions/4c63f8c2-6599-4e7d-9594-be5e0c25a8c7/webhooks\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"webhook\"}},\"id\":\"4c63f8c2-6599-4e7d-9594-be5e0c25a8c7\",\"url\":\"https://twopence.co/api/dwolla\",\"paused\":false,\"created\":\"2017-03-16T17:12:41.000Z\"}"
end
def http_response_body(:webhook_subscription, :list) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/webhook-subscriptions\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"webhook-subscription\"}},\"_embedded\":{\"webhook-subscriptions\":[{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/webhook-subscriptions/d2b4f94a-e0bf-4ef0-9285-a08efe023a4e\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"webhook-subscription\"},\"webhooks\":{\"href\":\"https://api-sandbox.dwolla.com/webhook-subscriptions/d2b4f94a-e0bf-4ef0-9285-a08efe023a4e/webhooks\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"webhook\"}},\"id\":\"d2b4f94a-e0bf-4ef0-9285-a08efe023a4e\",\"url\":\"https://twopence.co/api/dwolla\",\"paused\":false,\"created\":\"2017-03-16T17:26:48.000Z\"}]},\"total\":1}"
end
def http_response_body(:webhook, :get) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/webhooks/9ece9660-aa34-41eb-80d7-0125d53b45e8\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"webhook\"},\"subscription\":{\"href\":\"https://api-sandbox.dwolla.com/webhook-subscriptions/a0943041-7a5c-4e8f-92de-b55711ef3a83\"},\"retry\":{\"href\":\"https://api-sandbox.dwolla.com/webhooks/9ece9660-aa34-41eb-80d7-0125d53b45e8/retries\"},\"event\":{\"href\":\"https://api-sandbox.dwolla.com/events/03c7e14c-7f15-44a2-bcf7-83f2f7e95d50\"}},\"id\":\"9ece9660-aa34-41eb-80d7-0125d53b45e8\",\"topic\":\"transfer_created\",\"accountId\":\"ca32853c-48fa-40be-ae75-77b37504581b\",\"eventId\":\"03c7e14c-7f15-44a2-bcf7-83f2f7e95d50\",\"subscriptionId\":\"a0943041-7a5c-4e8f-92de-b55711ef3a83\",\"attempts\":[{\"id\":\"d4d16621-c6b0-40cb-8dc3-0469fa9dc4e8\",\"request\":{\"timestamp\":\"2015-10-27T17:07:34.304Z\",\"url\":\"https://myapp.runscope.net\",\"headers\":[{\"name\":\"X-Dwolla-Topic\",\"value\":\"transfer_created\"},{\"name\":\"X-Request-Signature\",\"value\":\"bd93780bd7e1ad77ab821094aaa0f9e3dece5ee3\"}],\"body\":{\"id\":\"03c7e14c-7f15-44a2-bcf7-83f2f7e95d50\",\"resourceId\":\"81BA6F36-CD7C-E511-80DB-0AA34A9B2388\",\"topic\":\"transfer_created\",\"timestamp\":\"2015-10-27T17:07:34.207Z\",\"_links\":{\"self\":{\"href\":\"https://api.dwolla.com/events/03c7e14c-7f15-44a2-bcf7-83f2f7e95d50\"},\"account\":{\"href\":\"https://api-sandbox.dwolla.com/accounts/ca32853c-48fa-40be-ae75-77b37504581b\"},\"resource\":{\"href\":\"https://api.dwolla.com/transfers/81BA6F36-CD7C-E511-80DB-0AA34A9B2388\"}}}},\"response\":{\"timestamp\":\"2015-10-27T17:07:34.308Z\",\"headers\":[{\"name\":\"Date\",\"value\":\"Tue,27Oct201517:07:34GMT\"},{\"name\":\"Content-Type\",\"value\":\"application/json;charset=UTF-8\"},{\"name\":\"Content-Length\",\"value\":\"1093\"},{\"name\":\"Connection\",\"value\":\"keep-alive\"},{\"name\":\"Access-Control-Allow-Credentials\",\"value\":\"true\"},{\"name\":\"Access-Control-Allow-Methods\",\"value\":\"GET,PUT,POST,PATCH,DELETE,OPTIONS,HEAD\"},{\"name\":\"Server\",\"value\":\"Runscope-Gateway/1.0\"},{\"name\":\"Runscope-Message-Id\",\"value\":\"97aa5bbd-784f-4007-80cc-8f56919000a0\"},{\"name\":\"Access-Control-Allow-Origin\",\"value\":\"*\"}],\"statusCode\":200,\"body\":{}}}]}"
end
def http_response_body(:webhook, :retries) do
"{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/webhooks/9ece9660-aa34-41eb-80d7-0125d53b45e8/retries\"}},\"_embedded\":{\"retries\":[{\"_links\":{\"self\":{\"href\":\"https://api-sandbox.dwolla.com/webhooks/9ece9660-aa34-41eb-80d7-0125d53b45e8/retries/5aa27a0f-cf99-418d-a3ee-67c0ff99a494\",\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"retries\"},\"webhook\":{\"href\":\"https://api.dwolla.com/webhooks/9ece9660-aa34-41eb-80d7-0125d53b45e8\"}},\"id\":\"5aa27a0f-cf99-418d-a3ee-67c0ff99a494\",\"timestamp\":\"2015-11-02T17:43:26.000Z\"}]},\"total\":1}"
end
def http_response_body(:bill_payment, :get) do
"{\"correlationId\":\"9ece9660-aa34-41eb-80d7-0125d53b45e8\",\"status\":\"pending\",\"id\":\"55bdfc3a-9568-4a67-92b3-867fde741a46\",\"created\":\"2018-03-29T17:43:35.692Z\",\"billedFor\":\"Biller Name\",\"_links\":{\"type\":\"application/vnd.dwolla.v1.hal+json\",\"transfers\":{\"href\":\"https://api-sandbox.dwolla.com/transfers/fd561bb4-7833-e811-8106-0a595ef38714\"},\"self\":{\"type\":\"application/vnd.dwolla.v1.hal+json\",\"resource-type\":\"bill-payment\",\"href\":\"https://api-sandbox.dwolla.com/bill-payments/55bdfc3a-9568-4a67-92b3-867fde741a46\"},\"resource-type\":\"transfer\"}}"
end
def http_response_header(:customer) do
{"Location", "https://api-sandbox.dwolla.com/customers/b2cf497a-b315-497e-95b7-d1238288f8cb"}
end
def http_response_header(:funding_source) do
{"Location", "https://api-sandbox.dwolla.com/funding-sources/e8b4d511-805d-4e91-bfb4-670cd9583a18"}
end
def http_response_header(:transfer) do
{"Location", "https://api-sandbox.dwolla.com/transfers/494b6269-d909-e711-80ee-0aa34a9b2388"}
end
def http_response_header(:webhook_subscription) do
{"Location", "https://api-sandbox.dwolla.com/webhook-subscriptions/d2b4f94a-e0bf-4ef0-9285-a08efe023a4e"}
end
def http_response_header(:webhook) do
{"Location", "https://api-sandbox.dwolla.com/webhooks/9ece9660-aa34-41eb-80d7-0125d53b45e8/retries/5aa27a0f-cf99-418d-a3ee-67c0ff99a494"}
end
end
| 247.652632 | 3,974 | 0.67871 |
03f5cb72fb8e41e13c450731ea5092ea84027e36 | 449 | ex | Elixir | patterns/splitter/elixir/splitter/lib/splitter/supervisor.ex | thetonymaster/thetonymaster.github.io | 2e24d46dd377fed6ab6d1609e5afe24b4953a0f2 | [
"MIT"
] | null | null | null | patterns/splitter/elixir/splitter/lib/splitter/supervisor.ex | thetonymaster/thetonymaster.github.io | 2e24d46dd377fed6ab6d1609e5afe24b4953a0f2 | [
"MIT"
] | null | null | null | patterns/splitter/elixir/splitter/lib/splitter/supervisor.ex | thetonymaster/thetonymaster.github.io | 2e24d46dd377fed6ab6d1609e5afe24b4953a0f2 | [
"MIT"
] | null | null | null | defmodule Splitter.Supervisor do
def start_link do
import Supervisor.Spec
children = [
worker(Splitter.Inventory, [Splitter.inventory_name()],id: :inventory),
worker(Splitter.PaymentProcessor, [Splitter.paymment_processor_name()],id: :paymentprocessor),
worker(Splitter.OrderProcessor, [Splitter.order_processor_name()],id: :orderprocessor)
]
Supervisor.start_link(children, strategy: :one_for_one)
end
end
| 28.0625 | 100 | 0.739421 |
03f5e2dd90def2fa72bfa171c53b7483d01d4793 | 1,610 | ex | Elixir | lib/discuss_web/endpoint.ex | shahnCM/discuss | a880950e090ecf9309d495e81c31d589d3655881 | [
"MIT"
] | null | null | null | lib/discuss_web/endpoint.ex | shahnCM/discuss | a880950e090ecf9309d495e81c31d589d3655881 | [
"MIT"
] | null | null | null | lib/discuss_web/endpoint.ex | shahnCM/discuss | a880950e090ecf9309d495e81c31d589d3655881 | [
"MIT"
] | null | null | null | defmodule DiscussWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :discuss
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_discuss_key",
signing_salt: "C+JHKrIQ"
]
socket "/socket", DiscussWeb.UserSocket,
websocket: true,
longpoll: false
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :discuss,
gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :discuss
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug DiscussWeb.Router
end
| 29.272727 | 97 | 0.718012 |
03f6151db9072c3d41b496d473f07a008f964ac2 | 1,029 | exs | Elixir | apps/queue/mix.exs | poteto/peedy | df9d5ee7fcbceb30b5939b36224a257249a180ea | [
"Apache-2.0"
] | 34 | 2017-05-07T08:50:59.000Z | 2021-11-25T00:27:11.000Z | apps/queue/mix.exs | poteto/peedy | df9d5ee7fcbceb30b5939b36224a257249a180ea | [
"Apache-2.0"
] | null | null | null | apps/queue/mix.exs | poteto/peedy | df9d5ee7fcbceb30b5939b36224a257249a180ea | [
"Apache-2.0"
] | 7 | 2017-05-10T12:42:30.000Z | 2021-11-03T01:21:02.000Z | defmodule Queue.Mixfile do
use Mix.Project
def project do
[app: :queue,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.4",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps()]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
# Specify extra applications you'll use from Erlang/Elixir
[extra_applications: [:logger],
mod: {Queue.Application, []}]
end
# Dependencies can be Hex packages:
#
# {:my_dep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
#
# To depend on another app inside the umbrella:
#
# {:my_app, in_umbrella: true}
#
# Type "mix help deps" for more examples and options
defp deps do
[{:gen_stage, "~> 0.11"}]
end
end
| 23.930233 | 79 | 0.600583 |
03f6519a5e19b3ae57be8d0fe8f22d6421591fd0 | 6,765 | exs | Elixir | test/controllers/registration_controller_test.exs | thefuture2092/coherence | 377d91ff01622773b5a9ec39fadf1f8c27328879 | [
"MIT"
] | 1,347 | 2016-07-04T23:20:10.000Z | 2022-02-10T20:10:48.000Z | test/controllers/registration_controller_test.exs | thefuture2092/coherence | 377d91ff01622773b5a9ec39fadf1f8c27328879 | [
"MIT"
] | 378 | 2016-07-06T16:30:28.000Z | 2021-09-16T13:34:05.000Z | test/controllers/registration_controller_test.exs | thefuture2092/coherence | 377d91ff01622773b5a9ec39fadf1f8c27328879 | [
"MIT"
] | 276 | 2016-07-06T20:26:17.000Z | 2021-12-06T19:32:41.000Z | defmodule CoherenceTest.RegistrationController do
use TestCoherence.ConnCase
import TestCoherenceWeb.Router.Helpers
setup %{conn: conn} = context do
Application.put_env(:coherence, :opts, [:confirmable, :registerable])
Application.put_env(
:coherence,
:confirm_email_updates,
Map.get(context, :confirm_email_updates, false)
)
user = insert_user(%{name: "John Doe"})
conn = assign(conn, :current_user, user)
{:ok, conn: conn, user: user}
end
describe "show" do
test "can visit show registration page", %{conn: conn} do
conn = get(conn, registration_path(conn, :show))
assert html_response(conn, 200)
assert conn.private[:phoenix_template] == "show.html"
end
end
describe "edit" do
test "can visit edit registration page", %{conn: conn} do
conn = get(conn, registration_path(conn, :edit))
assert html_response(conn, 200)
assert conn.private[:phoenix_template] == "edit.html"
end
end
describe "new" do
test "can visit new registration page", %{conn: conn} do
conn = assign(conn, :current_user, nil)
conn = get(conn, registration_path(conn, :new))
assert html_response(conn, 200)
assert conn.private[:phoenix_template] == "new.html"
end
end
describe "create" do
test "can create new registration with valid params, password_confirmation is not mandatory",
%{conn: conn} do
conn = assign(conn, :current_user, nil)
params = %{
"registration" => %{
"name" => "John Doe",
"email" => "john.doe@example.com",
"password" => "123123"
}
}
conn = post conn, registration_path(conn, :create), params
assert conn.private[:phoenix_flash] == %{"error" => "Mailer configuration required!"}
assert html_response(conn, 302)
end
test "password_confirmation checked only if present", %{conn: conn} do
conn = assign(conn, :current_user, nil)
params = %{
"registration" => %{
"name" => "John Doe",
"email" => "john.doe@example.com",
"password_confirmation" => "no match",
"password" => "123123"
}
}
conn = post conn, registration_path(conn, :create), params
errors = conn.assigns.changeset.errors
assert errors[:password_confirmation] ==
{"does not match confirmation", [validation: :confirmation]}
end
test "can not register with invalid params", %{conn: conn} do
conn = assign(conn, :current_user, nil)
params = %{"registration" => %{}}
conn = post conn, registration_path(conn, :create), params
errors = conn.assigns.changeset.errors
assert errors[:password] == {"can't be blank", []}
assert errors[:email] == {"can't be blank", [validation: :required]}
assert errors[:name] == {"can't be blank", [validation: :required]}
end
test "mass asignment not allowed", %{conn: conn} do
conn = assign(conn, :current_user, nil)
params = %{
"registration" => %{
"name" => "John Doe",
"email" => "john.doe@example.com",
"password" => "123123",
"current_sign_in_ip" => "mass_asignment"
}
}
conn = post conn, registration_path(conn, :create), params
assert conn.private[:phoenix_flash] == %{"error" => "Mailer configuration required!"}
assert html_response(conn, 302)
%{:current_sign_in_ip => current_sign_in_ip} =
get_user_by_email(params["registration"]["email"])
refute current_sign_in_ip == params["registration"]["current_sign_in_ip"]
end
end
@moduletag report: [:confirm_email_updates]
describe "update" do
test "can update registration with valid current password", %{conn: conn, user: user} do
params = %{"registration" => %{"current_password" => user.password}}
conn = put conn, registration_path(conn, :update), params
assert conn.private[:phoenix_flash] == %{"info" => "Account updated successfully."}
assert html_response(conn, 302)
end
test "can not update registration without current password", %{conn: conn} do
params = %{"registration" => %{password: "123123", password_confirmation: "123123"}}
conn = put conn, registration_path(conn, :update), params
errors = conn.assigns.changeset.errors
assert errors[:current_password] == {"can't be blank", []}
end
test "can not update registration without valid current password", %{conn: conn} do
params = %{
"registration" => %{
current_password: "123456",
password: "123123",
password_confirmation: "123123"
}
}
conn = put conn, registration_path(conn, :update), params
errors = conn.assigns.changeset.errors
assert errors[:current_password] == {"invalid current password", []}
end
test "mass assignment not allowed", %{conn: conn, user: user} do
params = %{
"registration" => %{
"current_password" => user.password,
"current_sign_in_ip" => "mass_asignment"
}
}
conn = put conn, registration_path(conn, :update), params
assert conn.private[:phoenix_flash] == %{"info" => "Account updated successfully."}
assert html_response(conn, 302)
%{:current_sign_in_ip => current_sign_in_ip} = get_user_by_email(user.email)
refute current_sign_in_ip == params["registration"]["current_sign_in_ip"]
end
test "can update email directly", %{conn: conn} do
params = %{"registration" => %{"email" => "john.doe@example.com"}}
conn = put conn, registration_path(conn, :update), params
assert html_response(conn, 302)
%{:email => email} = get_user_by_name("John Doe")
assert email == params["registration"]["email"]
end
@tag confirm_email_updates: true
test "cannot update email directly but unconfirmed_email", %{conn: conn} do
params = %{"registration" => %{"email" => "john.doe@example.com"}}
conn = put conn, registration_path(conn, :update), params
assert html_response(conn, 302)
user = get_user_by_name("John Doe")
assert user.unconfirmed_email == params["registration"]["email"]
refute user.email == params["registration"]["email"]
end
@tag confirm_email_updates: true
test "should not set unconfirmed email if email is the same", %{conn: conn, user: user} do
params = %{"registration" => %{"email" => user.email}}
conn = put conn, registration_path(conn, :update), params
assert html_response(conn, 302)
user = get_user_by_name("John Doe")
refute user.unconfirmed_email
assert user.email == user.email
end
end
end
| 35.984043 | 97 | 0.63119 |
03f6943f256a52ade1278e64125201267c32f923 | 15,108 | ex | Elixir | lib/elixir/lib/io.ex | kevsmith/elixir | 74825645e8cac770708f45139e651fd9d4e4264c | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/io.ex | kevsmith/elixir | 74825645e8cac770708f45139e651fd9d4e4264c | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/io.ex | kevsmith/elixir | 74825645e8cac770708f45139e651fd9d4e4264c | [
"Apache-2.0"
] | null | null | null | defmodule IO do
@moduledoc """
Functions handling input/output (IO).
Many functions in this module expect an IO device as an argument.
An IO device must be a PID or an atom representing a process.
For convenience, Elixir provides `:stdio` and `:stderr` as
shortcuts to Erlang's `:standard_io` and `:standard_error`.
The majority of the functions expect chardata, i.e. strings or
lists of characters and strings. In case another type is given,
functions will convert to string via the `String.Chars` protocol
(as shown in typespecs).
The functions starting with `bin` expect iodata as an argument,
i.e. binaries or lists of bytes and binaries.
## IO devices
An IO device may be an atom or a PID. In case it is an atom,
the atom must be the name of a registered process. In addition,
Elixir provides two shortcuts:
* `:stdio` - a shortcut for `:standard_io`, which maps to
the current `Process.group_leader/0` in Erlang
* `:stderr` - a shortcut for the named process `:standard_error`
provided in Erlang
IO devices maintain their position, that means subsequent calls to any
reading or writing functions will start from the place when the device
was last accessed. Position of files can be changed using the
`:file.position/2` function.
"""
@type device :: atom | pid
@type nodata :: {:error, term} | :eof
@type chardata() :: :unicode.chardata()
import :erlang, only: [group_leader: 0]
defmacrop is_iodata(data) do
quote do
is_list(unquote(data)) or is_binary(unquote(data))
end
end
@doc """
Reads from the IO `device`.
The `device` is iterated by the given number of characters or line by line if
`:line` is given.
Alternatively, if `:all` is given, then whole `device` is returned.
It returns:
* `data` - the output characters
* `:eof` - end of file was encountered
* `{:error, reason}` - other (rare) error condition;
for instance, `{:error, :estale}` if reading from an
NFS volume
If `:all` is given, `:eof` is never returned, but an
empty string in case the device has reached EOF.
"""
@spec read(device, :all | :line | non_neg_integer) :: chardata | nodata
def read(device \\ group_leader(), line_or_chars)
def read(device, :all) do
do_read_all(map_dev(device), "")
end
def read(device, :line) do
:io.get_line(map_dev(device), '')
end
def read(device, count) when is_integer(count) and count >= 0 do
:io.get_chars(map_dev(device), '', count)
end
defp do_read_all(mapped_dev, acc) do
case :io.get_line(mapped_dev, "") do
line when is_binary(line) -> do_read_all(mapped_dev, acc <> line)
:eof -> acc
other -> other
end
end
@doc """
Reads from the IO `device`. The operation is Unicode unsafe.
The `device` is iterated by the given number of bytes or line by line if
`:line` is given.
Alternatively, if `:all` is given, then whole `device` is returned.
It returns:
* `data` - the output bytes
* `:eof` - end of file was encountered
* `{:error, reason}` - other (rare) error condition;
for instance, `{:error, :estale}` if reading from an
NFS volume
If `:all` is given, `:eof` is never returned, but an
empty string in case the device has reached EOF.
Note: do not use this function on IO devices in Unicode mode
as it will return the wrong result.
"""
@spec binread(device, :all | :line | non_neg_integer) :: iodata | nodata
def binread(device \\ group_leader(), line_or_chars)
def binread(device, :all) do
do_binread_all(map_dev(device), "")
end
def binread(device, :line) do
case :file.read_line(map_dev(device)) do
{:ok, data} -> data
other -> other
end
end
def binread(device, count) when is_integer(count) and count >= 0 do
case :file.read(map_dev(device), count) do
{:ok, data} -> data
other -> other
end
end
@read_all_size 4096
defp do_binread_all(mapped_dev, acc) do
case :file.read(mapped_dev, @read_all_size) do
{:ok, data} -> do_binread_all(mapped_dev, acc <> data)
:eof -> acc
other -> other
end
end
@doc """
Writes `item` to the given `device`.
By default the `device` is the standard output.
It returns `:ok` if it succeeds.
## Examples
IO.write "sample"
#=> sample
IO.write :stderr, "error"
#=> error
"""
@spec write(device, chardata | String.Chars.t) :: :ok
def write(device \\ group_leader(), item) do
:io.put_chars map_dev(device), to_chardata(item)
end
@doc """
Writes `item` as a binary to the given `device`.
No Unicode conversion happens.
The operation is Unicode unsafe.
Check `write/2` for more information.
Note: do not use this function on IO devices in Unicode mode
as it will return the wrong result.
"""
@spec binwrite(device, iodata) :: :ok | {:error, term}
def binwrite(device \\ group_leader(), item) when is_iodata(item) do
:file.write map_dev(device), item
end
@doc """
Writes `item` to the given `device`, similar to `write/2`,
but adds a newline at the end.
"""
@spec puts(device, chardata | String.Chars.t) :: :ok
def puts(device \\ group_leader(), item) do
:io.put_chars map_dev(device), [to_chardata(item), ?\n]
end
@doc """
Writes a `message` to stderr, along with the given `stacktrace`.
This function also notifies the compiler a warning was printed
(in case --warnings-as-errors was enabled). It returns `:ok`
if it succeeds.
An empty list can be passed to avoid stacktrace printing.
## Examples
stacktrace = [{MyApp, :main, 1, [file: 'my_app.ex', line: 4]}]
IO.warn "variable bar is unused", stacktrace
#=> warning: variable bar is unused
#=> my_app.ex:4: MyApp.main/1
"""
@spec warn(chardata | String.Chars.t, Exception.stacktrace) :: :ok
def warn(message, []) do
:elixir_errors.warn([to_chardata(message), ?\n])
end
def warn(message, stacktrace) when is_list(stacktrace) do
formatted = Enum.map_join(stacktrace, "\n ", &Exception.format_stacktrace_entry(&1))
:elixir_errors.warn([to_chardata(message), ?\n, " ", formatted, ?\n])
end
@doc """
Writes a `message` to stderr, along with the current stacktrace.
It returns `:ok` if it succeeds.
## Examples
IO.warn "variable bar is unused"
#=> warning: variable bar is unused
#=> (iex) evaluator.ex:108: IEx.Evaluator.eval/4
"""
@spec warn(chardata | String.Chars.t) :: :ok
def warn(message) do
{:current_stacktrace, stacktrace} = Process.info(self(), :current_stacktrace)
warn(message, Enum.drop(stacktrace, 2))
end
@doc """
Inspects and writes the given `item` to the device.
It's important to note that it returns the given `item` unchanged.
This makes it possible to "spy" on values by inserting an
`IO.inspect/2` call almost anywhere in your code, for example,
in the middle of a pipeline.
It enables pretty printing by default with width of
80 characters. The width can be changed by explicitly
passing the `:width` option.
The output can be decorated with a label, by providing the `:label`
option to easily distinguish it from other `IO.inspect/2` calls.
The label will be printed before the inspected `item`.
See `Inspect.Opts` for a full list of remaining formatting options.
## Examples
IO.inspect <<0, 1, 2>>, width: 40
Prints:
<<0, 1, 2>>
We can use the `:label` option to decorate the output:
IO.inspect 1..100, label: "a wonderful range"
Prints:
a wonderful range: 1..100
The `:label` option is especially useful with pipelines:
[1, 2, 3]
|> IO.inspect(label: "before")
|> Enum.map(&(&1 * 2))
|> IO.inspect(label: "after")
|> Enum.sum
Prints:
before: [1, 2, 3]
after: [2, 4, 6]
"""
@spec inspect(item, Keyword.t) :: item when item: var
def inspect(item, opts \\ []) do
inspect group_leader(), item, opts
end
@doc """
Inspects `item` according to the given options using the IO `device`.
See `inspect/2` for a full list of options.
"""
@spec inspect(device, item, Keyword.t) :: item when item: var
def inspect(device, item, opts) when is_list(opts) do
label = if (label = opts[:label]), do: [to_chardata(label), ": "], else: []
opts = struct(Inspect.Opts, opts)
chardata = Inspect.Algebra.format(Inspect.Algebra.to_doc(item, opts), opts.width)
puts device, [label, chardata]
item
end
@doc """
Gets a number of bytes from IO device `:stdio`.
If `:stdio` is a Unicode device, `count` implies
the number of Unicode codepoints to be retrieved.
Otherwise, `count` is the number of raw bytes to be retrieved.
See `IO.getn/3` for a description of return values.
"""
@spec getn(chardata | String.Chars.t, pos_integer) :: chardata | nodata
@spec getn(device, chardata | String.Chars.t) :: chardata | nodata
def getn(prompt, count \\ 1)
def getn(prompt, count) when is_integer(count) and count > 0 do
getn(group_leader(), prompt, count)
end
def getn(device, prompt) when not is_integer(prompt) do
getn(device, prompt, 1)
end
@doc """
Gets a number of bytes from the IO `device`.
If the IO `device` is a Unicode device, `count` implies
the number of Unicode codepoints to be retrieved.
Otherwise, `count` is the number of raw bytes to be retrieved.
It returns:
* `data` - the input characters
* `:eof` - end of file was encountered
* `{:error, reason}` - other (rare) error condition;
for instance, `{:error, :estale}` if reading from an
NFS volume
"""
@spec getn(device, chardata | String.Chars.t, pos_integer) :: chardata | nodata
def getn(device, prompt, count) when is_integer(count) and count > 0 do
:io.get_chars(map_dev(device), to_chardata(prompt), count)
end
@doc ~S"""
Reads a line from the IO `device`.
It returns:
* `data` - the characters in the line terminated
by a line-feed (LF) or end of file (EOF)
* `:eof` - end of file was encountered
* `{:error, reason}` - other (rare) error condition;
for instance, `{:error, :estale}` if reading from an
NFS volume
## Examples
To display "What is your name?" as a prompt and await user input:
IO.gets "What is your name?\n"
"""
@spec gets(device, chardata | String.Chars.t) :: chardata | nodata
def gets(device \\ group_leader(), prompt) do
:io.get_line(map_dev(device), to_chardata(prompt))
end
@doc """
Converts the IO `device` into an `IO.Stream`.
An `IO.Stream` implements both `Enumerable` and
`Collectable`, allowing it to be used for both read
and write.
The `device` is iterated by the given number of characters or line by line if
`:line` is given.
This reads from the IO as utf-8. Check out
`IO.binstream/2` to handle the IO as a raw binary.
Note that an IO stream has side effects and every time
you go over the stream you may get different results.
## Examples
Here is an example on how we mimic an echo server
from the command line:
Enum.each IO.stream(:stdio, :line), &IO.write(&1)
"""
@spec stream(device, :line | pos_integer) :: Enumerable.t
def stream(device, line_or_codepoints)
when line_or_codepoints == :line
when is_integer(line_or_codepoints) and line_or_codepoints > 0 do
IO.Stream.__build__(map_dev(device), false, line_or_codepoints)
end
@doc """
Converts the IO `device` into an `IO.Stream`. The operation is Unicode unsafe.
An `IO.Stream` implements both `Enumerable` and
`Collectable`, allowing it to be used for both read
and write.
The `device` is iterated by the given number of bytes or line by line if
`:line` is given.
This reads from the IO device as a raw binary.
Note that an IO stream has side effects and every time
you go over the stream you may get different results.
Finally, do not use this function on IO devices in Unicode
mode as it will return the wrong result.
"""
@spec binstream(device, :line | pos_integer) :: Enumerable.t
def binstream(device, line_or_bytes)
when line_or_bytes == :line
when is_integer(line_or_bytes) and line_or_bytes > 0 do
IO.Stream.__build__(map_dev(device), true, line_or_bytes)
end
@doc """
Converts chardata (a list of integers representing codepoints,
lists and strings) into a string.
In case the conversion fails, it raises an `UnicodeConversionError`.
If a string is given, it returns the string itself.
## Examples
iex> IO.chardata_to_string([0x00E6, 0x00DF])
"æß"
iex> IO.chardata_to_string([0x0061, "bc"])
"abc"
iex> IO.chardata_to_string("string")
"string"
"""
@spec chardata_to_string(chardata) :: String.t | no_return
def chardata_to_string(string) when is_binary(string) do
string
end
def chardata_to_string(list) when is_list(list) do
List.to_string(list)
end
@doc """
Converts iodata (a list of integers representing bytes, lists
and binaries) into a binary.
The operation is Unicode unsafe.
Notice that this function treats lists of integers as raw bytes
and does not perform any kind of encoding conversion. If you want
to convert from a charlist to a string (UTF-8 encoded), please
use `chardata_to_string/1` instead.
If this function receives a binary, the same binary is returned.
Inlined by the compiler.
## Examples
iex> bin1 = <<1, 2, 3>>
iex> bin2 = <<4, 5>>
iex> bin3 = <<6>>
iex> IO.iodata_to_binary([bin1, 1, [2, 3, bin2], 4 | bin3])
<<1, 2, 3, 1, 2, 3, 4, 5, 4, 6>>
iex> bin = <<1, 2, 3>>
iex> IO.iodata_to_binary(bin)
<<1, 2, 3>>
"""
@spec iodata_to_binary(iodata) :: binary
def iodata_to_binary(item) do
:erlang.iolist_to_binary(item)
end
@doc """
Returns the size of an iodata.
Inlined by the compiler.
## Examples
iex> IO.iodata_length([1, 2 | <<3, 4>>])
4
"""
@spec iodata_length(iodata) :: non_neg_integer
def iodata_length(item) do
:erlang.iolist_size(item)
end
@doc false
def each_stream(device, line_or_codepoints) do
case read(device, line_or_codepoints) do
:eof ->
{:halt, device}
{:error, reason} ->
raise IO.StreamError, reason: reason
data ->
{[data], device}
end
end
@doc false
def each_binstream(device, line_or_chars) do
case binread(device, line_or_chars) do
:eof ->
{:halt, device}
{:error, reason} ->
raise IO.StreamError, reason: reason
data ->
{[data], device}
end
end
@compile {:inline, map_dev: 1, to_chardata: 1}
# Map the Elixir names for standard IO and error to Erlang names
defp map_dev(:stdio), do: :standard_io
defp map_dev(:stderr), do: :standard_error
defp map_dev(other) when is_atom(other) or is_pid(other) or is_tuple(other), do: other
defp to_chardata(list) when is_list(list), do: list
defp to_chardata(other), do: to_string(other)
end
| 28.134078 | 89 | 0.664416 |
03f697a5d48e5aa1fbb2cbef5201dce4fef6dba9 | 80 | exs | Elixir | test/liveman_web/views/page_view_test.exs | nimblehq/liveman-demo-api | e184349983f949c8434b8651f9223db597ef1025 | [
"MIT"
] | null | null | null | test/liveman_web/views/page_view_test.exs | nimblehq/liveman-demo-api | e184349983f949c8434b8651f9223db597ef1025 | [
"MIT"
] | 19 | 2021-07-02T08:14:52.000Z | 2021-07-30T09:33:12.000Z | test/liveman_web/views/page_view_test.exs | nimblehq/liveman | e184349983f949c8434b8651f9223db597ef1025 | [
"MIT"
] | null | null | null | defmodule LivemanWeb.PageViewTest do
use LivemanWeb.ConnCase, async: true
end
| 20 | 38 | 0.825 |
03f6a05771435a0f2ae66d0b159fd0289383952d | 1,206 | ex | Elixir | lib/unf_swuber/endpoint.ex | Swuber/Epik-Club | 0e56e602f0934e0e6225c7456bcb37f5b852be2d | [
"Apache-2.0"
] | 1 | 2017-06-15T14:59:01.000Z | 2017-06-15T14:59:01.000Z | lib/unf_swuber/endpoint.ex | Swuber/Epik-Club | 0e56e602f0934e0e6225c7456bcb37f5b852be2d | [
"Apache-2.0"
] | 1 | 2017-08-10T11:04:15.000Z | 2017-08-10T11:04:15.000Z | lib/unf_swuber/endpoint.ex | Swuber/Epik-Club | 0e56e602f0934e0e6225c7456bcb37f5b852be2d | [
"Apache-2.0"
] | 3 | 2017-08-10T22:54:28.000Z | 2018-10-18T22:32:55.000Z | defmodule UnfSwuber.Endpoint do
use Phoenix.Endpoint, otp_app: :unf_swuber
socket "/socket", UnfSwuber.UserSocket
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phoenix.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/", from: :unf_swuber, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
plug Plug.Session,
store: :cookie,
key: "_unf_swuber_key",
signing_salt: "1BkxIiHa"
plug UnfSwuber.Router
end
| 28.046512 | 69 | 0.718076 |
03f6a7cbd4e7642e48ee463a3aa68f943abdfe1e | 816 | exs | Elixir | test/bincode/tuple_test.exs | LeonardBesson/bincode | 0e2950e6d09eaf9e9cea439e33cad5397747e331 | [
"MIT"
] | null | null | null | test/bincode/tuple_test.exs | LeonardBesson/bincode | 0e2950e6d09eaf9e9cea439e33cad5397747e331 | [
"MIT"
] | null | null | null | test/bincode/tuple_test.exs | LeonardBesson/bincode | 0e2950e6d09eaf9e9cea439e33cad5397747e331 | [
"MIT"
] | null | null | null | defmodule Bincode.TupleTest do
use Bincode.BaseCase, async: true
test_serialization({255}, <<255>>, {:u8})
test_serialization({1, 1}, <<1, 1>>, {:u8, :u8})
test_serialization(
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
<<1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12>>,
{:u8, :u8, :u8, :u8, :u8, :u8, :u8, :u8, :u8, :u8, :u8, :u8},
varint: true
)
test_serialization({888, 999}, <<120, 3, 231, 3>>, {:u16, :u16})
test_serialization(
{[true, true], %{"map" => "in tuple"}},
<<2, 1, 1, 1, 3, 109, 97, 112, 8, 105, 110, 32, 116, 117, 112, 108, 101>>,
{{:list, :bool}, {:map, {:string, :string}}},
varint: true
)
test_serialization_fail(1, 1, {:u8})
test_serialization_fail("valid", "invalid", {:string, :u64})
test_serialization_fail(true, [], {:bool, {:list, :u8}})
end
| 30.222222 | 78 | 0.542892 |
03f6c316d696edf1b78b602277924f07055d5e70 | 1,562 | ex | Elixir | lib/remote_ip/headers/generic.ex | devstopfix/remote_ip | c52084369a0da2f7700679b35085dca0eed5ff0d | [
"MIT"
] | null | null | null | lib/remote_ip/headers/generic.ex | devstopfix/remote_ip | c52084369a0da2f7700679b35085dca0eed5ff0d | [
"MIT"
] | null | null | null | lib/remote_ip/headers/generic.ex | devstopfix/remote_ip | c52084369a0da2f7700679b35085dca0eed5ff0d | [
"MIT"
] | null | null | null | defmodule RemoteIp.Headers.Generic do
@moduledoc """
Generic parser for forwarding headers.
When there is no other special `RemoteIp.Headers.*` parser submodule,
`RemoteIp.Headers.parse/2` will use this module to parse the header value.
So, `RemoteIp.Headers.Generic` is used to parse `X-Forwarded-For`,
`X-Real-IP`, `X-Client-IP`, and generally unrecognized headers.
"""
@doc """
Parses a comma-separated list of IPs.
Any amount of whitespace is allowed before and after the commas, as well as
at the beginning/end of the input.
## Examples
iex> RemoteIp.Headers.Generic.parse("1.2.3.4, 5.6.7.8")
[{1, 2, 3, 4}, {5, 6, 7, 8}]
iex> RemoteIp.Headers.Generic.parse(" ::1 ")
[{0, 0, 0, 0, 0, 0, 0, 1}]
iex> RemoteIp.Headers.Generic.parse("invalid")
[]
"""
@type header :: String.t()
@type ip :: :inet.ip_address()
@spec parse(header) :: [ip]
def parse(header) when is_binary(header) do
header
|> split_commas
|> parse_ips
end
defp split_commas(header) do
header |> String.trim() |> String.split(~r/\s*,\s*/)
end
defp parse_ips(strings) do
Enum.reduce(strings, [], fn string, ips ->
case parse_ip(string) do
{:ok, ip} -> [ip | ips]
{:error, :einval} -> ips
{:error, :invalid_unicode} -> ips
end
end)
|> Enum.reverse()
end
defp parse_ip(string) do
try do
string |> to_charlist |> :inet.parse_strict_address()
rescue
UnicodeConversionError -> {:error, :invalid_unicode}
end
end
end
| 25.193548 | 77 | 0.622279 |
03f71fc2c1eba0560fe38b84c6d0f4068cd04af7 | 250 | ex | Elixir | lib/mix/tasks/lingohub/sync.ex | LostKobrakai/lingohub | f18af24f559f955b4556bb2396cfb622b6b0ce98 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/lingohub/sync.ex | LostKobrakai/lingohub | f18af24f559f955b4556bb2396cfb622b6b0ce98 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/lingohub/sync.ex | LostKobrakai/lingohub | f18af24f559f955b4556bb2396cfb622b6b0ce98 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Lingohub.Sync do
use Mix.Task
def run(args) do
Mix.Task.run("lingohub.upload", args)
Mix.shell().info("Wait for processing")
Process.sleep(:timer.seconds(10))
Mix.Task.run("lingohub.download", args)
end
end
| 22.727273 | 43 | 0.688 |
03f723623fdb4c392514af3bfe3b822cfa81942a | 376 | exs | Elixir | test/hexpm/web/controllers/user_controller_test.exs | findmypast/hexfmp | 38a50f5e1057833fd98748faac230bf4b9cc26a3 | [
"Apache-2.0"
] | null | null | null | test/hexpm/web/controllers/user_controller_test.exs | findmypast/hexfmp | 38a50f5e1057833fd98748faac230bf4b9cc26a3 | [
"Apache-2.0"
] | null | null | null | test/hexpm/web/controllers/user_controller_test.exs | findmypast/hexfmp | 38a50f5e1057833fd98748faac230bf4b9cc26a3 | [
"Apache-2.0"
] | null | null | null | defmodule Hexpm.Web.UserControllerTest do
use Hexpm.ConnCase, async: true
setup do
%{user: create_user("eric", "eric@mail.com", "hunter42"), password: "hunter42"}
end
test "show profile page", c do
conn = build_conn()
|> test_login(c.user)
|> get("users/#{c.user.username}")
assert response(conn, 200) =~ c.user.username
end
end
| 23.5 | 83 | 0.632979 |
03f75d1fe259ce379f80f83e0ce0390a433ee438 | 15,536 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/account_user_profiles.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/account_user_profiles.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/account_user_profiles.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"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.DFAReporting.V33.Api.AccountUserProfiles do
@moduledoc """
API calls for all endpoints tagged `AccountUserProfiles`.
"""
alias GoogleApi.DFAReporting.V33.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets one account user profile by ID.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `id` (*type:* `String.t`) - User profile ID.
* `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.DFAReporting.V33.Model.AccountUserProfile{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_account_user_profiles_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.AccountUserProfile.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def dfareporting_account_user_profiles_get(
connection,
profile_id,
id,
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("/dfareporting/v3.3/userprofiles/{profileId}/accountUserProfiles/{id}", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1),
"id" => URI.encode(id, &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.DFAReporting.V33.Model.AccountUserProfile{}])
end
@doc """
Inserts a new account user profile.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `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.DFAReporting.V33.Model.AccountUserProfile.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V33.Model.AccountUserProfile{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_account_user_profiles_insert(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.AccountUserProfile.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def dfareporting_account_user_profiles_insert(
connection,
profile_id,
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("/dfareporting/v3.3/userprofiles/{profileId}/accountUserProfiles", %{
"profileId" => URI.encode(profile_id, &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.DFAReporting.V33.Model.AccountUserProfile{}])
end
@doc """
Retrieves a list of account user profiles, possibly filtered. This method supports paging.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `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.
* `:active` (*type:* `boolean()`) - Select only active user profiles.
* `:ids` (*type:* `list(String.t)`) - Select only user profiles with these IDs.
* `:maxResults` (*type:* `integer()`) - Maximum number of results to return.
* `:pageToken` (*type:* `String.t`) - Value of the nextPageToken from the previous result page.
* `:searchString` (*type:* `String.t`) - Allows searching for objects by name, ID or email. Wildcards (*) are allowed. For example, "user profile*2015" will return objects with names like "user profile June 2015", "user profile April 2015", or simply "user profile 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "user profile" will match objects with name "my user profile", "user profile 2015", or simply "user profile".
* `:sortField` (*type:* `String.t`) - Field by which to sort the list.
* `:sortOrder` (*type:* `String.t`) - Order of sorted results.
* `:subaccountId` (*type:* `String.t`) - Select only user profiles with the specified subaccount ID.
* `:userRoleId` (*type:* `String.t`) - Select only user profiles with the specified user role ID.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V33.Model.AccountUserProfilesListResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_account_user_profiles_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.AccountUserProfilesListResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def dfareporting_account_user_profiles_list(
connection,
profile_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:active => :query,
:ids => :query,
:maxResults => :query,
:pageToken => :query,
:searchString => :query,
:sortField => :query,
:sortOrder => :query,
:subaccountId => :query,
:userRoleId => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/dfareporting/v3.3/userprofiles/{profileId}/accountUserProfiles", %{
"profileId" => URI.encode(profile_id, &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.DFAReporting.V33.Model.AccountUserProfilesListResponse{}]
)
end
@doc """
Updates an existing account user profile. This method supports patch semantics.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `id` (*type:* `String.t`) - User profile ID.
* `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.DFAReporting.V33.Model.AccountUserProfile.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V33.Model.AccountUserProfile{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_account_user_profiles_patch(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.AccountUserProfile.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def dfareporting_account_user_profiles_patch(
connection,
profile_id,
id,
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(:patch)
|> Request.url("/dfareporting/v3.3/userprofiles/{profileId}/accountUserProfiles", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :id, id)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V33.Model.AccountUserProfile{}])
end
@doc """
Updates an existing account user profile.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `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.DFAReporting.V33.Model.AccountUserProfile.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V33.Model.AccountUserProfile{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_account_user_profiles_update(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.AccountUserProfile.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def dfareporting_account_user_profiles_update(
connection,
profile_id,
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(:put)
|> Request.url("/dfareporting/v3.3/userprofiles/{profileId}/accountUserProfiles", %{
"profileId" => URI.encode(profile_id, &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.DFAReporting.V33.Model.AccountUserProfile{}])
end
end
| 42.332425 | 519 | 0.627317 |
03f76b24028bc0b0020065f17dac077a7ad330cf | 628 | ex | Elixir | lib/techtree/accounts/password.ex | kenkeiras/TechTree | 26c8ca59855002a88bf15eb0b64a6c788f438ec8 | [
"WTFPL"
] | 2 | 2018-10-26T06:06:42.000Z | 2020-02-16T15:01:42.000Z | lib/techtree/accounts/password.ex | kenkeiras/TechTree | 26c8ca59855002a88bf15eb0b64a6c788f438ec8 | [
"WTFPL"
] | 108 | 2018-10-25T10:30:33.000Z | 2021-07-28T04:18:03.000Z | lib/techtree/accounts/password.ex | kenkeiras/TechTree | 26c8ca59855002a88bf15eb0b64a6c788f438ec8 | [
"WTFPL"
] | null | null | null | defmodule Techtree.Accounts.Password do
use Ecto.Schema
import Ecto.Changeset
schema "passwords" do
field :password, :string
belongs_to :user, User
timestamps()
end
@doc false
def changeset(password, attrs) do
password
|> cast(attrs, [:password])
|> validate_required([:password])
|> unique_constraint(:password)
|> put_change(:password, hash_password(attrs["password"]))
end
@doc false
defp hash_password(password) do
Argon2.hash_pwd_salt(password)
end
def check(tested_password, %{ :password => hash }) do
Argon2.verify_pass(tested_password, hash)
end
end
| 20.258065 | 62 | 0.692675 |
03f76df20600cfdc517643a3568fb5c0ce63faa9 | 2,589 | ex | Elixir | lib/link_preview/processor.ex | dhirajbajaj/link_preview | b500c27b0244ec64563cae80a078c94adb12dec8 | [
"Apache-2.0"
] | null | null | null | lib/link_preview/processor.ex | dhirajbajaj/link_preview | b500c27b0244ec64563cae80a078c94adb12dec8 | [
"Apache-2.0"
] | null | null | null | lib/link_preview/processor.ex | dhirajbajaj/link_preview | b500c27b0244ec64563cae80a078c94adb12dec8 | [
"Apache-2.0"
] | null | null | null | defmodule LinkPreview.Processor do
@moduledoc """
Combines the logic of other modules with user input.
"""
alias LinkPreview.{Page, Requests}
alias LinkPreview.Parsers.{Basic, Opengraph, Html, Image}
@doc """
Takes url and returns result of processing.
"""
@spec call(String.t) :: LinkPreview.success | LinkPreview.failure
def call(url) do
case Requests.head(url) do
{:ok, %Tesla.Env{status: 200, url: final_url, headers: %{"content-type" => "text/html" <> _}}} ->
parsers = Application.get_env(:link_preview, :parsers, [Opengraph, Html])
do_call(url, final_url, parsers)
{:ok, %Tesla.Env{status: 200, url: final_url, headers: %{"content-type" => "image/" <> _}}} ->
do_image_call(url, final_url, [Image])
{:ok, _} ->
%LinkPreview.Error{origin: LinkPreview, message: "unsupported response"}
{:error, %{__struct__: origin, message: message}} ->
%LinkPreview.Error{origin: origin, message: message}
end
|> to_tuple()
catch
_, %{__struct__: origin, message: message} ->
{:error, %LinkPreview.Error{origin: origin, message: message}}
_, _ ->
{:error, %LinkPreview.Error{origin: :unknown}}
end
defp to_tuple(result) do
case result do
%Page{} -> {:ok, result}
%LinkPreview.Error{} -> {:error, result}
end
end
defp do_image_call(url, final_url, parsers) do
url
|> Page.new(final_url)
|> collect_data(parsers, nil)
end
defp do_call(url, final_url, parsers) do
case Requests.get(url) do
{:ok, %Tesla.Env{status: 200, body: body}} ->
url
|> Page.new(final_url)
|> collect_data(parsers, body)
_ ->
%LinkPreview.Error{origin: LinkPreview, message: "unsupported response"}
end
end
defp collect_data(page, parsers, body) do
Enum.reduce(parsers, page, &apply_each_function(&1, &2, body))
end
defp apply_each_function(parser, page, body) do
if Code.ensure_loaded?(parser) do
Enum.reduce_while(Basic.parsable(), page, &apply_or_halt(parser, &1, &2, body))
else
page
end
end
defp apply_or_halt(parser, :images, page, body) do
current_value = Map.get(page, :images)
if current_value == [] do
{:cont, apply(parser, :images, [page, body])}
else
{:halt, page}
end
end
defp apply_or_halt(parser, function, page, body) do
current_value = Map.get(page, function)
if is_nil(current_value) do
{:cont, apply(parser, function, [page, body])}
else
{:halt, page}
end
end
end
| 28.766667 | 103 | 0.626883 |
03f7da7245be9ed423b3478ae98e1284250ebfe3 | 5,225 | ex | Elixir | lib/logger/lib/logger/utils.ex | DmitryKakurin/elixir | a5df6a5a830d4cff8b7c8da54342b66cab999e0f | [
"Apache-2.0"
] | 1 | 2019-08-13T23:22:33.000Z | 2019-08-13T23:22:33.000Z | lib/logger/lib/logger/utils.ex | DmitryKakurin/elixir | a5df6a5a830d4cff8b7c8da54342b66cab999e0f | [
"Apache-2.0"
] | 1 | 2019-04-25T12:52:49.000Z | 2019-04-25T13:27:31.000Z | lib/logger/lib/logger/utils.ex | DmitryKakurin/elixir | a5df6a5a830d4cff8b7c8da54342b66cab999e0f | [
"Apache-2.0"
] | 1 | 2018-01-09T20:10:59.000Z | 2018-01-09T20:10:59.000Z | defmodule Logger.Utils do
@moduledoc false
@doc """
Truncates a `chardata` into `n` bytes.
There is a chance we truncate in the middle of a grapheme
cluster but we never truncate in the middle of a binary
code point. For this reason, truncation is not exact.
"""
@spec truncate(IO.chardata(), non_neg_integer) :: IO.chardata()
def truncate(chardata, :infinity) when is_binary(chardata) or is_list(chardata) do
chardata
end
def truncate(chardata, n) when n >= 0 do
{chardata, n} = truncate_n(chardata, n)
if n >= 0, do: chardata, else: [chardata, " (truncated)"]
end
defp truncate_n(_, n) when n < 0 do
{"", n}
end
defp truncate_n(binary, n) when is_binary(binary) do
remaining = n - byte_size(binary)
if remaining < 0 do
# There is a chance we are cutting at the wrong
# place so we need to fix the binary.
{fix_binary(binary_part(binary, 0, n)), remaining}
else
{binary, remaining}
end
end
defp truncate_n(int, n) when int in 0..127, do: {int, n - 1}
defp truncate_n(int, n) when int in 127..0x07FF, do: {int, n - 2}
defp truncate_n(int, n) when int in 0x800..0xFFFF, do: {int, n - 3}
defp truncate_n(int, n) when int >= 0x10000 and is_integer(int), do: {int, n - 4}
defp truncate_n(list, n) when is_list(list) do
truncate_n_list(list, n, [])
end
defp truncate_n(other, _n) do
raise ArgumentError,
"cannot truncate chardata because it contains something that is not " <>
"valid chardata: #{inspect(other)}"
end
defp truncate_n_list(_, n, acc) when n < 0 do
{:lists.reverse(acc), n}
end
defp truncate_n_list([h | t], n, acc) do
{h, n} = truncate_n(h, n)
truncate_n_list(t, n, [h | acc])
end
defp truncate_n_list([], n, acc) do
{:lists.reverse(acc), n}
end
defp truncate_n_list(t, n, acc) do
{t, n} = truncate_n(t, n)
{:lists.reverse(acc, t), n}
end
defp fix_binary(binary) do
# Use a thirteen-bytes offset to look back in the binary.
# This should allow at least two code points of 6 bytes.
suffix_size = min(byte_size(binary), 13)
prefix_size = byte_size(binary) - suffix_size
<<prefix::binary-size(prefix_size), suffix::binary-size(suffix_size)>> = binary
prefix <> fix_binary(suffix, "")
end
defp fix_binary(<<h::utf8, t::binary>>, acc) do
acc <> <<h::utf8>> <> fix_binary(t, "")
end
defp fix_binary(<<h, t::binary>>, acc) do
fix_binary(t, <<h, acc::binary>>)
end
defp fix_binary(<<>>, _acc) do
<<>>
end
@doc """
Receives a format string and arguments, scans them, and then replace `~p`,
`~P`, `~w` and `~W` by its inspected variants.
For information about format scanning and how to consume them,
check `:io_lib.scan_format/2`
"""
def scan_inspect(format, args, truncate, opts \\ %Inspect.Opts{})
def scan_inspect(format, args, truncate, opts) when is_atom(format) do
scan_inspect(Atom.to_charlist(format), args, truncate, opts)
end
def scan_inspect(format, args, truncate, opts) when is_binary(format) do
scan_inspect(:binary.bin_to_list(format), args, truncate, opts)
end
def scan_inspect(format, [], _truncate, _opts) when is_list(format) do
:io_lib.scan_format(format, [])
end
def scan_inspect(format, args, truncate, opts) when is_list(format) do
# A pre-pass that removes binaries from
# arguments according to the truncate limit.
{args, _} =
Enum.map_reduce(args, truncate, fn arg, acc ->
if is_binary(arg) and acc != :infinity do
truncate_n(arg, acc)
else
{arg, acc}
end
end)
format
|> :io_lib.scan_format(args)
|> Enum.map(&handle_format_spec(&1, opts))
end
@inspected_format_spec %{
adjust: :right,
args: [],
control_char: ?s,
encoding: :unicode,
pad_char: ?\s,
precision: :none,
strings: true,
width: :none
}
defp handle_format_spec(%{control_char: char} = spec, opts) when char in 'wWpP' do
%{args: args, width: width, strings: strings?} = spec
opts = %{
opts
| charlists: inspect_charlists(strings?, opts),
limit: inspect_limit(char, args, opts),
width: inspect_width(char, width)
}
%{@inspected_format_spec | args: [inspect_data(args, opts)]}
end
defp handle_format_spec(spec, _opts), do: spec
defp inspect_charlists(false, _), do: :as_lists
defp inspect_charlists(_, opts), do: opts.charlists
defp inspect_limit(char, [_, limit], _) when char in 'WP', do: limit
defp inspect_limit(_, _, opts), do: opts.limit
defp inspect_width(char, _) when char in 'wW', do: :infinity
defp inspect_width(_, width), do: width
defp inspect_data([data | _], opts) do
data
|> Inspect.Algebra.to_doc(opts)
|> Inspect.Algebra.format(opts.width)
end
@doc """
Returns a timestamp that includes milliseconds.
"""
def timestamp(utc_log?) do
{_, _, micro} = now = :os.timestamp()
{date, {hours, minutes, seconds}} =
case utc_log? do
true -> :calendar.now_to_universal_time(now)
false -> :calendar.now_to_local_time(now)
end
{date, {hours, minutes, seconds, div(micro, 1000)}}
end
end
| 28.243243 | 84 | 0.644976 |
03f7db457f62f5d295cc166bf5b54249a9f39121 | 2,003 | ex | Elixir | lib/parser.ex | lizhaochao/fun_pipelinex | 2602ee7ab7d9e58101ba6927bffd1190105dae1b | [
"MIT"
] | null | null | null | lib/parser.ex | lizhaochao/fun_pipelinex | 2602ee7ab7d9e58101ba6927bffd1190105dae1b | [
"MIT"
] | null | null | null | lib/parser.ex | lizhaochao/fun_pipelinex | 2602ee7ab7d9e58101ba6927bffd1190105dae1b | [
"MIT"
] | null | null | null | defmodule FunPipelinex.Parser do
@moduledoc false
alias FunPipelinex.{Error, Helper}
@allowed_fun_types [:def]
@not_support_types [:@, :defmodule, :use, :require, :import, :alias]
###
def parse_fun({:__block__, _, [_ | _] = block}), do: parse_fun(block, [])
def parse_fun(block), do: parse_fun([block], [])
def parse_fun([], funs), do: Enum.reverse(funs)
def parse_fun([expr | rest], funs) do
fun = do_parse_fun(expr, %{})
parse_fun(rest, [fun | funs])
end
defp do_parse_fun({type, _, fun}, parts) when type in @allowed_fun_types do
do_parse_fun(fun, parts)
end
defp do_parse_fun([{:when, _, fa_guard}, [{:do, block}]], parts) do
fa_guard
|> do_parse_fun(parts)
|> Map.put(:block, block)
end
defp do_parse_fun([fa, [{:do, block}]], parts) do
fa
|> do_parse_fun(parts)
|> Map.put(:block, block)
|> Map.put(:guard, true)
end
defp do_parse_fun([fa, guard], parts) do
fa
|> do_parse_fun(parts)
|> Map.put(:guard, guard)
end
defp do_parse_fun({f, _, [{_, _, _} | _] = a}, parts) when f not in @not_support_types do
parts
|> Map.put(:f, f)
|> Map.put(:a, a)
end
defp do_parse_fun({f, _, _}, parts) when f not in @not_support_types do
parts
|> Map.put(:f, f)
|> Map.put(:a, [])
end
defp do_parse_fun({type, _, [_ | _]}, _parts), do: raise(Error, "not support #{type}")
defp do_parse_fun(_other_expr, _parts), do: raise(Error, "unknown function")
###
def parse_filters({:__block__, _, filter_expr}), do: do_parse_filters(filter_expr, [])
def parse_filters(filter_expr), do: do_parse_filters([filter_expr], [])
def do_parse_filters([], filters), do: Enum.dedup(filters)
def do_parse_filters([{:filter, _, [{:__aliases__, _, term}]} | rest], filters),
do: do_parse_filters(rest, [Helper.make_m_name(term) | filters])
def do_parse_filters([{:filter, _, [f_name]} | rest], filters) when is_atom(f_name),
do: do_parse_filters(rest, [f_name | filters])
end
| 28.614286 | 91 | 0.637544 |
03f7ea0146b88a7e6b2bb4392038c95399f959af | 1,345 | ex | Elixir | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_hybrid_inspect_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_hybrid_inspect_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_hybrid_inspect_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2HybridInspectResponse do
@moduledoc """
Quota exceeded errors will be thrown once quota has been met.
## Attributes
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{}
end
defimpl Poison.Decoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2HybridInspectResponse do
def decode(value, options) do
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2HybridInspectResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2HybridInspectResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.02381 | 94 | 0.773234 |
03f7fe92f14b48b347aae17cdb3cf2c967aba60c | 5,849 | exs | Elixir | test/hexdocs/plug_test.exs | hexpm/hexdocs | 808d0b06bbd1a36c639231225ed78cec8c182cae | [
"Apache-2.0"
] | 29 | 2016-10-13T07:32:04.000Z | 2022-03-25T05:59:14.000Z | test/hexdocs/plug_test.exs | hexpm/hexdocs | 808d0b06bbd1a36c639231225ed78cec8c182cae | [
"Apache-2.0"
] | 21 | 2016-02-24T03:59:35.000Z | 2021-07-30T08:44:39.000Z | test/hexdocs/plug_test.exs | hexpm/hexdocs | 808d0b06bbd1a36c639231225ed78cec8c182cae | [
"Apache-2.0"
] | 12 | 2016-02-28T19:57:36.000Z | 2022-03-18T07:47:39.000Z | defmodule Hexdocs.PlugTest do
use ExUnit.Case, async: true
use Plug.Test
alias Hexdocs.{HexpmMock, Store}
@bucket :docs_private_bucket
test "requests without subdomain not supported" do
conn = conn(:get, "http://localhost:5002/foo") |> call()
assert conn.status == 400
end
test "redirect to hexpm with no session and no key" do
conn = conn(:get, "http://plugtest.localhost:5002/foo") |> call()
assert conn.status == 302
assert get_resp_header(conn, "location") ==
["http://localhost:5000/login?hexdocs=plugtest&return=/foo"]
end
test "update session and redirect when key is set" do
conn = conn(:get, "http://plugtest.localhost:5002/foo?key=abc") |> call()
assert conn.status == 302
assert get_resp_header(conn, "location") == ["/foo"]
assert get_session(conn, "key") == "abc"
assert recent?(get_session(conn, "key_refreshed_at"))
assert recent?(get_session(conn, "key_created_at"))
end
test "redirect to hexpm with with dead key" do
old = ~N[2018-01-01 00:00:00]
conn =
conn(:get, "http://plugtest.localhost:5002/foo")
|> init_test_session(%{"key" => "abc", "key_refreshed_at" => old, "key_created_at" => old})
|> call()
assert conn.status == 302
assert get_resp_header(conn, "location") ==
["http://localhost:5000/login?hexdocs=plugtest&return=/foo"]
end
test "reverify stale key succeeds", %{test: test} do
Mox.expect(HexpmMock, :verify_key, fn key, organization ->
assert key == "abc"
assert organization == "plugtest"
:ok
end)
old = NaiveDateTime.add(NaiveDateTime.utc_now(), -3600)
Store.put!(@bucket, "plugtest/#{test}/index.html", "body")
conn =
conn(:get, "http://plugtest.localhost:5002/#{test}/index.html")
|> init_test_session(%{"key" => "abc", "key_refreshed_at" => old, "key_created_at" => old})
|> call()
assert conn.status == 200
assert conn.resp_body == "body"
end
test "reverify stale key requires refresh and redirects", %{test: test} do
Mox.expect(HexpmMock, :verify_key, fn key, organization ->
assert key == "abc"
assert organization == "plugtest"
:refresh
end)
old = NaiveDateTime.add(NaiveDateTime.utc_now(), -3600)
Store.put!(@bucket, "plugtest/#{test}/index.html", "body")
conn =
conn(:get, "http://plugtest.localhost:5002/foo")
|> init_test_session(%{"key" => "abc", "key_refreshed_at" => old, "key_created_at" => old})
|> call()
assert conn.status == 302
assert get_resp_header(conn, "location") ==
["http://localhost:5000/login?hexdocs=plugtest&return=/foo"]
end
test "reverify stale key fails" do
Mox.expect(HexpmMock, :verify_key, fn key, organization ->
assert key == "abc"
assert organization == "plugtest"
{:error, "account not authorized"}
end)
old = NaiveDateTime.add(NaiveDateTime.utc_now(), -3600)
conn =
conn(:get, "http://plugtest.localhost:5002/foo")
|> init_test_session(%{"key" => "abc", "key_refreshed_at" => old, "key_created_at" => old})
|> call()
assert conn.status == 403
assert conn.resp_body =~ "account not authorized"
end
test "serve 200 page", %{test: test} do
now = NaiveDateTime.utc_now()
Store.put!(@bucket, "plugtest/#{test}/index.html", "body")
conn =
conn(:get, "http://plugtest.localhost:5002/#{test}/index.html")
|> init_test_session(%{"key" => "abc", "key_refreshed_at" => now, "key_created_at" => now})
|> call()
assert conn.status == 200
assert conn.resp_body == "body"
end
test "serve 404 page", %{test: test} do
now = NaiveDateTime.utc_now()
Store.put!(@bucket, "plugtest/#{test}/index.html", "body")
conn =
conn(:get, "http://plugtest.localhost:5002/#{test}/404.html")
|> init_test_session(%{"key" => "abc", "key_refreshed_at" => now, "key_created_at" => now})
|> call()
assert conn.status == 404
assert conn.resp_body =~ "Page not found"
end
test "redirect to root", %{test: test} do
now = NaiveDateTime.utc_now()
Store.put!(@bucket, "plugtest/#{test}/index.html", "body")
conn =
conn(:get, "http://plugtest.localhost:5002/#{test}")
|> init_test_session(%{"key" => "abc", "key_refreshed_at" => now, "key_created_at" => now})
|> call()
assert conn.status == 302
assert get_resp_header(conn, "location") == ["/#{test}/"]
end
test "serve index.html for root requests", %{test: test} do
now = NaiveDateTime.utc_now()
Store.put!(@bucket, "plugtest/#{test}/index.html", "body")
conn =
conn(:get, "http://plugtest.localhost:5002/#{test}/")
|> init_test_session(%{"key" => "abc", "key_refreshed_at" => now, "key_created_at" => now})
|> call()
assert conn.status == 200
assert conn.resp_body == "body"
end
test "serve docs_config.js for unversioned and versioned requests", %{test: test} do
now = NaiveDateTime.utc_now()
Store.put!(@bucket, "plugtest/#{test}/docs_config.js", "var versionNodes;")
conn =
conn(:get, "http://plugtest.localhost:5002/#{test}/docs_config.js")
|> init_test_session(%{"key" => "abc", "key_refreshed_at" => now, "key_created_at" => now})
|> call()
assert conn.status == 200
assert conn.resp_body == "var versionNodes;"
conn =
conn(:get, "http://plugtest.localhost:5002/#{test}/1.0.0/docs_config.js")
|> init_test_session(%{"key" => "abc", "key_refreshed_at" => now, "key_created_at" => now})
|> call()
assert conn.status == 200
assert conn.resp_body == "var versionNodes;"
end
defp call(conn) do
Hexdocs.Plug.call(conn, [])
end
defp recent?(datetime) do
abs(NaiveDateTime.diff(datetime, NaiveDateTime.utc_now())) < 3
end
end
| 31.788043 | 97 | 0.624893 |
03f80d2aa241c829d1c932ada46e40780c91bb3f | 955 | ex | Elixir | test/support/channel_case.ex | KZeillmann/MenuPlanner | 56bd6afca8e321261720dc290f180f4944b8b483 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | KZeillmann/MenuPlanner | 56bd6afca8e321261720dc290f180f4944b8b483 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | KZeillmann/MenuPlanner | 56bd6afca8e321261720dc290f180f4944b8b483 | [
"MIT"
] | null | null | null | defmodule MenuPlanner.Web.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build common datastructures and query the data layer.
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
# Import conveniences for testing with channels
use Phoenix.ChannelTest
# The default endpoint for testing
@endpoint MenuPlanner.Web.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(MenuPlanner.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(MenuPlanner.Repo, {:shared, self()})
end
:ok
end
end
| 25.131579 | 73 | 0.719372 |
03f814570ab3dcfdf4cc368e2540145c0fd6d5e4 | 237 | ex | Elixir | lib/mpdex/client.ex | bosko/mpdex | fe64ce453332770df99c12320bfeeb5ac8b801dc | [
"MIT"
] | null | null | null | lib/mpdex/client.ex | bosko/mpdex | fe64ce453332770df99c12320bfeeb5ac8b801dc | [
"MIT"
] | null | null | null | lib/mpdex/client.ex | bosko/mpdex | fe64ce453332770df99c12320bfeeb5ac8b801dc | [
"MIT"
] | null | null | null | defmodule Mpdex.Client do
@moduledoc """
Specifies client API required from MPD client
"""
@doc "Method for sending command to MPD server"
@callback send(cmd :: binary) :: {:ok, :any} | {:error, atom() | binary() | map()}
end
| 26.333333 | 84 | 0.649789 |
03f84e41336b6ac038caffbcfad61fb4890b7706 | 491 | ex | Elixir | lib/bloggex_web/views/error_view.ex | dreamingechoes/bloggex | 9ead10ec1fd8fda0da3cb08106c43a9043188199 | [
"MIT"
] | 1 | 2020-01-14T03:17:51.000Z | 2020-01-14T03:17:51.000Z | lib/bloggex_web/views/error_view.ex | dreamingechoes/bloggex | 9ead10ec1fd8fda0da3cb08106c43a9043188199 | [
"MIT"
] | null | null | null | lib/bloggex_web/views/error_view.ex | dreamingechoes/bloggex | 9ead10ec1fd8fda0da3cb08106c43a9043188199 | [
"MIT"
] | null | null | null | defmodule BloggexWeb.ErrorView do
use BloggexWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.html", _assigns) do
# "Internal Server Error"
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| 28.882353 | 61 | 0.735234 |
03f85c62846902c60a93e2c910661c7b91c39284 | 2,956 | ex | Elixir | lib/surface/components/utils.ex | RudolfMan/surface | ee8c1546b77c91fe08e7360e64666c613bc5a900 | [
"MIT"
] | 1,161 | 2019-12-12T02:30:52.000Z | 2021-03-11T17:55:44.000Z | lib/surface/components/utils.ex | RudolfMan/surface | ee8c1546b77c91fe08e7360e64666c613bc5a900 | [
"MIT"
] | 248 | 2021-03-12T07:39:37.000Z | 2022-03-31T13:36:44.000Z | lib/surface/components/utils.ex | RudolfMan/surface | ee8c1546b77c91fe08e7360e64666c613bc5a900 | [
"MIT"
] | 73 | 2019-12-12T13:57:41.000Z | 2021-03-11T21:46:10.000Z | defmodule Surface.Components.Utils do
@moduledoc false
import Surface, only: [event_to_opts: 2]
@valid_uri_schemes [
"http:",
"https:",
"ftp:",
"ftps:",
"mailto:",
"news:",
"irc:",
"gopher:",
"nntp:",
"feed:",
"telnet:",
"mms:",
"rtsp:",
"svn:",
"tel:",
"fax:",
"xmpp:"
]
def valid_destination!(%URI{} = uri, context) do
valid_destination!(URI.to_string(uri), context)
end
def valid_destination!({:safe, to}, context) do
{:safe, valid_string_destination!(IO.iodata_to_binary(to), context)}
end
def valid_destination!({other, to}, _context) when is_atom(other) do
[Atom.to_string(other), ?:, to]
end
def valid_destination!(to, context) do
valid_string_destination!(IO.iodata_to_binary(to), context)
end
for scheme <- @valid_uri_schemes do
def valid_string_destination!(unquote(scheme) <> _ = string, _context), do: string
end
def valid_string_destination!(to, context) do
if not match?("/" <> _, to) and String.contains?(to, ":") do
raise ArgumentError, """
unsupported scheme given to #{context}. In case you want to link to an
unknown or unsafe scheme, such as javascript, use a tuple: {:javascript, rest}
"""
else
to
end
end
def csrf_data(to, opts) do
case Keyword.pop(opts, :csrf_token, true) do
{csrf, opts} when is_binary(csrf) ->
{[csrf: csrf], opts}
{true, opts} ->
{[csrf: csrf_token(to)], opts}
{false, opts} ->
{[], opts}
end
end
defp csrf_token(to) do
{mod, fun, args} = Application.fetch_env!(:surface, :csrf_token_reader)
apply(mod, fun, [to | args])
end
def skip_csrf(opts) do
Keyword.delete(opts, :csrf_token)
end
def opts_to_phx_opts(opts) do
for {key, value} <- opts do
case key do
:trigger_action -> {:phx_trigger_action, value}
_ -> {key, value}
end
end
end
def events_to_opts(assigns) do
[
event_to_opts(assigns.capture_click, :phx_capture_click),
event_to_opts(assigns.click, :phx_click),
event_to_opts(assigns.window_focus, :phx_window_focus),
event_to_opts(assigns.window_blur, :phx_window_blur),
event_to_opts(assigns.focus, :phx_focus),
event_to_opts(assigns.blur, :phx_blur),
event_to_opts(assigns.window_keyup, :phx_window_keyup),
event_to_opts(assigns.window_keydown, :phx_window_keydown),
event_to_opts(assigns.keyup, :phx_keyup),
event_to_opts(assigns.keydown, :phx_keydown),
values_to_opts(assigns.values)
]
|> List.flatten()
end
defp values_to_opts([]) do
[]
end
defp values_to_opts(values) when is_list(values) do
values_to_attrs(values)
end
defp values_to_opts(_values) do
[]
end
defp values_to_attrs(values) when is_list(values) do
for {key, value} <- values do
{:"phx-value-#{key}", value}
end
end
end
| 24.229508 | 86 | 0.635995 |
03f86722894f79407bb030747b1e00f3d5b5fa37 | 104 | ex | Elixir | tests/dummy/web/views/history_relationship_view.ex | autoxjs/autox-phoenix | 6446f4487e3af28955f6560973cff6add34be4d4 | [
"MIT"
] | null | null | null | tests/dummy/web/views/history_relationship_view.ex | autoxjs/autox-phoenix | 6446f4487e3af28955f6560973cff6add34be4d4 | [
"MIT"
] | 20 | 2016-04-05T06:28:58.000Z | 2016-05-12T15:45:37.000Z | tests/dummy/web/views/history_relationship_view.ex | foxnewsnetwork/autox | 66ea3f0f7ba8b3f9e910984a2ed3cdf0ef5ef29a | [
"MIT"
] | null | null | null | defmodule Dummy.HistoryRelationshipView do
use Dummy.Web, :view
use Autox.RelationshipView
end | 17.333333 | 42 | 0.778846 |
03f8a3df4ea3a3e8b2de4c92eda8937ba4d9050b | 6,271 | ex | Elixir | lib/xplane_instance.ex | robinhilliard/elixplane | 8b2e5151f2ac3d19a77089da5c32e0e6b47a3d33 | [
"MIT"
] | 5 | 2018-10-01T17:15:21.000Z | 2021-05-24T19:13:46.000Z | lib/xplane_instance.ex | robinhilliard/elixplane | 8b2e5151f2ac3d19a77089da5c32e0e6b47a3d33 | [
"MIT"
] | null | null | null | lib/xplane_instance.ex | robinhilliard/elixplane | 8b2e5151f2ac3d19a77089da5c32e0e6b47a3d33 | [
"MIT"
] | null | null | null | defmodule XPlane.Instance do
@moduledoc """
Represent a running instance of X-Plane and provide a GenServer to monitor
the local network for X-Plane multicast "beacon" messages and return them
as a list.
## Example
```
iex> XPlane.Instance.start
{:ok, #PID<0.138.0>}
iex> XPlane.Instance.list
[
%XPlane.Instance{
computer_name: "Starboard",
host: :xplane,
ip: {192, 168, 0, 58},
addr: "192.168.0.58",
major_version: 1,
minor_version: 1,
port: 49000,
role: :extern_visual,
seconds_since_seen: 0,
version_number: 105101
}
]
iex> XPlane.Instance.stop
:ok
```
"""
defstruct [
:ip, # IP Address of X-Plane instance as tuple
:addr, # Same as dot separated string
:major_version, # 1 at the time of X-Plane 10.40
:minor_version, # 1 at the time of X-Plane 10.40
:version_number, # 104103 for X-Plane 10.41r3
:host, # :xplane | :planemaker
:role, # :master | :extern_visual | :ios
:port, # Port number X-Plane is listening on, 49000 by default
:computer_name, # Hostname of the computer
:seconds_since_seen] # Time since last beacon multicast received in seconds
@type t :: %XPlane.Instance{
ip: {integer, integer, integer, integer},
addr: String.t,
major_version: integer,
minor_version: integer,
version_number: integer,
host: :xplane | :planemaker,
role: :master | :extern_visual | :ios,
port: integer,
computer_name: String.t,
seconds_since_seen: integer
}
@beacon_addr {239, 255, 1, 1}
@beacon_port 49707
@zeros_addr {0, 0, 0, 0}
@startup_grace_period 2500
@sol_socket 0xffff
@so_reuseport 0x0200
use GenServer
# API
@doc """
Start GenServer that listens for X-Plane multicast beacon messages and
maintains a register of received beacon details. A short delay built in
to the function leaves enough time for beacons to be received so that
subsequent calls to list return reasonable results.
## Parameters
Accepts normal GenServer options apart from name which is set to the
module name.
"""
@spec start(list) :: {:ok, pid} | {:error, any} | :ignore
def start(opts \\ []) do
result = GenServer.start(__MODULE__, :ok, [name: __MODULE__] ++ opts)
:timer.sleep(@startup_grace_period) # Allow time for beacons to be picked up
result
end
@doc """
Start GenServer linked to current process that listens for X-Plane multicast
beacon messages and maintains a register of received beacon details. A short
delay built in to the function leaves enough time for beacons to be received
so that subsequent calls to list return reasonable results.
## Parameters
Accepts normal GenServer options apart from name which is set to the
module name.
"""
@spec start_link(list) :: {:ok, pid} | {:error, any} | :ignore
def start_link(opts \\ []) do
result = GenServer.start_link(__MODULE__, :ok, [name: __MODULE__] ++ opts)
:timer.sleep(@startup_grace_period) # Allow time for beacons to be picked up
result
end
@doc """
Return a list of the most recent X-Plane beacon details received from each
IP address. Note that a listing does not guarantee that the instance is
currently running, only that it was seen `seconds_since_seen` seconds ago.
Reuseport code based on:
https://github.com/refuge/rbeacon/blob/master/src/rbeacon.erl#L414-L425
"""
@spec list() :: list(XPlane.Instance.t)
def list() do
now = :erlang.system_time(:second)
Enum.map(
GenServer.call(__MODULE__, :list) |> Map.to_list,
fn {{ip, _}, {major_version, minor_version, host, version_number,
role, port, computer_name, last_seen}} ->
%XPlane.Instance{
ip: ip,
addr: (ip |> Tuple.to_list |> Enum.join(".")),
major_version: major_version,
minor_version: minor_version,
version_number: version_number,
host: [nil, :xplane, :planemaker] |> Enum.at(host),
role: [nil, :master, :extern_visual, :ios] |> Enum.at(role),
port: port,
computer_name: computer_name,
seconds_since_seen: now - last_seen
}
end
)
end
@doc """
Stop the GenServer listening for multicast X-Plane beacon messages
"""
@spec stop() :: :ok | {:error, any}
def stop() do
GenServer.cast(__MODULE__, :stop)
end
# GenServer Callbacks
def init(:ok) do
udp_options = [
:binary,
active: true,
add_membership: {@beacon_addr, @zeros_addr},
multicast_if: @zeros_addr,
multicast_loop: false,
multicast_ttl: 4,
reuseaddr: true] ++
# In addition to reuseaddr BSD variants have to specifically
# set reuseport (only) when listening to beacon according
# to "Sending Data to X-Plane"
case :os.type() do
{:unix, os_name} ->
cond do
os_name in [:darwin, :freebsd, :openbsd, :netbsd] ->
[{:raw, @sol_socket, @so_reuseport, <<1::native-32>>}]
true ->
[]
end
_ ->
[]
end
{:ok, _sock} = :gen_udp.open(@beacon_port, udp_options)
{:ok, %{}}
end
def handle_info({:udp, _sock, sender_ip, _sender,
<<"BECN\0",
major_version::unsigned,
minor_version::unsigned,
host::native-integer-32,
version_number::native-integer-32,
role::unsigned-native-32,
port::unsigned-native-16,
computer_name::binary>>}, state) do
{
:noreply,
state
|> Map.put(
{sender_ip, port}, {
major_version,
minor_version,
host,
version_number,
role,
port,
computer_name |> String.split(<<0>>) |> List.first,
:erlang.system_time(:second)
}
)
}
end
def handle_call(:list, _from, state) do
{:reply, state, state}
end
def handle_cast(:stop, state) do
{:stop, :normal, state}
end
end
| 27.747788 | 81 | 0.603413 |
03f8b117ab446601c740298da795aca69f5abf31 | 22,330 | exs | Elixir | test/graph_test.exs | renaudlenne/libgraph | bd9b71fcc0a4080551668cc69dfc6bee14be5a0c | [
"MIT"
] | 366 | 2017-06-03T23:10:04.000Z | 2022-03-22T12:26:38.000Z | test/graph_test.exs | renaudlenne/libgraph | bd9b71fcc0a4080551668cc69dfc6bee14be5a0c | [
"MIT"
] | 50 | 2017-07-14T17:55:53.000Z | 2022-03-11T07:40:31.000Z | test/graph_test.exs | renaudlenne/libgraph | bd9b71fcc0a4080551668cc69dfc6bee14be5a0c | [
"MIT"
] | 64 | 2017-07-29T07:01:42.000Z | 2022-03-20T12:07:55.000Z | defmodule GraphTest do
use ExUnit.Case, async: true
doctest Graph
doctest Graph.Edge
alias Graph.Edge
alias Graph.Test.Generators
test "injectable vertex_identifier" do
g = Graph.new()
g_with_custom_vertex_identifier =
Graph.new(vertex_identifier: fn v -> :erlang.phash2(v, trunc(:math.pow(2, 16))) end)
g = Graph.add_vertex(g, :v1, :labelA)
g_with_custom_vertex_identifier =
Graph.add_vertex(g_with_custom_vertex_identifier, :v1, :labelA)
assert Graph.has_vertex?(g, :v1)
assert Graph.has_vertex?(g_with_custom_vertex_identifier, :v1)
end
test "delete vertex" do
g = Graph.new()
g = Graph.add_vertex(g, :v1, :labelA)
g = Graph.delete_vertex(g, :v1)
g = Graph.add_vertex(g, :v1, :labelB)
assert [:labelB] = Graph.vertex_labels(g, :v1)
end
test "delete vertices" do
graph =
Graph.new()
|> Graph.add_vertices([1, 2, 4, 6])
|> Graph.add_edge(1, 2)
|> Graph.add_edge(2, 4)
|> Graph.add_edge(4, 6)
graph_two =
graph
|> Graph.add_vertices([3, 5, 7])
|> Graph.add_edge(1, 3)
|> Graph.add_edge(3, 4)
|> Graph.add_edge(3, 5)
|> Graph.add_edge(5, 6)
|> Graph.add_edge(5, 7)
assert graph == Graph.delete_vertices(graph_two, [3, 5, 7])
end
test "inspect" do
g =
Graph.new()
|> Graph.add_edges([
{:a, :b},
{:a, :b, label: :foo},
{:b, :c, weight: 3},
{:b, :a, label: {:complex, :label}}
])
ug =
Graph.new(type: :undirected)
|> Graph.add_edges([
{:a, :b},
{:a, :b, label: :foo},
{:b, :c, weight: 3},
{:b, :a, label: {:complex, :label}}
])
# structs: false
structs_false = "#{inspect(g, structs: false)}"
doc = Inspect.Algebra.format(Inspect.Algebra.to_doc(g, %Inspect.Opts{structs: false}), 99999)
assert ^structs_false = :erlang.iolist_to_binary(doc)
# pretty printed
str = "#{inspect(g)}"
assert "#Graph<type: directed, vertices: [:a, :b, :c], edges: [:a -[foo]-> :b, :a -> :b, :b -[{:complex, :label}]-> :a, :b -> :c]>" =
str
ustr = "#{inspect(ug)}"
assert "#Graph<type: undirected, vertices: [:a, :b, :c], edges: [:a <-[foo]-> :b, :a <-> :b, :a <-[{:complex, :label}]-> :b, :b <-> :c]>" =
ustr
# large graph
g = Enum.reduce(1..150, Graph.new(), fn i, g -> Graph.add_edge(g, i, i + 1) end)
str = "#{inspect(g)}"
assert "#Graph<type: directed, num_vertices: 151, num_edges: 150>" = str
end
test "get info about graph" do
g = build_basic_cyclic_graph()
assert %{type: :directed, num_vertices: 5, num_edges: 7} = Graph.info(g)
end
test "is_cyclic?" do
dg = build_basic_cyclic_digraph()
refute :digraph_utils.is_acyclic(dg)
g = build_basic_cyclic_graph()
assert Graph.is_cyclic?(g)
refute Graph.is_acyclic?(g)
end
test "is_acyclic?" do
dg = build_basic_acyclic_digraph()
assert :digraph_utils.is_acyclic(dg)
g = build_basic_acyclic_graph()
assert Graph.is_acyclic?(g)
refute Graph.is_cyclic?(g)
end
test "is_tree?" do
dg = build_basic_tree_digraph()
assert :digraph_utils.is_tree(dg)
g = build_basic_tree_graph()
assert Graph.is_tree?(g)
end
test "is_arborescence?" do
dg = build_basic_tree_digraph()
assert :digraph_utils.is_arborescence(dg)
g = build_basic_tree_graph()
assert Graph.is_arborescence?(g)
end
test "arborescence_root" do
dg = build_basic_tree_digraph()
assert {:yes, root} = :digraph_utils.arborescence_root(dg)
g = build_basic_tree_graph()
assert ^root = Graph.arborescence_root(g)
end
test "edges/2 returns both directions" do
generated_result =
Graph.new()
|> Graph.add_edges([
{:a, :b, label: "label1"},
{:a, :b, label: "label2"},
{:b, :a, label: "label3"}
])
|> Graph.edges(:a)
expected_result = [
%Graph.Edge{label: "label3", v1: :b, v2: :a, weight: 1},
%Graph.Edge{label: "label1", v1: :a, v2: :b, weight: 1},
%Graph.Edge{label: "label2", v1: :a, v2: :b, weight: 1}
]
assert generated_result == expected_result
end
test "is_subgraph?" do
g = build_basic_tree_graph()
sg = Graph.subgraph(g, [:a, :b, :c])
assert Graph.is_subgraph?(sg, g)
end
test "topsort" do
dg = build_basic_acyclic_digraph()
dg_sorted = :digraph_utils.topsort(dg)
assert is_list(dg_sorted)
g = build_basic_acyclic_graph()
assert ^dg_sorted = Graph.topsort(g)
end
test "find all paths" do
g = build_basic_cyclic_graph()
assert [[:a, :c, :d, :e], [:a, :b, :d, :e], [:a, :b, :c, :d, :e]] = Graph.get_paths(g, :a, :e)
end
test "find all paths on loopy graph" do
g =
Graph.new()
|> Graph.add_edge(:a, :b)
|> Graph.add_edge(:a, :c)
|> Graph.add_edge(:b, :d)
|> Graph.add_edge(:c, :d)
|> Graph.add_edge(:d, :e)
|> Graph.add_edge(:e, :d)
|> Graph.add_edge(:d, :f)
|> Graph.add_edge(:f, :d)
assert [[:a, :c, :d], [:a, :b, :d]] == Graph.get_paths(g, :a, :d)
end
test "find shortest path" do
g = build_basic_cyclic_graph()
assert [:a, :b, :d, :e] = Graph.get_shortest_path(g, :a, :e)
end
test "shortest path is correct" do
g = Generators.dag(1_000)
dg = Generators.libgraph_to_digraph(g)
paths = Graph.get_paths(g, 1, 1_000)
shortest_g = Graph.dijkstra(g, 1, 1_000)
shortest_dg = :digraph.get_short_path(dg, 1, 1_000)
assert is_list(shortest_g)
assert is_list(shortest_dg)
assert is_list(paths)
[shortest | _] = Enum.sort_by(paths, &length/1)
shortest_len = length(shortest)
assert ^shortest_len = length(shortest_dg)
assert ^shortest_len = length(shortest_g)
end
test "shortest path for complex graph" do
g = build_complex_graph()
shortest_g = Graph.dijkstra(g, "start", "end")
assert shortest_g ==
[
"start",
"start_0",
96,
97,
98,
33,
100,
34,
35,
36,
37,
19,
65,
66,
67,
"end_0",
"end"
]
end
test "shortest path for complex undirected graph" do
g = build_complex_graph(:undirected)
shortest_g = Graph.dijkstra(g, "start", "end")
assert shortest_g ==
["start", "start_0", 95, 94, 93, 39, 38, 21, 69, 68, "end_0", "end"]
end
test "shortest path for complex graph using float weights" do
g = build_complex_graph_float()
shortest_g = Graph.dijkstra(g, "start", "end")
assert shortest_g ==
[
"start",
"start_0",
96,
97,
98,
33,
100,
34,
35,
36,
37,
19,
65,
66,
67,
"end_0",
"end"
]
end
test "shortest path for complex undirected graph using float weights" do
g = build_complex_graph_float(:undirected)
shortest_g = Graph.dijkstra(g, "start", "end")
assert shortest_g ==
["start", "start_0", 95, 94, 93, 39, 38, 21, 69, 68, "end_0", "end"]
end
test "edge undirected graph v1 > v2" do
g = build_basic_undirected_graph()
e1 = Graph.edge(g, :a, :b)
e2 = Graph.edge(g, :b, :a)
assert e1 == e2
end
test "edge undirected graph v1 < v2" do
g = build_basic_undirected_graph()
e1 = Graph.edge(g, :b, :c)
e2 = Graph.edge(g, :c, :b)
assert e1 == e2
end
test "edges undirected graph v1 > v2" do
g = build_basic_undirected_graph()
e1 = Graph.edges(g, :a, :b)
e2 = Graph.edges(g, :b, :a)
assert e1 == e2
end
test "edges undirected graph v1 < v2" do
g = build_basic_undirected_graph()
e1 = Graph.edges(g, :b, :c)
e2 = Graph.edges(g, :c, :b)
assert e1 == e2
end
test "out_edges" do
g = build_basic_acyclic_graph()
assert [%Edge{v1: :c, v2: :d}] = Graph.out_edges(g, :c)
end
test "in_edges" do
g = build_basic_acyclic_graph()
assert [%Edge{v1: :b, v2: :d}, %Edge{v1: :c, v2: :d}] = Graph.in_edges(g, :d)
end
test "out_neighbors" do
g = build_basic_acyclic_graph()
assert [:d] = Graph.out_neighbors(g, :c)
end
test "in_neighbors" do
g = build_basic_acyclic_graph()
assert [:b, :c] = Graph.in_neighbors(g, :d)
end
test "cliques/1" do
g =
Graph.new(type: :undirected)
|> Graph.add_vertices([:a, :b, :c, :d, :e, :f])
|> Graph.add_edges([{:a, :b}, {:b, :c}, {:c, :d}, {:d, :e}, {:e, :a}, {:e, :b}, {:d, :f}])
cliques = Graph.cliques(g)
assert [[:a, :b, :e], [:b, :c], [:c, :d], [:d, :e], [:d, :f]] = cliques
end
test "k_cliques/2" do
g =
Graph.new(type: :undirected)
|> Graph.add_vertices([:a, :b, :c, :d, :e, :f])
|> Graph.add_edges([{:a, :b}, {:b, :c}, {:c, :d}, {:d, :e}, {:e, :a}, {:e, :b}, {:d, :f}])
assert [[:a, :b, :e]] = Graph.k_cliques(g, 3)
end
test "k_core/2" do
g =
Graph.new(type: :undirected)
|> Graph.add_vertices([:a, :b, :c, :d, :e, :f, :g, :h, :i])
|> Graph.add_edges([
{:a, :b},
{:a, :c},
{:a, :d},
{:b, :c},
{:b, :d},
{:c, :d},
{:c, :e},
{:e, :f},
{:f, :g},
{:f, :h}
])
zero_core = Graph.k_core(g, 0)
assert Graph.is_subgraph?(zero_core, g)
assert Graph.vertices(g) == Graph.vertices(zero_core)
one_core = Graph.k_core(g, 1)
assert Graph.is_subgraph?(one_core, zero_core)
assert Graph.vertices(one_core) == [:a, :b, :c, :d, :e, :f, :g, :h]
three_core = Graph.k_core(g, 3)
assert Graph.is_subgraph?(three_core, one_core)
assert Graph.vertices(three_core) == [:a, :b, :c, :d]
g =
Graph.new(type: :undirected)
|> Graph.add_vertices([:a, :b, :c, :d, :e, :f, :g, :h, :i])
|> Graph.add_edges([
{:a, :b},
{:a, :c},
{:a, :d},
{:b, :c},
{:b, :d},
{:c, :d},
{:d, :e},
{:e, :f},
{:f, :g},
{:g, :h},
{:h, :i},
{:i, :f},
{:f, :h},
{:i, :g}
])
three_core = Graph.k_core(g, 3)
assert Graph.vertices(three_core) == [:a, :b, :c, :d, :f, :g, :h, :i]
g =
Graph.new()
|> Graph.add_vertices([:a, :b, :c, :d, :e, :f, :g, :h, :i])
|> Graph.add_edges([
{:a, :b},
{:a, :c},
{:a, :d},
{:b, :a},
{:b, :c},
{:b, :d},
{:c, :a},
{:c, :b},
{:c, :d},
{:d, :a},
{:d, :b},
{:d, :c},
{:d, :e},
{:e, :d},
{:e, :f},
{:f, :e},
{:f, :g},
{:g, :f},
{:g, :h},
{:h, :g},
{:h, :i},
{:i, :h},
{:i, :f},
{:f, :i},
{:h, :f},
{:f, :h},
{:g, :i},
{:i, :g}
])
three_core = Graph.k_core(g, 3)
assert Graph.vertices(three_core) == [:a, :b, :c, :d, :f, :g, :h, :i]
end
test "k_core_components/1" do
g =
Graph.new(type: :undirected)
|> Graph.add_vertices([:a, :b, :c, :d, :e, :f, :g, :h, :i])
|> Graph.add_edges([
{:a, :a},
{:a, :b},
{:a, :c},
{:a, :d},
{:b, :c},
{:b, :d},
{:c, :d},
{:c, :e},
{:e, :f},
{:f, :g},
{:f, :h}
])
components = Graph.k_core_components(g)
assert [:i] = components[0]
assert [:e, :f, :g, :h] = components[1]
assert is_nil(components[2])
assert [:a, :b, :c, :d] = components[3]
end
test "coreness/2" do
g =
Graph.new(type: :undirected)
|> Graph.add_vertices([:a, :b, :c, :d, :e, :f, :g, :h, :i])
|> Graph.add_edges([
{:a, :b},
{:a, :c},
{:a, :d},
{:b, :c},
{:b, :d},
{:c, :d},
{:c, :e},
{:e, :f},
{:f, :g},
{:f, :h}
])
assert 3 = Graph.coreness(g, :a)
end
test "degeneracy_core/1" do
g =
Graph.new(type: :undirected)
|> Graph.add_vertices([:a, :b, :c, :d, :e, :f, :g, :h, :i])
|> Graph.add_edges([
{:a, :b},
{:a, :c},
{:a, :d},
{:b, :c},
{:b, :d},
{:c, :d},
{:c, :e},
{:e, :f},
{:f, :g},
{:f, :h}
])
assert 3 = Graph.degeneracy(g)
dg = Graph.degeneracy_core(g)
assert [:a, :b, :c, :d] = Graph.vertices(dg)
end
@tag timeout: 120_000
@enron_emails Path.join([__DIR__, "fixtures", "email-Enron.txt"])
test "degeneracy/1 - Enron emails" do
g = Graph.Test.Fixtures.Parser.parse(@enron_emails)
assert 36_692 = Graph.num_vertices(g)
assert 183_831 = Graph.num_edges(g)
assert 43 = Graph.degeneracy(g)
end
@tag timeout: 120_000
@hamster_friends Path.join([__DIR__, "fixtures", "petster", "edges.txt"])
test "degeneracy/1 - Petster hamster friendships" do
g = Graph.Test.Fixtures.Parser.parse(@hamster_friends)
assert 1_858 = Graph.num_vertices(g)
assert 12_534 = Graph.num_edges(g)
assert 20 = Graph.degeneracy(g)
end
defp build_basic_cyclic_graph do
Graph.new()
|> Graph.add_vertex(:a)
|> Graph.add_vertex(:b)
|> Graph.add_vertex(:c)
|> Graph.add_vertex(:d)
|> Graph.add_vertex(:e)
|> Graph.add_edge(:a, :b)
|> Graph.add_edge(:a, :c)
|> Graph.add_edge(:b, :c)
|> Graph.add_edge(:b, :d)
|> Graph.add_edge(:c, :d)
|> Graph.add_edge(:c, :a)
|> Graph.add_edge(:d, :e)
end
defp build_basic_cyclic_digraph do
dg = :digraph.new()
:digraph.add_vertex(dg, :a)
:digraph.add_vertex(dg, :b)
:digraph.add_vertex(dg, :c)
:digraph.add_vertex(dg, :d)
:digraph.add_vertex(dg, :e)
:digraph.add_edge(dg, :a, :b)
:digraph.add_edge(dg, :a, :c)
:digraph.add_edge(dg, :b, :c)
:digraph.add_edge(dg, :b, :d)
:digraph.add_edge(dg, :c, :d)
:digraph.add_edge(dg, :c, :a)
:digraph.add_edge(dg, :d, :e)
dg
end
defp build_basic_acyclic_graph do
Graph.new()
|> Graph.add_vertex(:a)
|> Graph.add_vertex(:b)
|> Graph.add_vertex(:c)
|> Graph.add_vertex(:d)
|> Graph.add_vertex(:e)
|> Graph.add_edge(:a, :b)
|> Graph.add_edge(:a, :c)
|> Graph.add_edge(:b, :c)
|> Graph.add_edge(:b, :d)
|> Graph.add_edge(:c, :d)
|> Graph.add_edge(:d, :e)
end
defp build_basic_acyclic_digraph do
dg = :digraph.new()
:digraph.add_vertex(dg, :a)
:digraph.add_vertex(dg, :b)
:digraph.add_vertex(dg, :c)
:digraph.add_vertex(dg, :d)
:digraph.add_vertex(dg, :e)
:digraph.add_edge(dg, :a, :b)
:digraph.add_edge(dg, :a, :c)
:digraph.add_edge(dg, :b, :c)
:digraph.add_edge(dg, :b, :d)
:digraph.add_edge(dg, :c, :d)
:digraph.add_edge(dg, :d, :e)
dg
end
defp build_basic_tree_graph do
Graph.new()
|> Graph.add_vertex(:a)
|> Graph.add_vertex(:b)
|> Graph.add_vertex(:c)
|> Graph.add_vertex(:d)
|> Graph.add_vertex(:e)
|> Graph.add_edge(:a, :b)
|> Graph.add_edge(:b, :c)
|> Graph.add_edge(:c, :d)
|> Graph.add_edge(:c, :e)
end
defp build_basic_tree_digraph do
dg = :digraph.new()
:digraph.add_vertex(dg, :a)
:digraph.add_vertex(dg, :b)
:digraph.add_vertex(dg, :c)
:digraph.add_vertex(dg, :d)
:digraph.add_vertex(dg, :e)
:digraph.add_edge(dg, :a, :b)
:digraph.add_edge(dg, :b, :c)
:digraph.add_edge(dg, :c, :d)
:digraph.add_edge(dg, :c, :e)
dg
end
defp build_basic_undirected_graph do
Graph.new(type: :undirected)
|> Graph.add_vertices([:a, :b, :c])
|> Graph.add_edge(:a, :b)
|> Graph.add_edge(:c, :b)
end
defp build_complex_graph(type \\ :directed) do
Graph.new(type: type)
|> Graph.add_edge(42, 25, weight: 2525)
|> Graph.add_edge(66, 67, weight: 2254)
|> Graph.add_edge(71, 72, weight: 3895)
|> Graph.add_edge(79, 80, weight: 37236)
|> Graph.add_edge(0, 1, weight: 1573)
|> Graph.add_edge(0, 64, weight: 1595)
|> Graph.add_edge(30, 31, weight: 518)
|> Graph.add_edge(58, 56, weight: 431)
|> Graph.add_edge(58, 60, weight: 468)
|> Graph.add_edge(58, 47, weight: 1175)
|> Graph.add_edge(23, 24, weight: 1807)
|> Graph.add_edge(50, 56, weight: 1192)
|> Graph.add_edge(50, 49, weight: 198)
|> Graph.add_edge(50, 57, weight: 1192)
|> Graph.add_edge(22, 23, weight: 1919)
|> Graph.add_edge(22, 91, weight: 4032)
|> Graph.add_edge(43, 44, weight: 255)
|> Graph.add_edge(60, 46, weight: 1167)
|> Graph.add_edge(60, 55, weight: 159)
|> Graph.add_edge(60, 58, weight: 468)
|> Graph.add_edge(36, 37, weight: 9132)
|> Graph.add_edge(75, 77, weight: 2120)
|> Graph.add_edge(14, 15, weight: 3483)
|> Graph.add_edge(32, 33, weight: 1008)
|> Graph.add_edge(41, 20, weight: 2271)
|> Graph.add_edge(101, 102, weight: 27752)
|> Graph.add_edge(102, 104, weight: 44964)
|> Graph.add_edge(102, 103, weight: 1287)
|> Graph.add_edge(104, 78, weight: 944)
|> Graph.add_edge(85, 86, weight: 3029)
|> Graph.add_edge(72, 73, weight: 2872)
|> Graph.add_edge(88, 89, weight: 7817)
|> Graph.add_edge(103, 92, weight: 2884)
|> Graph.add_edge(69, 70, weight: 1719)
|> Graph.add_edge(69, 21, weight: 3059)
|> Graph.add_edge(13, 14, weight: 3002)
|> Graph.add_edge(84, 85, weight: 3735)
|> Graph.add_edge(48, 47, weight: 204)
|> Graph.add_edge(34, 35, weight: 6487)
|> Graph.add_edge(80, 90, weight: 29876)
|> Graph.add_edge(80, 103, weight: 2047)
|> Graph.add_edge(95, "start_0", weight: 3130)
|> Graph.add_edge(49, 50, weight: 198)
|> Graph.add_edge(38, 39, weight: 11222)
|> Graph.add_edge(37, 19, weight: 5284)
|> Graph.add_edge(68, 69, weight: 2476)
|> Graph.add_edge(77, 78, weight: 2138)
|> Graph.add_edge(86, 87, weight: 8289)
|> Graph.add_edge(61, 64, weight: 508)
|> Graph.add_edge(61, 46, weight: 1181)
|> Graph.add_edge(61, 59, weight: 490)
|> Graph.add_edge("end_0", 68, weight: 288)
|> Graph.add_edge("end_0", "end", weight: 0)
|> Graph.add_edge(87, 88, weight: 5729)
|> Graph.add_edge(94, 95, weight: 2665)
|> Graph.add_edge(74, 75, weight: 1641)
|> Graph.add_edge(12, 13, weight: 5014)
|> Graph.add_edge(25, 30, weight: 1645)
|> Graph.add_edge(25, 24, weight: 248)
|> Graph.add_edge(15, 1, weight: 2005)
|> Graph.add_edge(4, 12, weight: 3150)
|> Graph.add_edge(54, 56, weight: 547)
|> Graph.add_edge(54, 52, weight: 1332)
|> Graph.add_edge(54, 27, weight: 2095)
|> Graph.add_edge(70, 71, weight: 22390)
|> Graph.add_edge(29, 32, weight: 2449)
|> Graph.add_edge(59, 47, weight: 1190)
|> Graph.add_edge(59, 57, weight: 418)
|> Graph.add_edge(59, 61, weight: 490)
|> Graph.add_edge(35, 36, weight: 6814)
|> Graph.add_edge(52, 51, weight: 195)
|> Graph.add_edge(52, 54, weight: 1332)
|> Graph.add_edge(52, 55, weight: 1186)
|> Graph.add_edge("start", "start_0", weight: 0)
|> Graph.add_edge(78, 84, weight: 3418)
|> Graph.add_edge(78, 79, weight: 6596)
|> Graph.add_edge("start_0", 96, weight: 120)
|> Graph.add_edge(39, 93, weight: 4220)
|> Graph.add_edge(39, 40, weight: 5082)
|> Graph.add_edge(45, 46, weight: 235)
|> Graph.add_edge(18, 29, weight: 600)
|> Graph.add_edge(73, 74, weight: 788)
|> Graph.add_edge(98, 41, weight: 2187)
|> Graph.add_edge(98, 33, weight: 1496)
|> Graph.add_edge(93, 94, weight: 13132)
|> Graph.add_edge(20, 42, weight: 566)
|> Graph.add_edge(67, "end_0", weight: 483)
|> Graph.add_edge(64, 0, weight: 1595)
|> Graph.add_edge(64, 44, weight: 1174)
|> Graph.add_edge(64, 61, weight: 508)
|> Graph.add_edge(96, 13, weight: 2865)
|> Graph.add_edge(96, 97, weight: 2773)
|> Graph.add_edge(46, 60, weight: 1167)
|> Graph.add_edge(46, 45, weight: 235)
|> Graph.add_edge(46, 61, weight: 1181)
|> Graph.add_edge(19, 70, weight: 2732)
|> Graph.add_edge(19, 65, weight: 1911)
|> Graph.add_edge(65, 66, weight: 2886)
|> Graph.add_edge(51, 52, weight: 195)
|> Graph.add_edge(33, 100, weight: 4369)
|> Graph.add_edge(89, 21, weight: 3165)
|> Graph.add_edge(89, 65, weight: 3221)
|> Graph.add_edge(1, 0, weight: 1573)
|> Graph.add_edge(1, 3, weight: 1999)
|> Graph.add_edge(100, 93, weight: 2056)
|> Graph.add_edge(100, 34, weight: 4038)
|> Graph.add_edge(55, 60, weight: 159)
|> Graph.add_edge(55, 52, weight: 1186)
|> Graph.add_edge(55, 57, weight: 358)
|> Graph.add_edge(21, 38, weight: 16458)
|> Graph.add_edge(40, 41, weight: 5104)
|> Graph.add_edge(3, 4, weight: 3476)
|> Graph.add_edge(91, 22, weight: 4032)
|> Graph.add_edge(91, 101, weight: 1970)
|> Graph.add_edge(44, 64, weight: 1174)
|> Graph.add_edge(44, 57, weight: 1129)
|> Graph.add_edge(44, 43, weight: 255)
|> Graph.add_edge(24, 22, weight: 1820)
|> Graph.add_edge(24, 25, weight: 248)
|> Graph.add_edge(27, 54, weight: 2095)
|> Graph.add_edge(27, 29, weight: 1205)
|> Graph.add_edge(57, 44, weight: 1129)
|> Graph.add_edge(57, 50, weight: 1192)
|> Graph.add_edge(57, 55, weight: 358)
|> Graph.add_edge(57, 59, weight: 418)
|> Graph.add_edge(92, 38, weight: 3589)
|> Graph.add_edge(47, 48, weight: 204)
|> Graph.add_edge(47, 59, weight: 1190)
|> Graph.add_edge(47, 58, weight: 1175)
|> Graph.add_edge(56, 50, weight: 1192)
|> Graph.add_edge(56, 54, weight: 547)
|> Graph.add_edge(56, 58, weight: 431)
|> Graph.add_edge(90, 91, weight: 2301)
|> Graph.add_edge(31, 18, weight: 861)
|> Graph.add_edge(31, 27, weight: 1178)
|> Graph.add_edge(97, 98, weight: 13465)
end
defp build_complex_graph_float(type \\ :directed) do
build_complex_graph(type)
|> Graph.edges()
|> Enum.reduce(Graph.new(type: type), fn %Graph.Edge{weight: weight} = edge, acc ->
acc
|> Graph.add_edge(%Graph.Edge{edge | weight: weight / 1000})
end)
end
end
| 28.591549 | 143 | 0.545992 |
03f8ef161fe7746b1c5c9f82679806cf46d5b89a | 1,115 | exs | Elixir | thermostat_umbrella/apps/serial/config/config.exs | ecoutu/thermostat | 1b6b636b29ba7d81c1e240db5dbab163b6d3fd6b | [
"Apache-2.0"
] | 3 | 2016-12-01T18:48:24.000Z | 2017-09-26T18:45:36.000Z | thermostat_umbrella/apps/serial/config/config.exs | ecoutu/thermostat | 1b6b636b29ba7d81c1e240db5dbab163b6d3fd6b | [
"Apache-2.0"
] | null | null | null | thermostat_umbrella/apps/serial/config/config.exs | ecoutu/thermostat | 1b6b636b29ba7d81c1e240db5dbab163b6d3fd6b | [
"Apache-2.0"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :serial, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:serial, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 35.967742 | 73 | 0.750673 |
03f9b8595641eea4aed9a4169c4f09469bdf6709 | 4,936 | exs | Elixir | test/phoenix_live_view/router_test.exs | almirsarajcic/phoenix_live_view | 6cecf857494d4ec43d89be5d6cc4d4d4ff53780d | [
"MIT"
] | 1 | 2021-06-28T12:31:07.000Z | 2021-06-28T12:31:07.000Z | test/phoenix_live_view/router_test.exs | almirsarajcic/phoenix_live_view | 6cecf857494d4ec43d89be5d6cc4d4d4ff53780d | [
"MIT"
] | null | null | null | test/phoenix_live_view/router_test.exs | almirsarajcic/phoenix_live_view | 6cecf857494d4ec43d89be5d6cc4d4d4ff53780d | [
"MIT"
] | null | null | null | defmodule Phoenix.LiveView.RouterTest do
use ExUnit.Case, async: true
import Phoenix.ConnTest
import Phoenix.LiveViewTest
alias Phoenix.LiveView.{Route, Session}
alias Phoenix.LiveViewTest.{Endpoint, DashboardLive, DOM}
alias Phoenix.LiveViewTest.Router.Helpers, as: Routes
@endpoint Endpoint
def verified_session(html) do
[{id, session_token, static_token} | _] = html |> DOM.parse() |> DOM.find_live_views()
{:ok, live_session} =
Session.verify_session(@endpoint, "lv:#{id}", session_token, static_token)
live_session.session
end
setup config do
conn = Plug.Test.init_test_session(build_conn(), config[:plug_session] || %{})
{:ok, conn: conn}
end
test "routing at root", %{conn: conn} do
{:ok, _view, html} = live(conn, "/")
assert html =~ ~r/<article[^>]*class="thermo"[^>]*>/
end
test "routing with empty session", %{conn: conn} do
conn = get(conn, "/router/thermo_defaults/123")
assert conn.resp_body =~ ~s(session: %{})
end
@tag plug_session: %{user_id: "chris"}
test "routing with custom session", %{conn: conn} do
conn = get(conn, "/router/thermo_session/123")
assert conn.resp_body =~ ~s(session: %{"user_id" => "chris"})
end
test "routing with module container", %{conn: conn} do
conn = get(conn, "/thermo")
assert conn.resp_body =~ ~r/<article[^>]*class="thermo"[^>]*>/
end
test "routing with container", %{conn: conn} do
conn = get(conn, "/router/thermo_container/123")
assert conn.resp_body =~
~r/<span[^>]*class="Phoenix.LiveViewTest.DashboardLive"[^>]*style="flex-grow">/
end
test "live non-action helpers", %{conn: conn} do
assert Routes.live_path(conn, DashboardLive, 1) == "/router/thermo_defaults/1"
assert Routes.custom_live_path(conn, DashboardLive, 1) == "/router/thermo_session/custom/1"
end
test "live action helpers", %{conn: conn} do
assert Routes.foo_bar_path(conn, :index) == "/router/foobarbaz"
assert Routes.foo_bar_index_path(conn, :index) == "/router/foobarbaz/index"
assert Routes.foo_bar_index_path(conn, :show) == "/router/foobarbaz/show"
assert Routes.foo_bar_nested_index_path(conn, :index) == "/router/foobarbaz/nested/index"
assert Routes.foo_bar_nested_index_path(conn, :show) == "/router/foobarbaz/nested/show"
assert Routes.custom_foo_bar_path(conn, :index) == "/router/foobarbaz/custom"
assert Routes.nested_module_path(conn, :action) == "/router/foobarbaz/with_live"
assert Routes.custom_route_path(conn, :index) == "/router/foobarbaz/nosuffix"
end
test "user-defined metadata is available inside of metadata key" do
assert Phoenix.LiveViewTest.Router
|> Phoenix.Router.route_info("GET", "/thermo-with-metadata", nil)
|> Map.get(:route_name) == "opts"
end
describe "live_session" do
test "with defaults", %{conn: conn} do
path = "/thermo-live-session"
assert {:internal, route} = Route.live_link_info(@endpoint, Phoenix.LiveViewTest.Router, path)
assert route.live_session_name == :test
assert route.live_session_vsn
assert conn |> get(path) |> html_response(200) |> verified_session() == %{}
end
test "with extra session metadata", %{conn: conn} do
path = "/thermo-live-session-admin"
assert {:internal, route} = Route.live_link_info(@endpoint, Phoenix.LiveViewTest.Router, path)
assert route.live_session_name == :admin
assert route.live_session_vsn
assert conn |> get(path) |> html_response(200) |> verified_session() ==
%{"admin" => true}
end
test "with session MFA metadata", %{conn: conn} do
path = "/thermo-live-session-mfa"
assert {:internal, route} = Route.live_link_info(@endpoint, Phoenix.LiveViewTest.Router, path)
assert route.live_session_name == :mfa
assert route.live_session_vsn
assert conn |> get(path) |> html_response(200) |> verified_session() ==
%{"inlined" => true, "called" => true}
end
test "raises when nesting" do
assert_raise(RuntimeError, ~r"attempting to define live_session :invalid inside :ok", fn ->
Code.eval_quoted(
quote do
defmodule NestedRouter do
import Phoenix.LiveView.Router
live_session :ok do
live_session :invalid do
end
end
end
end
)
end)
end
test "raises when redefining" do
assert_raise(RuntimeError, ~r"attempting to redefine live_session :one", fn ->
Code.eval_quoted(
quote do
defmodule DupRouter do
import Phoenix.LiveView.Router
live_session :one do
end
live_session :two do
end
live_session :one do
end
end
end
)
end)
end
end
end
| 34.041379 | 100 | 0.6406 |
03f9bcbb646ed6cd9350d1ddd3bae71a04bf27d9 | 3,648 | exs | Elixir | test/shopify/oauth/request_test.exs | kurt-friedrich/shopify-oauth-elixir | bccac1c34ea35445fb737933a5d075d2972ea0be | [
"MIT"
] | 3 | 2020-01-13T22:36:29.000Z | 2021-12-12T17:59:03.000Z | test/shopify/oauth/request_test.exs | kurt-friedrich/shopify-oauth-elixir | bccac1c34ea35445fb737933a5d075d2972ea0be | [
"MIT"
] | 6 | 2020-04-23T16:20:26.000Z | 2021-08-03T05:47:44.000Z | test/shopify/oauth/request_test.exs | kurt-friedrich/shopify-oauth-elixir | bccac1c34ea35445fb737933a5d075d2972ea0be | [
"MIT"
] | 1 | 2020-04-23T16:29:37.000Z | 2020-04-23T16:29:37.000Z | defmodule Shopify.OAuth.RequestTest do
use ExUnit.Case, async: true
alias Shopify.OAuth.{ Config, Operation, Request, Response }
setup do
bypass = Bypass.open()
config = %Config{ host: "localhost", port: bypass.port, protocol: "http" }
operation = %Operation{ method: :post, params: %{ var: "a" }, path: "/fake" }
%{ bypass: bypass, config: config, operation: operation}
end
describe "send/3" do
test "returns { :ok, %Shopify.OAuth.Response{} } when response has an HTTP status code of 200", tags do
bypass = Map.get(tags, :bypass)
config = Map.get(tags, :config)
operation = Map.get(tags, :operation)
Bypass.expect(bypass, fn(conn) -> Plug.Conn.send_resp(conn, 200, "{\"ok\":true}") end)
assert { :ok, %Response{} } = Request.send(operation, config, %{})
end
test "returns { :error, %Shopify.OAuth.Response{} } when response has an HTTP status code of 400", tags do
bypass = Map.get(tags, :bypass)
config = Map.get(tags, :config)
operation = Map.get(tags, :operation)
Bypass.expect(bypass, fn(conn) -> Plug.Conn.send_resp(conn, 400, "{\"ok\":false}") end)
assert { :error, %Response{} } = Request.send(operation, config, %{})
end
test "makes a request", tags do
bypass = Map.get(tags, :bypass)
config = Map.get(tags, :config)
operation = Map.get(tags, :operation)
Bypass.expect(bypass, fn
(conn) ->
conn_opts = Plug.Parsers.init([json_decoder: Jason, parsers: [:json, :urlencoded], pass: ["*/*"]])
conn = Plug.Parsers.call(conn, conn_opts)
assert conn.method == "POST"
assert conn.body_params == %{ "var" => "a" }
Plug.Conn.send_resp(conn, 200, "{\"ok\":true}")
end)
Request.send(operation, config, %{})
end
test "does not retry when status code is 200", tags do
bypass = Map.get(tags, :bypass)
config = Map.get(tags, :config)
operation = Map.get(tags, :operation)
Bypass.expect(bypass, fn
(conn) ->
conn_opts = Plug.Parsers.init([json_decoder: Jason, parsers: [:json, :urlencoded], pass: ["*/*"]])
conn = Plug.Parsers.call(conn, conn_opts)
Plug.Conn.send_resp(conn, 200, "{\"ok\":true}")
end)
config = Map.merge(config, %{ retry: true })
assert { :ok, %Response{ private: %{ attempts: 1 } } } = Request.send(operation, config, %{})
end
test "does not retry when status code is 400", tags do
bypass = Map.get(tags, :bypass)
config = Map.get(tags, :config)
operation = Map.get(tags, :operation)
Bypass.expect(bypass, fn
(conn) ->
conn = Plug.Parsers.call(conn, Plug.Parsers.init([json_decoder: Jason, parsers: [:json], pass: ["*/*"]]))
Plug.Conn.send_resp(conn, 400, "{\"ok\":true}")
end)
config = Map.merge(config, %{ retry: true })
assert { :error, %Response{ private: %{ attempts: 1 } } } = Request.send(operation, config, %{})
end
test "retries when status code is 500", tags do
bypass = Map.get(tags, :bypass)
config = Map.get(tags, :config)
operation = Map.get(tags, :operation)
Bypass.expect(bypass, fn
(conn) ->
conn = Plug.Parsers.call(conn, Plug.Parsers.init([json_decoder: Jason, parsers: [:json], pass: ["*/*"]]))
Plug.Conn.send_resp(conn, 500, "{\"ok\":false}")
end)
config = Map.merge(config, %{ retry: true, retry_opts: [max_attempts: 3] })
assert { :error, %Response{ private: %{ attempts: 3 } } } = Request.send(operation, config, %{})
end
end
end
| 32.864865 | 115 | 0.592379 |
03f9bd788f40288d0cc169f9b9a57dcda17b2c8e | 80 | exs | Elixir | test/control_web/views/page_view_test.exs | irvingreid/control | 07c661ed2e12bc60d53311ed2c7259efc8e88f96 | [
"BSD-3-Clause"
] | 2 | 2020-06-24T22:13:10.000Z | 2021-01-07T18:01:14.000Z | test/control_web/views/page_view_test.exs | irvingreid/control | 07c661ed2e12bc60d53311ed2c7259efc8e88f96 | [
"BSD-3-Clause"
] | null | null | null | test/control_web/views/page_view_test.exs | irvingreid/control | 07c661ed2e12bc60d53311ed2c7259efc8e88f96 | [
"BSD-3-Clause"
] | null | null | null | defmodule ControlWeb.PageViewTest do
use ControlWeb.ConnCase, async: true
end
| 20 | 38 | 0.825 |
03f9c2016f191e2b221b612845485d66ba3ddec8 | 2,311 | ex | Elixir | lib/daguex/processor/put_image.ex | secretworry/daguex | 323e9eb6dfe29cb94783937e89244b6de8de7d0c | [
"Apache-2.0"
] | null | null | null | lib/daguex/processor/put_image.ex | secretworry/daguex | 323e9eb6dfe29cb94783937e89244b6de8de7d0c | [
"Apache-2.0"
] | null | null | null | lib/daguex/processor/put_image.ex | secretworry/daguex | 323e9eb6dfe29cb94783937e89244b6de8de7d0c | [
"Apache-2.0"
] | null | null | null | defmodule Daguex.Processor.PutImage do
use Daguex.Processor
alias Daguex.Image
import Daguex.Processor.StorageHelper
def init(opts) do
%{storage: init_storage(required_option(:storage)), name: required_option(:name)}
end
def process(context, %{storage: storage, name: name}) do
image = context.image
variants = Image.variants_with_origal(image) |> filter_variants(image, name)
with {:ok, context, variant_and_images} <- load_local_images(context, variants) do
async(context, %{storage: storage, name: name, variants: variant_and_images}, &async_process/2, &post_process/2)
end
end
def async_process(context, %{storage: {storage, opts}, name: name, variants: variants}) do
bucket = Keyword.get(context.opts, :bucket)
Enum.reduce_while(variants, {:ok, []}, fn {format, %{"key" => key}, image_file}, {:ok, acc} ->
case storage.put(image_file.uri |> to_string, key, bucket, opts) do
{:ok, identifier} -> {:cont, {:ok, [%{storage_name: name, format: format, key: identifier} | acc]}}
{:ok, identifier, extra} -> {:cont, {:ok, [%{storage_name: name, format: format, key: identifier, extra: extra}|acc]}}
error -> {:halt, error}
end
end)
end
def post_process(context, data) do
Enum.reduce(data, {:ok, context}, fn
%{storage_name: name, format: format, key: key}, {:ok, context} ->
image = context.image |> update_key(name, format, key)
{:ok, %{context | image: image}}
%{storage_name: name, format: format, key: key, extra: extra}, {:ok, context} ->
image = context.image |> update_key(name, format, key) |> update_extra(name, format, extra)
{:ok, %{context | image: image}}
end)
end
defp load_local_images(context, variants) do
Enum.reduce_while(variants, {:ok, context, []}, fn {format, variant}, {:ok, context, acc} ->
with {:ok, context, image_file} <- load_local_image(context, format) do
{:cont, {:ok, context, [{format, variant, image_file}|acc]}}
else
e -> {:halt, e}
end
end)
end
defp init_storage({storage, opts}), do: {storage, opts}
defp init_storage(storage), do: {storage, []}
defp filter_variants(variants, image, name) do
Enum.reject(variants, &saved?(image, name, elem(&1, 0)))
end
end
| 39.169492 | 126 | 0.645608 |
03f9d7d88b0c4f45eae0773298fa6d321b08f3e7 | 1,447 | exs | Elixir | 12-new-project/my_agent/test/my_agent_test.exs | kranfix/elixir-playground | 28f1314b137eb591946f501647e76d8017070ffa | [
"MIT"
] | null | null | null | 12-new-project/my_agent/test/my_agent_test.exs | kranfix/elixir-playground | 28f1314b137eb591946f501647e76d8017070ffa | [
"MIT"
] | null | null | null | 12-new-project/my_agent/test/my_agent_test.exs | kranfix/elixir-playground | 28f1314b137eb591946f501647e76d8017070ffa | [
"MIT"
] | 1 | 2020-11-17T07:06:17.000Z | 2020-11-17T07:06:17.000Z | defmodule MyAgentTest do
use ExUnit.Case
doctest MyAgent
test "Raises an error on start" do
reason = "some reason"
{:error, e} = MyAgent.start_link(fn -> raise reason end)
assert e.__struct__ == RuntimeError
assert e.message == reason
end
test "Creates an agent and gets 3" do
initial = 30
{:ok, pid} = MyAgent.start_link(fn -> initial end)
assert initial == MyAgent.get(pid, fn val -> val end)
MyAgent.stop(pid)
{:ok, pid} = MyAgent.start_link(fn -> {initial, true} end)
^initial = MyAgent.get(pid, fn {val, true} -> val end)
true = MyAgent.get(pid, fn {_val, true} -> true end)
MyAgent.stop(pid)
end
test "Updates the agent" do
initial = 10
{:ok, pid} = MyAgent.start_link(fn -> {initial, true} end)
assert :ok == MyAgent.update(pid, fn {val, bool} -> {val + 1, not bool} end)
expected = initial + 1
{^expected, false} = MyAgent.get(pid, fn state -> state end)
MyAgent.stop(pid)
end
test "stops the agent" do
initial = 10
{:ok, pid} = MyAgent.start_link(fn -> {initial, true} end)
MyAgent.stop(pid)
try do
MyAgent.get(pid, fn state -> state end)
raise "The agent is stop and must not get a value from state"
catch
:exit, _ -> nil
end
try do
MyAgent.update(pid, fn state -> state end)
raise "The agent is stop and must not update the state"
catch
:exit, _ -> nil
end
end
end
| 27.301887 | 80 | 0.61783 |
03f9ff03887470f6a29a37d8af0ea17e4719d47f | 665 | ex | Elixir | lib/white_bread/regex_extension.ex | ejscunha/white-bread | 1c2eed1c98545beeb70b590426ce9026a8455e97 | [
"MIT"
] | 209 | 2015-03-03T14:14:28.000Z | 2020-10-26T03:23:48.000Z | lib/white_bread/regex_extension.ex | ejscunha/white-bread | 1c2eed1c98545beeb70b590426ce9026a8455e97 | [
"MIT"
] | 83 | 2015-03-23T11:46:51.000Z | 2020-11-04T09:47:06.000Z | lib/white_bread/regex_extension.ex | ejscunha/white-bread | 1c2eed1c98545beeb70b590426ce9026a8455e97 | [
"MIT"
] | 46 | 2015-06-12T17:37:21.000Z | 2020-10-30T09:52:45.000Z | defmodule WhiteBread.RegexExtension do
@doc ~S"""
Takes a regex and matches it against the string. Returns named groups
with atoms as keys.
## Examples
iex> atom_keyed_named_captures(~r/hello (?<world>[a-z]+)/, "hello earth")
%{world: "earth"}
iex> atom_keyed_named_captures(~r/(?<a>[a-z]+) (?<b>[a-z]+)/, "hello earth")
%{a: "hello", b: "earth"}
iex> atom_keyed_named_captures(~r/.+/, "hello earth")
%{}
"""
def atom_keyed_named_captures(regex, string) do
regex
|> Regex.named_captures(string)
|> Enum.map(fn({key, value}) -> {String.to_atom(key), value} end)
|> Enum.into(%{})
end
end
| 25.576923 | 82 | 0.604511 |
03fa14f13f4db6098cdb94cd59ac0fe8048d7d5c | 173 | exs | Elixir | apps/exred_ui/priv/repo/migrations/20180314015534_add_ui_attributes_to_node.exs | exredorg/exred | 0ece8e6680747ba8f30b4413ede598a45495aa7c | [
"MIT"
] | null | null | null | apps/exred_ui/priv/repo/migrations/20180314015534_add_ui_attributes_to_node.exs | exredorg/exred | 0ece8e6680747ba8f30b4413ede598a45495aa7c | [
"MIT"
] | null | null | null | apps/exred_ui/priv/repo/migrations/20180314015534_add_ui_attributes_to_node.exs | exredorg/exred | 0ece8e6680747ba8f30b4413ede598a45495aa7c | [
"MIT"
] | null | null | null | defmodule ExredUI.Repo.Migrations.AddUiAttributesToNode do
use Ecto.Migration
def change do
alter table(:nodes) do
add :ui_attributes, :map
end
end
end
| 17.3 | 58 | 0.722543 |
03fa5a649f347cce695f1adb8782bd1653b281e6 | 7,000 | ex | Elixir | apps/omg_eth/test/support/dev_helpers.ex | PinkDiamond1/elixir-omg | 70dfd24a0a1ddf5d1d9d71aab61ea25300f889f7 | [
"Apache-2.0"
] | null | null | null | apps/omg_eth/test/support/dev_helpers.ex | PinkDiamond1/elixir-omg | 70dfd24a0a1ddf5d1d9d71aab61ea25300f889f7 | [
"Apache-2.0"
] | null | null | null | apps/omg_eth/test/support/dev_helpers.ex | PinkDiamond1/elixir-omg | 70dfd24a0a1ddf5d1d9d71aab61ea25300f889f7 | [
"Apache-2.0"
] | 1 | 2021-12-04T00:37:46.000Z | 2021-12-04T00:37:46.000Z | # Copyright 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 OMG.Eth.DevHelpers do
@moduledoc """
Helpers used when setting up development environment and test fixtures, related to contracts and ethereum.
Run against `geth --dev` and similar.
"""
alias OMG.Eth
alias OMG.Eth.WaitFor
import Eth.Encoding, only: [to_hex: 1, from_hex: 1, int_from_hex: 1]
require Logger
@one_hundred_eth trunc(:math.pow(10, 18) * 100)
# about 4 Ethereum blocks on "realistic" networks, use to timeout synchronous operations in demos on testnets
# NOTE: such timeout works only in dev setting; on mainnet one must track its transactions carefully
@about_4_blocks_time 60_000
@passphrase "ThisIsATestnetPassphrase"
@doc """
Prepares the developer's environment with respect to the root chain contract and its configuration within
the application.
- `root_path` should point to `elixir-omg` root or wherever where `./_build/contracts` holds the compiled contracts
"""
def prepare_env!(opts \\ [], exit_period_seconds \\ nil) do
opts = Keyword.merge([root_path: "./"], opts)
%{root_path: root_path} = Enum.into(opts, %{})
exit_period_seconds = get_exit_period(exit_period_seconds)
with {:ok, _} <- Application.ensure_all_started(:ethereumex),
{:ok, authority} <- create_and_fund_authority_addr(opts),
{:ok, deployer_addr} <- get_deployer_address(opts),
{:ok, txhash, contract_addr} <- Eth.Deployer.create_new(OMG.Eth.RootChain, root_path, deployer_addr),
{:ok, _} <-
Eth.RootChainHelper.init(exit_period_seconds, authority, contract_addr) |> Eth.DevHelpers.transact_sync!() do
%{contract_addr: contract_addr, txhash_contract: txhash, authority_addr: authority}
else
{:error, :econnrefused} = error ->
Logger.error("It seems that Ethereum instance is not running. Check README.md")
error
other ->
other
end
end
def create_conf_file(%{contract_addr: contract_addr, txhash_contract: txhash, authority_addr: authority_addr}) do
"""
use Mix.Config
config :omg_eth,
contract_addr: #{inspect(to_hex(contract_addr))},
txhash_contract: #{inspect(to_hex(txhash))},
authority_addr: #{inspect(to_hex(authority_addr))}
"""
end
@doc """
Will take a map with eth-account information (from &generate_entity/0) and then
import priv key->unlock->fund with lots of ether on that account
"""
def import_unlock_fund(%{priv: account_priv}, opts \\ []) do
account_priv_enc = Base.encode16(account_priv)
{:ok, account_enc} = create_account_from_secret(OMG.Eth.backend(), account_priv_enc, @passphrase)
{:ok, _} = fund_address_from_faucet(account_enc, opts)
{:ok, from_hex(account_enc)}
end
@doc """
Use with contract-transacting functions that return {:ok, txhash}, e.g. `Eth.Token.mint`, for synchronous waiting
for mining of a successful result
"""
@spec transact_sync!({:ok, Eth.hash()}) :: {:ok, map}
def transact_sync!({:ok, txhash} = _transaction_submission_result) when byte_size(txhash) == 32 do
{:ok, %{"status" => "0x1"} = result} = WaitFor.eth_receipt(txhash, @about_4_blocks_time)
{:ok, result |> Map.update!("blockNumber", &int_from_hex(&1))}
end
@doc """
Uses `transact_sync!` for synchronous deploy-transaction sending and extracts important data from the receipt
"""
@spec deploy_sync!({:ok, Eth.hash()}) :: {:ok, Eth.hash(), Eth.address()}
def deploy_sync!({:ok, txhash} = transaction_submission_result) do
{:ok, %{"contractAddress" => contract, "status" => "0x1"}} = transact_sync!(transaction_submission_result)
{:ok, txhash, from_hex(contract)}
end
def wait_for_root_chain_block(awaited_eth_height, timeout \\ 600_000) do
f = fn ->
{:ok, eth_height} = Eth.get_ethereum_height()
if eth_height < awaited_eth_height, do: :repeat, else: {:ok, eth_height}
end
fn -> WaitFor.repeat_until_ok(f) end |> Task.async() |> Task.await(timeout)
end
def wait_for_next_child_block(blknum, timeout \\ 10_000, contract \\ nil) do
f = fn ->
{:ok, next_num} = Eth.RootChain.get_next_child_block(contract)
if next_num < blknum, do: :repeat, else: {:ok, next_num}
end
fn -> WaitFor.repeat_until_ok(f) end |> Task.async() |> Task.await(timeout)
end
def create_account_from_secret(:geth, secret, passphrase) do
{:ok, _} = Ethereumex.HttpClient.request("personal_importRawKey", [secret, passphrase], [])
end
def create_account_from_secret(:parity, secret, passphrase) when byte_size(secret) == 64 do
secret = secret |> Base.decode16!(case: :upper) |> Eth.Encoding.to_hex()
{:ok, _} = Ethereumex.HttpClient.request("parity_newAccountFromSecret", [secret, passphrase], [])
end
# private
# returns well-funded faucet address for contract deployment or first address returned from node otherwise
defp get_deployer_address(opts) do
with {:ok, [addr | _]} <- Ethereumex.HttpClient.eth_accounts(),
do: {:ok, from_hex(Keyword.get(opts, :faucet, addr))}
end
defp create_and_fund_authority_addr(opts) do
with {:ok, authority} <- Ethereumex.HttpClient.request("personal_newAccount", [@passphrase], []),
{:ok, _} <- fund_address_from_faucet(authority, opts) do
{:ok, from_hex(authority)}
end
end
defp get_exit_period(nil) do
DeferredConfig.populate(:omg_eth)
Application.fetch_env!(:omg_eth, :exit_period_seconds)
end
defp get_exit_period(exit_period), do: exit_period
defp fund_address_from_faucet(account_enc, opts) do
{:ok, [default_faucet | _]} = Ethereumex.HttpClient.eth_accounts()
defaults = [faucet: default_faucet, initial_funds: @one_hundred_eth]
%{faucet: faucet, initial_funds: initial_funds} =
defaults
|> Keyword.merge(opts)
|> Enum.into(%{})
unlock_if_possible(account_enc)
params = %{from: faucet, to: account_enc, value: to_hex(initial_funds)}
{:ok, tx_fund} = OMG.Eth.send_transaction(params)
tx_fund |> WaitFor.eth_receipt(@about_4_blocks_time)
end
defp unlock_if_possible(account_enc) do
unlock_if_possible(account_enc, OMG.Eth.backend())
end
defp unlock_if_possible(account_enc, :geth) do
{:ok, true} = Ethereumex.HttpClient.request("personal_unlockAccount", [account_enc, @passphrase, 0], [])
end
defp unlock_if_possible(_account_enc, :parity) do
:dont_bother_will_use_personal_sendTransaction
end
end
| 37.433155 | 120 | 0.706571 |
03fa63d1cebde0f65666cdb0ec943a603d4bda76 | 449 | exs | Elixir | server/test/idai_field_server_web/views/error_view_test.exs | felixwolter/idai-field | 146ab8dbdedb23035a4ba19eac95f02a1fa2329f | [
"Apache-2.0"
] | null | null | null | server/test/idai_field_server_web/views/error_view_test.exs | felixwolter/idai-field | 146ab8dbdedb23035a4ba19eac95f02a1fa2329f | [
"Apache-2.0"
] | null | null | null | server/test/idai_field_server_web/views/error_view_test.exs | felixwolter/idai-field | 146ab8dbdedb23035a4ba19eac95f02a1fa2329f | [
"Apache-2.0"
] | null | null | null | defmodule IdaiFieldServerWeb.ErrorViewTest do
use IdaiFieldServerWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(IdaiFieldServerWeb.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(IdaiFieldServerWeb.ErrorView, "500.html", []) == "Internal Server Error"
end
end
| 29.933333 | 100 | 0.752784 |
03fab9eb53725bf975f309ba280154f6b205a384 | 163 | ex | Elixir | lib/speed.ex | njonsson/speed | eacbd2e89e0499806beecfcec1c9f2e6128c49df | [
"MIT"
] | null | null | null | lib/speed.ex | njonsson/speed | eacbd2e89e0499806beecfcec1c9f2e6128c49df | [
"MIT"
] | null | null | null | lib/speed.ex | njonsson/speed | eacbd2e89e0499806beecfcec1c9f2e6128c49df | [
"MIT"
] | null | null | null | defmodule Speed do
@moduledoc """
Contains an implementation of the Speed card game.
"""
@typedoc "An error result"
@type error :: {:error, binary}
end
| 18.111111 | 52 | 0.674847 |
03fabffeb38121fb7969bd4d97d08afb38edb213 | 4,069 | ex | Elixir | apps/andi/lib/andi/input_schemas/ingestions.ex | UrbanOS-Public/smartcitiesdata | c4f4d83fcd1bbae5f4d3f47a9b218f3d991a51cd | [
"Apache-2.0"
] | 8 | 2021-10-31T18:45:02.000Z | 2022-03-05T18:33:08.000Z | apps/andi/lib/andi/input_schemas/ingestions.ex | UrbanOS-Public/smartcitiesdata | c4f4d83fcd1bbae5f4d3f47a9b218f3d991a51cd | [
"Apache-2.0"
] | 7 | 2022-01-14T21:21:23.000Z | 2022-03-16T17:23:10.000Z | apps/andi/lib/andi/input_schemas/ingestions.ex | UrbanOS-Public/smartcitiesdata | c4f4d83fcd1bbae5f4d3f47a9b218f3d991a51cd | [
"Apache-2.0"
] | 1 | 2022-03-08T23:45:02.000Z | 2022-03-08T23:45:02.000Z | defmodule Andi.InputSchemas.Ingestions do
@moduledoc false
alias Andi.InputSchemas.Ingestion
alias Andi.Repo
alias Andi.InputSchemas.InputConverter
alias Andi.InputSchemas.StructTools
alias Ecto.Changeset
use Properties, otp_app: :andi
import Ecto.Query, only: [from: 2]
require Logger
def get(nil), do: nil
def get(id) do
Repo.get(Ingestion, id)
|> Ingestion.preload()
end
def get_all() do
query =
from(ingestion in Ingestion,
join: extractSteps in assoc(ingestion, :extractSteps),
join: schema in assoc(ingestion, :schema),
preload: [extractSteps: extractSteps, schema: schema]
)
Repo.all(query)
end
def create(dataset_id) do
new_ingestion_id = UUID.uuid4()
new_changeset =
Ingestion.changeset_for_draft(
%Ingestion{},
%{
id: new_ingestion_id,
targetDataset: dataset_id
}
)
{:ok, new_ingestion} = save(new_changeset)
new_ingestion
end
def create() do
new_ingestion_id = UUID.uuid4()
current_date = Date.utc_today()
new_ingestion_title = "New Ingestion - #{current_date}"
new_changeset =
Ingestion.changeset_for_draft(
%Ingestion{},
%{
id: new_ingestion_id,
name: new_ingestion_title
}
)
{:ok, new_ingestion} = save(new_changeset)
new_ingestion
end
def update(%SmartCity.Ingestion{} = smrt_ingestion) do
andi_ingestion =
case get(smrt_ingestion.id) do
nil -> %Ingestion{}
ingestion -> ingestion
end
changes = InputConverter.prepare_smrt_ingestion_for_casting(smrt_ingestion)
andi_ingestion
|> Andi.Repo.preload([:extractSteps, :schema, :transformations])
|> Ingestion.changeset(changes)
|> save()
end
def update(%Ingestion{} = andi_ingestion) do
original_ingestion =
case get(andi_ingestion.id) do
nil -> %Ingestion{}
ingestion -> ingestion
end
update(original_ingestion, andi_ingestion)
end
def update(%Ingestion{} = from_ingestion, changes) do
changes_as_map = StructTools.to_map(changes)
from_ingestion
|> Andi.Repo.preload([:extractSteps, :schema])
|> Ingestion.changeset_for_draft(changes_as_map)
|> save()
end
def save(%Ecto.Changeset{} = changeset) do
Repo.insert_or_update(changeset)
end
def save_form_changeset(ingestion_id, form_changeset) do
form_changes = InputConverter.form_changes_from_changeset(form_changeset)
update_from_form(ingestion_id, form_changes)
end
def update_from_form(ingestion_id, form_changes) do
existing_ingestion = get(ingestion_id)
changeset = InputConverter.andi_ingestion_to_full_ui_changeset(existing_ingestion)
ingestion_changes =
changeset
|> Changeset.apply_changes()
|> StructTools.to_map()
|> Map.merge(form_changes)
update(existing_ingestion, ingestion_changes)
end
def update_cadence(ingestion_id, cadence) do
from_ingestion = get(ingestion_id) || %Ingestion{id: ingestion_id}
updated = Map.put(from_ingestion, :cadence, cadence)
update(from_ingestion, updated)
end
def delete(ingestion_id) do
Repo.delete(%Ingestion{id: ingestion_id})
rescue
_e in Ecto.StaleEntryError ->
{:error, "attempted to remove an ingestion (id: #{ingestion_id}) that does not exist."}
end
def full_validation_changeset_for_publish(schema, changes) do
Ingestion.changeset(schema, changes)
end
def full_validation_submission_changeset_for_publish(schema, changes) do
Ingestion.submission_changeset(schema, changes)
end
def update_ingested_time(ingestion_id, ingested_time) do
from_ingestion = get(ingestion_id) || %Ingestion{id: ingestion_id}
iso_ingested_time = DateTime.to_iso8601(ingested_time)
update(from_ingestion, %{ingestedTime: iso_ingested_time})
end
def update_submission_status(ingestion_id, status) do
from_ingestion = get(ingestion_id)
update(from_ingestion, %{submissionStatus: status})
end
end
| 25.591195 | 93 | 0.700909 |
03fad2c99587a93736f6e744b6bf46989ceec46f | 499 | ex | Elixir | lib/alfredoChat_web/views/error_view.ex | lujeremy/AlfredoChat | edabdcb3e077002e379efad841b17158b184ace4 | [
"MIT"
] | null | null | null | lib/alfredoChat_web/views/error_view.ex | lujeremy/AlfredoChat | edabdcb3e077002e379efad841b17158b184ace4 | [
"MIT"
] | 2 | 2021-03-09T12:33:57.000Z | 2021-05-10T02:49:27.000Z | lib/alfredoChat_web/views/error_view.ex | lujeremy/BasicChat | edabdcb3e077002e379efad841b17158b184ace4 | [
"MIT"
] | null | null | null | defmodule AlfredoChatWeb.ErrorView do
use AlfredoChatWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.html", _assigns) do
# "Internal Server Error"
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| 29.352941 | 61 | 0.739479 |
03faee9fd237f459d507ae6bdbea658d9b1404df | 790 | ex | Elixir | apps/sim/lib/sim/realm/event_bus.ex | grrrisu/thundermoon-umbrella | d7e4f063e28b8d20545f90d6cddc27527fe9efe0 | [
"MIT"
] | 10 | 2019-08-02T06:41:23.000Z | 2022-03-09T16:12:30.000Z | apps/sim/lib/sim/realm/event_bus.ex | grrrisu/thundermoon-umbrella | d7e4f063e28b8d20545f90d6cddc27527fe9efe0 | [
"MIT"
] | 319 | 2019-06-11T20:16:26.000Z | 2022-03-09T16:24:22.000Z | apps/sim/lib/sim/realm/event_bus.ex | grrrisu/thundermoon-umbrella | d7e4f063e28b8d20545f90d6cddc27527fe9efe0 | [
"MIT"
] | 4 | 2019-08-15T19:52:07.000Z | 2021-12-02T14:52:54.000Z | defmodule Sim.Realm.EventBus do
use GenServer
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: opts[:name])
end
@impl true
def init(opts) do
{:ok, %{task_supervisor_name: opts[:task_supervisor_name], reducers: opts[:reducers]}}
end
def add_events(server, events) do
GenServer.cast(server, {:add_events, events})
end
@impl true
def handle_cast({:add_events, events}, state) do
Enum.each(events, fn event -> reduce_event(event, state) end)
{:noreply, state}
end
def reduce_event(event, state) do
Task.Supervisor.async_stream_nolink(
state.task_supervisor_name,
state.reducers,
fn {reducer_module, reducer} ->
reducer_module.reduce(reducer, event)
end
)
|> Stream.run()
end
end
| 23.235294 | 90 | 0.681013 |
03faf6a8ac37262b47b8906dd763c91288abfdf9 | 3,043 | ex | Elixir | lib/graphql/resolvers/project.ex | paulelliott/accent | fabd0d2768088adf780317c6e44fcabcccadba11 | [
"BSD-3-Clause"
] | null | null | null | lib/graphql/resolvers/project.ex | paulelliott/accent | fabd0d2768088adf780317c6e44fcabcccadba11 | [
"BSD-3-Clause"
] | null | null | null | lib/graphql/resolvers/project.ex | paulelliott/accent | fabd0d2768088adf780317c6e44fcabcccadba11 | [
"BSD-3-Clause"
] | null | null | null | defmodule Accent.GraphQL.Resolvers.Project do
require Ecto.Query
alias Accent.Scopes.Project, as: ProjectScope
alias Accent.{
GraphQL.Paginated,
Operation,
Plugs.GraphQLContext,
Project,
ProjectCreator,
ProjectDeleter,
ProjectUpdater,
Repo,
User
}
alias Ecto.Query
@typep project_operation :: {:ok, %{project: Project.t() | nil, errors: [String.t()] | nil}}
@spec create(any(), %{name: String.t(), language_id: String.t()}, GraphQLContext.t()) :: project_operation
def create(_, args, info) do
params = %{
"name" => args.name,
"main_color" => args.main_color,
"logo" => args.logo,
"language_id" => args.language_id
}
case ProjectCreator.create(params: params, user: info.context[:conn].assigns[:current_user]) do
{:ok, project} ->
{:ok, %{project: project, errors: nil}}
{:error, _reason} ->
{:ok, %{project: nil, errors: ["unprocessable_entity"]}}
end
end
@spec delete(Project.t(), any(), GraphQLContext.t()) :: project_operation
def delete(project, _, _) do
{:ok, _} = ProjectDeleter.delete(project: project)
{:ok, %{project: project, errors: nil}}
end
@spec update(Project.t(), %{name: String.t(), main_color: String.t()}, GraphQLContext.t()) :: project_operation
def update(project, args, info) do
args =
Map.merge(
%{
is_file_operations_locked: nil,
logo: nil
},
args
)
params = %{
"name" => args.name,
"main_color" => args.main_color,
"logo" => args.logo,
"locked_file_operations" => args.is_file_operations_locked
}
case ProjectUpdater.update(project: project, params: params, user: info.context[:conn].assigns[:current_user]) do
{:ok, project} ->
{:ok, %{project: project, errors: nil}}
{:error, _reason} ->
{:ok, %{project: nil, errors: ["unprocessable_entity"]}}
end
end
@spec list_viewer(User.t(), %{query: String.t(), page: number()}, GraphQLContext.t()) :: {:ok, Paginated.t(Project.t())}
def list_viewer(viewer, args, _info) do
Project
|> Query.join(:inner, [p], c in assoc(p, :collaborators))
|> Query.where([_, c], c.user_id == ^viewer.id)
|> Query.order_by([p, _], asc: p.name)
|> ProjectScope.from_search(args[:query])
|> Repo.paginate(page: args[:page])
|> Paginated.format()
|> (&{:ok, &1}).()
end
@spec show_viewer(any(), %{id: String.t()}, GraphQLContext.t()) :: {:ok, Project.t() | nil}
def show_viewer(_, %{id: id}, _) do
Project
|> Repo.get(id)
|> (&{:ok, &1}).()
end
@spec last_activity(Project.t(), any(), GraphQLContext.t()) :: {:ok, Operation.t() | nil}
def last_activity(project, _, _) do
Operation
|> Query.join(:left, [o], r in assoc(o, :revision))
|> Query.where([o, r], r.project_id == ^project.id or o.project_id == ^project.id)
|> Query.order_by([o], desc: o.inserted_at)
|> Query.limit(1)
|> Repo.one()
|> (&{:ok, &1}).()
end
end
| 29.259615 | 122 | 0.595136 |
03fb0f0a7308368e4bfb9b078a5f3ade8e9cec0e | 3,333 | ex | Elixir | lib/elixir_script/passes/translate/forms/js.ex | beadsland/elixirscript | cb9698ad96075fcbe87b3933009d7ab2a2c939de | [
"MIT"
] | 854 | 2017-02-19T01:50:45.000Z | 2022-03-14T18:55:38.000Z | lib/elixir_script/passes/translate/forms/js.ex | beadsland/elixirscript | cb9698ad96075fcbe87b3933009d7ab2a2c939de | [
"MIT"
] | 210 | 2017-02-20T17:44:39.000Z | 2020-08-01T10:18:07.000Z | lib/elixir_script/passes/translate/forms/js.ex | beadsland/elixirscript | cb9698ad96075fcbe87b3933009d7ab2a2c939de | [
"MIT"
] | 56 | 2017-02-19T14:50:05.000Z | 2022-02-25T17:25:30.000Z | defmodule ElixirScript.Translate.Forms.JS do
@moduledoc false
alias ESTree.Tools.Builder, as: J
alias ElixirScript.Translate.Helpers
alias ElixirScript.Translate.Form
def call_property() do
J.member_expression(
Helpers.functions(),
J.identifier("call_property")
)
end
def compile({{:., _, [ElixirScript.JS, :debugger]}, _, _}, state) do
ast = J.debugger_statement()
{ast, state}
end
def compile({{:., _, [ElixirScript.JS, :this]}, _, _}, state) do
ast = J.this_expression()
{ast, state}
end
def compile({{:., _, [ElixirScript.JS, :new]}, _, [module, params]}, state) do
members = Module.split(module)
members = case members do
["JS" | rest] ->
rest
x ->
x
end
params = case params do
p when is_list(p) ->
Enum.map(params, &Form.compile!(&1, state))
_ ->
[J.rest_element(Form.compile!(params, state))]
end
ast = Helpers.new(
ElixirScript.Translate.Identifier.make_namespace_members(members),
params
)
{ast, state}
end
def compile({{:., _, [ElixirScript.JS, :throw]}, _, [term]}, state) do
ast = J.throw_statement(
Form.compile!(term, state)
)
{ast, state}
end
def compile({{:., _, [ElixirScript.JS, :import]}, _, [term]}, state) do
ast = Helpers.call(
J.identifier("import"),
[Form.compile!(term, state)]
)
{ast, state}
end
def compile({{:., _, [ElixirScript.JS, :mutate]}, _, [object, map]}, state) do
ast = Helpers.call(
J.member_expression(
J.identifier("Object"),
J.identifier("assign")
),
[
Form.compile!(object, state),
Form.compile!(map, state)
]
)
{ast, state}
end
def compile({{:., _, [ElixirScript.JS, :mutate]}, _, [object, key, value]}, state) do
ast = Helpers.assign(
J.member_expression(
Form.compile!(object, state),
Form.compile!(key, state),
true
),
Form.compile!(value, state)
)
{ast, state}
end
def compile({{:., _, [ElixirScript.JS, :map_to_object]}, _, [map]}, state) do
ast = Helpers.call(
J.member_expression(
Helpers.functions(),
J.identifier("map_to_object")
),
[
Form.compile!(map, state)
]
)
{ast, state}
end
def compile({{:., _, [ElixirScript.JS, :map_to_object]}, _, [map, options]}, state) do
ast = Helpers.call(
J.member_expression(
Helpers.functions(),
J.identifier("map_to_object")
),
[
Form.compile!(map, state),
Form.compile!(options, state)
]
)
{ast, state}
end
def compile({{:., _, [ElixirScript.JS, :object_to_map]}, _, [object]}, state) do
ast = Helpers.call(
J.member_expression(
Helpers.functions(),
J.identifier("object_to_map")
),
[
Form.compile!(object, state)
]
)
{ast, state}
end
def compile({{:., _, [ElixirScript.JS, :object_to_map]}, _, [object, options]}, state) do
ast = Helpers.call(
J.member_expression(
Helpers.functions(),
J.identifier("object_to_map")
),
[
Form.compile!(object, state),
Form.compile!(options, state)
]
)
{ast, state}
end
end
| 21.927632 | 91 | 0.560156 |
03fb29f1061d11f9a6e382ef160c288945ab6e7b | 2,906 | exs | Elixir | spec/kerbal_maps/users_spec.exs | CraigCottingham/ksp-maps | ffd81c5e667cf6ca7770e717c736e51489c0c3d3 | [
"Apache-2.0"
] | 6 | 2019-01-25T12:07:43.000Z | 2021-09-09T20:31:39.000Z | spec/kerbal_maps/users_spec.exs | CraigCottingham/ksp-maps | ffd81c5e667cf6ca7770e717c736e51489c0c3d3 | [
"Apache-2.0"
] | 144 | 2019-01-26T02:20:07.000Z | 2021-07-21T06:28:23.000Z | spec/kerbal_maps/users_spec.exs | CraigCottingham/ksp-maps | ffd81c5e667cf6ca7770e717c736e51489c0c3d3 | [
"Apache-2.0"
] | 2 | 2019-07-31T21:11:00.000Z | 2020-04-15T19:51:14.000Z | defmodule KerbalMaps.Users.Spec do
@moduledoc false
use ESpec
require Logger
import KerbalMaps.Factory
alias KerbalMaps.Repo
alias KerbalMaps.Users
# alias KerbalMaps.Users.User
# doctest KerbalMaps.Users
example_group "users" do
describe "list_users/1" do
before do: allow Repo |> to(accept(:all, fn(_) -> static_list() end))
let :static_list, do: [build(:user)]
let :all_users, do: Users.list_users()
it do: expect (all_users()) |> to(have_count(Enum.count(static_list())))
it do: expect (all_users()) |> to(match_list(static_list()))
end
# before do
# {:shared,
# valid_attrs: %{name: "some name"},
# update_attrs: %{name: "some updated name"},
# invalid_attrs: %{name: nil}
# }
# end
# let :celestial_body_fixture do
# {:ok, user} =
# attrs
# |> Enum.into(shared.valid_attrs)
# |> Users.create_celestial_body()
#
# user
# end
# describe "list_users/0" do
# let :user, do: celestial_body_fixture()
# it do
# expect (Users.list_users()) |> to(match_array([user()]))
# end
# end
# test "list_users/0 returns all users" do
# user = celestial_body_fixture()
# assert Users.list_users() == [user]
# end
# test "get_celestial_body!/1 returns the user with given id" do
# user = celestial_body_fixture()
# assert Users.get_celestial_body!(user.id) == user
# end
# test "create_celestial_body/1 with valid data creates a user" do
# assert {:ok, %CelestialBody{} = user} = Users.create_celestial_body(@valid_attrs)
# assert user.name == "some name"
# end
# test "create_celestial_body/1 with invalid data returns error changeset" do
# assert {:error, %Ecto.Changeset{}} = Users.create_celestial_body(@invalid_attrs)
# end
# test "update_celestial_body/2 with valid data updates the user" do
# user = celestial_body_fixture()
# assert {:ok, %CelestialBody{} = user} = Users.update_celestial_body(user, @update_attrs)
# assert user.name == "some updated name"
# end
# test "update_celestial_body/2 with invalid data returns error changeset" do
# user = celestial_body_fixture()
# assert {:error, %Ecto.Changeset{}} = Users.update_celestial_body(user, @invalid_attrs)
# assert user == Users.get_celestial_body!(user.id)
# end
# test "delete_celestial_body/1 deletes the user" do
# user = celestial_body_fixture()
# assert {:ok, %CelestialBody{}} = Users.delete_celestial_body(user)
# assert_raise Ecto.NoResultsError, fn -> Users.get_celestial_body!(user.id) end
# end
# test "change_celestial_body/1 returns a user changeset" do
# user = celestial_body_fixture()
# assert %Ecto.Changeset{} = Users.change_celestial_body(user)
# end
end
end
| 31.247312 | 96 | 0.642808 |
03fb3a6b8328f3616c5c7d219d45269bb111f2f3 | 293 | ex | Elixir | server/lib/melody_match_web/views/spotify_view.ex | brianjaustin/melody-match | 5200fd347f7ae636ec782398896c782d80c17f59 | [
"Apache-1.1"
] | null | null | null | server/lib/melody_match_web/views/spotify_view.ex | brianjaustin/melody-match | 5200fd347f7ae636ec782398896c782d80c17f59 | [
"Apache-1.1"
] | 4 | 2021-03-28T03:09:37.000Z | 2021-04-10T17:45:10.000Z | server/lib/melody_match_web/views/spotify_view.ex | brianjaustin/melody-match | 5200fd347f7ae636ec782398896c782d80c17f59 | [
"Apache-1.1"
] | null | null | null | defmodule MelodyMatchWeb.SpotifyView do
use MelodyMatchWeb, :view
alias MelodyMatchWeb.SpotifyView
def render("show.json", %{result: result}) do
%{data: render_one(result, SpotifyView, "spotify.json")}
end
def render("spotify.json", %{spotify: result}) do
result
end
end
| 22.538462 | 60 | 0.716724 |
03fb3a9ca3bd12ec0e886e17226a59d39727234b | 9,761 | exs | Elixir | deps/sqlitex/test/sqlitex_test.exs | scouten/crash_esqlite_case | 986f0b0721399c7ed520f6b9df133980906e3f51 | [
"MIT"
] | null | null | null | deps/sqlitex/test/sqlitex_test.exs | scouten/crash_esqlite_case | 986f0b0721399c7ed520f6b9df133980906e3f51 | [
"MIT"
] | null | null | null | deps/sqlitex/test/sqlitex_test.exs | scouten/crash_esqlite_case | 986f0b0721399c7ed520f6b9df133980906e3f51 | [
"MIT"
] | null | null | null | defmodule SqlitexTest do
use ExUnit.Case
doctest Sqlitex
@shared_cache 'file::memory:?cache=shared'
setup_all do
{:ok, db} = Sqlitex.open(@shared_cache)
on_exit fn ->
Sqlitex.close(db)
end
{:ok, golf_db: TestDatabase.init(db)}
end
test "server basic query" do
{:ok, conn} = Sqlitex.Server.start_link(@shared_cache)
{:ok, [row]} = Sqlitex.Server.query(conn, "SELECT * FROM players ORDER BY id LIMIT 1")
assert row == [id: 1, name: "Mikey", created_at: {{2012,10,14},{05,46,28,318_107}}, updated_at: {{2013,09,06},{22,29,36,610_911}}, type: nil]
Sqlitex.Server.stop(conn)
end
test "server basic query by name" do
{:ok, _} = Sqlitex.Server.start_link(@shared_cache, name: :sql)
{:ok, [row]} = Sqlitex.Server.query(:sql, "SELECT * FROM players ORDER BY id LIMIT 1")
assert row == [id: 1, name: "Mikey", created_at: {{2012,10,14},{05,46,28,318_107}}, updated_at: {{2013,09,06},{22,29,36,610_911}}, type: nil]
Sqlitex.Server.stop(:sql)
end
test "that it returns an error for a bad query" do
{:ok, _} = Sqlitex.Server.start_link(":memory:", name: :bad_create)
assert {:error, {:sqlite_error, 'near "WHAT": syntax error'}} == Sqlitex.Server.query(:bad_create, "CREATE WHAT")
end
test "a basic query returns a list of keyword lists", context do
{:ok, [row]} = Sqlitex.query(context[:golf_db], "SELECT * FROM players ORDER BY id LIMIT 1")
assert row == [id: 1, name: "Mikey", created_at: {{2012,10,14},{05,46,28,318_107}}, updated_at: {{2013,09,06},{22,29,36,610_911}}, type: nil]
end
test "a basic query returns a list of maps when into: %{} is given", context do
{:ok, [row]} = Sqlitex.query(context[:golf_db], "SELECT * FROM players ORDER BY id LIMIT 1", into: %{})
assert row == %{id: 1, name: "Mikey", created_at: {{2012,10,14},{05,46,28,318_107}}, updated_at: {{2013,09,06},{22,29,36,610_911}}, type: nil}
end
test "with_db" do
{:ok, [row]} = Sqlitex.with_db(@shared_cache, fn(db) ->
Sqlitex.query(db, "SELECT * FROM players ORDER BY id LIMIT 1")
end)
assert row == [id: 1, name: "Mikey", created_at: {{2012,10,14},{05,46,28,318_107}}, updated_at: {{2013,09,06},{22,29,36,610_911}}, type: nil]
end
test "table creation works as expected" do
{:ok, [row]} = Sqlitex.with_db(":memory:", fn(db) ->
Sqlitex.create_table(db, :users, id: {:integer, [:primary_key, :not_null]}, name: :text)
Sqlitex.query(db, "SELECT * FROM sqlite_master", into: %{})
end)
assert row.type == "table"
assert row.name == "users"
assert row.tbl_name == "users"
assert row.sql == "CREATE TABLE \"users\" (\"id\" integer PRIMARY KEY NOT NULL, \"name\" text )"
end
test "a parameterized query", context do
{:ok, [row]} = Sqlitex.query(context[:golf_db], "SELECT id, name FROM players WHERE name LIKE ?1 AND type == ?2", bind: ["s%", "Team"])
assert row == [id: 25, name: "Slothstronauts"]
end
test "a parameterized query into %{}", context do
{:ok, [row]} = Sqlitex.query(context[:golf_db], "SELECT id, name FROM players WHERE name LIKE ?1 AND type == ?2", bind: ["s%", "Team"], into: %{})
assert row == %{id: 25, name: "Slothstronauts"}
end
test "exec" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (a INTEGER, b INTEGER, c INTEGER)")
:ok = Sqlitex.exec(db, "INSERT INTO t VALUES (1, 2, 3)")
{:ok, [row]} = Sqlitex.query(db, "SELECT * FROM t LIMIT 1")
assert row == [a: 1, b: 2, c: 3]
Sqlitex.close(db)
end
test "it handles queries with no columns" do
{:ok, db} = Sqlitex.open(':memory:')
assert {:ok, []} == Sqlitex.query(db, "CREATE TABLE t (a INTEGER, b INTEGER, c INTEGER)")
Sqlitex.close(db)
end
test "it handles different cases of column types" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (inserted_at DATETIME, updated_at DateTime)")
:ok = Sqlitex.exec(db, "INSERT INTO t VALUES ('2012-10-14 05:46:28.312941', '2012-10-14 05:46:35.758815')")
{:ok, [row]} = Sqlitex.query(db, "SELECT inserted_at, updated_at FROM t")
assert row[:inserted_at] == {{2012, 10, 14}, {5, 46, 28, 312_941}}
assert row[:updated_at] == {{2012, 10, 14}, {5, 46, 35, 758_815}}
end
test "it inserts nil" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (a INTEGER)")
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?1)", bind: [nil])
{:ok, [row]} = Sqlitex.query(db, "SELECT a FROM t")
assert row[:a] == nil
end
test "it inserts boolean values" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (id INTEGER, a BOOLEAN)")
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?1, ?2)", bind: [1, true])
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?1, ?2)", bind: [2, false])
{:ok, [row1, row2]} = Sqlitex.query(db, "SELECT a FROM t ORDER BY id")
assert row1[:a] == true
assert row2[:a] == false
end
test "it inserts Erlang date types" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (d DATE)")
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?)", bind: [{1985, 10, 26}])
{:ok, [row]} = Sqlitex.query(db, "SELECT d FROM t")
assert row[:d] == {1985, 10, 26}
end
test "it inserts Elixir time types" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (t TIME)")
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?)", bind: [{1, 20, 0, 666}])
{:ok, [row]} = Sqlitex.query(db, "SELECT t FROM t")
assert row[:t] == {1, 20, 0, 666}
end
test "it inserts Erlang datetime tuples" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (dt DATETIME)")
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?)", bind: [{{1985, 10, 26}, {1, 20, 0, 666}}])
{:ok, [row]} = Sqlitex.query(db, "SELECT dt FROM t")
assert row[:dt] == {{1985, 10, 26}, {1, 20, 0, 666}}
end
test "query! returns data" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (num INTEGER)")
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?)", bind: [1])
results = Sqlitex.query!(db, "SELECT num from t")
assert results == [[num: 1]]
end
test "query! throws on error" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (num INTEGER)")
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?)", bind: [1])
assert_raise Sqlitex.QueryError, "Query failed: {:sqlite_error, 'no such column: nope'}", fn ->
[_res] = Sqlitex.query!(db, "SELECT nope from t")
end
end
test "query_rows returns {:ok, data}", context do
{:ok, result} = Sqlitex.query_rows(context[:golf_db], "SELECT id, name FROM players WHERE name LIKE ?1 AND type == ?2", bind: ["s%", "Team"])
%{rows: rows, columns: columns, types: types} = result
assert rows == [[25, "Slothstronauts"]]
assert columns == [:id, :name]
assert types == [:INTEGER, :"varchar(255)"]
end
test "query_rows return {:error, reason}", context do
{:error, reason} = Sqlitex.query_rows(context[:golf_db], "SELECT wat FROM players")
assert reason == {:sqlite_error, 'no such column: wat'}
end
test "query_rows! returns data", context do
result = Sqlitex.query_rows!(context[:golf_db], "SELECT id, name FROM players WHERE name LIKE ?1 AND type == ?2", bind: ["s%", "Team"])
%{rows: rows, columns: columns, types: types} = result
assert rows == [[25, "Slothstronauts"]]
assert columns == [:id, :name]
assert types == [:INTEGER, :"varchar(255)"]
end
test "query_rows! raises on error", context do
assert_raise Sqlitex.QueryError, "Query failed: {:sqlite_error, 'no such column: wat'}", fn ->
[_res] = Sqlitex.query_rows!(context[:golf_db], "SELECT wat FROM players")
end
end
test "server query times out" do
{:ok, conn} = Sqlitex.Server.start_link(":memory:")
assert match?({:timeout, _},
catch_exit(Sqlitex.Server.query(conn, "SELECT * FROM sqlite_master", timeout: 0)))
receive do # wait for the timed-out message
msg -> msg
end
end
test "decimal types" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (f DECIMAL)")
d = Decimal.new(1.123)
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?)", bind: [d])
{:ok, [row]} = Sqlitex.query(db, "SELECT f FROM t")
assert row[:f] == d
end
test "decimal types with scale and precision" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (id INTEGER, f DECIMAL(3,2))")
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?,?)", bind: [1, Decimal.new(1.123)])
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?,?)", bind: [2, Decimal.new(244.37)])
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?,?)", bind: [3, Decimal.new(1997)])
# results should be truncated to the appropriate precision and scale:
Sqlitex.query!(db, "SELECT f FROM t ORDER BY id")
|> Enum.map(fn row -> row[:f] end)
|> Enum.zip([Decimal.new(1.12), Decimal.new(244), Decimal.new(1990)])
|> Enum.each(fn {res, ans} -> assert Decimal.equal?(res, ans) end)
end
test "it handles datetime, date, time with empty string" do
{:ok, db} = Sqlitex.open(":memory:")
:ok = Sqlitex.exec(db, "CREATE TABLE t (a datetime NOT NULL, b date NOT NULL, c time NOT NULL)")
{:ok, []} = Sqlitex.query(db, "INSERT INTO t VALUES (?, ?, ?)", bind: ["", "", ""])
{:ok, [row]} = Sqlitex.query(db, "SELECT a, b, c FROM t")
assert row[:a] == nil
assert row[:b] == nil
assert row[:c] == nil
end
end
| 43.190265 | 150 | 0.608852 |
03fb42530b94ea0e46284e8ae5ea8313e5a6beef | 10,107 | ex | Elixir | lib/wechat/server_message/xml_message.ex | feng19/wechat | 431c22818c60cd01fc5c676aa060feb303d0c444 | [
"Apache-2.0"
] | 7 | 2021-01-22T04:07:29.000Z | 2021-12-14T14:01:30.000Z | lib/wechat/server_message/xml_message.ex | feng19/wechat | 431c22818c60cd01fc5c676aa060feb303d0c444 | [
"Apache-2.0"
] | 1 | 2021-03-17T15:44:26.000Z | 2021-03-17T15:44:26.000Z | lib/wechat/server_message/xml_message.ex | feng19/wechat | 431c22818c60cd01fc5c676aa060feb303d0c444 | [
"Apache-2.0"
] | 2 | 2021-03-17T14:35:56.000Z | 2021-08-10T07:44:10.000Z | defmodule WeChat.ServerMessage.XmlMessage do
@moduledoc """
被动回复消息
[官方文档](https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Passive_user_reply_message.html){:target="_blank"}
"""
import WeChat.Utils, only: [doc_link_prefix: 0, work_doc_link_prefix: 0, def_eex: 2]
@doc_link "#{doc_link_prefix()}/doc/offiaccount/Message_Management/Passive_user_reply_message.html"
@doc """
回包加密 -
[官方文档](#{doc_link_prefix()}/doc/oplatform/Third-party_Platforms/Message_Encryption/Message_encryption_and_decryption.html)
```xml
<xml>
<Encrypt><![CDATA[encrypt_content]]></Encrypt>
<MsgSignature><![CDATA[signature]]></MsgSignature>
<TimeStamp>timestamp</TimeStamp>
<Nonce><![CDATA[nonce]]></Nonce>
</xml>
```
"""
def_eex reply_msg(signature, nonce, timestamp, encrypt_content) do
"""
<xml>
<Encrypt><![CDATA[<%= encrypt_content %>]]></Encrypt>
<MsgSignature><![CDATA[<%= signature %>]]></MsgSignature>
<TimeStamp><%= timestamp %></TimeStamp>
<Nonce><![CDATA[<%= nonce %>]]></Nonce>
</xml>
"""
end
@doc """
回复文本消息 -
[官方文档](#{@doc_link}#0){:target="_blank"}
```xml
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType>text></MsgType>
<Content><![CDATA[你好]]></Content>
</xml>
```
"""
def_eex reply_text(to_openid, from_wx_no, timestamp, content) do
"""
<xml>
<ToUserName><![CDATA[<%= to_openid %>]]></ToUserName>
<FromUserName><![CDATA[<%= from_wx_no %>]]></FromUserName>
<CreateTime><%= timestamp %></CreateTime>
<MsgType>text</MsgType>
<Content><![CDATA[<%= content %>]]></Content>
</xml>
"""
end
@doc """
回复图片消息 -
[官方文档](#{@doc_link}#1){:target="_blank"}
```xml
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType>image</MsgType>
<Image>
<MediaId><![CDATA[media_id]]></MediaId>
</Image>
</xml>
```
"""
def_eex reply_image(to_openid, from_wx_no, timestamp, media_id) do
"""
<xml>
<ToUserName><![CDATA[<%= to_openid %>]]></ToUserName>
<FromUserName><![CDATA[<%= from_wx_no %>]]></FromUserName>
<CreateTime><%= timestamp %></CreateTime>
<MsgType>image</MsgType>
<Image>
<MediaId><![CDATA[<%= media_id %>]]></MediaId>
</Image>
</xml>
"""
end
@doc """
回复语音消息 -
[官方文档](#{@doc_link}#2){:target="_blank"}
```xml
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType>voice</MsgType>
<Voice>
<MediaId><![CDATA[media_id]]></MediaId>
</Voice>
</xml>
```
"""
def_eex reply_voice(to_openid, from_wx_no, timestamp, media_id) do
"""
<xml>
<ToUserName><![CDATA[<%= to_openid %>]]></ToUserName>
<FromUserName><![CDATA[<%= from_wx_no %>]]></FromUserName>
<CreateTime><%= timestamp %></CreateTime>
<MsgType>voice</MsgType>
<Voice>
<MediaId><![CDATA[<%= media_id %>]]></MediaId>
</Voice>
</xml>
"""
end
@doc """
回复视频消息 -
[官方文档](#{@doc_link}#3){:target="_blank"}
```xml
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType>video</MsgType>
<Video>
<MediaId><![CDATA[media_id]]></MediaId>
<Title><![CDATA[title]]></Title>
<Description><![CDATA[description]]></Description>
</Video>
</xml>
```
"""
def_eex reply_video(to_openid, from_wx_no, timestamp, media_id, title, desc) do
"""
<xml>
<ToUserName><![CDATA[<%= to_openid %>]]></ToUserName>
<FromUserName><![CDATA[<%= from_wx_no %>]]></FromUserName>
<CreateTime><%= timestamp %></CreateTime>
<MsgType>video</MsgType>
<Video>
<MediaId><![CDATA[<%= media_id %>]]></MediaId>
<Title><![CDATA[<%= title %>]]></Title>
<Description><![CDATA[<%= desc %>]]></Description>
</Video>
</xml>
"""
end
@doc """
回复音乐消息 -
[官方文档](#{@doc_link}#4){:target="_blank"}
```xml
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType>music</MsgType>
<Music>
<Title><![CDATA[title]]></Title>
<Description><![CDATA[description]]></Description>
<MusicUrl><![CDATA[MUSIC_Url]]></MusicUrl>
<HQMusicUrl><![CDATA[HQ_MUSIC_Url]]></HQMusicUrl>
<ThumbMediaId><![CDATA[media_id]]></ThumbMediaId>
</Music>
</xml>
```
"""
def_eex reply_music(
to_openid,
from_wx_no,
timestamp,
title,
desc,
music_url,
hq_music_url,
thumb_media_id
) do
"""
<xml>
<ToUserName><![CDATA[<%= to_openid %>]]></ToUserName>
<FromUserName><![CDATA[<%= from_wx_no %>]]></FromUserName>
<CreateTime><%= timestamp %></CreateTime>
<MsgType>music</MsgType>
<Music>
<Title><![CDATA[<%= title %>]]></Title>
<Description><![CDATA[<%= desc %>]]></Description>
<MusicUrl><![CDATA[<%= music_url %>]]></MusicUrl>
<HQMusicUrl><![CDATA[<%= hq_music_url %>]]></HQMusicUrl>
<ThumbMediaId><![CDATA[<%= thumb_media_id %>]]></ThumbMediaId>
</Music>
</xml>
"""
end
@doc """
回复图文消息 -
[官方文档](#{@doc_link}#5){:target="_blank"}
```xml
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType>news</MsgType>
<ArticleCount>1</ArticleCount>
<Articles>
<item>
<Title><![CDATA[title1]]></Title>
<Description><![CDATA[description1]]></Description>
<PicUrl><![CDATA[picurl]]></PicUrl>
<Url><![CDATA[url]]></Url>
</item>
</Articles>
</xml>
```
"""
def_eex reply_news(to_openid, from_wx_no, timestamp, article_items) do
"""
<xml>
<ToUserName><![CDATA[<%= to_openid %>]]></ToUserName>
<FromUserName><![CDATA[<%= from_wx_no %>]]></FromUserName>
<CreateTime><%= timestamp %></CreateTime>
<MsgType>news</MsgType>
<ArticleCount><%= length(article_items) %></ArticleCount>
<Articles>
<%= for article_item <- article_items do %>
<item>
<Title><![CDATA[<%= article_item.title %>]]></Title>
<Description><![CDATA[<%= article_item.desc %>]]></Description>
<PicUrl><![CDATA[<%= article_item.pic_url %>]]></PicUrl>
<Url><![CDATA[<%= article_item.url %>]]></Url>
</item>
<% end %>
</Articles>
</xml>
"""
end
@doc """
消息转发客服消息 -
[官方文档](#{doc_link_prefix()}/doc/offiaccount/Customer_Service/Forwarding_of_messages_to_service_center.html){:target="_blank"}
```xml
<xml>
<ToUserName><![CDATA[touser]]></ToUserName>
<FromUserName><![CDATA[fromuser]]></FromUserName>
<CreateTime>1399197672</CreateTime>
<MsgType>transfer_customer_service</MsgType>
</xml>
```
"""
def_eex transfer_customer_service(to_openid, from_wx_no, timestamp) do
"""
<xml>
<ToUserName><![CDATA[<%= to_openid %>]]></ToUserName>
<FromUserName><![CDATA[<%= from_wx_no %>]]></FromUserName>
<CreateTime><%= timestamp %></CreateTime>
<MsgType>transfer_customer_service</MsgType>
</xml>
"""
end
@doc """
消息转发到指定客服 -
[官方文档](#{doc_link_prefix()}/doc/offiaccount/Customer_Service/Forwarding_of_messages_to_service_center.html){:target="_blank"}
```xml
<xml>
<ToUserName><![CDATA[touser]]></ToUserName>
<FromUserName><![CDATA[fromuser]]></FromUserName>
<CreateTime>1399197672</CreateTime>
<MsgType>transfer_customer_service</MsgType>
<TransInfo>
<KfAccount><![CDATA[test1@test]]></KfAccount>
</TransInfo>
</xml>
```
"""
def_eex transfer_customer_service(to_openid, from_wx_no, timestamp, kf_account) do
"""
<xml>
<ToUserName><![CDATA[<%= to_openid %>]]></ToUserName>
<FromUserName><![CDATA[<%= from_wx_no %>]]></FromUserName>
<CreateTime><%= timestamp %></CreateTime>
<MsgType>transfer_customer_service</MsgType>
<TransInfo>
<KfAccount><![CDATA[<%= kf_account %>]]></KfAccount>
</TransInfo>
</xml>
"""
end
@doc """
模板卡片更新消息(更新点击用户的按钮点击文案) -
[官方文档](#{work_doc_link_prefix()}/90135/90241#模板卡片更新消息){:target="_blank"}
```xml
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1357290913</CreateTime>
<MsgType>update_button</MsgType>
<Button>
<ReplaceName><![CDATA[ReplaceName]]></ReplaceName>
</Button>
</xml>
```
"""
def_eex update_template_card_button(to_user, from_user, timestamp, replace_name) do
"""
<xml>
<ToUserName><![CDATA[<%= to_user %>]]></ToUserName>
<FromUserName><![CDATA[<%= from_user %>]]></FromUserName>
<CreateTime><%= timestamp %></CreateTime>
<MsgType>update_button</MsgType>
<Button>
<ReplaceName><![CDATA[<%= replace_name %>]]></ReplaceName>
</Button>
</xml>
"""
end
@doc """
模板卡片更新消息(更新点击用户的整张卡片) -
[官方文档](#{work_doc_link_prefix()}/90135/90241#更新点击用户的整张卡片){:target="_blank"}
```xml
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1357290913</CreateTime>
<MsgType>update_button</MsgType>
template_card_xml
</xml>
```
"""
def_eex update_template_card(to_user, from_user, timestamp, template_card_xml) do
"""
<xml>
<ToUserName><![CDATA[<%= to_user %>]]></ToUserName>
<FromUserName><![CDATA[<%= from_user %>]]></FromUserName>
<CreateTime><%= timestamp %></CreateTime>
<MsgType>update_template_card</MsgType>
<%= template_card_xml %>
</xml>
"""
end
end
| 28.390449 | 127 | 0.592659 |
03fb4bcf09e5f18c22cba62e91b07215bbd37f3b | 124 | exs | Elixir | config/config.exs | reichert621/swoosh | b85f6d44be939fd006abfb76fd15de0859c9a5f9 | [
"MIT"
] | null | null | null | config/config.exs | reichert621/swoosh | b85f6d44be939fd006abfb76fd15de0859c9a5f9 | [
"MIT"
] | null | null | null | config/config.exs | reichert621/swoosh | b85f6d44be939fd006abfb76fd15de0859c9a5f9 | [
"MIT"
] | null | null | null | use Mix.Config
config :bypass, adapter: Plug.Adapters.Cowboy2
if Mix.env() == :test do
config :logger, level: :info
end
| 15.5 | 46 | 0.709677 |
03fb98c7555f93048607cfec955dc9605f32c458 | 688 | exs | Elixir | test/cog/chat/slack/templates/embedded/role_create_test.exs | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 1,003 | 2016-02-23T17:21:12.000Z | 2022-02-20T14:39:35.000Z | test/cog/chat/slack/templates/embedded/role_create_test.exs | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 906 | 2016-02-22T22:54:19.000Z | 2022-03-11T15:19:43.000Z | test/cog/chat/slack/templates/embedded/role_create_test.exs | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 95 | 2016-02-23T13:42:31.000Z | 2021-11-30T14:39:55.000Z | defmodule Cog.Chat.Slack.Templates.Embedded.RoleCreateTest do
use Cog.TemplateCase
test "role-create template" do
data = %{"results" => [%{"name" => "foo"}]}
expected = "Created role 'foo'"
assert_rendered_template(:slack, :embedded, "role-create", data, expected)
end
test "role-create template with multiple inputs" do
data = %{"results" => [%{"name" => "foo"},
%{"name" => "bar"},
%{"name" => "baz"}]}
expected = """
Created role 'foo'
Created role 'bar'
Created role 'baz'
""" |> String.strip
assert_rendered_template(:slack, :embedded, "role-create", data, expected)
end
end
| 28.666667 | 78 | 0.578488 |
03fbc5e24ee4e69d094845f85108ae29186059ab | 1,123 | exs | Elixir | config/config.exs | shawnHartsell/hai-elixir | 384383fa4e69f541a41247d4454b73eba31486e2 | [
"MIT"
] | null | null | null | config/config.exs | shawnHartsell/hai-elixir | 384383fa4e69f541a41247d4454b73eba31486e2 | [
"MIT"
] | null | null | null | config/config.exs | shawnHartsell/hai-elixir | 384383fa4e69f541a41247d4454b73eba31486e2 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :hai_elixir, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:hai_elixir, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 36.225806 | 73 | 0.752449 |
03fbf24a3b44c877a0414411db713e79fae52b5e | 1,143 | exs | Elixir | clients/machine_learning/mix.exs | MechimCook/elixir-google-api | 0240ede69ec77115076724d223f9d1f849ff1d6b | [
"Apache-2.0"
] | null | null | null | clients/machine_learning/mix.exs | MechimCook/elixir-google-api | 0240ede69ec77115076724d223f9d1f849ff1d6b | [
"Apache-2.0"
] | null | null | null | clients/machine_learning/mix.exs | MechimCook/elixir-google-api | 0240ede69ec77115076724d223f9d1f849ff1d6b | [
"Apache-2.0"
] | null | null | null | defmodule GoogleApi.MachineLearning.V1.Mixfile do
use Mix.Project
@version "0.8.0"
def project() do
[
app: :google_api_machine_learning,
version: @version,
elixir: "~> 1.4",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/machine_learning"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.1.0"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
An API to enable creating and using machine learning models.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/machine_learning",
"Homepage" => "https://cloud.google.com/ml-engine/"
}
]
end
end
| 23.326531 | 116 | 0.596675 |
03fc1cb29c88c262afef5d7ea98b2afe2f349cd4 | 73 | ex | Elixir | lib/dwarlixir/components/container.ex | Trevoke/dwarlixir | e0a7ae39d3687d8e649fba67ce3dee413f00307e | [
"MIT"
] | 54 | 2017-03-09T20:43:11.000Z | 2022-03-29T16:59:20.000Z | lib/dwarlixir/components/container.ex | Trevoke/dwarlixir | e0a7ae39d3687d8e649fba67ce3dee413f00307e | [
"MIT"
] | 17 | 2017-03-12T18:16:21.000Z | 2017-05-30T03:34:57.000Z | lib/dwarlixir/components/container.ex | Trevoke/dwarlixir | e0a7ae39d3687d8e649fba67ce3dee413f00307e | [
"MIT"
] | 2 | 2017-04-23T23:47:41.000Z | 2017-11-19T13:38:25.000Z | defmodule Dwarlixir.Components.Container do
use Ecstatic.Component
end
| 18.25 | 43 | 0.849315 |
03fc25bf3b85295bf8d5508167cac89f8a53b725 | 4,000 | exs | Elixir | mix.exs | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | 1 | 2018-12-07T06:21:21.000Z | 2018-12-07T06:21:21.000Z | mix.exs | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | null | null | null | mix.exs | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | null | null | null | defmodule EWallet.Umbrella.Mixfile do
use Mix.Project
def project do
[
apps_path: "apps",
start_permanent: Mix.env() == :prod,
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
deps: deps(),
aliases: aliases(),
docs: docs(),
dialyzer: [
flags: [:underspecs, :unknown, :unmatched_returns],
plt_add_apps: [:iex, :mix],
ignore_warnings: ".dialyzer_ignore.exs"
]
]
end
# Dependencies listed here are available only for this
# project and cannot be accessed from applications inside
# the apps folder.
#
# Run "mix help deps" for examples and options.
defp deps do
[
{:credo, "0.10.0", only: [:dev, :test], runtime: false},
{:ex_doc, "~> 0.16", only: :dev, runtime: false},
{:excoveralls, "~> 0.8", only: :test, runtime: false},
{:dialyxir, "~> 1.0.0-rc.3", only: [:dev], runtime: false}
]
end
# Aliases for easier command executions
def aliases do
[
init: [
"ecto.create",
"ecto.migrate",
"seed"
],
reset: [
"ecto.drop",
"ecto.create",
"ecto.migrate"
],
seed: [
"omg.seed"
]
]
end
def docs do
[
assets: "assets/",
main: "introduction",
extra_section: "Guides",
extras: [
{"README.md", [filename: "introduction", title: "Introduction"]},
"docs/demo.md",
"docs/faq.md",
# Design
"docs/design/components.md",
"docs/design/conventions.md",
"docs/design/databases.md",
"docs/design/design.md",
"docs/design/transactions_and_entries.md",
"docs/design/wallets.md",
# Guides
"docs/guides/api_responsibilities.md",
"docs/guides/entities.md",
"docs/guides/ewallet_api_websockets.md",
"docs/guides/guides.md",
"docs/guides/transaction_request_flow.md",
"docs/guides/usage.md",
# Setup
"docs/setup/advanced/api_specs.md",
"docs/setup/advanced/clustering.md",
"docs/setup/advanced/env.md",
"docs/setup/upgrading/20180619-encryption-upgrade.md",
"docs/setup/bare_metal.md",
"docs/setup/docker.md",
"docs/setup/vagrant.md",
# Tests
"docs/tests/tests.md"
],
groups_for_extras: [
"Getting Started": [
"README.md",
"docs/demo.md",
"docs/faq.md"
],
"Setting Up": [
"docs/setup/docker.md",
"docs/setup/vagrant.md",
"docs/setup/bare_metal.md"
],
Guides: [
"docs/guides/usage.md",
"docs/guides/api_responsibilities.md",
"docs/guides/entities.md",
"docs/guides/transaction_request_flow.md",
"docs/guides/ewallet_api_websockets.md"
],
"Technical Design": [
"docs/design/components.md",
"docs/design/databases.md",
"docs/design/wallets.md",
"docs/design/transactions_and_entries.md",
"docs/design/conventions.md"
],
Tests: [
"docs/tests/tests.md"
],
"Advanced Setup": [
"docs/setup/advanced/env.md",
"docs/setup/advanced/clustering.md",
"docs/setup/advanced/api_specs.md"
]
],
groups_for_modules: [
"eWallet API": ~r/EWalletAPI(?!\.V\d+)(\..+)*$/,
"eWallet API V1": ~r/EWalletAPI.V1(\..+)*$/,
"Admin API": ~r/AdminAPI(?!\.V\d+)(\..+)*$/,
"Admin API V1": ~r/AdminAPI.V1(\..+)*$/,
eWallet: ~r/EWallet(\..+)*$/,
"eWallet DB": ~r/EWalletDB(\..+)*$/,
"Local Ledger": ~r/LocalLedger(\..+)*$/,
"Local Ledger DB": ~r/LocalLedgerDB(\..+)*$/,
"URL Dispatcher": ~r/UrlDispatcher(\..+)*$/
]
]
end
end
| 28.368794 | 73 | 0.53 |
03fc286a359190267c4b4c06ba0b976a15eb94b2 | 1,537 | ex | Elixir | clients/surveys/lib/google_api/surveys/v2/model/field_mask.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/surveys/lib/google_api/surveys/v2/model/field_mask.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/surveys/lib/google_api/surveys/v2/model/field_mask.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Surveys.V2.Model.FieldMask do
@moduledoc """
## Attributes
* `fields` (*type:* `list(GoogleApi.Surveys.V2.Model.FieldMask.t)`, *default:* `nil`) -
* `id` (*type:* `integer()`, *default:* `nil`) -
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:fields => list(GoogleApi.Surveys.V2.Model.FieldMask.t()),
:id => integer()
}
field(:fields, as: GoogleApi.Surveys.V2.Model.FieldMask, type: :list)
field(:id)
end
defimpl Poison.Decoder, for: GoogleApi.Surveys.V2.Model.FieldMask do
def decode(value, options) do
GoogleApi.Surveys.V2.Model.FieldMask.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Surveys.V2.Model.FieldMask do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 30.74 | 92 | 0.712427 |
03fc3237c2fd44b9cd85df5003fd3636b89c9266 | 1,111 | ex | Elixir | lib/sanbase/clickhouse/metric/table_metric.ex | santiment/sanbase2 | 9ef6e2dd1e377744a6d2bba570ea6bd477a1db31 | [
"MIT"
] | 81 | 2017-11-20T01:20:22.000Z | 2022-03-05T12:04:25.000Z | lib/sanbase/clickhouse/metric/table_metric.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 359 | 2017-10-15T14:40:53.000Z | 2022-01-25T13:34:20.000Z | lib/sanbase/clickhouse/metric/table_metric.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 16 | 2017-11-19T13:57:40.000Z | 2022-02-07T08:13:02.000Z | defmodule Sanbase.Clickhouse.MetricAdapter.TableMetric do
import Sanbase.Clickhouse.MetricAdapter.TableSqlQuery
import Sanbase.Utils.Transform
alias Sanbase.ClickhouseRepo
def table_data(_metric, %{slug: []}, _from, _to) do
{:ok,
%{
rows: [],
columns: [],
values: []
}}
end
def table_data(
"labelled_exchange_balance_sum" = metric,
%{slug: slug_or_slugs},
from,
to,
_opts
) do
slugs = List.wrap(slug_or_slugs)
{query, args} = table_data_query(metric, slugs, from, to)
ClickhouseRepo.query_transform(query, args, fn [_label | tail] -> tail end)
|> maybe_apply_function(&transform_table_data(&1, slugs))
end
# Private functiions
defp transform_table_data(owner_value_pairs, slugs) do
rows = Enum.map(owner_value_pairs, fn [owner | _values] -> owner end)
values =
Enum.map(owner_value_pairs, fn [_owner | values] -> values end)
|> List.flatten()
|> Enum.chunk_every(length(slugs))
%{
rows: rows,
columns: slugs,
values: values
}
end
end
| 23.638298 | 79 | 0.634563 |
03fc480626085c38a6323fb055ca2cc4de66ad71 | 843 | ex | Elixir | lib/scenic/primitive/style/text_height.ex | ruan-brandao/scenic | cbd8bf50c4239bb5e4ae7971bbc9850ae1f9f2b7 | [
"Apache-2.0"
] | null | null | null | lib/scenic/primitive/style/text_height.ex | ruan-brandao/scenic | cbd8bf50c4239bb5e4ae7971bbc9850ae1f9f2b7 | [
"Apache-2.0"
] | null | null | null | lib/scenic/primitive/style/text_height.ex | ruan-brandao/scenic | cbd8bf50c4239bb5e4ae7971bbc9850ae1f9f2b7 | [
"Apache-2.0"
] | null | null | null | #
# Created by Boyd Multerer on 2017-05-12.
# Copyright © 2017 Kry10 Industries. All rights reserved.
#
defmodule Scenic.Primitive.Style.TextHeight do
@moduledoc false
use Scenic.Primitive.Style
# alias Scenic.Primitive.Style
# @dflag Style.dflag()
# @type_code 0x0020
# ============================================================================
# data verification and serialization
# --------------------------------------------------------
@doc false
def info(data),
do: """
#{IO.ANSI.red()}#{__MODULE__} data must be a number
#{IO.ANSI.yellow()}Received: #{inspect(data)}
#{IO.ANSI.default_color()}
"""
# --------------------------------------------------------
@doc false
def verify(height) when is_number(height), do: true
def verify(_), do: false
end
| 26.34375 | 80 | 0.493476 |
03fc7eb115af2314f6fdcc77e44dea48d8dbb948 | 1,131 | exs | Elixir | test/shopify/oauth_test.exs | kurt-friedrich/shopify-oauth-elixir | bccac1c34ea35445fb737933a5d075d2972ea0be | [
"MIT"
] | 3 | 2020-01-13T22:36:29.000Z | 2021-12-12T17:59:03.000Z | test/shopify/oauth_test.exs | kurt-friedrich/shopify-oauth-elixir | bccac1c34ea35445fb737933a5d075d2972ea0be | [
"MIT"
] | 6 | 2020-04-23T16:20:26.000Z | 2021-08-03T05:47:44.000Z | test/shopify/oauth_test.exs | kurt-friedrich/shopify-oauth-elixir | bccac1c34ea35445fb737933a5d075d2972ea0be | [
"MIT"
] | 1 | 2020-04-23T16:29:37.000Z | 2020-04-23T16:29:37.000Z | defmodule Shopify.OAuthTest do
use ExUnit.Case, async: true
alias Shopify.OAuth.{ Operation }
test "create_access_token/1" do
params = %{ client_id: "💩", client_secret: "💩", code: "💩" }
expected = %Operation{ method: :post, params: params, path: "/oauth/access_token" }
assert ^expected = Shopify.OAuth.create_access_token(params)
end
test "verify_hmac/2" do
query = "code=0907a61c0c8d55e99db179b68161bc00&hmac=700e2dadb827fcc8609e9d5ce208b2e9cdaab9df07390d2cbca10d7c328fc4bf&shop=some-shop.myshopify.com&state=0.6784241404160823×tamp=1337178173"
hmac = "700e2dadb827fcc8609e9d5ce208b2e9cdaab9df07390d2cbca10d7c328fc4bf"
shared_secret = "hush"
assert { :ok, ^hmac } = Shopify.OAuth.verify_hmac(query, shared_secret)
end
test "verify_hmac/3" do
hmac = "700e2dadb827fcc8609e9d5ce208b2e9cdaab9df07390d2cbca10d7c328fc4bf"
message = "code=0907a61c0c8d55e99db179b68161bc00&shop=some-shop.myshopify.com&state=0.6784241404160823×tamp=1337178173"
shared_secret = "hush"
assert { :ok, ^hmac } = Shopify.OAuth.verify_hmac(hmac, message, shared_secret)
end
end
| 33.264706 | 196 | 0.756852 |
03fc935ad2fe0c784a5fbb96c8efcc7ff4e075c6 | 2,007 | ex | Elixir | lib/adyen_checkout_ex/model/checkout_voucher_action.ex | rsystem-se/adyen_checkout_ex | 4210f1c7150152e81f350dc6ca55aeb19665b85b | [
"MIT"
] | 1 | 2021-05-30T20:45:10.000Z | 2021-05-30T20:45:10.000Z | lib/adyen_checkout_ex/model/checkout_voucher_action.ex | rsystem-se/adyen_checkout_ex | 4210f1c7150152e81f350dc6ca55aeb19665b85b | [
"MIT"
] | null | null | null | lib/adyen_checkout_ex/model/checkout_voucher_action.ex | rsystem-se/adyen_checkout_ex | 4210f1c7150152e81f350dc6ca55aeb19665b85b | [
"MIT"
] | null | null | null | # NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
# https://openapi-generator.tech
# Do not edit the class manually.
defmodule AdyenCheckoutEx.Model.CheckoutVoucherAction do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:"alternativeReference",
:"collectionInstitutionNumber",
:"downloadUrl",
:"entity",
:"expiresAt",
:"initialAmount",
:"instructionsUrl",
:"issuer",
:"maskedTelephoneNumber",
:"merchantName",
:"merchantReference",
:"paymentData",
:"paymentMethodType",
:"reference",
:"shopperEmail",
:"shopperName",
:"surcharge",
:"totalAmount",
:"type",
:"url"
]
@type t :: %__MODULE__{
:"alternativeReference" => String.t | nil,
:"collectionInstitutionNumber" => String.t | nil,
:"downloadUrl" => String.t | nil,
:"entity" => String.t | nil,
:"expiresAt" => String.t | nil,
:"initialAmount" => AdyenCheckoutEx.Model.Amount.t | nil,
:"instructionsUrl" => String.t | nil,
:"issuer" => String.t | nil,
:"maskedTelephoneNumber" => String.t | nil,
:"merchantName" => String.t | nil,
:"merchantReference" => String.t | nil,
:"paymentData" => String.t | nil,
:"paymentMethodType" => String.t | nil,
:"reference" => String.t | nil,
:"shopperEmail" => String.t | nil,
:"shopperName" => String.t | nil,
:"surcharge" => AdyenCheckoutEx.Model.Amount.t | nil,
:"totalAmount" => AdyenCheckoutEx.Model.Amount.t | nil,
:"type" => String.t,
:"url" => String.t | nil
}
end
defimpl Poison.Decoder, for: AdyenCheckoutEx.Model.CheckoutVoucherAction do
import AdyenCheckoutEx.Deserializer
def decode(value, options) do
value
|> deserialize(:"initialAmount", :struct, AdyenCheckoutEx.Model.Amount, options)
|> deserialize(:"surcharge", :struct, AdyenCheckoutEx.Model.Amount, options)
|> deserialize(:"totalAmount", :struct, AdyenCheckoutEx.Model.Amount, options)
end
end
| 29.514706 | 91 | 0.642252 |
03fcf73c9481289ad51b8b4c081e16485463ddba | 135 | ex | Elixir | lib/spike/volatile_entry.ex | thiamsantos/spike-kv | 9fc1a779ef335721b7181808537248fc19ac8c04 | [
"Apache-2.0"
] | 1 | 2019-04-16T22:13:23.000Z | 2019-04-16T22:13:23.000Z | lib/spike/volatile_entry.ex | thiamsantos/spike-kv | 9fc1a779ef335721b7181808537248fc19ac8c04 | [
"Apache-2.0"
] | null | null | null | lib/spike/volatile_entry.ex | thiamsantos/spike-kv | 9fc1a779ef335721b7181808537248fc19ac8c04 | [
"Apache-2.0"
] | null | null | null | defmodule Spike.VolatileEntry do
@enforce_keys [:key, :value, :exp, :inserted_at]
defstruct [:key, :value, :exp, :inserted_at]
end
| 27 | 50 | 0.718519 |
03fd6c0579fc2b464872c7e29b37c92bad6fa923 | 1,862 | ex | Elixir | apps/omg_api/test/support/state/prop_test/form_block.ex | SingularityMatrix/elixir-omg | 7db3fcc3adfa303e30ff7703148cc5110b587d20 | [
"Apache-2.0"
] | null | null | null | apps/omg_api/test/support/state/prop_test/form_block.ex | SingularityMatrix/elixir-omg | 7db3fcc3adfa303e30ff7703148cc5110b587d20 | [
"Apache-2.0"
] | null | null | null | apps/omg_api/test/support/state/prop_test/form_block.ex | SingularityMatrix/elixir-omg | 7db3fcc3adfa303e30ff7703148cc5110b587d20 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule OMG.API.State.PropTest.FormBlock do
@moduledoc """
Generates function needed to produce block in propcheck test
"""
alias OMG.API.PropTest.Constants
alias OMG.API.PropTest.Helper
require Constants
def impl do
OMG.API.State.PropTest.StateCoreGS.form_block(Constants.child_block_interval())
end
def post(%{model: %{history: history}}, [], {:ok, {_, transactions, _}}) do
expected_transactions =
history
|> Enum.take_while(&(elem(&1, 0) != :form_block))
|> Enum.filter(&(elem(&1, 0) == :transaction))
|> Enum.map(&elem(&1, 1))
|> Enum.reverse()
transactions = transactions |> Enum.map(fn %{tx: tx} -> Helper.format_transaction(tx) end)
expected_transactions == transactions
end
def next(%{model: %{history: history} = model, eth: %{blknum: number} = eth} = state, [], _) do
blknum = div(number, Constants.child_block_interval()) * Constants.child_block_interval()
%{
state
| eth: %{eth | blknum: blknum + Constants.child_block_interval()},
model: %{model | history: [{:form_block, blknum} | history]}
}
end
defmacro __using__(_opt) do
quote [location: :keep], do: defcommand(:form_block, do: unquote(Helper.create_delegate_to_defcommand(__MODULE__)))
end
end
| 35.132075 | 119 | 0.694952 |
03fd7bb767e5f3b7c08a37d2d12ab243a8e8b867 | 3,406 | ex | Elixir | clients/script/lib/google_api/script/v1/model/operation.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/script/lib/google_api/script/v1/model/operation.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/script/lib/google_api/script/v1/model/operation.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.Script.V1.Model.Operation do
@moduledoc """
A representation of an execution of an Apps Script function started with run. The execution response does not arrive until the function finishes executing. The maximum execution runtime is listed in the [Apps Script quotas guide](/apps-script/guides/services/quotas#current_limitations). After execution has started, it can have one of four outcomes: - If the script function returns successfully, the response field contains an ExecutionResponse object with the function's return value in the object's `result` field. - If the script function (or Apps Script itself) throws an exception, the error field contains a Status object. The `Status` object's `details` field contains an array with a single ExecutionError object that provides information about the nature of the error. - If the execution has not yet completed, the done field is `false` and the neither the `response` nor `error` fields are present. - If the `run` call itself fails (for example, because of a malformed request or an authorization error), the method returns an HTTP response code in the 4XX range with a different format for the response body. Client libraries automatically convert a 4XX response into an exception class.
## Attributes
* `done` (*type:* `boolean()`, *default:* `nil`) - This field indicates whether the script execution has completed. A completed execution has a populated `response` field containing the ExecutionResponse from function that was executed.
* `error` (*type:* `GoogleApi.Script.V1.Model.Status.t`, *default:* `nil`) - If a `run` call succeeds but the script function (or Apps Script itself) throws an exception, this field contains a Status object. The `Status` object's `details` field contains an array with a single ExecutionError object that provides information about the nature of the error.
* `response` (*type:* `map()`, *default:* `nil`) - If the script function returns successfully, this field contains an ExecutionResponse object with the function's return value.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:done => boolean() | nil,
:error => GoogleApi.Script.V1.Model.Status.t() | nil,
:response => map() | nil
}
field(:done)
field(:error, as: GoogleApi.Script.V1.Model.Status)
field(:response, type: :map)
end
defimpl Poison.Decoder, for: GoogleApi.Script.V1.Model.Operation do
def decode(value, options) do
GoogleApi.Script.V1.Model.Operation.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Script.V1.Model.Operation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 64.264151 | 1,203 | 0.754257 |
03fdad528cb6588ffea503deada45c46c1010520 | 56 | exs | Elixir | test/test_helper.exs | angelikatyborska/mazes | cba3b1d6aaaa896f4ca505b477cf03b67523ebf0 | [
"MIT"
] | 116 | 2020-12-26T20:56:01.000Z | 2022-03-12T15:12:37.000Z | test/test_helper.exs | lohayon/mazes | 98a6276ea7440af938edfb14476a5877fdc295e1 | [
"MIT"
] | null | null | null | test/test_helper.exs | lohayon/mazes | 98a6276ea7440af938edfb14476a5877fdc295e1 | [
"MIT"
] | 10 | 2020-12-29T05:11:43.000Z | 2022-01-02T00:57:12.000Z | Application.ensure_all_started(:hackney)
ExUnit.start()
| 18.666667 | 40 | 0.839286 |
03fdb6f2d06664080122d0d7db8f6d1b5f2c3e52 | 1,173 | exs | Elixir | sample_app/config/dev.exs | tanyakavrakova/phoenix_params | 3d6a4522c7a9f3a6d55101fa45330c18f72933c1 | [
"MIT"
] | 15 | 2018-09-05T13:36:40.000Z | 2021-03-18T15:00:12.000Z | sample_app/config/dev.exs | tanyakavrakova/phoenix_params | 3d6a4522c7a9f3a6d55101fa45330c18f72933c1 | [
"MIT"
] | null | null | null | sample_app/config/dev.exs | tanyakavrakova/phoenix_params | 3d6a4522c7a9f3a6d55101fa45330c18f72933c1 | [
"MIT"
] | 1 | 2018-11-15T09:33:53.000Z | 2018-11-15T09:33:53.000Z | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :my_app, MyAppWeb.Endpoint,
http: [port: 4000],
debug_errors: false,
code_reloader: true,
check_origin: false,
watchers: []
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# command from your terminal:
#
# openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem
#
# The `http:` config above can be replaced with:
#
# https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
| 33.514286 | 170 | 0.734868 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.