hexsha
stringlengths 40
40
| size
int64 2
991k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
208
| max_stars_repo_name
stringlengths 6
106
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
33.5k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
208
| max_issues_repo_name
stringlengths 6
106
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
16.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
208
| max_forks_repo_name
stringlengths 6
106
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
6.91k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 2
991k
| avg_line_length
float64 1
36k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9e8dd698236d6c597e7521eb7a3b83304c473155 | 1,895 | ex | Elixir | clients/vision/lib/google_api/vision/v1/model/color_info.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/vision/lib/google_api/vision/v1/model/color_info.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/vision/lib/google_api/vision/v1/model/color_info.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Vision.V1.Model.ColorInfo do
@moduledoc """
Color information consists of RGB channels, score, and the fraction of
the image that the color occupies in the image.
## Attributes
* `color` (*type:* `GoogleApi.Vision.V1.Model.Color.t`, *default:* `nil`) - RGB components of the color.
* `pixelFraction` (*type:* `number()`, *default:* `nil`) - The fraction of pixels the color occupies in the image.
Value in range [0, 1].
* `score` (*type:* `number()`, *default:* `nil`) - Image-specific score for this color. Value in range [0, 1].
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:color => GoogleApi.Vision.V1.Model.Color.t(),
:pixelFraction => number(),
:score => number()
}
field(:color, as: GoogleApi.Vision.V1.Model.Color)
field(:pixelFraction)
field(:score)
end
defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.ColorInfo do
def decode(value, options) do
GoogleApi.Vision.V1.Model.ColorInfo.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.ColorInfo do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.454545 | 118 | 0.706596 |
9e8dfc15aa8af1e9463bf5cd9a2ca050e714e985 | 3,485 | exs | Elixir | config/dev.exs | kianmeng/website | 1948f46eeeb1c1b598408bfb049bbe24189ace2e | [
"Apache-2.0"
] | 1 | 2019-10-31T19:59:41.000Z | 2019-10-31T19:59:41.000Z | config/dev.exs | kianmeng/website | 1948f46eeeb1c1b598408bfb049bbe24189ace2e | [
"Apache-2.0"
] | null | null | null | config/dev.exs | kianmeng/website | 1948f46eeeb1c1b598408bfb049bbe24189ace2e | [
"Apache-2.0"
] | null | null | null | 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 webpack to recompile .js and .css sources.
config :erlef,
secret: "UFxcBGAa6OnsKUezTOCmSDg+yr2K9Dmd8Lq9EM/vZalBsoaUmlWjmmwWFmJ6EItl"
config :erlef, ErlefWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--watch",
"--watch-options-stdin",
cd: "assets",
env: [{"TAILWIND_MODE", "watch"}]
]
]
# Watch static and templates for browser reloading.
config :erlef, ErlefWeb.Endpoint,
live_reload: [
patterns: [
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"priv/data/community/.*(exs)$",
~r"priv/data/.*(exs)$",
~r"lib/erlef/community/.*(ex)$",
~r"lib/erlef_web/{live,views}/.*(ex)$",
~r"lib/erlef_web/templates/.*(eex)$"
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
config :erlef, Erlef.Mailer, adapter: Swoosh.Adapters.Local
config :erlef, env: :dev
config :erlef, :twitter_client, Erlef.Twitter
config :swoosh, preview_port: 4001
# A model (fake server) of the wildapricot api is used in dev / test mode
# See test/support/models/wild_apricot.ex for details
config :erlef, :domain, "localhost"
config :erlef, :wild_apricot,
base_api_url: "http://127.0.0.1:9999",
base_auth_url: "http://127.0.0.1:9999",
account_id: "account_id",
api_key: "api_key",
client_id: "client_id",
client_secret: "client_secret"
config :erlef, Erlef.Repo,
database: "erlef_website_dev",
username: "postgres",
password: "postgres",
migration_primary_key: [id: :uuid, type: :binary_id],
migration_timestamps: [type: :utc_datetime],
show_sensitive_data_on_connection_error: true,
pool_size: 10
# ExTwitter is not used in dev or test mode, but we set the config here for good measure
# to fake credentials
config :extwitter, :oauth,
consumer_key: "consumer_key",
consumer_secret: "consumer_secret",
access_token: "access_token",
access_token_secret: "access_token_secret"
config :ex_aws,
access_key_id: ["access_key_id", :instance_role],
secret_access_key: ["secret_access_key", :instance_role],
s3: [
scheme: "http://",
region: "New Jersey",
host: "127.0.0.1",
port: 9998
]
config :honeybadger,
environment_name: :dev,
api_key: "dev",
exclude_envs: [:dev]
config :erlef, api_key: "key"
config :erlef, :conference_perks, %{
code_beam_v_2021: %{
ends: ~D[2021-03-13],
discount: %{
link: "https://foo.bar/",
starts: ~D[2021-03-07],
ends: ~D[2021-03-13]
},
keynote: %{
link: "https://foo.bar/",
starts: ~U[2021-03-11 21:30:00.000000Z],
ends: ~U[2021-03-11 22:10:00.000000Z]
},
bof: %{
link: "https://foo.bar/",
starts: ~U[2021-03-11 22:10:00.000000Z],
ends: ~U[2021-03-11 23:10:00.000000Z]
}
}
}
| 27.226563 | 88 | 0.673745 |
9e8e0364765011aa3692c95900a4baed3eb48fd9 | 1,960 | ex | Elixir | lib/absinthe/phoenix/endpoint.ex | jerel/absinthe_phoenix | a0c9f0297197443cef4a6ba2114b5dff5133469c | [
"MIT"
] | null | null | null | lib/absinthe/phoenix/endpoint.ex | jerel/absinthe_phoenix | a0c9f0297197443cef4a6ba2114b5dff5133469c | [
"MIT"
] | null | null | null | lib/absinthe/phoenix/endpoint.ex | jerel/absinthe_phoenix | a0c9f0297197443cef4a6ba2114b5dff5133469c | [
"MIT"
] | null | null | null | defmodule Absinthe.Phoenix.Endpoint do
defmacro __using__(_) do
quote do
@behaviour Absinthe.Subscription.Pubsub
@before_compile unquote(__MODULE__)
end
end
defmacro __before_compile__(_) do
quote do
def publish_mutation(topic, mutation_result, subscribed_fields) do
Absinthe.Phoenix.Endpoint.publish_mutation(@otp_app, __MODULE__, topic, mutation_result, subscribed_fields)
end
def publish_subscription(topic, data) do
Absinthe.Phoenix.Endpoint.publish_subscription(@otp_app, __MODULE__, topic, data)
end
end
end
@doc false
# when publishing subscription results we only care about
# publishing to the local node. Each node manages and runs documents separately
# so there's no point in pushing out the results to other nodes.
def publish_subscription(otp_app, endpoint, topic, result) do
pubsub = pubsub(otp_app, endpoint)
broadcast = %Phoenix.Socket.Broadcast{
topic: topic,
event: "subscription:data",
payload: %{result: result, subscriptionId: topic},
}
pubsub
|> Phoenix.PubSub.node_name()
|> Phoenix.PubSub.direct_broadcast(pubsub, topic, broadcast)
end
@doc false
def publish_mutation(otp_app, endpoint, proxy_topic, mutation_result, subscribed_fields) do
pubsub = pubsub(otp_app, endpoint)
# we need to include the current node as part of the broadcast.
# This is because this broadcast will also be picked up by proxies within the
# current node, and they need to be able to ignore this message.
message = %{
node: node(),
subscribed_fields: subscribed_fields,
mutation_result: mutation_result,
}
Phoenix.PubSub.broadcast(pubsub, proxy_topic, message)
end
defp pubsub(otp_app, endpoint) do
Application.get_env(otp_app, endpoint)[:pubsub][:name] || raise """
Pubsub needs to be configured for #{inspect otp_app} #{inspect endpoint}!
"""
end
end
| 32.666667 | 115 | 0.715816 |
9e8e038aefb732b1a156f8f2e2d8b28cebe0a1a0 | 1,287 | exs | Elixir | mix.exs | nathanfaucett/ex-prop_types | 5ad0a884280dadf71abe4778bf693d1dd3ac8de3 | [
"MIT"
] | null | null | null | mix.exs | nathanfaucett/ex-prop_types | 5ad0a884280dadf71abe4778bf693d1dd3ac8de3 | [
"MIT"
] | null | null | null | mix.exs | nathanfaucett/ex-prop_types | 5ad0a884280dadf71abe4778bf693d1dd3ac8de3 | [
"MIT"
] | null | null | null | defmodule PropTypes.Mixfile do
use Mix.Project
def project do
[app: :prop_types,
version: "0.0.3",
description: description,
package: package,
elixir: "~> 1.2",
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
[applications: [
:tipo]]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# Type "mix help deps" for more examples and options
defp deps do
[{:tipo, "~> 0.0.3"},
{:ex_doc, ">= 0.0.0", only: :dev}]
end
defp description do
"""
Property Type validations and checkers for elixir apps
"""
end
defp package do
[# These are the default files included in the package
name: :prop_types,
files: ["lib", "mix.exs", "README*", "LICENSE*"],
maintainers: ["Nathan Faucett"],
licenses: ["MIT"],
links: %{
"GitHub" => "https://github.com/nathanfaucett/ex-prop_types",
"Docs" => "https://github.com/nathanfaucett/ex-prop_types"
}
]
end
end
| 22.982143 | 77 | 0.592852 |
9e8e58a5cea0acdef456eddda81bcbf383a634d3 | 3,351 | ex | Elixir | apps/artemis_web/lib/artemis_web/controllers/event_report_controller.ex | artemis-platform/artemis_teams | 9930c3d9528e37b76f0525390e32b66eed7eadde | [
"MIT"
] | 2 | 2020-04-23T02:29:18.000Z | 2020-07-07T13:13:17.000Z | apps/artemis_web/lib/artemis_web/controllers/event_report_controller.ex | chrislaskey/artemis_teams | 9930c3d9528e37b76f0525390e32b66eed7eadde | [
"MIT"
] | 4 | 2020-04-26T20:35:36.000Z | 2020-11-10T22:13:19.000Z | apps/artemis_web/lib/artemis_web/controllers/event_report_controller.ex | chrislaskey/artemis_teams | 9930c3d9528e37b76f0525390e32b66eed7eadde | [
"MIT"
] | null | null | null | defmodule ArtemisWeb.EventReportController do
use ArtemisWeb, :controller
alias Artemis.GetEventTemplate
alias Artemis.ListEventReports
alias Artemis.ListEventQuestions
alias Artemis.ListProjects
alias Artemis.ListUserTeams
def index(conn, %{"event_id" => event_template_id} = params) do
authorize(conn, "event-reports:list", fn ->
user = current_user(conn)
event_template = GetEventTemplate.call!(event_template_id, user)
event_questions = get_event_questions(event_template_id, user)
event_reports = get_event_reports(params, event_template, event_questions, user)
projects = get_projects(event_template.team_id, user)
filter_data = get_filter_data(event_template, user)
assigns = [
event_questions: event_questions,
event_reports: event_reports,
event_template: event_template,
filter_data: filter_data,
projects: projects
]
authorize_in_team(conn, event_template.team_id, fn ->
render_format(conn, "index", assigns)
end)
end)
end
# Helpers
defp get_event_reports(params, event_template, event_questions, user) do
params = Artemis.Helpers.keys_to_strings(params)
# Event Instance Reports
requested_reports = [
:event_instance_engagement_by_date
]
event_instance_reports = ListEventReports.call(requested_reports, params, user)
# Event Question Reports
requested_reports = [
:event_questions_percent_by_date
]
team_id = event_template.team_id
event_question_visibility = ArtemisWeb.EventQuestionView.get_event_question_visibility(team_id, user)
numeric_event_question_ids =
event_questions
|> Enum.filter(&(&1.type == "number"))
|> Enum.map(& &1.id)
required_params = %{
"filters" => %{
"event_question_id" => numeric_event_question_ids,
"event_question_visibility_or_user_id" => event_question_visibility
}
}
event_question_params = Artemis.Helpers.deep_merge(params, required_params)
event_question_reports = ListEventReports.call(requested_reports, event_question_params, user)
Map.merge(event_instance_reports, event_question_reports)
end
defp get_filter_data(event_template, user) do
team_id = event_template.team_id
event_question_options =
event_template.id
|> get_event_questions(user)
|> Enum.map(&[key: &1.title, value: &1.id])
project_options =
team_id
|> get_projects(user)
|> Enum.map(&[key: &1.title, value: &1.id])
user_options =
team_id
|> get_team_members(user)
|> Enum.map(&[key: &1.user.name, value: &1.user.id])
%{
event_question_options: event_question_options,
project_options: project_options,
user_options: user_options
}
end
defp get_event_questions(event_template_id, user) do
params = %{
filters: %{
event_template_id: event_template_id
}
}
ListEventQuestions.call(params, user)
end
defp get_projects(team_id, user) do
params = %{
filters: %{
team_id: team_id
}
}
ListProjects.call(params, user)
end
defp get_team_members(team_id, user) do
params = %{
filters: %{
team_id: team_id
}
}
ListUserTeams.call(params, user)
end
end
| 25.976744 | 105 | 0.688153 |
9e8e611ab804f3ea3e5b7bcac2c4e68294524a63 | 1,238 | ex | Elixir | lib/codes/codes_a27.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_a27.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_a27.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_A27 do
alias IcdCode.ICDCode
def _A270 do
%ICDCode{full_code: "A270",
category_code: "A27",
short_code: "0",
full_name: "Leptospirosis icterohemorrhagica",
short_name: "Leptospirosis icterohemorrhagica",
category_name: "Leptospirosis icterohemorrhagica"
}
end
def _A2781 do
%ICDCode{full_code: "A2781",
category_code: "A27",
short_code: "81",
full_name: "Aseptic meningitis in leptospirosis",
short_name: "Aseptic meningitis in leptospirosis",
category_name: "Aseptic meningitis in leptospirosis"
}
end
def _A2789 do
%ICDCode{full_code: "A2789",
category_code: "A27",
short_code: "89",
full_name: "Other forms of leptospirosis",
short_name: "Other forms of leptospirosis",
category_name: "Other forms of leptospirosis"
}
end
def _A279 do
%ICDCode{full_code: "A279",
category_code: "A27",
short_code: "9",
full_name: "Leptospirosis, unspecified",
short_name: "Leptospirosis, unspecified",
category_name: "Leptospirosis, unspecified"
}
end
end
| 28.790698 | 62 | 0.61874 |
9e8e69934dbb206ce111671547b7b0e013ab6f1e | 1,863 | ex | Elixir | clients/service_broker/lib/google_api/service_broker/v1/model/google_iam_v1__set_iam_policy_request.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/service_broker/lib/google_api/service_broker/v1/model/google_iam_v1__set_iam_policy_request.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/service_broker/lib/google_api/service_broker/v1/model/google_iam_v1__set_iam_policy_request.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.ServiceBroker.V1.Model.GoogleIamV1SetIamPolicyRequest do
@moduledoc """
Request message for `SetIamPolicy` method.
## Attributes
- policy (GoogleIamV1Policy): REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:policy => GoogleApi.ServiceBroker.V1.Model.GoogleIamV1Policy.t()
}
field(:policy, as: GoogleApi.ServiceBroker.V1.Model.GoogleIamV1Policy)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceBroker.V1.Model.GoogleIamV1SetIamPolicyRequest do
def decode(value, options) do
GoogleApi.ServiceBroker.V1.Model.GoogleIamV1SetIamPolicyRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceBroker.V1.Model.GoogleIamV1SetIamPolicyRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.8125 | 287 | 0.764895 |
9e8e7182e2d74bae7eb6cdce1d5da578252a3ac4 | 177 | ex | Elixir | lib/shortly_web/views/page_view.ex | abratashov/shortly | 39dbf813f0cf643525b9038adb39764466e75d5e | [
"MIT"
] | null | null | null | lib/shortly_web/views/page_view.ex | abratashov/shortly | 39dbf813f0cf643525b9038adb39764466e75d5e | [
"MIT"
] | null | null | null | lib/shortly_web/views/page_view.ex | abratashov/shortly | 39dbf813f0cf643525b9038adb39764466e75d5e | [
"MIT"
] | null | null | null | defmodule ShortlyWeb.PageView do
use ShortlyWeb, :view
@base_url Application.get_env(:shortly, :base_url)
def full_short_url(url) do
"#{@base_url}/#{url}"
end
end
| 17.7 | 52 | 0.711864 |
9e8e807d99b2ef09a4fe99399a00f1cca7b7d2e0 | 1,500 | ex | Elixir | lib/mp_api_web.ex | jsvelasquezv/mp_api | 9a2262188b5b12c0e2ecd9284a8e7f445d2be4a0 | [
"MIT"
] | null | null | null | lib/mp_api_web.ex | jsvelasquezv/mp_api | 9a2262188b5b12c0e2ecd9284a8e7f445d2be4a0 | [
"MIT"
] | null | null | null | lib/mp_api_web.ex | jsvelasquezv/mp_api | 9a2262188b5b12c0e2ecd9284a8e7f445d2be4a0 | [
"MIT"
] | null | null | null | defmodule MpApiWeb 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 MpApiWeb, :controller
use MpApiWeb, :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: MpApiWeb
import Plug.Conn
import MpApiWeb.Router.Helpers
import MpApiWeb.Gettext
end
end
def view do
quote do
use Phoenix.View, root: "lib/mp_api_web/templates",
namespace: MpApiWeb
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_flash: 2, view_module: 1]
import MpApiWeb.Router.Helpers
import MpApiWeb.ErrorHelpers
import MpApiWeb.Gettext
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 MpApiWeb.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.076923 | 69 | 0.684667 |
9e8e92f09b5ac9b9c29dc2ca520e22452319ce2d | 1,510 | ex | Elixir | clients/cloud_user_accounts/lib/google_api/cloud_user_accounts/vm_alpha/model/test_permissions_request.ex | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/cloud_user_accounts/lib/google_api/cloud_user_accounts/vm_alpha/model/test_permissions_request.ex | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/cloud_user_accounts/lib/google_api/cloud_user_accounts/vm_alpha/model/test_permissions_request.ex | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.CloudUserAccounts.Vm_alpha.Model.TestPermissionsRequest do
@moduledoc """
## Attributes
- permissions (List[String]): The set of permissions to check for the 'resource'. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. Defaults to: `null`.
"""
defstruct [
:"permissions"
]
end
defimpl Poison.Decoder, for: GoogleApi.CloudUserAccounts.Vm_alpha.Model.TestPermissionsRequest do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudUserAccounts.Vm_alpha.Model.TestPermissionsRequest do
def encode(value, options) do
GoogleApi.CloudUserAccounts.Vm_alpha.Deserializer.serialize_non_nil(value, options)
end
end
| 32.826087 | 201 | 0.757616 |
9e8ea5549696237a67e4e2db6758beba7afc5c78 | 1,514 | ex | Elixir | api/web/web.ex | cnole/phoenix-react-slack-clone | 852cc32ee157a18c93ddd1eb627ddf61bc294cda | [
"MIT"
] | 34 | 2017-01-02T14:00:25.000Z | 2021-11-20T20:51:41.000Z | api/web/web.ex | cnole/phoenix-react-slack-clone | 852cc32ee157a18c93ddd1eb627ddf61bc294cda | [
"MIT"
] | 3 | 2017-08-02T19:38:27.000Z | 2022-03-02T03:34:27.000Z | api/web/web.ex | cnole/phoenix-react-slack-clone | 852cc32ee157a18c93ddd1eb627ddf61bc294cda | [
"MIT"
] | 5 | 2017-02-19T20:34:09.000Z | 2021-10-05T11:35:11.000Z | defmodule Sling.Web do
@moduledoc """
A module that keeps using definitions for controllers,
views and so on.
This can be used in your application as:
use Sling.Web, :controller
use Sling.Web, :view
The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below.
"""
def model do
quote do
use Ecto.Schema
import Ecto
import Ecto.Changeset
import Ecto.Query
end
end
def controller do
quote do
use Phoenix.Controller
alias Sling.Repo
import Ecto
import Ecto.Query
import Sling.Router.Helpers
import Sling.Gettext
end
end
def view do
quote do
use Phoenix.View, root: "web/templates"
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
import Sling.Router.Helpers
import Sling.ErrorHelpers
import Sling.Gettext
end
end
def router do
quote do
use Phoenix.Router
end
end
def channel do
quote do
use Phoenix.Channel
alias Sling.Repo
import Ecto
import Ecto.Query
import Sling.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
| 19.164557 | 88 | 0.663144 |
9e8ed295c02dcdffb336497c901e2acab83f7880 | 974 | exs | Elixir | mix.exs | CraigCottingham/advent-of-code-2019 | 76a1545e4cca14fe1e9e0de475de253170da1645 | [
"Apache-2.0"
] | null | null | null | mix.exs | CraigCottingham/advent-of-code-2019 | 76a1545e4cca14fe1e9e0de475de253170da1645 | [
"Apache-2.0"
] | null | null | null | mix.exs | CraigCottingham/advent-of-code-2019 | 76a1545e4cca14fe1e9e0de475de253170da1645 | [
"Apache-2.0"
] | null | null | null | defmodule AoC.MixProject do
@moduledoc false
use Mix.Project
def project do
[
app: :advent_of_code,
version: "2019.0.1",
elixir: "~> 1.9",
elixirc_options: [warnings_as_errors: true],
start_permanent: Mix.env() == :prod,
preferred_cli_env: [espec: :test],
aliases: aliases(),
deps: deps()
]
end
def application do
[
extra_applications: [:logger]
]
end
defp aliases do
[
test: ["format", "credo --strict", "dialyzer", "espec"]
]
end
defp deps do
[
{:credo, "~> 1.1", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.0.0-rc.7", only: [:dev, :test], runtime: false},
{:espec, "~> 1.7", only: :test},
{:exprintf, "~> 0.2.1"},
{:libgraph, "~> 0.13.3"},
{:math, git: "git://github.com/CraigCottingham/math.git"},
{:max, "~> 0.1.3"},
{:mix_test_watch, "~> 1.0", only: [:dev, :test], runtime: false}
]
end
end
| 22.136364 | 72 | 0.527721 |
9e8edc76a5bc912c57649aa64ae80d179bae298d | 714 | ex | Elixir | lib/cookbook_web/gettext.ex | joerichsen/live_view_cookbook | a211e6bcfaa872df120f186b3d65e0672f410365 | [
"MIT"
] | null | null | null | lib/cookbook_web/gettext.ex | joerichsen/live_view_cookbook | a211e6bcfaa872df120f186b3d65e0672f410365 | [
"MIT"
] | 11 | 2021-12-19T09:07:30.000Z | 2022-01-01T17:54:43.000Z | lib/cookbook_web/gettext.ex | joerichsen/live_view_cookbook | a211e6bcfaa872df120f186b3d65e0672f410365 | [
"MIT"
] | null | null | null | defmodule CookbookWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import CookbookWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :cookbook
end
| 28.56 | 72 | 0.679272 |
9e8f0e4772e3e848a62423654d227b0ce4ee3c30 | 351 | exs | Elixir | priv/repo/seeds.exs | ninedraft/habitat | 425c6753e0f15b008c7c452bad7878c0e1e4ce07 | [
"MIT"
] | null | null | null | priv/repo/seeds.exs | ninedraft/habitat | 425c6753e0f15b008c7c452bad7878c0e1e4ce07 | [
"MIT"
] | 2 | 2020-08-15T08:57:57.000Z | 2020-12-14T08:41:30.000Z | priv/repo/seeds.exs | ninedraft/habitat | 425c6753e0f15b008c7c452bad7878c0e1e4ce07 | [
"MIT"
] | null | null | null | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Habitat.Repo.insert!(%Habitat.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 29.25 | 61 | 0.706553 |
9e8f28144fe3d12c3ece14960fa4624292aeeb2b | 595 | exs | Elixir | template/$PROJECT_NAME$/apps/db/mix.exs | mitjok/gen_template_litslink_umbrella | eadef26e83a1bb540a360f0bf5db0f519a100f8b | [
"Apache-2.0"
] | 1 | 2020-07-01T07:09:02.000Z | 2020-07-01T07:09:02.000Z | template/$PROJECT_NAME$/apps/db/mix.exs | mitjok/gen_template_litslink_umbrella | eadef26e83a1bb540a360f0bf5db0f519a100f8b | [
"Apache-2.0"
] | null | null | null | template/$PROJECT_NAME$/apps/db/mix.exs | mitjok/gen_template_litslink_umbrella | eadef26e83a1bb540a360f0bf5db0f519a100f8b | [
"Apache-2.0"
] | null | null | null | defmodule DB.MixProject do
use Mix.Project
def project do
[
app: :db,
version: "0.1.0",
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {DB.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
| 19.833333 | 87 | 0.564706 |
9e8f4155940a3e2735e8d77b028cfa412fce8162 | 125 | ex | Elixir | apps/tools_1/lib/random_server_app.ex | WhiteRookPL/elixir-fire-brigade-workshop | 1c6183339fc623842a09f4d10be75bcecf2c37e7 | [
"MIT"
] | 14 | 2017-08-09T14:21:47.000Z | 2022-03-11T04:10:49.000Z | apps/tools_1/lib/random_server_app.ex | nicholasjhenry/elixir-fire-brigade-workshop | 1c6183339fc623842a09f4d10be75bcecf2c37e7 | [
"MIT"
] | null | null | null | apps/tools_1/lib/random_server_app.ex | nicholasjhenry/elixir-fire-brigade-workshop | 1c6183339fc623842a09f4d10be75bcecf2c37e7 | [
"MIT"
] | 15 | 2017-09-05T15:43:53.000Z | 2020-04-13T16:20:18.000Z | defmodule RandomServer do
use Application
def start(_type, _args) do
RandomServer.Supervisor.start_link()
end
end
| 15.625 | 40 | 0.76 |
9e8f45f4a0819e7becf5f1c9ee65d943bbd876ea | 1,480 | ex | Elixir | config/authorization/config.ex | benjay10/app-poc-diff | 13e4ab68bd5408317ec9cd46b24acc470c4056d3 | [
"MIT"
] | null | null | null | config/authorization/config.ex | benjay10/app-poc-diff | 13e4ab68bd5408317ec9cd46b24acc470c4056d3 | [
"MIT"
] | null | null | null | config/authorization/config.ex | benjay10/app-poc-diff | 13e4ab68bd5408317ec9cd46b24acc470c4056d3 | [
"MIT"
] | null | null | null | alias Acl.Accessibility.Always, as: AlwaysAccessible
alias Acl.GraphSpec.Constraint.Resource, as: ResourceConstraint
alias Acl.GraphSpec.Constraint.ResourceFormat, as: ResourceFormatConstraint
alias Acl.Accessibility.ByQuery, as: AccessByQuery
alias Acl.GraphSpec, as: GraphSpec
alias Acl.GraphSpec.Constraint.Resource.AllPredicates, as: AllPredicates
alias Acl.GroupSpec, as: GroupSpec
alias Acl.GroupSpec.GraphCleanup, as: GraphCleanup
defmodule Acl.UserGroups.Config do
def user_groups do
[
# // PUBLIC
%GroupSpec{
name: "public",
useage: [:write, :read],
access: %AlwaysAccessible{},
graphs: [ %GraphSpec{
graph: "http://mu.semte.ch/graphs/public",
constraint: %ResourceConstraint{
source_graph: "http://mu.semte.ch/application",
resource_types: [
"http://schema.org/Author",
"http://schema.org/Book",
"http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#FileDataObject"
],
predicates: %AllPredicates{} }
# constraint: %ResourceFormatConstraint{
# resource_prefix: ""
# }
} ] },
# // CLEANUP
%GraphCleanup{
originating_graph: "http://mu.semte.ch/application",
useage: [:write],
name: "clean"
}
]
end
end
| 35.238095 | 97 | 0.579054 |
9e8f46410af7b597d8fc4736f2bbce9977988ba1 | 768 | exs | Elixir | test/assertions/enum/have_max_test.exs | bblaszkow06/espec | 4d9819ca5c68c6eb70276c7d9c9630ded01ba778 | [
"Apache-2.0"
] | null | null | null | test/assertions/enum/have_max_test.exs | bblaszkow06/espec | 4d9819ca5c68c6eb70276c7d9c9630ded01ba778 | [
"Apache-2.0"
] | null | null | null | test/assertions/enum/have_max_test.exs | bblaszkow06/espec | 4d9819ca5c68c6eb70276c7d9c9630ded01ba778 | [
"Apache-2.0"
] | null | null | null | defmodule Enum.HaveMaxTest do
use ExUnit.Case, async: true
defmodule SomeSpec do
use ESpec
let :range, do: 1..3
context "Success" do
it do: expect(range()).to(have_max(3))
it do: expect(range()).to_not(have_max(2))
end
context "Error" do
it do: expect(range()).to_not(have_max(3))
it do: expect(range()).to(have_max(2))
end
end
setup_all do
examples = ESpec.SuiteRunner.run_examples(SomeSpec.examples(), true)
{:ok, success: Enum.slice(examples, 0, 1), errors: Enum.slice(examples, 2, 3)}
end
test "Success", context do
Enum.each(context[:success], &assert(&1.status == :success))
end
test "Errors", context do
Enum.each(context[:errors], &assert(&1.status == :failure))
end
end
| 23.272727 | 82 | 0.640625 |
9e8f495b5032584c0e6b4718066a0e9ce77133b1 | 3,881 | ex | Elixir | lib/oban/plugins/lifeline.ex | polvalente/oban | 7267f8f37f8257b735d498d81cc1e43147cefc49 | [
"Apache-2.0"
] | null | null | null | lib/oban/plugins/lifeline.ex | polvalente/oban | 7267f8f37f8257b735d498d81cc1e43147cefc49 | [
"Apache-2.0"
] | null | null | null | lib/oban/plugins/lifeline.ex | polvalente/oban | 7267f8f37f8257b735d498d81cc1e43147cefc49 | [
"Apache-2.0"
] | null | null | null | defmodule Oban.Plugins.Lifeline do
@moduledoc """
Naively transition jobs stuck `executing` back to `available`.
The `Lifeline` plugin periodically rescues orphaned jobs, i.e. jobs that are stuck in the
`executing` state because the node was shut down before the job could finish. Rescuing is
purely based on time, rather than any heuristic about the job's expected execution time or
whether the node is still alive.
If an executing job has exhausted all attempts, the Lifeline plugin will mark it `discarded`
rather than `available`.
_🌟 This plugin may transition jobs that are genuinely `executing` and cause duplicate
execution. For more accurate rescuing, or to rescue jobs that have exhaused retry attempts, see
the `DynamicLifeline` plugin in [Oban Pro][pro]._
[pro]: dynamic_lifeline.html
## Using the Plugin
Rescue orphaned jobs that are still `executing` after the default of 60 minutes:
config :my_app, Oban,
plugins: [Oban.Plugins.Lifeline],
...
Override the default period to rescue orphans after a more aggressive period of 5 minutes:
config :my_app, Oban,
plugins: [{Oban.Plugins.Lifeline, rescue_after: :timer.minutes(5)}],
...
## Options
* `:rescue_after` — the maximum amount of time, in milliseconds, that a job may execute before
being rescued. 60 minutes by default, and rescuing is performed once a minute.
## Instrumenting with Telemetry
The `Oban.Plugins.Lifeline` plugin adds the following metadata to the `[:oban, :plugin, :stop]`
event:
* `:rescued_count` — the number of jobs transitioned back to `available`
"""
use GenServer
import Ecto.Query, only: [update: 3, where: 3]
alias Oban.{Config, Job, Peer, Repo}
@type option ::
{:conf, Config.t()}
| {:interval, timeout()}
| {:name, GenServer.name()}
| {:rescue_after, pos_integer()}
defmodule State do
@moduledoc false
defstruct [
:conf,
:name,
:timer,
interval: :timer.minutes(1),
rescue_after: :timer.minutes(60)
]
end
defmacrop rescued_state(attempt, max_attempts) do
quote do
fragment(
"(CASE WHEN ? < ? THEN 'available' ELSE 'discarded' END)::oban_job_state",
unquote(attempt),
unquote(max_attempts)
)
end
end
@doc false
@spec start_link([option()]) :: GenServer.on_start()
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: opts[:name])
end
@impl GenServer
def init(opts) do
state = struct!(State, opts)
{:ok, schedule_rescue(state)}
end
@impl GenServer
def terminate(_reason, %State{timer: timer}) do
if is_reference(timer), do: Process.cancel_timer(timer)
:ok
end
@impl GenServer
def handle_info(:rescue, %State{} = state) do
meta = %{conf: state.conf, plugin: __MODULE__}
:telemetry.span([:oban, :plugin], meta, fn ->
case check_leadership_and_rescue_jobs(state) do
{:ok, {rescued_count, _}} when is_integer(rescued_count) ->
{:ok, Map.put(meta, :rescued_count, rescued_count)}
error ->
{:error, Map.put(meta, :error, error)}
end
end)
{:noreply, schedule_rescue(state)}
end
defp check_leadership_and_rescue_jobs(state) do
if Peer.leader?(state.conf) do
Repo.transaction(state.conf, fn ->
time = DateTime.add(DateTime.utc_now(), -state.rescue_after, :millisecond)
query =
Job
|> where([j], j.state == "executing" and j.attempted_at < ^time)
|> update([j], set: [state: rescued_state(j.attempt, j.max_attempts)])
Repo.update_all(state.conf, query, [])
end)
else
{:ok, 0}
end
end
defp schedule_rescue(state) do
timer = Process.send_after(self(), :rescue, state.interval)
%{state | timer: timer}
end
end
| 27.721429 | 97 | 0.658335 |
9e8f4eacb149b3606e1c549d30dd29f96cca2d7c | 7,677 | ex | Elixir | lib/vowpal_client.ex | jackdoe/elixir-vowpal-client | 4a4f0446c4097ec93d9a8b124842f2a5fc2a2840 | [
"MIT"
] | null | null | null | lib/vowpal_client.ex | jackdoe/elixir-vowpal-client | 4a4f0446c4097ec93d9a8b124842f2a5fc2a2840 | [
"MIT"
] | null | null | null | lib/vowpal_client.ex | jackdoe/elixir-vowpal-client | 4a4f0446c4097ec93d9a8b124842f2a5fc2a2840 | [
"MIT"
] | null | null | null | defmodule VowpalClient do
@moduledoc """
Provides a TCP client for [Vowpal Wabbit](https://github.com/VowpalWabbit/vowpal_wabbit), and exports functions `VowpalClient.train/3`, `VowpalClient.predict/2`, and `VowpalClient.save/2`
`VowpalClient.spawn_vowpal/2` is just for debugging purposes, ideally you will have vowpal running somewhere else (`vw --foreground --port 12312 --num_children 1 ...`)
Vowpal Wabbit is amazing and fast linear model tool, (and by fast I mean *fast*)
make sure you check out: [Vowpal Examples](https://github.com/VowpalWabbit/vowpal_wabbit/wiki/Examples)
This is *incomplete* client, that at the moment works with my very-basic use case, but as I am using it, it will get more complete.
[issues](https://github.com/jackdoe/elixir-vowpal-client/issues) [fork](https://github.com/jackdoe/elixir-vowpal-client) [license - MIT](https://en.wikipedia.org/wiki/MIT_License)
## Examples
iex> VowpalClient.spawn_vowpal(12123)
#PID<0.140.0>
iex> VowpalClient.start_link(:vw, {127,0,0,1}, 12123, 1000)
{:ok, #PID<0.143.0>}
iex> VowpalClient.train(:vw, -1, [{"features",["a","b","c"]}])
-0.856059
iex> VowpalClient.predict(:vw, [{"features",["a","b","c"]}])
-0.998616
iex> VowpalClient.predict(:vw, [{"features",["a","b","d"]}])
-0.748962
"""
use GenServer
@doc """
spawns vw with `System.cmd/3`, used mainly for debugging and testing, you should start vw stand alone
## Parameters
- port: port to listen to (--port xyz)
- arguments: additional arguments passed to `System.cmd/3`
## Examples
iex> VowpalClient.spawn_vowpal(12123)
#PID<0.140.0>
"""
@spec spawn_vowpal(integer(), list(String.t())) :: pid()
def spawn_vowpal(port, arguments \\ []) do
spawn_link(fn ->
System.cmd(
System.find_executable("vw"),
["--port", "#{port}", "--foreground", "--num_children", "1"] ++ arguments,
into: IO.stream(:stdio, :line)
)
end)
end
@doc """
Connects to Vowpal Wabbit server on specific port
## Parameters
- server_name: genserver server name, e.g. :vw
- address: inet address e.g.: {127,0,0,1}
- port: the port to connect to
- timeout: connect timeout ngiven to `:gen_tcp.connect/4`
## Examples
iex> VowpalClient.start_link(:vw, {127,0,0,1}, 12123, 1000)
{:ok, #PID<0.143.0>}
this sends to vw: "-1 |features a b c\\n"
"""
@spec start_link(GenServer.name(), :gen_tcp.address(), integer(), integer()) ::
GenServer.on_start()
def start_link(name, address, port, timeout) do
GenServer.start_link(__MODULE__, {address, port, timeout}, name: name)
end
@type feature() :: {integer(), float()} | {String.t(), float()} | String.t() | integer()
@type namespace() :: {Strinb.t(), list(feature())}
defp toLine(namespaces) do
line =
namespaces
|> Enum.map(fn {name, features} ->
f =
features
|> Enum.map(fn e ->
case e do
{name, value} ->
"#{name}:#{value}"
name ->
"#{name}:1"
end
end)
|> Enum.join(" ")
"|#{name} #{f}"
end)
|> Enum.join(" ")
line
end
@doc """
Sends a train line to Vowpal Wabbit
vowpal accepts format as: "label |namespace feature feature feature |namespace featuree:value ...
label is integer, features can be either integer or string or touple of {string/int, float value}
## Parameters
- server_name: genserver server name (same you gave to `start_link/3`)
- label: the training label (for example -1 for click, 1 for convert)
- namespaces: training features of that example, list of `namespace/0` type
## Examples
iex> VowpalClient.start_link(:vw, {127,0,0,1}, 12123, 1000)
{:ok, #PID<0.143.0>}
iex> VowpalClient.predict(:vw, [{"features",["a","b","c"]}])
-0.998616
this sends to vw: "|features a b c\\n"
"""
@spec train(GenServer.server(), integer(), list(namespace())) :: float()
def train(server_name, label, namespaces) do
line = toLine(namespaces)
v = GenServer.call(server_name, {:send, "#{label} #{line}\n"})
{f, _} = Float.parse(v)
f
end
@doc """
Sends a predict line to Vowpal Wabbit, almost the same as `train/3` but without the label
vowpal accepts format as: "|namespace feature feature feature |namespace featuree:value ...
## Parameters
- server_name: genserver server name (same you gave to `start_link/3`)
- namespaces: training features of that example
## Examples
iex> VowpalClient.start_link(:vw, {127,0,0,1}, 12123, 1000)
{:ok, #PID<0.143.0>}
iex> VowpalClient.train(:vw, -1, [{"features",["a","b","c"]}])
-0.856059
this sends to vw: "-1 |features a b c\\n"
"""
@spec predict(GenServer.server(), list(namespace())) :: float()
def predict(server_name, namespaces) do
line = toLine(namespaces)
v = GenServer.call(server_name, {:send, "#{line}\n"})
{f, _} = Float.parse(v)
f
end
@doc """
Sends a line to Vowpal Wabbit, and waits for vw to reply back
## Parameters
- server_name: genserver server name (same you gave to `start_link/3`)
- line: string ending with \\n
## Examples
iex> VowpalClient.send(VowpalClientTest, "|a 12 3\\n")
"0\\n"
this sends to vw: "|a 12 3\\n"
"""
@spec send(GenServer.server(), String.t()) :: String.t()
def send(server_name, line) do
GenServer.call(server_name, {:send, line})
end
@doc """
Asks Vowpal Wabbit to save the regressor (model) by sending a line save_path_to_model, e.g. save_/tmp/example
## Parameters
- server_name: genserver server name (same you gave to `start_link/3`)
- path: path to where the model will be saved
The models is saved async from vw, so the function polls waiting for the filename to appear
then it reads it and returns the binary so you can save it
if you want to start vowpal loading initial regressor pass --initial_regressor /path/to/file
## Examples
iex> VowpalClient.save(:vw, "/tmp/abc.txt")
<<6, 0, 0, 0, 56, 46, 54, 46, 49, 0, 1, 0, 0, 0, 0, 109, 0, 0, 128, 191, 0, 0,
0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 32, 45,
45, 104, 97, 115, ...
this sends to vw: "save_/tmp/abc.txt\\n"
"""
@spec save(GenServer.server(), String.t()) :: binary()
def save(server_name, path) do
GenServer.call(server_name, {:save, path})
end
@impl true
def init({address, port, timeout}) do
{:ok, socket} =
:gen_tcp.connect(
address,
port,
[:binary, packet: :line, active: false, reuseaddr: true],
timeout
)
{:ok, socket}
end
@impl true
def handle_call({type, line}, from, socket) do
case type do
:send ->
if !String.ends_with?(line, "\n") do
raise ArgumentError, message: "line must end with \\n"
end
# let it die
:ok = :gen_tcp.send(socket, line)
{:ok, data} = :gen_tcp.recv(socket, 0)
{:reply, data, socket}
:save ->
:ok = :gen_tcp.send(socket, "save_#{line}\n")
# vw will save the model async
Task.start_link(fn ->
waitToExist(line, 1000)
GenServer.reply(from, File.read!(line))
end)
{:noreply, socket}
_ ->
raise ArgumentError, message: "not sure what to do"
end
end
defp waitToExist(path, interval) do
if File.exists?(path) do
true
else
:timer.sleep(interval)
waitToExist(path, interval)
end
end
end
| 28.969811 | 189 | 0.609613 |
9e8f4fae609eb0aff8e348691896928d13a9a4b4 | 474 | ex | Elixir | lib/entity/definitions/enemy/frowny.ex | doawoo/elixir_rpg | 4dcd0eb717bd1d654b3e6a06be31aba4c3254fb3 | [
"MIT"
] | 23 | 2021-10-24T00:21:13.000Z | 2022-03-13T12:33:38.000Z | lib/entity/definitions/enemy/frowny.ex | doawoo/elixir_rpg | 4dcd0eb717bd1d654b3e6a06be31aba4c3254fb3 | [
"MIT"
] | null | null | null | lib/entity/definitions/enemy/frowny.ex | doawoo/elixir_rpg | 4dcd0eb717bd1d654b3e6a06be31aba4c3254fb3 | [
"MIT"
] | 3 | 2021-11-04T02:42:25.000Z | 2022-02-02T14:22:52.000Z | use ElixirRPG.DSL.Entity
defentity Frowny do
component DemoStats, %{
max_hp: 20,
hp: 20,
max_mp: 200,
mp: 200,
speed: 9
}
component Status
component Sprite, %{sprite_name: "enemy/frowny.png", full_image: true}
component ActorName, %{name: "Frowny"}
component NPCBrain, %{brain_name: "frowny"}
component ActiveBattle
component AnimationMod
component Targetable, %{actions_enabled: [:shock, :burn, :attack]}
component Enemy
end
| 17.555556 | 72 | 0.687764 |
9e8f542cce92ec9e5ca7bb1d24e818584e12dc2c | 406 | exs | Elixir | clients/service_management/test/test_helper.exs | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/service_management/test/test_helper.exs | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | null | null | null | clients/service_management/test/test_helper.exs | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | ExUnit.start()
defmodule GoogleApi.ServiceManagement.V1.TestHelper do
defmacro __using__(opts) do
quote do
use ExUnit.Case, unquote(opts)
import GoogleApi.ServiceManagement.V1.TestHelper
end
end
def for_scope(scopes) when is_list(scopes), do: for_scope(Enum.join(scopes, " "))
def for_scope(scope) do
{:ok, token} = Goth.Token.for_scope(scope)
token.token
end
end
| 21.368421 | 83 | 0.711823 |
9e8f76523f42a5a26d800b1e560ef120306e0282 | 1,200 | ex | Elixir | lib/console/multi_buys/multi_buy.ex | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 83 | 2018-05-31T14:49:10.000Z | 2022-03-27T16:49:49.000Z | lib/console/multi_buys/multi_buy.ex | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 267 | 2018-05-22T23:19:02.000Z | 2022-03-31T04:31:06.000Z | lib/console/multi_buys/multi_buy.ex | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 18 | 2018-11-20T05:15:54.000Z | 2022-03-28T08:20:13.000Z | defmodule Console.MultiBuys.MultiBuy do
use Ecto.Schema
import Ecto.Changeset
import Ecto.Query, warn: false
alias Console.Devices.Device
alias Console.Labels.Label
alias Console.Organizations.Organization
alias Console.Helpers
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "multi_buys" do
field :name, :string
field :value, :integer
belongs_to :organization, Organization
has_many :devices, Device
has_many :labels, Label
timestamps()
end
def changeset(multi_buy, attrs) do
attrs = Helpers.sanitize_attrs(attrs, ["name"])
multi_buy
|> cast(attrs, [:name, :value, :organization_id])
|> validate_required([:organization_id, :value])
|> validate_required(:name, message: "Name cannot be blank")
|> validate_length(:name, min: 3, message: "Name must be at least 3 characters")
|> validate_length(:name, max: 25, message: "Name cannot be longer than 25 characters")
|> validate_number(:value, greater_than: 0, less_than: 11)
|> unique_constraint(:name, name: :multi_buys_name_organization_id_index, message: "This name has already been used in this organization")
end
end
| 33.333333 | 142 | 0.723333 |
9e8f8513c4d425b5d47f39abc77603405d036bc3 | 164 | ex | Elixir | lib/magirator_app_channel_web/controllers/page_controller.ex | Devotu/magirator_app_channel | 75810edaef8f781981366702556da85460c07073 | [
"MIT"
] | null | null | null | lib/magirator_app_channel_web/controllers/page_controller.ex | Devotu/magirator_app_channel | 75810edaef8f781981366702556da85460c07073 | [
"MIT"
] | null | null | null | lib/magirator_app_channel_web/controllers/page_controller.ex | Devotu/magirator_app_channel | 75810edaef8f781981366702556da85460c07073 | [
"MIT"
] | null | null | null | defmodule MagiratorAppChannelWeb.PageController do
use MagiratorAppChannelWeb, :controller
def index(conn, _params) do
render conn, "index.html"
end
end
| 20.5 | 50 | 0.780488 |
9e8fbfd817ea5769ec775e4d5171b58cd3b5d0b2 | 12,893 | exs | Elixir | test/saxy/parser/element_test.exs | duffelhq/saxy | fb37f1d9ce919e6085a924c2483c515ee6cb997b | [
"MIT"
] | null | null | null | test/saxy/parser/element_test.exs | duffelhq/saxy | fb37f1d9ce919e6085a924c2483c515ee6cb997b | [
"MIT"
] | null | null | null | test/saxy/parser/element_test.exs | duffelhq/saxy | fb37f1d9ce919e6085a924c2483c515ee6cb997b | [
"MIT"
] | null | null | null | defmodule Saxy.Parser.ElementTest do
use ExUnit.Case, async: true
use ExUnitProperties
import Saxy.Parser.Element, only: [parse: 5]
alias Saxy.ParseError
alias Saxy.TestHandlers.StackHandler
test "parses element having no attributes" do
buffer = "<foo></foo>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
assert [{:start_element, {"foo", []}} | events] = events
assert [{:end_element, "foo"} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
buffer = "<fóo></fóo>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
assert [{:start_element, {"fóo", []}} | events] = events
assert [{:end_element, "fóo"} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
end
test "parses element with nested children" do
buffer = """
<item name="[日本語] Tom & Jerry" category='movie' >
<author name='William Hanna & Joseph Barbera' />
<!--Ignore me please I am just a comment-->
<?foo Hmm? Then probably ignore me too?>
<description><![CDATA[<strong>"Tom & Jerry" is a cool movie!</strong>]]></description>
<actors>
<actor>Tom</actor>
<actor>Jerry</actor>
</actors>
</item>
<!--a very bottom comment-->
<?foo what a instruction ?>
"""
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
item_attributes = [{"name", "[日本語] Tom & Jerry"}, {"category", "movie"}]
assert [{:start_element, {"item", ^item_attributes}} | events] = events
author_attributes = [{"name", "William Hanna & Joseph Barbera"}]
assert [{:start_element, {"author", ^author_attributes}} | events] = events
assert [{:end_element, "author"} | events] = events
assert [{:start_element, {"description", []}} | events] = events
assert [{:characters, "<strong>\"Tom & Jerry\" is a cool movie!</strong>"} | events] = events
assert [{:end_element, "description"} | events] = events
assert [{:start_element, {"actors", []}} | events] = events
assert [{:start_element, {"actor", []}} | events] = events
assert [{:characters, "Tom"} | events] = events
assert [{:end_element, "actor"} | events] = events
assert [{:start_element, {"actor", []}} | events] = events
assert [{:characters, "Jerry"} | events] = events
assert [{:end_element, "actor"} | events] = events
assert [{:end_element, "actors"} | events] = events
assert [{:end_element, "item"} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
end
test "parses empty element" do
buffer = "<foo />"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
assert [{:start_element, {"foo", []}} | events] = events
assert [{:end_element, "foo"} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
buffer = "<foo foo='FOO' bar='BAR'/>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
element = {"foo", [{"foo", "FOO"}, {"bar", "BAR"}]}
assert [{:start_element, ^element} | events] = events
assert [{:end_element, "foo"} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
buffer = "<foo foo='Tom & Jerry' bar='bar' />"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
element = {"foo", [{"foo", "Tom & Jerry"}, {"bar", "bar"}]}
assert [{:start_element, ^element} | events] = events
assert [{:end_element, "foo"} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
end
test "parses element content" do
buffer = "<foo>Lorem Ipsum Lorem Ipsum</foo>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
assert [{:start_element, {"foo", []}} | events] = events
assert [{:characters, "Lorem Ipsum Lorem Ipsum"} | events] = events
assert [{:end_element, "foo"} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
buffer = """
<foo>
Lorem Ipsum Lorem Ipsum
</foo>
"""
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
assert [{:start_element, {"foo", []}} | events] = events
assert [{:characters, "\nLorem Ipsum Lorem Ipsum\n"} | events] = events
assert [{:end_element, "foo"} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
end
test "parses comments" do
buffer = "<foo><!--IGNORE ME--></foo>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
assert [{:start_element, {"foo", []}} | events] = events
assert [{:end_element, "foo"} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
end
test "handles malformed comments" do
buffer = "<foo><!--IGNORE ME---></foo>"
assert {:error, error} = parse(buffer, false, buffer, 0, make_state())
assert ParseError.message(error) == "unexpected byte \"-\", expected token: :comment"
end
test "parses element references" do
buffer = "<foo>Tom & Jerry</foo>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
assert find_event(state, :characters, "Tom & Jerry")
buffer = "<foo>Tom & Jerry</foo>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
assert find_event(state, :characters, "Tom & Jerry")
buffer = "<foo>Tom & Jerry</foo>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
assert find_event(state, :characters, "Tom & Jerry")
end
test "handles malformed references in element" do
buffer = "<foo>Tom &#xt5; Jerry</foo>"
assert {:error, error} = parse(buffer, false, buffer, 0, make_state())
assert ParseError.message(error) == "unexpected byte \"t\", expected token: :char_ref"
buffer = "<foo>Tom &#t5; Jerry</foo>"
assert {:error, error} = parse(buffer, false, buffer, 0, make_state())
assert ParseError.message(error) == "unexpected byte \"t\", expected token: :char_ref"
buffer = "<foo>Tom &t5 Jerry</foo>"
assert {:error, error} = parse(buffer, false, buffer, 0, make_state())
assert ParseError.message(error) == "unexpected byte \" \", expected token: :entity_ref"
end
test "parses CDATA" do
buffer = "<foo><![CDATA[John Cena <foo></foo> &]]></foo>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
assert find_events(state, :characters) == [{:characters, "John Cena <foo></foo> &"}]
end
test "handles malformed CDATA" do
buffer = "<foo><![CDATA[John Cena </foo>"
assert {:error, error} = parse(buffer, false, buffer, 0, make_state())
assert ParseError.message(error) == "unexpected end of input, expected token: :\"]]\""
end
test "parses processing instruction" do
buffer = "<foo><?hello the instruction?></foo>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
assert length(state.user_state) == 3
end
test "handles malformed processing instruction" do
buffer = "<foo><?hello the instruction"
assert {:error, error} = parse(buffer, false, buffer, 0, make_state())
assert ParseError.message(error) == "unexpected end of input, expected token: :processing_instruction"
end
test "parses element attributes" do
buffer = "<foo abc='123' def=\"456\" g:hi='789' />"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
tag = {"foo", [{"abc", "123"}, {"def", "456"}, {"g:hi", "789"}]}
assert find_event(state, :start_element, tag)
assert find_event(state, :end_element, "foo")
buffer = ~s(<foo abc = "ABC" />)
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
tag = {"foo", [{"abc", "ABC"}]}
assert find_event(state, :start_element, tag)
assert find_event(state, :end_element, "foo")
buffer = ~s(<foo val="Tom & Jerry" />)
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
assert find_event(state, :start_element, {"foo", [{"val", "Tom & Jerry"}]})
assert find_event(state, :end_element, "foo")
buffer = ~s(<foo val="Tom & Jerry" />)
assert {:error, error} = parse(buffer, false, buffer, 0, make_state())
assert ParseError.message(error) == "unexpected byte \" \", expected token: :char_ref"
buffer = ~s(<foo val="Tom & Jerry" />)
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
assert find_event(state, :start_element, {"foo", [{"val", "Tom & Jerry"}]})
assert find_event(state, :end_element, "foo")
buffer = ~s(<foo val="Tom & Jerry" />)
assert {:error, error} = parse(buffer, false, buffer, 0, make_state())
assert ParseError.message(error) == "unexpected byte \" \", expected token: :char_ref"
buffer = ~s(<foo val="Tom & Jerry" />)
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
assert find_event(state, :start_element, {"foo", [{"val", "Tom & Jerry"}]})
assert find_event(state, :end_element, "foo")
end
@tag :property
property "element name" do
check all name <- name() do
buffer = "<#{name}></#{name}>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
assert [{:start_element, {^name, []}} | events] = events
assert [{:end_element, ^name} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
end
check all name <- name() do
buffer = "<#{name}/>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
assert [{:start_element, {^name, []}} | events] = events
assert [{:end_element, ^name} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
end
end
property "attribute name" do
check all attribute_name <- name() do
buffer = "<foo #{attribute_name}='bar'></foo>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
element = {"foo", [{attribute_name, "bar"}]}
assert [{:start_element, ^element} | events] = events
assert [{:end_element, "foo"} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
end
end
property "attribute value" do
reference_generator =
gen all name <- name() do
"&" <> name <> ";"
end
check all attribute_value_chars <- string(:alphanumeric),
reference <- reference_generator do
attribute_value =
[attribute_value_chars, reference]
|> Enum.shuffle()
|> IO.iodata_to_binary()
buffer = "<foo foo='#{attribute_value}'></foo>"
assert {:ok, state} = parse(buffer, false, buffer, 0, make_state())
events = Enum.reverse(state.user_state)
element = {"foo", [{"foo", attribute_value}]}
assert [{:start_element, ^element} | events] = events
assert [{:end_element, "foo"} | events] = events
assert [{:end_document, {}} | events] = events
assert events == []
end
end
defp make_state(state \\ []) do
%Saxy.State{
prolog: nil,
handler: StackHandler,
user_state: state,
expand_entity: :keep
}
end
defp find_events(state, event_type) do
Enum.filter(state.user_state, fn {type, _data} -> type == event_type end)
end
defp find_event(state, event_type, event_data) do
Enum.find(state.user_state, fn {type, data} ->
type == event_type && data == event_data
end)
end
defp name() do
name_start_char_ranges = [
?:,
?A..?Z,
?a..?z,
?_,
0xC0..0xD6,
0xD8..0xF6,
0xF8..0x2FF,
0x370..0x200D,
0x2070..0x218F,
0x2C00..0x2FEF,
0x3001..0xD7FF,
0xF900..0xFDCF,
0xFDF0..0xFFFD,
0x10000..0xEFFFF
]
name_char_ranges =
name_start_char_ranges ++
[
?0..?9,
?-,
?.,
0xB7,
0x300..0x036F,
0x203F..0x2040
]
gen all start_char <- string(name_start_char_ranges, min_length: 1, max_length: 4),
chars <- string(name_char_ranges) do
start_char <> chars
end
end
end
| 32.394472 | 106 | 0.604437 |
9e901d6ae0d9786216b71718ca523ceec204eac8 | 835 | exs | Elixir | config/test.exs | shanesveller/ex_venture | 68507da11442a9e0423073fcd305e9021f649ca1 | [
"MIT"
] | null | null | null | config/test.exs | shanesveller/ex_venture | 68507da11442a9e0423073fcd305e9021f649ca1 | [
"MIT"
] | null | null | null | config/test.exs | shanesveller/ex_venture | 68507da11442a9e0423073fcd305e9021f649ca1 | [
"MIT"
] | null | null | null | use Mix.Config
config :logger, level: :error
config :ex_venture, Data.Repo,
adapter: Ecto.Adapters.Postgres,
database: "ex_venture_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
config :ex_venture, :networking,
host: "localhost",
port: 5555,
server: false,
socket_module: Test.Networking.Socket
config :ex_venture, :game,
world: false,
npc: Test.Game.NPC,
zone: Test.Game.Zone,
room: Test.Game.Room,
environment: Test.Game.Environment,
shop: Test.Game.Shop,
zone: Test.Game.Zone,
rand: Test.ChanceSuccess,
report_users: false,
continue_wait: 10,
random_effect_range: 0..0
config :ex_venture, :npc, reaction_time_ms: 0
config :bcrypt_elixir, :log_rounds, 4
config :ex_venture, :mailer, from: "[email protected]"
config :ex_venture, ExVenture.Mailer, adapter: Bamboo.TestAdapter
| 23.194444 | 65 | 0.735329 |
9e901fa75296e30bad907f52de6708233844b1b5 | 106 | ex | Elixir | test/support/repo.ex | basmoura/cpf | a3c37daa7598358b7e15a5ce4b342ed551df79d3 | [
"MIT"
] | 34 | 2019-04-14T22:57:21.000Z | 2022-01-06T01:26:25.000Z | test/support/repo.ex | basmoura/cpf | a3c37daa7598358b7e15a5ce4b342ed551df79d3 | [
"MIT"
] | 4 | 2019-06-09T15:48:53.000Z | 2022-01-29T13:13:57.000Z | test/support/repo.ex | basmoura/cpf | a3c37daa7598358b7e15a5ce4b342ed551df79d3 | [
"MIT"
] | 10 | 2019-04-16T04:26:56.000Z | 2020-10-08T18:00:47.000Z | defmodule CPF.Support.Repo do
use Ecto.Repo,
otp_app: :cpf,
adapter: Ecto.Adapters.Postgres
end
| 17.666667 | 35 | 0.716981 |
9e90424ab40f940ab2a4bdfb12c51a5fd334bba3 | 5,926 | exs | Elixir | test/sanbase_web/graphql/user/apikey_resolver_test.exs | santiment/sanbase2 | 9ef6e2dd1e377744a6d2bba570ea6bd477a1db31 | [
"MIT"
] | 81 | 2017-11-20T01:20:22.000Z | 2022-03-05T12:04:25.000Z | test/sanbase_web/graphql/user/apikey_resolver_test.exs | santiment/sanbase2 | 9ef6e2dd1e377744a6d2bba570ea6bd477a1db31 | [
"MIT"
] | 359 | 2017-10-15T14:40:53.000Z | 2022-01-25T13:34:20.000Z | test/sanbase_web/graphql/user/apikey_resolver_test.exs | santiment/sanbase2 | 9ef6e2dd1e377744a6d2bba570ea6bd477a1db31 | [
"MIT"
] | 16 | 2017-11-19T13:57:40.000Z | 2022-02-07T08:13:02.000Z | defmodule SanbaseWeb.Graphql.ApikeyResolverTest do
use SanbaseWeb.ConnCase, async: false
import SanbaseWeb.Graphql.TestHelpers
import Sanbase.Factory
alias Sanbase.Repo
alias Sanbase.Accounts.{UserApikeyToken, Hmac}
@moduletag capture_log: true
setup do
user = insert(:user)
conn = setup_jwt_auth(build_conn(), user)
%{user: user2} = insert(:subscription_premium, user: insert(:user))
conn2 = setup_jwt_auth(build_conn(), user2)
%{conn: conn, conn2: conn2, user: user, user2: user2}
end
test "can get apikey list with jwt auth", %{conn: conn} do
_ = generate_apikey(conn)
apikeys =
get_apikeys(conn)
|> json_response(200)
|> get_in(["data", "currentUser", "apikeys"])
assert is_list(apikeys)
assert length(apikeys) > 0
end
test "cannot get apikey list with apikey auth", %{user: user} do
{:ok, apikey} = Sanbase.Accounts.Apikey.generate_apikey(user)
apikey_conn = setup_apikey_auth(build_conn(), apikey)
error =
get_apikeys(apikey_conn)
|> json_response(200)
|> get_in(["errors"])
|> hd()
assert error["message"] =~ "Only JWT authenticated users can access their apikeys"
end
test "generate a valid apikey", %{conn: conn} do
apikeys =
generate_apikey(conn)
|> json_response(200)
|> extract_api_key_list()
# A single apikey should be generated
assert Enum.count(apikeys) == 1
apikey = List.first(apikeys)
# The generated apikey is valid
assert apikey_valid?(apikey)
end
test "revoke an apikey", %{conn: conn} do
# Generate and check that a valid single apikey is present
apikeys =
generate_apikey(conn)
|> json_response(200)
|> extract_api_key_list()
assert Enum.count(apikeys) == 1
apikey = List.first(apikeys)
assert apikey_valid?(apikey)
# Revoke and check that the apikey is now not present and not valid
apikeys2 =
revoke_apikey(conn, apikey)
|> json_response(200)
|> extract_api_key_list()
# There are no more apikeys
assert apikeys2 == []
# The previously valid apikey is now invalid
refute apikey_valid?(apikey)
end
test "other users cannot revoke my apikey", %{conn: conn, conn2: conn2} do
# Get apikey for user1
apikey =
generate_apikey(conn)
|> json_response(200)
|> extract_api_key_list()
|> List.first()
# Check that user2 cannot revoke it
result2 =
revoke_apikey(conn2, apikey)
|> json_response(200)
err_struct = result2["errors"] |> List.first()
assert err_struct["message"] =~ "Provided apikey is malformed or not valid"
end
test "can have more than one apikey", %{conn: conn} do
generate_apikey(conn)
generate_apikey(conn)
[apikey1, apikey2, apikey3] =
generate_apikey(conn)
|> json_response(200)
|> extract_api_key_list()
assert apikey_valid?(apikey1)
assert apikey_valid?(apikey2)
assert apikey_valid?(apikey3)
end
test "revoke apikey twice", %{conn: conn} do
[apikey] =
generate_apikey(conn)
|> json_response(200)
|> extract_api_key_list()
revoke_apikey(conn, apikey)
revoke_apikey(conn, apikey)
result =
revoke_apikey(conn, apikey)
|> json_response(200)
err_struct = result["errors"] |> List.first()
assert err_struct["message"] =~ "Provided apikey is malformed or not valid"
end
test "user dropped while the connection is up", %{conn: conn, user: user} do
[apikey] =
generate_apikey(conn)
|> json_response(200)
|> extract_api_key_list()
Repo.delete(user)
result = revoke_apikey(conn, apikey)
{:ok, msg} = result.resp_body |> Jason.decode()
assert result.status == 400
assert msg["errors"]["details"] == "Bad authorization header: Invalid JSON Web Token (JWT)"
end
test "on delete user delete all user's tokens", %{conn: conn, user: user} do
generate_apikey(conn)
[apikey1, apikey2] =
generate_apikey(conn)
|> json_response(200)
|> extract_api_key_list()
Repo.delete(user)
{:ok, {token1, _apikey}} = Hmac.split_apikey(apikey1)
{:ok, {token2, _apikey}} = Hmac.split_apikey(apikey1)
refute apikey_valid?(apikey1)
refute apikey_valid?(apikey2)
refute UserApikeyToken.has_token?(token1)
refute UserApikeyToken.has_token?(token2)
end
test "cannot revoke malformed apikey", %{conn: conn} do
[apikey] =
generate_apikey(conn)
|> json_response(200)
|> extract_api_key_list()
apikey = apikey <> "s"
result =
revoke_apikey(conn, apikey)
|> json_response(200)
err_struct = result["errors"] |> List.first()
assert err_struct["message"] =~ "Provided apikey is malformed or not valid"
end
# Private functions
defp apikey_valid?(apikey) do
{:ok, {token, _apikey}} = Hmac.split_apikey(apikey)
Hmac.apikey_valid?(token, apikey) && UserApikeyToken.has_token?(token)
end
defp generate_apikey(conn) do
query = """
mutation {
generateApikey {
apikeys
}
}
"""
conn |> post("/graphql", mutation_skeleton(query))
end
defp extract_api_key_list(%{
"data" => %{
"generateApikey" => %{
"apikeys" => apikeys
}
}
}) do
apikeys
end
defp extract_api_key_list(%{
"data" => %{
"revokeApikey" => %{
"apikeys" => apikeys
}
}
}) do
apikeys
end
defp revoke_apikey(conn, apikey) do
query = """
mutation {
revokeApikey(apikey: "#{apikey}") {
apikeys
}
}
"""
conn |> post("/graphql", mutation_skeleton(query))
end
defp get_apikeys(conn) do
query = """
{
currentUser{
apikeys
}
}
"""
conn |> post("/graphql", query_skeleton(query))
end
end
| 24.089431 | 95 | 0.629936 |
9e905316b49a3fb3060fbfb73743d5526491f711 | 2,954 | ex | Elixir | lib/git_pair_ex/command.ex | PZiaugra/git_pair_ex | cebfe9b7b26519e8f7664ecba48aa86b8f41f30a | [
"MIT"
] | null | null | null | lib/git_pair_ex/command.ex | PZiaugra/git_pair_ex | cebfe9b7b26519e8f7664ecba48aa86b8f41f30a | [
"MIT"
] | 2 | 2022-02-22T20:24:09.000Z | 2022-02-22T20:24:56.000Z | lib/git_pair_ex/command.ex | PZiaugra/git_pair_ex | cebfe9b7b26519e8f7664ecba48aa86b8f41f30a | [
"MIT"
] | 1 | 2022-02-22T20:26:23.000Z | 2022-02-22T20:26:23.000Z | defmodule GitPairEx.Command do
def show_authors(opts \\ ["--local"]) do
{config_list, 0} = System.cmd("git", ["config", "--list"] ++ opts)
authors =
config_list
|> String.split("\n")
|> Enum.filter(&Regex.match?(~r/^git\-pair\.authors/, &1))
|> Enum.map(fn line ->
Regex.run(author_regex(), line, capture: :all_but_first) |> Enum.join(" - ")
end)
|> Enum.join("\n")
"""
Authors
========
#{authors}
"""
end
defp author_regex, do: ~r/^git-pair.authors.([^=]+)=(.+)$/
def add(abbr, email, opts \\ ["--local"]) do
{_, 0} = System.cmd("git", ["config"] ++ opts ++ ["git-pair.authors.#{abbr}", email])
abbr <> " - " <> email <> " added as a git-pair author."
end
def find(abbr, opts \\ ["--local"]) do
case System.cmd("git", ["config"] ++ opts ++ ["git-pair.authors.#{abbr}"]) do
{author, 0} ->
author |> String.trim()
{_, 1} ->
""
end
end
def remove(abbr, opts \\ ["--local"]) do
{_, _} = System.cmd("git", ["config"] ++ opts ++ ["--unset", "git-pair.authors.#{abbr}"])
"'#{abbr}' removed."
end
def status(opts \\ ["--local"]) do
case System.cmd("git", ["config"] ++ opts ++ ["git-pair.pair"]) do
{status, 0} ->
status
|> String.trim()
|> Kernel.<>(" are pairing.")
{_, 1} ->
"No paired author is set. Run 'git-pair ab cd' to set the pair."
end
end
def base(abbrs, opts \\ ["--local"]) do
case authors_exist(abbrs, opts) do
[[name_1, email_1], [name_2, _email_2]] ->
System.cmd(
"git",
["config"] ++ opts ++ ["git-pair.pair", "#{name_1} + #{name_2} <#{email_1}>"]
)
"#{name_1} and #{name_2} are pairing."
[[name, _], nil] ->
"Only #{name} found. Use `git-pair add` to add missing author."
[nil, [name, _]] ->
"Only #{name} found. Use `git-pair add` to add missing author."
[_, _] ->
"Neither author found. Use `git-pair add` to add missing authors."
end
end
defp authors_exist(abbrs, opts) do
abbrs
|> Enum.map(&find(&1, opts))
|> Enum.map(&Regex.run(~r/(?:"?([^"]*)"?\s)?(?:<?(.+@[^>]+)>?)/, &1, capture: :all_but_first))
end
def clear(opts \\ ["--local"]) do
case System.cmd("git", ["config"] ++ opts ++ ["--unset", "git-pair.pair"]) do
{_, 0} ->
"Pair cleared."
_ ->
nil
end
end
def get_pair(opts \\ ["--local"]) do
case System.cmd("git", ["config"] ++ opts ++ ["git-pair.pair"]) do
{author, 0} ->
author |> String.trim()
{_, 1} ->
"No pair set. Try `git pair ab cd` to set a pair."
end
end
def commit(args, opts \\ ["--local"]) do
command_args = ["commit", "--author", get_pair(opts)] ++ args
case System.cmd("git", command_args) do
{output, 0} ->
output
{other, _} ->
other
end
end
end
| 25.465517 | 98 | 0.49763 |
9e906fdef17da31ae437084e708d1e5f4be48248 | 1,656 | exs | Elixir | rel/config/prod.exs | HenkPoley/ellie | 045212b56142341fc95b79659c3ca218b0d5d282 | [
"BSD-3-Clause"
] | 377 | 2018-04-05T03:36:00.000Z | 2022-03-30T19:12:44.000Z | rel/config/prod.exs | HenkPoley/ellie | 045212b56142341fc95b79659c3ca218b0d5d282 | [
"BSD-3-Clause"
] | 91 | 2018-05-24T21:56:06.000Z | 2022-02-26T03:54:04.000Z | rel/config/prod.exs | HenkPoley/ellie | 045212b56142341fc95b79659c3ca218b0d5d282 | [
"BSD-3-Clause"
] | 34 | 2018-05-29T03:54:35.000Z | 2022-01-13T07:12:46.000Z | use Mix.Config
app = System.get_env("APPLICATION_NAME")
env = System.get_env("ENVIRONMENT_NAME")
region = System.get_env("AWS_REGION")
aws = System.find_executable("aws")
cond do
is_nil(app) ->
raise "APPLICATION_NAME is unset!"
is_nil(env) ->
raise "ENVIRONMENT_NAME is unset!"
is_nil(aws) ->
raise "Unable to find `aws` executable!"
:else ->
:ok
end
# Pull runtime secrets from Parameter Store
secret_root = "/#{app}-#{env}/"
cmd_options = [
"ssm",
"get-parameters-by-path",
"--region=#{region}",
"--path=#{secret_root}",
"--with-decryption",
"--query=Parameters[*].{Name:Name,Value:Value}"
]
secrets =
case System.cmd(aws, cmd_options) do
{json, 0} ->
json
|> Poison.Parser.parse!()
|> Enum.reduce(Map.new(), fn %{"Name" => k, "Value" => v}, acc ->
Map.put(acc, String.replace_leading(k, secret_root, ""), v)
end)
{output, status} ->
raise "Unable to get secrets, command exited with status #{status}:\n#{output}"
end
config :porcelain, :goon_driver_path, "#{:code.priv_dir(:ellie)}/bin/goon"
config :porcelain, driver: Porcelain.Driver.Goon
config :ellie, EllieWeb.Endpoint,
http: [port: 4000],
url: [host: System.get_env("DOMAIN_NAME"), port: 443, scheme: "https"],
static_url: [host: System.get_env("CDN_DOMAIN_NAME"), port: 443, scheme: "https"],
check_origin: ["https://" <> System.get_env("DOMAIN_NAME")],
root: ".",
secret_key_base: Map.get(secrets, "SECRET_KEY_BASE")
config :ellie, Ellie.Repo, url: Map.get(secrets, "DATABASE_URL")
config :sentry,
dsn: Map.get(secrets, "SENTRY_DSN"),
api_key: Map.get(secrets, "SENTRY_API_KEY")
| 26.285714 | 85 | 0.655193 |
9e90936da8bf0feb7f22a0db74a9f50b09348a86 | 202 | ex | Elixir | lib/apq/strategy.ex | fuelen/apq | 3cf1d5bdf58d690711ed33d506b92096939da9ae | [
"MIT"
] | 41 | 2018-09-15T13:02:28.000Z | 2022-01-11T23:17:11.000Z | lib/apq/strategy.ex | fuelen/apq | 3cf1d5bdf58d690711ed33d506b92096939da9ae | [
"MIT"
] | 41 | 2018-09-15T13:17:56.000Z | 2022-03-24T04:03:50.000Z | lib/apq/strategy.ex | fuelen/apq | 3cf1d5bdf58d690711ed33d506b92096939da9ae | [
"MIT"
] | 4 | 2018-09-25T09:59:30.000Z | 2021-11-15T10:08:37.000Z | defmodule Apq.Strategy do
@moduledoc """
Behaviour to customize how Apq interacts with Absinthe pipeline
"""
@callback pipeline(Absinthe.Pipeline.t(), Keyword.t()) :: Absinthe.Pipeline.t()
end
| 25.25 | 81 | 0.727723 |
9e909639aefdacf2863d3395ed18a4f010e91acd | 244 | exs | Elixir | test/exfile/hasher/random_test.exs | sreecodeslayer/exfile | c88288563d688fb47a6fcae190dbe1b8eb64bf9b | [
"MIT"
] | 100 | 2015-12-25T12:38:41.000Z | 2021-12-31T11:41:20.000Z | test/exfile/hasher/random_test.exs | sreecodeslayer/exfile | c88288563d688fb47a6fcae190dbe1b8eb64bf9b | [
"MIT"
] | 62 | 2015-12-26T01:43:54.000Z | 2019-09-15T16:16:35.000Z | test/exfile/hasher/random_test.exs | sreecodeslayer/exfile | c88288563d688fb47a6fcae190dbe1b8eb64bf9b | [
"MIT"
] | 22 | 2016-04-19T11:54:38.000Z | 2021-09-29T14:48:46.000Z | defmodule Exfile.Hasher.RandomTest do
use ExUnit.Case, async: true
@hasher Exfile.Hasher.Random
test "returns a random ID" do
assert String.length(@hasher.hash(nil)) == 60
refute @hasher.hash(nil) == @hasher.hash(nil)
end
end
| 22.181818 | 49 | 0.704918 |
9e90a4dd557fc758e9f667dff99b47f2d132010a | 1,674 | ex | Elixir | clients/analytics/lib/google_api/analytics/v3/model/webproperty_parent_link.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/analytics/lib/google_api/analytics/v3/model/webproperty_parent_link.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/analytics/lib/google_api/analytics/v3/model/webproperty_parent_link.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.Analytics.V3.Model.WebpropertyParentLink do
@moduledoc """
Parent link for this web property. Points to the account to which this web property belongs.
## Attributes
* `href` (*type:* `String.t`, *default:* `nil`) - Link to the account for this web property.
* `type` (*type:* `String.t`, *default:* `analytics#account`) - Type of the parent link. Its value is "analytics#account".
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:href => String.t(),
:type => String.t()
}
field(:href)
field(:type)
end
defimpl Poison.Decoder, for: GoogleApi.Analytics.V3.Model.WebpropertyParentLink do
def decode(value, options) do
GoogleApi.Analytics.V3.Model.WebpropertyParentLink.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Analytics.V3.Model.WebpropertyParentLink do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.48 | 126 | 0.726404 |
9e90ad57d55e825722a32b76b8ef026a293e944f | 373 | ex | Elixir | distributor/lib/distributor/spec_utils.ex | fknop/distributor | 1b1a4910ec0887b8c10c636e55f15921d67bfa86 | [
"MIT"
] | 1 | 2019-12-27T10:21:13.000Z | 2019-12-27T10:21:13.000Z | distributor/lib/distributor/spec_utils.ex | fknop/distributor | 1b1a4910ec0887b8c10c636e55f15921d67bfa86 | [
"MIT"
] | 209 | 2019-12-25T17:16:14.000Z | 2022-03-25T23:13:05.000Z | distributor/lib/distributor/spec_utils.ex | fknop/distributor | 1b1a4910ec0887b8c10c636e55f15921d67bfa86 | [
"MIT"
] | null | null | null | defmodule Distributor.SpecUtils do
def compare_files(a, b) when length(a) != length(b), do: false
def compare_files([], []), do: true
def compare_files([H1 | T1], [H2 | T2]) when H1 == H2, do: compare_files(T1, T2)
def compare_files(_, _), do: false
def hash_files(spec_files) do
:crypto.hash(:sha3_256, spec_files) |> Base.encode16(case: :lower)
end
end
| 31.083333 | 82 | 0.675603 |
9e90c5de04adc1a2a00df46407dcd3fef9cf5e88 | 3,256 | ex | Elixir | clients/cloud_billing/lib/google_api/cloud_billing/v1/model/pricing_info.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/cloud_billing/lib/google_api/cloud_billing/v1/model/pricing_info.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/cloud_billing/lib/google_api/cloud_billing/v1/model/pricing_info.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.CloudBilling.V1.Model.PricingInfo do
@moduledoc """
Represents the pricing information for a SKU at a single point of time.
## Attributes
* `aggregationInfo` (*type:* `GoogleApi.CloudBilling.V1.Model.AggregationInfo.t`, *default:* `nil`) - Aggregation Info. This can be left unspecified if the pricing expression
doesn't require aggregation.
* `currencyConversionRate` (*type:* `float()`, *default:* `nil`) - Conversion rate used for currency conversion, from USD to the currency
specified in the request. This includes any surcharge collected for billing
in non USD currency. If a currency is not specified in the request this
defaults to 1.0.
Example: USD * currency_conversion_rate = JPY
* `effectiveTime` (*type:* `DateTime.t`, *default:* `nil`) - The timestamp from which this pricing was effective within the requested
time range. This is guaranteed to be greater than or equal to the
start_time field in the request and less than the end_time field in the
request. If a time range was not specified in the request this field will
be equivalent to a time within the last 12 hours, indicating the latest
pricing info.
* `pricingExpression` (*type:* `GoogleApi.CloudBilling.V1.Model.PricingExpression.t`, *default:* `nil`) - Expresses the pricing formula. See `PricingExpression` for an example.
* `summary` (*type:* `String.t`, *default:* `nil`) - An optional human readable summary of the pricing information, has a
maximum length of 256 characters.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:aggregationInfo => GoogleApi.CloudBilling.V1.Model.AggregationInfo.t(),
:currencyConversionRate => float(),
:effectiveTime => DateTime.t(),
:pricingExpression => GoogleApi.CloudBilling.V1.Model.PricingExpression.t(),
:summary => String.t()
}
field(:aggregationInfo, as: GoogleApi.CloudBilling.V1.Model.AggregationInfo)
field(:currencyConversionRate)
field(:effectiveTime, as: DateTime)
field(:pricingExpression, as: GoogleApi.CloudBilling.V1.Model.PricingExpression)
field(:summary)
end
defimpl Poison.Decoder, for: GoogleApi.CloudBilling.V1.Model.PricingInfo do
def decode(value, options) do
GoogleApi.CloudBilling.V1.Model.PricingInfo.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudBilling.V1.Model.PricingInfo do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 46.514286 | 180 | 0.733415 |
9e90ce00b5400ebd04f4af56010c90753569ec23 | 462 | exs | Elixir | config/test.exs | jeffutter/ex_rogue | 57207966764516db95a8af7625ba6e3cdc12651d | [
"MIT"
] | null | null | null | config/test.exs | jeffutter/ex_rogue | 57207966764516db95a8af7625ba6e3cdc12651d | [
"MIT"
] | 2 | 2021-03-10T11:32:10.000Z | 2021-05-11T07:17:36.000Z | config/test.exs | jeffutter/ex_rogue | 57207966764516db95a8af7625ba6e3cdc12651d | [
"MIT"
] | null | null | null | use Mix.Config
# Configure your database
config :ex_rogue, ExRogue.Repo,
username: "postgres",
password: "postgres",
database: "ex_rogue_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :ex_rogue, ExRogueWeb.Endpoint,
http: [port: 4002],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
| 24.315789 | 56 | 0.733766 |
9e90f9e97b94622dd2e94bb881bf9af56f208904 | 470 | ex | Elixir | lib/huffman/encoder.ex | Tmw/huffman | 837a6d4e13f88d7a5e23998edff4d172523c33f3 | [
"MIT"
] | 5 | 2020-09-06T18:29:51.000Z | 2021-03-13T13:38:34.000Z | lib/huffman/encoder.ex | Tmw/huffman | 837a6d4e13f88d7a5e23998edff4d172523c33f3 | [
"MIT"
] | null | null | null | lib/huffman/encoder.ex | Tmw/huffman | 837a6d4e13f88d7a5e23998edff4d172523c33f3 | [
"MIT"
] | 1 | 2020-09-06T18:29:54.000Z | 2020-09-06T18:29:54.000Z | defmodule Huffman.Encoder do
alias Huffman.{Codebook, Tree, FrequencyMap, Packer, Queue}
@spec encode(String.t()) :: {:ok, Packer.packed_data()}
def encode(text) do
tree =
text
|> FrequencyMap.create()
|> Queue.from_map()
|> Tree.build()
encoded =
tree
|> Codebook.from_tree()
|> Codebook.encode(text)
packed =
tree
|> Tree.serialize()
|> Packer.pack(encoded)
{:ok, packed}
end
end
| 18.8 | 61 | 0.576596 |
9e90fc91d55f2f84c1e818c97ed424a0deb5e842 | 1,394 | ex | Elixir | lib/handler/freifunka_greeting_handler.ex | geistesk/ircbot | 1501b27d310169839a907f228cd80b572e1deb3f | [
"Zlib"
] | null | null | null | lib/handler/freifunka_greeting_handler.ex | geistesk/ircbot | 1501b27d310169839a907f228cd80b572e1deb3f | [
"Zlib"
] | null | null | null | lib/handler/freifunka_greeting_handler.ex | geistesk/ircbot | 1501b27d310169839a907f228cd80b572e1deb3f | [
"Zlib"
] | null | null | null | require Logger
alias ExIrc.SenderInfo
defmodule FreifunkaGreetingHandler do
@moduledoc """
This is an event handler which is greeting Users from the hsmr-webirc
(based on hostname) specially.
"""
def start_link(client) do
GenServer.start_link(__MODULE__, [client])
end
def init([client]) do
ExIrc.Client.add_handler client, self()
{:ok, client}
end
def handle_info({:joined, channel, %SenderInfo{nick: nick, host: host, user: user}}, client) do
# Check if a new joining user seems to use the webchat
ff_host = Application.get_env(:ircbot, :freifunkaHost)
ff_user = Application.get_env(:ircbot, :freifunkaUser)
ff_ignr = Application.get_env(:ircbot, :freifunkaNameIgnore)
cond do
Regex.match?(ff_ignr, nick) ->
Logger.info(
"[FreifunkaGreetingHandler] #{nick} matches ignore-RegEx and won't be greeted.")
{:noreply, client}
ff_host == host and ff_user == user ->
Logger.info(
"[FreifunkaGreetingHandler] #{nick} joined from the webchat.")
["Hej #{nick}!" | Application.get_env(:ircbot, :freifunkaGreet)]
|> Enum.each(&ExIrc.Client.msg(client, :privmsg, channel, &1))
{:noreply, client}
true ->
{:noreply, client}
end
end
# Catch-all for messages you don't care about
def handle_info(_msg, client) do
{:noreply, client}
end
end
| 29.041667 | 97 | 0.662123 |
9e90ffcdb0c6239f4ddb9e23d62d96db6acd685d | 1,568 | exs | Elixir | mix.exs | angordeyev/grpc | 3547eccf5968a2a9d31a6dc3eea0a445269c67c0 | [
"Apache-2.0"
] | null | null | null | mix.exs | angordeyev/grpc | 3547eccf5968a2a9d31a6dc3eea0a445269c67c0 | [
"Apache-2.0"
] | null | null | null | mix.exs | angordeyev/grpc | 3547eccf5968a2a9d31a6dc3eea0a445269c67c0 | [
"Apache-2.0"
] | null | null | null | defmodule GRPC.Mixfile do
use Mix.Project
@version "0.5.0-beta.1"
def project do
[
app: :grpc,
version: @version,
elixir: "~> 1.5",
elixirc_paths: elixirc_paths(Mix.env()),
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
deps: deps(),
package: package(),
description: "The Elixir implementation of gRPC",
docs: [
extras: ["README.md"],
main: "readme",
source_ref: "v#{@version}",
source_url: "https://github.com/elixir-grpc/grpc"
],
dialyzer: [
plt_add_apps: [:mix, :iex]
],
xref: [exclude: [IEx]]
]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[extra_applications: [:logger]]
end
defp deps do
[
{:protobuf, "~> 0.5"},
{:cowboy, "~> 2.9"},
{:gun, "~> 2.0.0-rc.2"},
# 2.9.0 fixes some important bugs, so it's better to use ~> 2.9.0
# {:cowlib, "~> 2.9.0", override: true},
{:ex_doc, "~> 0.23", only: :dev},
{:inch_ex, "~> 2.0", only: [:dev, :test]},
{:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false}
]
end
defp package do
%{
maintainers: ["Bing Han"],
licenses: ["Apache 2"],
links: %{"GitHub" => "https://github.com/elixir-grpc/grpc"},
files: ~w(mix.exs README.md lib src config LICENSE .formatter.exs)
}
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
end
| 25.290323 | 72 | 0.543367 |
9e91286c3e753641d332cb581ad3545236de1dd3 | 297 | ex | Elixir | lib/swoosh.ex | augnustin/swoosh | f163dab67cadbf68b4faaf5c8cf17fe4548294d7 | [
"MIT"
] | null | null | null | lib/swoosh.ex | augnustin/swoosh | f163dab67cadbf68b4faaf5c8cf17fe4548294d7 | [
"MIT"
] | null | null | null | lib/swoosh.ex | augnustin/swoosh | f163dab67cadbf68b4faaf5c8cf17fe4548294d7 | [
"MIT"
] | null | null | null | defmodule Swoosh do
@moduledoc File.read!("README.md") |> String.replace("# Swoosh\n\n", "", global: false)
@version "0.23.4"
@doc false
def version, do: @version
@json_library Application.get_env(:swoosh, :json_library, Jason)
@doc false
def json_library, do: @json_library
end
| 21.214286 | 89 | 0.690236 |
9e9143ed25d2bd4ae0f7622f95d6409c1e22dc97 | 407 | exs | Elixir | test/pummpcomm/history/exercise_marker_test.exs | infinity-aps/pummpcomm | 7380585ecd110ab1c19d2aea3880e51e3f433050 | [
"MIT"
] | 15 | 2017-08-31T00:58:47.000Z | 2020-01-12T03:53:13.000Z | test/pummpcomm/history/exercise_marker_test.exs | vladhj38/pummpcomm | 7380585ecd110ab1c19d2aea3880e51e3f433050 | [
"MIT"
] | 1 | 2017-09-15T02:09:31.000Z | 2017-09-15T02:09:31.000Z | test/pummpcomm/history/exercise_marker_test.exs | vladhj38/pummpcomm | 7380585ecd110ab1c19d2aea3880e51e3f433050 | [
"MIT"
] | 3 | 2017-09-10T17:24:59.000Z | 2019-09-10T19:41:49.000Z | defmodule Pummpcomm.History.ExerciseMarkerTest do
use ExUnit.Case
# TODO capture this in real life
test "Exercise Marker" do
{:ok, history_page} = Base.decode16("4100722713040F00")
decoded_events = Pummpcomm.History.decode_records(history_page, %{})
assert {:exercise_marker, %{timestamp: ~N[2015-04-04 19:39:50], raw: ^history_page}} =
Enum.at(decoded_events, 0)
end
end
| 31.307692 | 90 | 0.707617 |
9e91473acb2fa966ae8cd951ad98309935bfd029 | 1,129 | ex | Elixir | test/support/channel_case.ex | JeffyMesquita/elixirHeat | 3ec3c59021e90058f00c2eb288a5e6c286e96342 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | JeffyMesquita/elixirHeat | 3ec3c59021e90058f00c2eb288a5e6c286e96342 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | JeffyMesquita/elixirHeat | 3ec3c59021e90058f00c2eb288a5e6c286e96342 | [
"MIT"
] | null | null | null | defmodule ElixirHeatWeb.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 data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use ElixirHeatWeb.ChannelCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
import Phoenix.ChannelTest
import ElixirHeatWeb.ChannelCase
# The default endpoint for testing
@endpoint ElixirHeatWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(ElixirHeat.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(ElixirHeat.Repo, {:shared, self()})
end
:ok
end
end
| 27.536585 | 72 | 0.731621 |
9e91752cb91fdd7cfa1f4ce97923d02893c67850 | 2,081 | exs | Elixir | test/surface_bootstrap4/button_group_test.exs | tschmidleithner/surface_bootstrap4 | 1968905a01d451639b52f58ab0e397aba1f938e6 | [
"MIT"
] | 10 | 2020-06-14T01:40:19.000Z | 2020-11-17T05:39:37.000Z | test/surface_bootstrap4/button_group_test.exs | tschmidleithner/surface_bootstrap4 | 1968905a01d451639b52f58ab0e397aba1f938e6 | [
"MIT"
] | null | null | null | test/surface_bootstrap4/button_group_test.exs | tschmidleithner/surface_bootstrap4 | 1968905a01d451639b52f58ab0e397aba1f938e6 | [
"MIT"
] | 1 | 2020-06-14T01:40:22.000Z | 2020-06-14T01:40:22.000Z | defmodule SurfaceBootstrap4.ButtonGroupTest do
use ExUnit.Case, async: true
use ExUnit.Parameterized
alias SurfaceBootstrap4.ButtonGroup, warn: false
alias SurfaceBootstrap4.Button, warn: false
import ComponentTestHelper
test_with_params "button_group variants", &assert_component/2 do
[
button_group_default: {
"""
<ButtonGroup>
<Button color="secondary">
Left
</Button>
<Button color="secondary">
Middle
</Button>
<Button color="secondary">
Right
</Button>
</ButtonGroup>
""",
"""
<div class="btn-group"><button type="button" class="btn btn-secondary">
Left
</button><button type="button" class="btn btn-secondary">
Middle
</button><button type="button" class="btn btn-secondary">
Right
</button></div>
"""
},
button_group_vertical: {
~S(<ButtonGroup vertical>Vertically stacked</ButtonGroup>),
"""
<div class="btn-group-vertical">
Vertically stacked
</div>
"""
}
]
end
test_with_params "button_group size", &assert_component/2 do
[
sm: {
~S(<ButtonGroup size="sm"><Button>Small</Button></ButtonGroup>),
"""
<div class="btn-group btn-group-sm"><button type="button" class="btn">
Small
</button></div>
"""
},
md: {
~S(<ButtonGroup size="md"><Button>Medium</Button></ButtonGroup>),
"""
<div class="btn-group btn-group-md"><button type="button" class="btn">
Medium
</button></div>
"""
},
lg: {
~S(<ButtonGroup size="lg"><Button>Large</Button></ButtonGroup>),
"""
<div class="btn-group btn-group-lg"><button type="button" class="btn">
Large
</button></div>
"""
}
]
end
defp assert_component(component, expected) do
assert render_live(component) =~ expected
end
end
| 26.341772 | 79 | 0.542047 |
9e919c7b177f351efd269e92b8fd965f004bca69 | 1,646 | ex | Elixir | clients/street_view_publish/lib/google_api/street_view_publish/v1/model/connection.ex | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | null | null | null | clients/street_view_publish/lib/google_api/street_view_publish/v1/model/connection.ex | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | null | null | null | clients/street_view_publish/lib/google_api/street_view_publish/v1/model/connection.ex | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.StreetViewPublish.V1.Model.Connection do
@moduledoc """
A connection is the link from a source photo to a destination photo.
## Attributes
- target (PhotoId): Required. The destination of the connection from the containing photo to another photo. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:target => GoogleApi.StreetViewPublish.V1.Model.PhotoId.t()
}
field(:target, as: GoogleApi.StreetViewPublish.V1.Model.PhotoId)
end
defimpl Poison.Decoder, for: GoogleApi.StreetViewPublish.V1.Model.Connection do
def decode(value, options) do
GoogleApi.StreetViewPublish.V1.Model.Connection.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.StreetViewPublish.V1.Model.Connection do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.291667 | 130 | 0.755772 |
9e91b22b372ef8049e2c749207a17d39f2a3b203 | 3,941 | ex | Elixir | lib/blue_jet/app/goods/stockable.ex | freshcom/freshcom-api | 4f2083277943cf4e4e8fd4c4d443c7309f285ad7 | [
"BSD-3-Clause"
] | 44 | 2018-05-09T01:08:57.000Z | 2021-01-19T07:25:26.000Z | lib/blue_jet/app/goods/stockable.ex | freshcom/freshcom-api | 4f2083277943cf4e4e8fd4c4d443c7309f285ad7 | [
"BSD-3-Clause"
] | 36 | 2018-05-08T23:59:54.000Z | 2018-09-28T13:50:30.000Z | lib/blue_jet/app/goods/stockable.ex | freshcom/freshcom-api | 4f2083277943cf4e4e8fd4c4d443c7309f285ad7 | [
"BSD-3-Clause"
] | 9 | 2018-05-09T14:09:19.000Z | 2021-03-21T21:04:04.000Z | defmodule BlueJet.Goods.Stockable.Default do
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
def schema do
alias Ecto.UUID
quote do
field :account_id, UUID
field :account, :map, virtual: true
field :status, :string, default: "active"
field :code, :string
field :name, :string
field :label, :string
field :print_name, :string
field :unit_of_measure, :string
field :variable_weight, :boolean, default: false
field :storage_type, :string
field :storage_size, :integer
field :stackable, :boolean, default: false
field :specification, :string
field :storage_description, :string
field :caption, :string
field :description, :string
field :custom_data, :map, default: %{}
field :translations, :map, default: %{}
field :avatar_id, UUID
field :avatar, :map, virtual: true
field :file_collections, {:array, :map}, virtual: true, default: []
timestamps()
end
end
def impl do
alias BlueJet.Translation
alias BlueJet.Goods.Stockable.Proxy
quote do
@type t :: Ecto.Schema.t
@system_fields [
:id,
:account_id,
:inserted_at,
:updated_at
]
def writable_fields do
__MODULE__.__schema__(:fields) -- @system_fields
end
def translatable_fields do
[
:name,
:print_name,
:unit_of_measure,
:caption,
:description,
:specification,
:storage_description,
:custom_data
]
end
@spec changeset(__MODULE__.t(), :insert, map) :: Changeset.t()
def changeset(stockable, action, fields)
def changeset(stockable, :insert, fields) do
stockable
|> cast(fields, writable_fields())
|> Map.put(:action, :insert)
|> validate()
|> _put_print_name()
end
@spec changeset(__MODULE__.t(), :update, map, String.t()) :: Changeset.t()
def changeset(stockable, action, fields, locale \\ nil)
def changeset(stockable, :update, fields, locale) do
stockable = Proxy.put_account(stockable)
default_locale = stockable.account.default_locale
locale = locale || default_locale
stockable
|> cast(fields, writable_fields())
|> Map.put(:action, :update)
|> validate()
|> _put_print_name()
|> Translation.put_change(translatable_fields(), locale, default_locale)
end
@spec changeset(__MODULE__.t(), :delete) :: Changeset.t()
def changeset(stockable, action)
def changeset(stockable, :delete) do
change(stockable)
|> Map.put(:action, :delete)
end
@spec validate(Changeset.t()) :: Changeset.t()
def validate(changeset) do
changeset
|> validate_required([:name, :unit_of_measure])
end
defp _put_print_name(changeset = %{ changes: %{ print_name: _ } }), do: changeset
defp _put_print_name(changeset = %{ data: %{ print_name: nil }, valid?: true }) do
put_change(changeset, :print_name, get_field(changeset, :name))
end
defp _put_print_name(changeset), do: changeset
defoverridable [
validate: 1,
changeset: 2,
changeset: 3,
changeset: 4
]
end
end
end
defmodule BlueJet.Goods.Stockable do
@behaviour BlueJet.Data
use BlueJet, :data
alias __MODULE__.Default
schema "stockables" do
use Default, :schema
end
use Default, :impl
end
defmodule MyApp.Goods.Stockable do
use BlueJet, :data
alias BlueJet.Goods.Stockable.Default
schema "stockables" do
use Default, :schema
field :supplier_name, :string, virtual: true
end
use Default, :impl
def validate(changeset) do
changeset
|> validate_required([:supplier_name])
|> super()
end
end | 24.32716 | 88 | 0.615834 |
9e91ba8ddcf82e8332e2884dff93e240ebc5809e | 96 | exs | Elixir | config/test.exs | Plus17/sepomex-api | 3c9f76205d6f31b59969db1cefe60c3214e06330 | [
"Apache-2.0"
] | null | null | null | config/test.exs | Plus17/sepomex-api | 3c9f76205d6f31b59969db1cefe60c3214e06330 | [
"Apache-2.0"
] | null | null | null | config/test.exs | Plus17/sepomex-api | 3c9f76205d6f31b59969db1cefe60c3214e06330 | [
"Apache-2.0"
] | 1 | 2022-02-09T00:23:25.000Z | 2022-02-09T00:23:25.000Z | import Config
config :sepomex_api, http_port: 4002
config :sepomets, file: "priv/sepomex.zip"
| 16 | 42 | 0.770833 |
9e91da38091479d4a4627caa68279dbc2d99a802 | 144 | ex | Elixir | web/controllers/page_controller.ex | raincrash/pasteboard | e6b6f027bd18e1e4494c62c8127b89363b7466f5 | [
"MIT"
] | null | null | null | web/controllers/page_controller.ex | raincrash/pasteboard | e6b6f027bd18e1e4494c62c8127b89363b7466f5 | [
"MIT"
] | null | null | null | web/controllers/page_controller.ex | raincrash/pasteboard | e6b6f027bd18e1e4494c62c8127b89363b7466f5 | [
"MIT"
] | null | null | null | defmodule Pasteboard.PageController do
use Pasteboard.Web, :controller
def index(conn, _params) do
render conn, "index.html"
end
end
| 18 | 38 | 0.743056 |
9e91ec415c05b7cf84f2a54b90ac1f5a1f7f8a00 | 1,670 | ex | Elixir | clients/tag_manager/lib/google_api/tag_manager/v2/model/revert_zone_response.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/tag_manager/lib/google_api/tag_manager/v2/model/revert_zone_response.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/tag_manager/lib/google_api/tag_manager/v2/model/revert_zone_response.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.TagManager.V2.Model.RevertZoneResponse do
@moduledoc """
The result of reverting a zone in a workspace.
## Attributes
* `zone` (*type:* `GoogleApi.TagManager.V2.Model.Zone.t`, *default:* `nil`) - Zone as it appears in the latest container version since the last workspace synchronization operation. If no zone is present, that means the zone was deleted in the latest container version.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:zone => GoogleApi.TagManager.V2.Model.Zone.t()
}
field(:zone, as: GoogleApi.TagManager.V2.Model.Zone)
end
defimpl Poison.Decoder, for: GoogleApi.TagManager.V2.Model.RevertZoneResponse do
def decode(value, options) do
GoogleApi.TagManager.V2.Model.RevertZoneResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.TagManager.V2.Model.RevertZoneResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.531915 | 272 | 0.750299 |
9e921397f8e1db6db23d73245deab700b2857f96 | 1,046 | exs | Elixir | apps/fz_wall/mix.exs | jasonboukheir/firezone | 79d610b94f67ae25c8ca26f391c0edf288f6aaa5 | [
"Apache-2.0"
] | null | null | null | apps/fz_wall/mix.exs | jasonboukheir/firezone | 79d610b94f67ae25c8ca26f391c0edf288f6aaa5 | [
"Apache-2.0"
] | null | null | null | apps/fz_wall/mix.exs | jasonboukheir/firezone | 79d610b94f67ae25c8ca26f391c0edf288f6aaa5 | [
"Apache-2.0"
] | null | null | null | defmodule FzWall.MixProject do
use Mix.Project
def project do
[
app: :fz_wall,
version: "0.2.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
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()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {FzWall.Application, []},
registered: [:fz_wall_server]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:fz_common, in_umbrella: true},
{:inet_cidr, "~> 1.0.0"},
{:credo, "~> 1.4", only: [:dev, :test], runtime: false},
{:excoveralls, "~> 0.13", only: :test}
]
end
end
| 23.772727 | 62 | 0.545889 |
9e92274f72642f9e354ed3360d4cf8ce178ce48b | 2,738 | ex | Elixir | lib/elixir/lib/file/stream.ex | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | 4 | 2015-12-22T02:46:39.000Z | 2016-04-26T06:11:09.000Z | lib/elixir/lib/file/stream.ex | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/file/stream.ex | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | null | null | null | defmodule File.Stream do
@moduledoc """
Defines a `File.Stream` struct returned by `File.stream!/3`.
The following fields are public:
* `path` - the file path
* `modes` - the file modes
* `raw` - a boolean indicating if bin functions should be used
* `line_or_bytes` - if reading should read lines or a given amount of bytes
"""
defstruct path: nil, modes: [], line_or_bytes: :line, raw: true
@type t :: %__MODULE__{}
@doc false
def __build__(path, modes, line_or_bytes) do
raw = :lists.keyfind(:encoding, 1, modes) == false
modes =
if raw do
if :lists.keyfind(:read_ahead, 1, modes) == {:read_ahead, false} do
[:raw|modes]
else
[:raw, :read_ahead|modes]
end
else
modes
end
%File.Stream{path: path, modes: modes, raw: raw, line_or_bytes: line_or_bytes}
end
defimpl Collectable do
def into(%{path: path, modes: modes, raw: raw} = stream) do
modes = for mode <- modes, not mode in [:read], do: mode
case :file.open(path, [:write|modes]) do
{:ok, device} ->
{:ok, into(device, stream, raw)}
{:error, reason} ->
raise File.Error, reason: reason, action: "stream", path: path
end
end
defp into(device, stream, raw) do
fn
:ok, {:cont, x} ->
case raw do
true -> IO.binwrite(device, x)
false -> IO.write(device, x)
end
:ok, :done ->
# If delayed_write option is used and the last write failed will
# MatchError here as {:error, _} is returned.
:ok = :file.close(device)
stream
:ok, :halt ->
# If delayed_write option is used and the last write failed will
# MatchError here as {:error, _} is returned.
:ok = :file.close(device)
end
end
end
defimpl Enumerable do
def reduce(%{path: path, modes: modes, line_or_bytes: line_or_bytes, raw: raw}, acc, fun) do
modes = for mode <- modes, not mode in [:write, :append], do: mode
start_fun =
fn ->
case :file.open(path, modes) do
{:ok, device} -> device
{:error, reason} ->
raise File.Error, reason: reason, action: "stream", path: path
end
end
next_fun =
case raw do
true -> &IO.each_binstream(&1, line_or_bytes)
false -> &IO.each_stream(&1, line_or_bytes)
end
Stream.resource(start_fun, next_fun, &:file.close/1).(acc, fun)
end
def count(_stream) do
{:error, __MODULE__}
end
def member?(_stream, _term) do
{:error, __MODULE__}
end
end
end
| 27.656566 | 96 | 0.559533 |
9e92567ee3cd880d38130e1509a0f67b16474338 | 4,415 | ex | Elixir | lib/eex/lib/eex/tokenizer.ex | Nicd/elixir | e62ef92a4be1b562033d35b2d822cc9d6c661077 | [
"Apache-2.0"
] | 4 | 2016-04-05T05:51:36.000Z | 2019-10-31T06:46:35.000Z | lib/eex/lib/eex/tokenizer.ex | Nicd/elixir | e62ef92a4be1b562033d35b2d822cc9d6c661077 | [
"Apache-2.0"
] | null | null | null | lib/eex/lib/eex/tokenizer.ex | Nicd/elixir | e62ef92a4be1b562033d35b2d822cc9d6c661077 | [
"Apache-2.0"
] | 5 | 2015-02-01T06:01:19.000Z | 2019-08-29T09:02:35.000Z | defmodule EEx.Tokenizer do
@moduledoc false
@doc """
Tokenizes the given char list or binary.
It returns 4 different types of tokens as result:
* { :text, line, contents }
* { :expr, line, marker, contents }
* { :start_expr, line, marker, contents }
* { :end_expr, line, marker, contents }
"""
def tokenize(bin, line) when is_binary(bin) do
tokenize(:unicode.characters_to_list(bin), line)
end
def tokenize(list, line) do
Enum.reverse(tokenize(list, line, line, [], []))
end
defp tokenize('<%%' ++ t, current_line, line, buffer, acc) do
{ buffer, new_line, rest } = tokenize_expr t, line, [?%,?<|buffer]
tokenize rest, current_line, new_line, [?>,?%|buffer], acc
end
defp tokenize('<%#' ++ t, current_line, line, buffer, acc) do
{ _, new_line, rest } = tokenize_expr t, line, []
tokenize rest, current_line, new_line, buffer, acc
end
defp tokenize('<%' ++ t, current_line, line, buffer, acc) do
{ marker, t } = retrieve_marker(t)
{ expr, new_line, rest } = tokenize_expr t, line, []
token = token_name(expr)
acc = tokenize_text(current_line, buffer, acc)
final = { token, line, marker, Enum.reverse(expr) }
tokenize rest, new_line, new_line, [], [final | acc]
end
defp tokenize('\n' ++ t, current_line, line, buffer, acc) do
tokenize t, current_line, line + 1, [?\n|buffer], acc
end
defp tokenize([h|t], current_line, line, buffer, acc) do
tokenize t, current_line, line, [h|buffer], acc
end
defp tokenize([], current_line, _line, buffer, acc) do
tokenize_text(current_line, buffer, acc)
end
# Retrieve marker for <%
defp retrieve_marker('=' ++ t) do
{ '=', t }
end
defp retrieve_marker(t) do
{ '', t }
end
# Tokenize an expression until we find %>
defp tokenize_expr([?%,?>|t], line, buffer) do
{ buffer, line, t }
end
defp tokenize_expr('\n' ++ t, line, buffer) do
tokenize_expr t, line + 1, [?\n|buffer]
end
defp tokenize_expr([h|t], line, buffer) do
tokenize_expr t, line, [h|buffer]
end
defp tokenize_expr([], _line, _buffer) do
raise EEx.SyntaxError, message: "missing token: %>"
end
# Receive an expression content and check
# if it is a start, middle or an end token.
#
# Start tokens finish with `do` and `fn ->`
# Middle tokens are marked with `->` or keywords
# End tokens contain only the end word
defp token_name([h|t]) when h in [?\s, ?\t] do
token_name(t)
end
defp token_name('od' ++ [h|_]) when h in [?\s, ?\t, ?)] do
:start_expr
end
defp token_name('>-' ++ rest) do
rest = Enum.reverse(rest)
# Tokenize the remaining passing check_terminators as
# false, which relax the tokenizer to not error on
# unmatched pairs. Then, we check if there is a "fn"
# token and, if so, it is not followed by an "end"
# token. If this is the case, we are on a start expr.
case :elixir_tokenizer.tokenize(rest, 1, file: "eex", check_terminators: false) do
{ :ok, tokens } ->
tokens = Enum.reverse(tokens)
fn_index = fn_index(tokens)
if fn_index && end_index(tokens) > fn_index do
:start_expr
else
:middle_expr
end
_error ->
:middle_expr
end
end
defp token_name('esle' ++ t), do: check_spaces(t, :middle_expr)
defp token_name('retfa' ++ t), do: check_spaces(t, :middle_expr)
defp token_name('hctac' ++ t), do: check_spaces(t, :middle_expr)
defp token_name('eucser' ++ t), do: check_spaces(t, :middle_expr)
defp token_name('dne' ++ t), do: check_spaces(t, :end_expr)
defp token_name(_) do
:expr
end
defp fn_index(tokens) do
Enum.find_index(tokens, function do
{ :fn_paren, _ } -> true
{ :fn, _ } -> true
_ -> false
end)
end
defp end_index(tokens) do
Enum.find_index(tokens, match?({ :end, _ }, &1)) || :infinity
end
defp check_spaces(string, token) do
if only_spaces?(string), do: token, else: :expr
end
defp only_spaces?([h|t]) when h in [?\s, ?\t], do: only_spaces?(t)
defp only_spaces?(other), do: other == []
# Tokenize the buffered text by appending
# it to the given accumulator.
defp tokenize_text(_line, [], acc) do
acc
end
defp tokenize_text(line, buffer, acc) do
[{ :text, line, :unicode.characters_to_binary(Enum.reverse(buffer)) } | acc]
end
end
| 27.59375 | 86 | 0.625595 |
9e9256f3fb1f35e3820f70ff181e29de9c7d0b1e | 704 | exs | Elixir | test/scribe/migration_test.exs | rramsden/scribe | 4ef506714140da032a76d62b39109cf7a79c9d91 | [
"MIT"
] | 1 | 2016-01-24T11:43:59.000Z | 2016-01-24T11:43:59.000Z | test/scribe/migration_test.exs | rramsden/scribe | 4ef506714140da032a76d62b39109cf7a79c9d91 | [
"MIT"
] | null | null | null | test/scribe/migration_test.exs | rramsden/scribe | 4ef506714140da032a76d62b39109cf7a79c9d91 | [
"MIT"
] | null | null | null | defmodule ScribeMigrationTest do
use ExUnit.Case, async: true
import Scribe.Migration
import Scribe.TestHelpers
setup meta do
setup_project(meta)
end
teardown meta do
teardown_project(meta)
end
test "runs migration", meta do
config = Scribe.Config.new(adapter: Scribe.Adapters.MockAdapter)
Scribe.create_migration("my_migration", meta[:project_dir])
assert up(meta[:project_dir], config)
end
test "rolls a migration back", meta do
config = Scribe.Config.new(adapter: Scribe.Adapters.MockAdapter)
Scribe.create_migration("my_migration", meta[:project_dir])
assert up(meta[:project_dir], config)
assert down(meta[:project_dir], config)
end
end
| 26.074074 | 68 | 0.735795 |
9e9278f813cbc1c6794135f5cabcddefc8db16a7 | 489 | exs | Elixir | test/ingest_api/test_api_test.exs | darkua/logger_humio_backend | a1ae5a1db339e1a575ea03bf12fa02434374ccae | [
"MIT"
] | null | null | null | test/ingest_api/test_api_test.exs | darkua/logger_humio_backend | a1ae5a1db339e1a575ea03bf12fa02434374ccae | [
"MIT"
] | null | null | null | test/ingest_api/test_api_test.exs | darkua/logger_humio_backend | a1ae5a1db339e1a575ea03bf12fa02434374ccae | [
"MIT"
] | null | null | null | defmodule Logger.Backend.Humio.IngestApi.TestIngestApiTest do
@moduledoc """
An example test for the Test IngestAPI.
This serves mainly as an example for how to use the Test IngestAPI in other tests.
"""
use ExUnit.Case, async: true
alias Logger.Backend.Humio.IngestApi
setup do
IngestApi.Test.start_link(self())
:ok
end
test "send and receive" do
params = "testParams"
IngestApi.Test.transmit(params)
assert_receive {:transmit, params}
end
end
| 22.227273 | 84 | 0.719836 |
9e9293d5eb09b8d162aa9d2a3326476abcb7e7f4 | 2,312 | exs | Elixir | mix.exs | kianmeng/commanded-ecto-projections | aa5a99488e969fe338db780898cb8bd22599df15 | [
"MIT"
] | null | null | null | mix.exs | kianmeng/commanded-ecto-projections | aa5a99488e969fe338db780898cb8bd22599df15 | [
"MIT"
] | null | null | null | mix.exs | kianmeng/commanded-ecto-projections | aa5a99488e969fe338db780898cb8bd22599df15 | [
"MIT"
] | null | null | null | defmodule Commanded.Projections.Ecto.Mixfile do
use Mix.Project
@version "1.2.1"
def project do
[
app: :commanded_ecto_projections,
version: @version,
elixir: "~> 1.6",
elixirc_paths: elixirc_paths(Mix.env()),
aliases: aliases(),
description: description(),
package: package(),
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
deps: deps(),
dialyzer: dialyzer(),
docs: docs()
]
end
def application do
[
extra_applications: [:logger]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_env), do: ["lib"]
defp deps do
[
{:commanded, "~> 1.2"},
{:ecto, "~> 3.5"},
{:ecto_sql, "~> 3.5"},
{:postgrex, ">= 0.0.0", only: :test},
# Optional dependencies
{:jason, "~> 1.2", optional: true},
# Test & build tooling
{:dialyxir, "~> 1.0.0", only: [:dev, :test], runtime: false},
{:ex_doc, ">= 0.0.0", only: :dev},
{:mix_test_watch, "~> 1.0", only: :dev, runtime: false}
]
end
defp aliases do
[
setup: ["ecto.create", "ecto.migrate"],
reset: ["ecto.drop", "setup"]
]
end
defp description do
"""
Read model projections for Commanded using Ecto.
"""
end
defp dialyzer do
[
plt_add_apps: [:ecto, :ex_unit],
plt_add_deps: :app_tree,
plt_file: {:no_warn, "priv/plts/commanded_ecto_projections.plt"}
]
end
defp docs do
[
main: "Commanded.Projections.Ecto",
canonical: "http://hexdocs.pm/commanded_ecto_projections",
source_ref: "v#{@version}",
extra_section: "GUIDES",
extras: [
"CHANGELOG.md",
"guides/Getting Started.md",
"guides/Usage.md"
],
groups_for_extras: [
Introduction: [
"guides/Getting Started.md",
"guides/Usage.md"
]
]
]
end
defp package do
[
files: [
"lib",
"mix.exs",
".formatter.exs",
"README*",
"LICENSE*",
"priv/repo/migrations"
],
maintainers: ["Ben Smith"],
licenses: ["MIT"],
links: %{
"GitHub" => "https://github.com/commanded/commanded-ecto-projections"
}
]
end
end
| 21.407407 | 77 | 0.535467 |
9e92dd61d467023c9f506fab1de51820cd3a9967 | 4,098 | ex | Elixir | lib/phoenix/router/scope.ex | knewter/phoenix | 191909d97511ab99f9bbcc776cba9988c8b07596 | [
"MIT"
] | null | null | null | lib/phoenix/router/scope.ex | knewter/phoenix | 191909d97511ab99f9bbcc776cba9988c8b07596 | [
"MIT"
] | null | null | null | lib/phoenix/router/scope.ex | knewter/phoenix | 191909d97511ab99f9bbcc776cba9988c8b07596 | [
"MIT"
] | null | null | null | defmodule Phoenix.Router.Scope do
alias Phoenix.Router.Scope
@moduledoc false
@stack :phoenix_router_scopes
@pipes :phoenix_pipeline_scopes
defstruct path: nil, alias: nil, as: nil, pipes: [], host: nil
@doc """
Initializes the scope.
"""
def init(module) do
Module.put_attribute(module, @stack, [%Scope{}])
Module.put_attribute(module, @pipes, HashSet.new)
end
@doc """
Builds a route based on the top of the stack.
"""
def route(module, verb, path, controller, action, options) do
as = Keyword.get(options, :as, Phoenix.Naming.resource_name(controller, "Controller"))
{path, host, alias, as, pipe_through} = join(module, path, controller, as)
Phoenix.Router.Route.build(verb, path, host, alias, action, as, pipe_through)
end
@doc """
Defines the given pipeline.
"""
def pipeline(module, pipe) when is_atom(pipe) do
update_pipes module, &HashSet.put(&1, pipe)
end
@doc """
Appends the given pipes to the current scope pipe through.
"""
def pipe_through(module, pipes) do
pipes = List.wrap(pipes)
available = get_pipes(module)
Enum.each pipes, fn pipe ->
cond do
pipe == :before ->
raise ArgumentError, "the :before pipeline is always piped through"
pipe in available ->
:ok
true ->
raise ArgumentError, "unknown pipeline #{inspect pipe}"
end
end
update_stack(module, fn [scope|stack] ->
scope = put_in scope.pipes, scope.pipes ++ pipes
[scope|stack]
end)
end
@doc """
Pushes a scope into the module stack.
"""
def push(module, path) when is_binary(path) do
push(module, path: path)
end
def push(module, opts) when is_list(opts) do
path = Keyword.get(opts, :path)
if path, do: path = Plug.Router.Utils.split(path)
alias = Keyword.get(opts, :alias)
if alias, do: alias = Atom.to_string(alias)
scope = struct(Scope, path: path,
alias: alias,
as: Keyword.get(opts, :as),
host: Keyword.get(opts, :host),
pipes: [])
update_stack(module, fn stack -> [scope|stack] end)
end
@doc """
Pops a scope from the module stack.
"""
def pop(module) do
update_stack(module, fn [_|stack] -> stack end)
end
@doc """
Returns true if modules definition is currently within a scope block
"""
def inside_scope?(module), do: length(get_stack(module)) > 1
defp join(module, path, alias, as) do
stack = get_stack(module)
{join_path(stack, path), find_host(stack), join_alias(stack, alias),
join_as(stack, as), join_pipe_through(stack)}
end
defp join_path(stack, path) do
"/" <>
([Plug.Router.Utils.split(path)|extract(stack, :path)]
|> Enum.reverse()
|> Enum.concat()
|> Enum.join("/"))
end
defp join_alias(stack, alias) when is_atom(alias) do
[alias|extract(stack, :alias)]
|> Enum.reverse()
|> Module.concat()
end
defp join_as(_stack, nil), do: nil
defp join_as(stack, as) when is_atom(as) or is_binary(as) do
[as|extract(stack, :as)]
|> Enum.reverse()
|> Enum.join("_")
end
defp join_pipe_through(stack) do
for scope <- Enum.reverse(stack),
item <- scope.pipes,
do: item
end
defp find_host(stack) do
Enum.find_value(stack, & &1.host)
end
defp extract(stack, attr) do
for scope <- stack,
item = Map.fetch!(scope, attr),
do: item
end
defp get_stack(module) do
get_attribute(module, @stack)
end
defp update_stack(module, fun) do
update_attribute(module, @stack, fun)
end
defp get_pipes(module) do
get_attribute(module, @pipes)
end
defp update_pipes(module, fun) do
update_attribute(module, @pipes, fun)
end
defp get_attribute(module, attr) do
Module.get_attribute(module, attr) ||
raise "Phoenix router scope was not initialized"
end
defp update_attribute(module, attr, fun) do
Module.put_attribute(module, attr, fun.(get_attribute(module, attr)))
end
end
| 25.453416 | 90 | 0.631528 |
9e92ec60de22469f6cd43e50faa91cc930937ae9 | 516 | ex | Elixir | lib/scenic_scrollable.ex | zwetsloot-r-j/scenic_scrollable | 8904d1f158793a10fe2c8e394ab5fb251b3678ae | [
"MIT"
] | 2 | 2021-11-05T01:31:01.000Z | 2022-02-09T19:07:36.000Z | lib/scenic_scrollable.ex | zwetsloot-r-j/scenic_scrollable | 8904d1f158793a10fe2c8e394ab5fb251b3678ae | [
"MIT"
] | null | null | null | lib/scenic_scrollable.ex | zwetsloot-r-j/scenic_scrollable | 8904d1f158793a10fe2c8e394ab5fb251b3678ae | [
"MIT"
] | 2 | 2021-08-03T22:46:24.000Z | 2021-08-03T22:47:41.000Z | defmodule Scenic.Scrollable.Application do
@moduledoc """
Starter application using the Scenic framework.
"""
def start(_type, _args) do
import Supervisor.Spec, warn: false
# load the viewport configuration from config
main_viewport_config = Application.get_env(:scenic_scrollable, :viewport)
# start the application with the viewport
children = [
supervisor(Scenic, viewports: [main_viewport_config])
]
Supervisor.start_link(children, strategy: :one_for_one)
end
end
| 25.8 | 77 | 0.732558 |
9e9323bef69cfc9bacfa248c9cf0323e3135adc5 | 860 | ex | Elixir | lib/phoenix_client_ssl/verify_issuer.ex | Prato/phoenix-client-ssl | 510c2381e6d95c9baa6de9985d86d0a5dfe27b29 | [
"MIT"
] | 17 | 2017-12-01T09:12:41.000Z | 2021-04-16T07:53:37.000Z | lib/phoenix_client_ssl/verify_issuer.ex | Prato/phoenix-client-ssl | 510c2381e6d95c9baa6de9985d86d0a5dfe27b29 | [
"MIT"
] | 2 | 2018-01-29T13:04:26.000Z | 2018-05-24T11:03:55.000Z | lib/phoenix_client_ssl/verify_issuer.ex | Prato/phoenix-client-ssl | 510c2381e6d95c9baa6de9985d86d0a5dfe27b29 | [
"MIT"
] | 6 | 2018-05-24T07:42:22.000Z | 2020-11-14T17:41:35.000Z | defmodule PhoenixClientSsl.VerifyIssuer do
@moduledoc """
Check separate Issuer
"""
def verify(certificate, :valid_peer, ca_paths) do
ca_paths
|> Enum.map(&File.read!/1)
|> Enum.flat_map(fn contents ->
contents
|> :public_key.pem_decode()
|> Enum.map(fn {_, bin, _} -> bin end)
end)
|> Enum.any?(fn trusted ->
case :public_key.pkix_path_validation(trusted, [certificate], []) do
{:ok, _} -> true
_ -> false
end
end)
|> if do
{:valid_peer, []}
else
{:fail, :invalid_issuer}
end
end
def verify(_certificate, :valid, user_state) do
{:valid, user_state}
end
def verify(_certificate, {:extension, _}, user_state) do
{:unknown, user_state}
end
def verify(_certificate, {:bad_cert, _} = reason, _user_state) do
{:fail, reason}
end
end
| 22.051282 | 74 | 0.603488 |
9e93664aa6e1db004141fca8d614d2fb0e277b55 | 143 | ex | Elixir | install/packaging/libsodium/debian/libsodium18.cron.d.ex | GridProtectionAlliance/ARMORE | 0e5a73b0343873114b897365976bd956bd9948bb | [
"MIT"
] | 8 | 2016-08-31T20:50:57.000Z | 2021-10-04T01:48:37.000Z | install/packaging/libsodium/debian/libsodium18.cron.d.ex | GridProtectionAlliance/ARMORE | 0e5a73b0343873114b897365976bd956bd9948bb | [
"MIT"
] | null | null | null | install/packaging/libsodium/debian/libsodium18.cron.d.ex | GridProtectionAlliance/ARMORE | 0e5a73b0343873114b897365976bd956bd9948bb | [
"MIT"
] | 6 | 2016-12-26T05:03:16.000Z | 2020-04-08T04:30:24.000Z | #
# Regular cron jobs for the libsodium18 package
#
0 4 * * * root [ -x /usr/bin/libsodium18_maintenance ] && /usr/bin/libsodium18_maintenance
| 28.6 | 90 | 0.727273 |
9e93ca9a4f4d493104fec58d8794f2b2695437ca | 3,731 | ex | Elixir | lib/codes/codes_k59.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_k59.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_k59.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_K59 do
alias IcdCode.ICDCode
def _K5900 do
%ICDCode{full_code: "K5900",
category_code: "K59",
short_code: "00",
full_name: "Constipation, unspecified",
short_name: "Constipation, unspecified",
category_name: "Constipation, unspecified"
}
end
def _K5901 do
%ICDCode{full_code: "K5901",
category_code: "K59",
short_code: "01",
full_name: "Slow transit constipation",
short_name: "Slow transit constipation",
category_name: "Slow transit constipation"
}
end
def _K5902 do
%ICDCode{full_code: "K5902",
category_code: "K59",
short_code: "02",
full_name: "Outlet dysfunction constipation",
short_name: "Outlet dysfunction constipation",
category_name: "Outlet dysfunction constipation"
}
end
def _K5903 do
%ICDCode{full_code: "K5903",
category_code: "K59",
short_code: "03",
full_name: "Drug induced constipation",
short_name: "Drug induced constipation",
category_name: "Drug induced constipation"
}
end
def _K5904 do
%ICDCode{full_code: "K5904",
category_code: "K59",
short_code: "04",
full_name: "Chronic idiopathic constipation",
short_name: "Chronic idiopathic constipation",
category_name: "Chronic idiopathic constipation"
}
end
def _K5909 do
%ICDCode{full_code: "K5909",
category_code: "K59",
short_code: "09",
full_name: "Other constipation",
short_name: "Other constipation",
category_name: "Other constipation"
}
end
def _K591 do
%ICDCode{full_code: "K591",
category_code: "K59",
short_code: "1",
full_name: "Functional diarrhea",
short_name: "Functional diarrhea",
category_name: "Functional diarrhea"
}
end
def _K592 do
%ICDCode{full_code: "K592",
category_code: "K59",
short_code: "2",
full_name: "Neurogenic bowel, not elsewhere classified",
short_name: "Neurogenic bowel, not elsewhere classified",
category_name: "Neurogenic bowel, not elsewhere classified"
}
end
def _K5931 do
%ICDCode{full_code: "K5931",
category_code: "K59",
short_code: "31",
full_name: "Toxic megacolon",
short_name: "Toxic megacolon",
category_name: "Toxic megacolon"
}
end
def _K5939 do
%ICDCode{full_code: "K5939",
category_code: "K59",
short_code: "39",
full_name: "Other megacolon",
short_name: "Other megacolon",
category_name: "Other megacolon"
}
end
def _K594 do
%ICDCode{full_code: "K594",
category_code: "K59",
short_code: "4",
full_name: "Anal spasm",
short_name: "Anal spasm",
category_name: "Anal spasm"
}
end
def _K598 do
%ICDCode{full_code: "K598",
category_code: "K59",
short_code: "8",
full_name: "Other specified functional intestinal disorders",
short_name: "Other specified functional intestinal disorders",
category_name: "Other specified functional intestinal disorders"
}
end
def _K599 do
%ICDCode{full_code: "K599",
category_code: "K59",
short_code: "9",
full_name: "Functional intestinal disorder, unspecified",
short_name: "Functional intestinal disorder, unspecified",
category_name: "Functional intestinal disorder, unspecified"
}
end
end
| 30.08871 | 74 | 0.597695 |
9e93cac75b910b87dbe8e0c74708d85e72d8dbcf | 735 | ex | Elixir | lib/util/mod_util.ex | doawoo/elixir_rpg | 4dcd0eb717bd1d654b3e6a06be31aba4c3254fb3 | [
"MIT"
] | 23 | 2021-10-24T00:21:13.000Z | 2022-03-13T12:33:38.000Z | lib/util/mod_util.ex | doawoo/elixir_rpg | 4dcd0eb717bd1d654b3e6a06be31aba4c3254fb3 | [
"MIT"
] | null | null | null | lib/util/mod_util.ex | doawoo/elixir_rpg | 4dcd0eb717bd1d654b3e6a06be31aba4c3254fb3 | [
"MIT"
] | 3 | 2021-11-04T02:42:25.000Z | 2022-02-02T14:22:52.000Z | defmodule ElixirRPG.Util.ModUtil do
def get_entity_types do
{:ok, mods} = :application.get_key(:elixir_rpg, :modules)
mods
|> Enum.filter(fn mod ->
parts = Module.split(mod)
match?(["ElixirRPG", "EntityTypes" | _], parts)
end)
end
def get_component_types do
{:ok, mods} = :application.get_key(:elixir_rpg, :modules)
mods
|> Enum.filter(fn mod ->
parts = Module.split(mod)
match?(["ElixirRPG", "ComponentTypes" | _], parts)
end)
end
def get_system_types do
{:ok, mods} = :application.get_key(:elixir_rpg, :modules)
mods
|> Enum.filter(fn mod ->
parts = Module.split(mod)
match?(["ElixirRPG", "RuntimeSystems" | _], parts)
end)
end
end
| 22.96875 | 61 | 0.617687 |
9e93ce839b75500ca51a8e129832ecc91581fe4a | 1,364 | exs | Elixir | source/elixir_clients/doorpi/apps/fw/mix.exs | rveshovda/pifog | 127c2de6ff2666ebc9987d8c2cfd5431ce5ff888 | [
"Apache-2.0"
] | 1 | 2017-07-05T06:47:57.000Z | 2017-07-05T06:47:57.000Z | source/elixir_clients/doorpi/apps/fw/mix.exs | royveshovda/pifog | 127c2de6ff2666ebc9987d8c2cfd5431ce5ff888 | [
"Apache-2.0"
] | null | null | null | source/elixir_clients/doorpi/apps/fw/mix.exs | royveshovda/pifog | 127c2de6ff2666ebc9987d8c2cfd5431ce5ff888 | [
"Apache-2.0"
] | null | null | null | defmodule Fw.Mixfile do
use Mix.Project
@target System.get_env("NERVES_TARGET") || "rpi"
def project do
[app: :fw,
version: "0.1.0",
target: @target,
archives: [nerves_bootstrap: "~> 0.2.1"],
deps_path: "../../deps/#{@target}",
build_path: "../../_build/#{@target}",
config_path: "../../config/config.exs",
lockfile: "../../mix.lock",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
aliases: aliases(),
deps: deps() ++ system(@target)]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[mod: {Fw, []},
applications: [:logger]]
end
def deps do
[
{:nerves, "~> 0.3.4"},
{:nerves_interim_wifi, "~> 0.1.0"},
#{:nerves_ntp, "~> 0.1"},
{:nerves_ntp, git: "https://github.com/evokly/nerves_ntp.git"},
{:getopt, "~> 0.8.2", override: true},
{:logic, in_umbrella: true},
{:hw, in_umbrella: true},
{:relx, "~> 3.21", override: true},
{:erlware_commons, "~> 0.21.0", override: true}
]
end
def system(target) do
[{:"nerves_system_#{target}", ">= 0.0.0"}]
end
def aliases do
["deps.precompile": ["nerves.precompile", "deps.precompile"],
"deps.loadpaths": ["deps.loadpaths", "nerves.loadpaths"]]
end
end
| 23.929825 | 69 | 0.565249 |
9e93f7cdc0185683190ebbb09ec3bb9b17d25d70 | 2,526 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_query_input.ex | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | 1 | 2019-01-03T22:30:36.000Z | 2019-01-03T22:30:36.000Z | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_query_input.ex | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_query_input.ex | hauptbenutzer/elixir-google-api | 7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2QueryInput do
@moduledoc """
Represents the query input. It can contain either: 1. An audio config which instructs the speech recognizer how to process the speech audio. 2. A conversational query in the form of text,. 3. An event that specifies which intent to trigger.
## Attributes
- audioConfig (GoogleCloudDialogflowV2InputAudioConfig): Instructs the speech recognizer how to process the speech audio. Defaults to: `null`.
- event (GoogleCloudDialogflowV2EventInput): The event to be processed. Defaults to: `null`.
- text (GoogleCloudDialogflowV2TextInput): The natural language text to be processed. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:audioConfig =>
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2InputAudioConfig.t(),
:event => GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2EventInput.t(),
:text => GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2TextInput.t()
}
field(:audioConfig, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2InputAudioConfig)
field(:event, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2EventInput)
field(:text, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2TextInput)
end
defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2QueryInput do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2QueryInput.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2QueryInput do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 45.927273 | 252 | 0.77118 |
9e9407f7209d70673c44634c0e000f6280c3ec38 | 2,744 | exs | Elixir | config/prod.exs | EBKH/cap-react-webpack | 08638c4e4cc30e2cb35e0299a99a7c68a24f2128 | [
"MIT"
] | null | null | null | config/prod.exs | EBKH/cap-react-webpack | 08638c4e4cc30e2cb35e0299a99a7c68a24f2128 | [
"MIT"
] | null | null | null | config/prod.exs | EBKH/cap-react-webpack | 08638c4e4cc30e2cb35e0299a99a7c68a24f2128 | [
"MIT"
] | null | null | null | use Mix.Config
# For production, we often load configuration from external
# sources, such as your system environment. For this reason,
# you won't find the :http configuration below, but set inside
# CapPhoenixReactWebpackWeb.Endpoint.init/2 when load_from_system_env is
# true. Any dynamic configuration should be done there.
#
# Don't forget to configure the url host to something meaningful,
# Phoenix uses this information when generating URLs.
#
# Finally, we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the mix phx.digest task
# which you typically run after static files are built.
config :cap_phoenix_react_webpack, CapPhoenixReactWebpackWeb.Endpoint,
load_from_system_env: true,
debug_errors: true,
url: [scheme: "https", host: "react-cap.herokuapp.com", port: 443],
force_ssl: [rewrite_on: [:x_forwarded_proto]],
cache_static_manifest: "priv/webpack/build/cache_manifest.json",
secret_key_base: Map.fetch!(System.get_env(), "SECRET_KEY_BASE")
# Configure your database
config :cap_phoenix_react_webpack, CapPhoenixReactWebpack.Repo,
adapter: Ecto.Adapters.Postgres,
url: System.get_env("DATABASE_URL"),
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
ssl: true
# Do not print debug messages in production
config :logger, level: :info
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :cap_phoenix_react_webpack, CapPhoenixReactWebpackWeb.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [:inet6,
# port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :cap_phoenix_react_webpack, CapPhoenixReactWebpackWeb.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :cap_phoenix_react_webpack, CapPhoenixReactWebpackWeb.Endpoint, server: true
#
# Finally import the config/prod.secret.exs
# which should be versioned separately.
# import_config "prod.secret.exs"
| 36.586667 | 89 | 0.741618 |
9e9408b58684ad78e45c6662ba079a05097930f6 | 565 | ex | Elixir | priv/templates/phoenix.gen.json/changeset_view.ex | misfo/phoenix | 04464429d9b958e331b2ffe0f0f5926690ab3b56 | [
"MIT"
] | 8 | 2019-06-02T05:02:36.000Z | 2021-08-11T04:23:10.000Z | priv/templates/phoenix.gen.json/changeset_view.ex | misfo/phoenix | 04464429d9b958e331b2ffe0f0f5926690ab3b56 | [
"MIT"
] | 7 | 2019-05-15T08:32:51.000Z | 2020-06-10T07:46:43.000Z | priv/templates/phoenix.gen.json/changeset_view.ex | misfo/phoenix | 04464429d9b958e331b2ffe0f0f5926690ab3b56 | [
"MIT"
] | 2 | 2020-08-02T04:00:17.000Z | 2020-10-07T16:07:37.000Z | defmodule <%= base %>.ChangesetView do
use <%= base %>.Web, :view
@doc """
Traverses and translates changeset errors.
See `Ecto.Changeset.traverse_errors/2` and
`<%= base %>.ErrorHelpers.translate_error/1` for more details.
"""
def translate_errors(changeset) do
Ecto.Changeset.traverse_errors(changeset, &translate_error/1)
end
def render("error.json", %{changeset: changeset}) do
# When encoded, the changeset returns its errors
# as a JSON object. So we just pass it forward.
%{errors: translate_errors(changeset)}
end
end
| 28.25 | 65 | 0.702655 |
9e94723a898f7052979ae26c98a480b925b1e494 | 8,986 | exs | Elixir | test/client_tests/arrays_test.exs | juljimm/opex62541 | c44c157213a8a3fb07283f6e697e6dd018693315 | [
"MIT"
] | null | null | null | test/client_tests/arrays_test.exs | juljimm/opex62541 | c44c157213a8a3fb07283f6e697e6dd018693315 | [
"MIT"
] | null | null | null | test/client_tests/arrays_test.exs | juljimm/opex62541 | c44c157213a8a3fb07283f6e697e6dd018693315 | [
"MIT"
] | null | null | null | defmodule ClientArraysTest do
use ExUnit.Case, async: false
alias OpcUA.{NodeId, Server, QualifiedName, Client}
setup do
{:ok, pid} = OpcUA.Server.start_link()
Server.set_default_config(pid)
{:ok, ns_index} = OpcUA.Server.add_namespace(pid, "Room")
# Object Node
requested_new_node_id =
NodeId.new(ns_index: ns_index, identifier_type: "string", identifier: "R1_TS1_VendorName")
parent_node_id = NodeId.new(ns_index: 0, identifier_type: "integer", identifier: 85)
reference_type_node_id = NodeId.new(ns_index: 0, identifier_type: "integer", identifier: 35)
browse_name = QualifiedName.new(ns_index: ns_index, name: "Temperature sensor")
type_definition = NodeId.new(ns_index: 0, identifier_type: "integer", identifier: 58)
:ok = Server.add_object_node(pid,
requested_new_node_id: requested_new_node_id,
parent_node_id: parent_node_id,
reference_type_node_id: reference_type_node_id,
browse_name: browse_name,
type_definition: type_definition
)
# Variable Node
requested_new_node_id =
NodeId.new(ns_index: ns_index, identifier_type: "string", identifier: "R1_TS1_Temperature")
parent_node_id =
NodeId.new(ns_index: ns_index, identifier_type: "string", identifier: "R1_TS1_VendorName")
reference_type_node_id = NodeId.new(ns_index: 0, identifier_type: "integer", identifier: 47)
browse_name = QualifiedName.new(ns_index: ns_index, name: "Temperature")
type_definition = NodeId.new(ns_index: 0, identifier_type: "integer", identifier: 63)
:ok = Server.add_variable_node(pid,
requested_new_node_id: requested_new_node_id,
parent_node_id: parent_node_id,
reference_type_node_id: reference_type_node_id,
browse_name: browse_name,
type_definition: type_definition
)
:ok = Server.write_node_access_level(pid, requested_new_node_id, 3)
:ok = Server.write_node_write_mask(pid, requested_new_node_id, 3)
:ok = Server.write_node_value_rank(pid, requested_new_node_id, 1)
:ok = Server.write_node_array_dimensions(pid, requested_new_node_id, [4])
:ok = Server.write_node_blank_array(pid, requested_new_node_id, 11, [4])
:ok = Server.start(pid)
{:ok, c_pid} = Client.start_link()
:ok = Client.set_config(c_pid)
:ok = Client.connect_by_url(c_pid, url: "opc.tcp://localhost:4840/")
%{c_pid: c_pid, s_pid: pid, ns_index: ns_index}
end
test "write/read array dimension node", state do
node_id = NodeId.new(ns_index: state.ns_index, identifier_type: "string", identifier: "R1_TS1_Temperature")
resp = Client.write_node_array_dimensions(state.c_pid, node_id, [4])
assert resp == :ok
resp = Client.read_node_array_dimensions(state.c_pid, node_id)
assert resp == {:ok, [4]}
resp = Client.write_node_array_dimensions(state.c_pid, node_id, [4])
assert resp == :ok
resp = Client.read_node_array_dimensions(state.c_pid, node_id)
assert resp == {:ok, [4]}
end
test "write/read array node by index (string)", state do
node_id = NodeId.new(ns_index: state.ns_index, identifier_type: "string", identifier: "R1_TS1_Temperature")
resp = Client.read_node_value_by_index(state.c_pid, node_id, 0)
assert resp == {:ok, ""}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 1)
assert resp == {:ok, ""}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 2)
assert resp == {:ok, ""}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 3)
assert resp == {:ok, ""}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 4)
assert resp == {:error, "BadTypeMismatch"}
resp = Client.write_node_value(state.c_pid, node_id, 11, "alde103_1", 0)
assert resp == :ok
resp = Client.write_node_value(state.c_pid, node_id, 11, "alde103_2", 1)
assert resp == :ok
resp = Client.write_node_value(state.c_pid, node_id, 11, "alde103_3", 2)
assert resp == :ok
resp = Client.write_node_value(state.c_pid, node_id, 11, "alde103_4", 3)
assert resp == :ok
resp = Client.write_node_value(state.c_pid, node_id, 11, "alde103_error", 4)
assert resp == {:error, "BadTypeMismatch"}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 0)
assert resp == {:ok, "alde103_1"}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 1)
assert resp == {:ok, "alde103_2"}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 2)
assert resp == {:ok, "alde103_3"}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 3)
assert resp == {:ok, "alde103_4"}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 4)
assert resp == {:error, "BadTypeMismatch"}
resp = Client.read_node_value(state.c_pid, node_id)
assert resp == {:ok, ["alde103_1", "alde103_2", "alde103_3", "alde103_4"]}
end
test "write/read array node by index (double)", state do
node_id = NodeId.new(ns_index: state.ns_index, identifier_type: "string", identifier: "R1_TS1_Temperature")
:ok = Server.write_node_blank_array(state.s_pid, node_id, 10, [4])
resp = Client.read_node_value_by_index(state.c_pid, node_id, 0)
assert resp == {:ok, 0.0}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 1)
assert resp == {:ok, 0.0}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 2)
assert resp == {:ok, 0.0}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 3)
assert resp == {:ok, 0.0}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 4)
assert resp == {:error, "BadTypeMismatch"}
resp = Client.write_node_value(state.c_pid, node_id, 10, 103.0, 0)
assert resp == :ok
resp = Client.write_node_value(state.c_pid, node_id, 10, 103103.0, 1)
assert resp == :ok
resp = Client.write_node_value(state.c_pid, node_id, 10, 103103103.0, 2)
assert resp == :ok
resp = Client.write_node_value(state.c_pid, node_id, 10, 103103.103, 3)
assert resp == :ok
resp = Client.write_node_value(state.c_pid, node_id, 10, 103103.0, 4)
assert resp == {:error, "BadTypeMismatch"}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 0)
assert resp == {:ok, 103.0}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 1)
assert resp == {:ok, 103103.0}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 2)
assert resp == {:ok, 103103103.0}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 3)
assert resp == {:ok, 103103.103}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 4)
assert resp == {:error, "BadTypeMismatch"}
resp = Client.read_node_value(state.c_pid, node_id)
assert resp == {:ok, [103.0, 103103.0, 103103103.0, 103103.103]}
end
test "write/read array node by index (node_id)", state do
node_id = NodeId.new(ns_index: state.ns_index, identifier_type: "string", identifier: "R1_TS1_Temperature")
:ok = Server.write_node_blank_array(state.s_pid, node_id, 16, [4])
resp = Client.read_node_value_by_index(state.c_pid, node_id, 0)
assert resp == {:ok, %OpcUA.NodeId{identifier: 0, identifier_type: 0, ns_index: 0}}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 1)
assert resp == {:ok, %OpcUA.NodeId{identifier: 0, identifier_type: 0, ns_index: 0}}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 2)
assert resp == {:ok, %OpcUA.NodeId{identifier: 0, identifier_type: 0, ns_index: 0}}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 3)
assert resp == {:ok, %OpcUA.NodeId{identifier: 0, identifier_type: 0, ns_index: 0}}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 4)
assert resp == {:error, "BadTypeMismatch"}
resp = Client.write_node_value(state.c_pid, node_id, 16, node_id, 0)
assert resp == :ok
resp = Client.write_node_value(state.c_pid, node_id, 16, node_id, 1)
assert resp == :ok
resp = Client.write_node_value(state.c_pid, node_id, 16, node_id, 2)
assert resp == :ok
resp = Client.write_node_value(state.c_pid, node_id, 16, node_id, 3)
assert resp == :ok
# resp = Client.write_node_value(state.c_pid, node_id, 16, node_id, 4)
# assert resp == {:error, "BadTypeMismatch"}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 0)
assert resp == {:ok, node_id}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 1)
assert resp == {:ok, node_id}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 2)
assert resp == {:ok, node_id}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 3)
assert resp == {:ok, node_id}
resp = Client.read_node_value_by_index(state.c_pid, node_id, 4)
assert resp == {:error, "BadTypeMismatch"}
resp = Client.read_node_value(state.c_pid, node_id)
assert resp == {:ok, [node_id, node_id, node_id, node_id]}
end
end
| 38.076271 | 111 | 0.69931 |
9e9476cabe73d1ec68776a12f1c9c8341e4a5337 | 7,723 | ex | Elixir | lib/witchcraft/monad.ex | peksapro/witchcraft | d821ebf74777805b260a705380bde8ca837d18a5 | [
"MIT"
] | 1 | 2019-10-04T11:32:01.000Z | 2019-10-04T11:32:01.000Z | lib/witchcraft/monad.ex | peksapro/witchcraft | d821ebf74777805b260a705380bde8ca837d18a5 | [
"MIT"
] | null | null | null | lib/witchcraft/monad.ex | peksapro/witchcraft | d821ebf74777805b260a705380bde8ca837d18a5 | [
"MIT"
] | null | null | null | import TypeClass
defclass Witchcraft.Monad do
@moduledoc """
Very similar to `Chain`, `Monad` provides a way to link actions, and a way
to bring plain values into the correct context (`Applicative`).
This allows us to view actions in a full framework along the lines of
functor and applicative:
data ---------------- function ----------------------------> result
| | |
of(Container, data) of/2, or similar of(Container, result)
↓ ↓ ↓
%Container<data> --- (data -> %Container<updated_data>) ---> %Container<updated_data>
As you can see, the linking function may just be `of` now that we have that.
For a nice, illustrated introduction,
see [Functors, Applicatives, And Monads In Pictures](http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html).
Having `of` also lets us enhance do-notation with a convenuenct `return` function (see `monad/2`)
## Type Class
An instance of `Witchcraft.Monad` must also implement `Witchcraft.Applicative`
and `Wicthcraft.Chainable`.
Functor [map/2]
↓
Apply [convey/2]
↓ ↓
[of/2] Applicative Chain [chain/2]
↓ ↓
Monad
[_]
"""
extend Witchcraft.Applicative
extend Witchcraft.Chain
use Witchcraft.Applicative
use Witchcraft.Chain
defmacro __using__(opts \\ []) do
quote do
use Witchcraft.Applicative, unquote(opts)
use Witchcraft.Chain, unquote(opts)
import unquote(__MODULE__), unquote(opts)
end
end
properties do
import Witchcraft.Applicative
import Witchcraft.Chain
def left_identity(data) do
a = generate(data)
f = &Witchcraft.Functor.replace(a, inspect(&1))
left = a |> of(a) |> chain(f)
right = f.(a)
equal?(left, right)
end
def right_identity(data) do
a = generate(data)
left = a >>> (&of(a, &1))
equal?(a, left)
end
end
@doc """
Asynchronous variant of `Witchcraft.Chain.chain/2`.
Note that _each_ `async_chain` call awaits that step's completion. This is a
feature not a bug, since `chain` can introduce dependencies between nested links.
However, this means that the async features on only really useful on larger data sets,
because otherwise we're just sparking tasks and immediaetly waiting a single application.
## Examples
iex> async_chain([1, 2, 3], fn x -> [x, x] end)
[1, 1, 2, 2, 3, 3]
iex> async_chain([1, 2, 3], fn x ->
...> async_chain([x + 1], fn y ->
...> [x * y]
...> end)
...> end)
[2, 6, 12]
0..10_000
|> Enum.to_list()
|> async_chain(fn x ->
async_chain([x + 1], fn y ->
Process.sleep(500)
[x * y]
end)
end)
#=> [0, 2, 6, 12, 20, 30, 42, ...] in around a second
"""
@spec async_chain(Chain.t(), Chain.link()) :: Chain.t()
def async_chain(chainable, link) do
chainable
|> chain(fn x ->
# credo:disable-for-lines:3 Credo.Check.Refactor.PipeChainStart
fn -> link.(x) end
|> Task.async()
|> to(chainable)
end)
|> chain(&Task.await/1)
end
@doc "Alias for `async_chain/2`"
@spec async_chain(Chain.t(), Chain.link()) :: Chain.t()
def async_bind(chainable, link), do: async_chain(chainable, link)
@doc """
Asynchronous variant of `Witchcraft.Chain.draw/2`.
Note that _each_ `async_draw` call awaits that step's completion. This is a
feature not a bug, since `chain` can introduce dependencies between nested links.
However, this means that the async features on only really useful on larger data sets,
because otherwise we're just sparking tasks and immediaetly waiting a single application.
## Examples
iex> async_draw(fn x -> [x, x] end, [1, 2, 3])
[1, 1, 2, 2, 3, 3]
iex> (fn y -> [y * 5, y * 10] end)
...> |> async_draw(fn x -> [x, x] end
...> |> async_draw([1, 2, 3])) # note the "extra" closing paren
[5, 10, 5, 10, 10, 20, 10, 20, 15, 30, 15, 30]
iex> fn x ->
...> fn y ->
...> [x * y]
...> end
...> |> async_draw([x + 1])
...> end
...> |> async_draw([1, 2, 3])
[2, 6, 12]
fn x ->
fn y ->
Process.sleep(500)
[x * y]
end
|> async_draw([x + 1])
end
|> async_draw(Enum.to_list(0..10_000))
[0, 2, 6, 12, ...] # in under a second
"""
@spec async_draw(Chain.t(), Chain.link()) :: Chain.t()
def async_draw(link, chainable), do: async_chain(chainable, link)
@doc ~S"""
do-notation enhanced with a `return` operation.
`return` is the simplest possible linking function, providing the correct `of/2`
instance for your monad.
## Examples
iex> monad [] do
...> [1, 2, 3]
...> end
[1, 2, 3]
iex> monad [] do
...> [1, 2, 3]
...> [4, 5, 6]
...> [7, 8, 9]
...> end
[
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9
]
iex> monad [] do
...> Witchcraft.Applicative.of([], 1)
...> end
[1]
iex> monad [] do
...> return 1
...> end
[1]
iex> monad [] do
...> a <- [1,2,3]
...> b <- [4,5,6]
...> return(a * b)
...> end
[
4, 5, 6,
8, 10, 12,
12, 15, 18
]
iex> monad [] do
...> a <- return 1
...> b <- return 2
...> return(a + b)
...> end
[3]
"""
defmacro monad(sample, do: input) do
returnized = desugar_return(input, sample)
Witchcraft.Chain.do_notation(returnized, &Witchcraft.Chain.chain/2)
end
@doc ~S"""
Variant of `monad/2` where each step internally occurs asynchonously, but lines
run strictly one after another.
## Examples
iex> async [] do
...> [1, 2, 3]
...> end
[1, 2, 3]
iex> async [] do
...> [1, 2, 3]
...> [4, 5, 6]
...> [7, 8, 9]
...> end
[
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9,
7, 8, 9
]
iex> async [] do
...> Witchcraft.Applicative.of([], 1)
...> end
[1]
iex> async [] do
...> a <- [1,2,3]
...> b <- [4,5,6]
...> return(a * b)
...> end
[
4, 5, 6,
8, 10, 12,
12, 15, 18
]
iex> async [] do
...> a <- return 1
...> b <- return 2
...> return(a + b)
...> end
[3]
"""
defmacro async(sample, do: input) do
returnized = desugar_return(input, sample)
Witchcraft.Chain.do_notation(returnized, &Witchcraft.Monad.async_bind/2)
end
@doc false
# Convert `return`s to `of`s in the correct monadic context
def desugar_return(ast, sample) do
ast
|> Macro.prewalk(fn
{:return, _ctx, [inner]} ->
quote do: Witchcraft.Applicative.of(unquote(sample), unquote(inner))
ast ->
ast
end)
end
end
definst Witchcraft.Monad, for: Function
definst Witchcraft.Monad, for: List
definst Witchcraft.Monad, for: Tuple do
use Witchcraft.Semigroup
import TypeClass.Property.Generator, only: [generate: 1]
custom_generator(_) do
{generate(""), generate("")}
end
end
| 24.993528 | 140 | 0.513013 |
9e9492ad622fe82e4259fef9483b1a7919eb00eb | 1,691 | ex | Elixir | lib/retrospectivex_web/controllers/retrospectives/board_controller.ex | dreamingechoes/retrospectivex | cad0df6cfde5376121d841f4a8b36861b6ec5d45 | [
"MIT"
] | 5 | 2018-06-27T17:51:51.000Z | 2020-10-05T09:59:04.000Z | lib/retrospectivex_web/controllers/retrospectives/board_controller.ex | dreamingechoes/retrospectivex | cad0df6cfde5376121d841f4a8b36861b6ec5d45 | [
"MIT"
] | 1 | 2018-10-08T11:33:12.000Z | 2018-10-08T11:33:12.000Z | lib/retrospectivex_web/controllers/retrospectives/board_controller.ex | dreamingechoes/retrospectivex | cad0df6cfde5376121d841f4a8b36861b6ec5d45 | [
"MIT"
] | 2 | 2018-10-08T11:31:55.000Z | 2020-10-05T09:59:05.000Z | defmodule RetrospectivexWeb.Retrospectives.BoardController do
use RetrospectivexWeb, :controller
alias Retrospectivex.Retrospectives
alias Retrospectivex.Retrospectives.Schemas.Board
def new(conn, _params) do
changeset = Retrospectives.change_board(%Board{state: :opened})
render(conn, "new.html", changeset: changeset)
end
def create(conn = %{assigns: %{current_user: %{id: user_id}}}, %{
"board" => board_params,
"g-recaptcha-response" => g_recaptcha_response
}) do
case Recaptcha.verify(g_recaptcha_response) do
{:ok, _response} ->
case Retrospectives.create_board(
Map.put(board_params, "user_id", user_id)
) do
{:ok, %{id: board_id}} ->
# We need to reload the board in order to have available the auto-generated
# 'uuid' field to execute the proper redirection.
board = Retrospectives.get_board!(board_id)
conn
|> put_flash(:info, "Board created successfully.")
|> redirect(to: Routes.board_path(conn, :show, board.slug, u: board.uuid))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", changeset: changeset)
end
{:error, _error} ->
render(
conn,
"new.html",
changeset: Retrospectives.change_board(%Board{state: :opened})
)
end
end
def show(conn, %{"slug" => slug, "u" => uuid}) do
board = Retrospectives.get_board_by_slug_and_uuid!(slug, uuid)
action_items = Retrospectives.list_action_items_by_board(board)
render(conn, "show.html", board: board, action_items: action_items)
end
end
| 33.82 | 87 | 0.633353 |
9e94db9b7be567c0110c01e34b791e2473f3011f | 1,328 | ex | Elixir | lib/structs/attachment.ex | Drahcirius/crux_structs | 53ba17c6ab0adfadbf69e236ec936fed8015420e | [
"MIT"
] | null | null | null | lib/structs/attachment.ex | Drahcirius/crux_structs | 53ba17c6ab0adfadbf69e236ec936fed8015420e | [
"MIT"
] | null | null | null | lib/structs/attachment.ex | Drahcirius/crux_structs | 53ba17c6ab0adfadbf69e236ec936fed8015420e | [
"MIT"
] | null | null | null | defmodule Crux.Structs.Attachment do
@moduledoc """
Represents a Discord [Attachment Object](https://discordapp.com/developers/docs/resources/channel#attachment-object-attachment-structure)
Height and width are only present for images.
"""
@behaviour Crux.Structs
alias Crux.Structs.{Attachment, Snowflake, Util}
require Util
Util.modulesince("0.1.0")
defstruct(
id: nil,
filename: nil,
size: nil,
url: nil,
proxy_url: nil,
height: nil,
width: nil
)
Util.typesince("0.1.0")
@type t :: %__MODULE__{
id: Snowflake.t(),
filename: String.t(),
size: integer(),
url: String.t(),
proxy_url: String.t(),
height: integer() | nil,
width: integer() | nil
}
@doc """
Creates a `t:Crux.Structs.Attachment.t/0` struct from raw data.
> Automatically invoked by `Crux.Structs.create/2`.
"""
@spec create(data :: map()) :: t()
Util.since("0.1.0")
def create(data) do
attachment =
data
|> Util.atomify()
|> Map.update(:id, nil, &Snowflake.to_snowflake/1)
struct(__MODULE__, attachment)
end
defimpl String.Chars, for: Crux.Structs.Attachment do
@spec to_string(Attachment.t()) :: String.t()
def to_string(%Attachment{url: url}), do: url
end
end
| 22.508475 | 141 | 0.615211 |
9e94ec1a111c9b77992b18d6235cd64d860c8f8c | 2,457 | ex | Elixir | lib/mix/tasks/generate.answers.ex | sparrell/quizquadaminos | 6388252b7c32aa4101486cbf45d0d57d4e3a79da | [
"MIT"
] | 1 | 2022-01-11T20:06:31.000Z | 2022-01-11T20:06:31.000Z | lib/mix/tasks/generate.answers.ex | sFractal-Podii/quizquadaminos | 4c9023b9c6212a92741b0f21d9eb05871aa73916 | [
"MIT"
] | 484 | 2021-02-15T18:43:40.000Z | 2022-03-29T12:27:24.000Z | lib/mix/tasks/generate.answers.ex | sFractal-Podii/quizquadaminos | 4c9023b9c6212a92741b0f21d9eb05871aa73916 | [
"MIT"
] | 8 | 2021-02-15T19:12:51.000Z | 2021-12-15T03:02:46.000Z | defmodule Mix.Tasks.Gen.Answers do
use Mix.Task
@directories ["qna", "courses"]
require Logger
@shortdoc "Generates json file answers to the specified directory"
def run(names) do
validate_directory_name(names)
names =
case names do
[] -> @directories
names -> names
end
Enum.each(names, fn dir ->
Logger.info("Generating answers for #{dir}..")
incoming_answers = dir |> answer() |> Enum.into(%{}, fn {k, v} -> {k, convert(v)} end)
file_path = dir <> "/answers.json"
existing_answers =
case File.read(file_path) do
{:ok, content} -> Jason.decode!(content)
_ -> %{}
end
new_answers = merge_answers(incoming_answers, existing_answers)
content = new_answers |> Jason.encode!(pretty: true)
:ok = File.write!(file_path, content)
Logger.info("Answers written to #{file_path}")
end)
end
defp merge_answers(map, map1) do
Map.merge(map, map1, fn
_k, v1, v2 when is_map(v2) ->
merge_answers(v1, v2)
_k, _v1, v2 ->
v2
end)
end
defp answer(dir) do
if File.dir?(dir), do: answer(dir, :dir), else: answer(dir, :file)
end
defp answer(name, :file) do
[file_name | _] = String.split(name, "/") |> Enum.reverse()
answer =
case question_type(name) do
"free-form" -> "secret"
"multi-choice" -> 0
end
{file_name, answer}
end
defp answer(name, :dir) do
File.ls!(name)
|> Enum.map(fn folder ->
path = name <> "/" <> folder
if File.dir?(path) do
{folder, answer(path, :dir)}
else
answer(path, :file)
end
end)
end
defp question_type(filepath) do
content = File.read!(filepath)
header =
case String.split(content, "---") do
[header, _body] -> header
[_body] -> ""
end
case Code.eval_string(header) do
{%{type: type}, _} -> type
_ -> "multi-choice"
end
end
defp convert(value) when is_list(value) do
Enum.into(value, %{}, fn {k, v} -> {k, convert(v)} end)
end
defp convert(value) do
value
end
defp validate_directory_name([]), do: nil
defp validate_directory_name(names) do
Enum.each(names, fn name ->
unless name in @directories do
Logger.error(
"\"#{name}\" is not a valid directory, use #{@directories |> Enum.join(", ")}"
)
end
end)
end
end
| 22.135135 | 92 | 0.571429 |
9e94f8102c14069988c665b1711032026e12a12e | 9,776 | ex | Elixir | lib/vintage_net_wifi/wpa_supplicant_decoder.ex | dognotdog/vintage_net_wifi | 3e2904a46d04ae7982f53f1e471d1cd599dc5142 | [
"Apache-2.0"
] | null | null | null | lib/vintage_net_wifi/wpa_supplicant_decoder.ex | dognotdog/vintage_net_wifi | 3e2904a46d04ae7982f53f1e471d1cd599dc5142 | [
"Apache-2.0"
] | null | null | null | lib/vintage_net_wifi/wpa_supplicant_decoder.ex | dognotdog/vintage_net_wifi | 3e2904a46d04ae7982f53f1e471d1cd599dc5142 | [
"Apache-2.0"
] | null | null | null | defmodule VintageNetWiFi.WPASupplicantDecoder do
@moduledoc false
require Logger
@doc """
Decode notifications from the wpa_supplicant
"""
def decode_notification(<<"CTRL-REQ-", rest::binary>>) do
[field, net_id, text] = String.split(rest, "-", parts: 3, trim: true)
{:interactive, "CTRL-REQ-" <> field, String.to_integer(net_id), text}
end
def decode_notification(<<"CTRL-EVENT-BSS-ADDED", rest::binary>>) do
[entry_id, bssid] = String.split(rest, " ", trim: true)
{:event, "CTRL-EVENT-BSS-ADDED", String.to_integer(entry_id), bssid}
end
def decode_notification(<<"CTRL-EVENT-BSS-REMOVED", rest::binary>>) do
[entry_id, bssid] = String.split(rest, " ", trim: true)
{:event, "CTRL-EVENT-BSS-REMOVED", String.to_integer(entry_id), bssid}
end
# This message is just not shaped the same as others for some reason.
def decode_notification(<<"CTRL-EVENT-CONNECTED", rest::binary>>) do
["-", "Connection", "to", bssid, status | info] = String.split(rest)
info =
Regex.scan(~r(\w+=[a-zA-Z0-9:\"_]+), Enum.join(info, " "))
|> Map.new(fn [str] ->
[key, val] = String.split(str, "=")
{key, unescape_string(val)}
end)
{:event, "CTRL-EVENT-CONNECTED", bssid, status, info}
end
def decode_notification(<<"CTRL-EVENT-DISCONNECTED", rest::binary>>) do
decode_kv_notification("CTRL-EVENT-DISCONNECTED", rest)
end
# "CTRL-EVENT-REGDOM-CHANGE init=CORE"
def decode_notification(<<"CTRL-EVENT-REGDOM-CHANGE", rest::binary>>) do
decode_kv_notification("CTRL-EVENT-REGDOM-CHANGE", rest)
end
# "CTRL-EVENT-ASSOC-REJECT bssid=00:00:00:00:00:00 status_code=16"
def decode_notification(<<"CTRL-EVENT-ASSOC-REJECT", rest::binary>>) do
decode_kv_notification("CTRL-EVENT-ASSOC-REJECT", rest)
end
# "CTRL-EVENT-SSID-TEMP-DISABLED id=1 ssid=\"FarmbotConnect\" auth_failures=1 duration=10 reason=CONN_FAILED"
def decode_notification(<<"CTRL-EVENT-SSID-TEMP-DISABLED", rest::binary>>) do
decode_kv_notification("CTRL-EVENT-SSID-TEMP-DISABLED", rest)
end
# "CTRL-EVENT-SUBNET-STATUS-UPDATE status=0"
def decode_notification(<<"CTRL-EVENT-SUBNET-STATUS-UPDATE", rest::binary>>) do
decode_kv_notification("CTRL-EVENT-SUBNET-STATUS-UPDATE", rest)
end
# CTRL-EVENT-SSID-REENABLED id=1 ssid=\"FarmbotConnect\""
def decode_notification(<<"CTRL-EVENT-SSID-REENABLED", rest::binary>>) do
decode_kv_notification("CTRL-EVENT-SSID-REENABLED", rest)
end
# "CTRL-EVENT-EAP-PEER-CERT depth=0 subject='/C=US/ST=California/L=San Luis Obispo/O=FarmBot Inc/CN=Connor Rigby/[email protected]' hash=ae7b11dc19b0ed3497540ac551d9730fd86380b3da9d494bb27cb8f2bda8fbd6"
def decode_notification(<<"CTRL-EVENT-EAP-PEER-CERT ", rest::binary>>) do
info = eap_peer_cert_decode(rest)
{:event, "CTRL-EVENT-EAP-PEER-CERT", info}
end
def decode_notification(<<"CTRL-EVENT-EAP-STATUS", rest::binary>>) do
info =
Regex.scan(~r/\w+=(["'])(?:(?=(\\?))\2.)*?\1/, rest)
|> Map.new(fn [str | _] ->
[key, val] = String.split(str, "=", parts: 2)
{key, unquote_string(val)}
end)
{:event, "CTRL-EVENT-EAP-STATUS", info}
end
def decode_notification(<<"CTRL-EVENT-EAP-FAILURE", rest::binary>>) do
{:event, "CTRL-EVENT-EAP-FAILURE", String.trim(rest)}
end
def decode_notification(<<"CTRL-EVENT-EAP-METHOD", rest::binary>>) do
{:event, "CTRL-EVENT-EAP-METHOD", String.trim(rest)}
end
def decode_notification(<<"CTRL-EVENT-EAP-PROPOSED-METHOD", rest::binary>>) do
decode_kv_notification("CTRL-EVENT-EAP-PROPOSED-METHOD", rest)
end
def decode_notification(<<"CTRL-EVENT-", _type::binary>> = event) do
{:event, String.trim_trailing(event)}
end
def decode_notification(<<"WPS-", _type::binary>> = event) do
{:event, String.trim_trailing(event)}
end
def decode_notification(<<"AP-STA-CONNECTED ", mac::binary>>) do
{:event, "AP-STA-CONNECTED", String.trim_trailing(mac)}
end
def decode_notification(<<"AP-STA-DISCONNECTED ", mac::binary>>) do
{:event, "AP-STA-DISCONNECTED", String.trim_trailing(mac)}
end
# MESH-PEER-DISCONNECTED 00:00:00:00:00:00
def decode_notification(<<"MESH-PEER-DISCONNECTED ", mac::binary>>) do
{:event, "MESH-PEER-DISCONNECTED", String.trim_trailing(mac)}
end
# MESH-PEER-CONNECTED 00:00:00:00:00:00
def decode_notification(<<"MESH-PEER-CONNECTED ", mac::binary>>) do
{:event, "MESH-PEER-CONNECTED", String.trim_trailing(mac)}
end
# MESH-GROUP-STARTED ssid=\"my-mesh\" id=1
def decode_notification(<<"MESH-GROUP-STARTED ", rest::binary>>) do
decode_kv_notification("MESH-GROUP-STARTED", rest)
end
# MESH-GROUP-REMOVED mesh0
def decode_notification(<<"MESH-GROUP-REMOVED ", ifname::binary>>) do
{:event, "MESH-GROUP-REMOVED", String.trim_trailing(ifname)}
end
# MESH-SAE-AUTH-FAILURE addr=00:00:00:00:00:00
def decode_notification(<<"MESH-SAE-AUTH-FAILURE ", rest::binary>>) do
decode_kv_notification("MESH-SAE-AUTH-FAILURE", rest)
end
# MESH-SAE-AUTH-BLOCKED addr=00:00:00:00:00:00 duration=5
def decode_notification(<<"MESH-SAE-AUTH-BLOCKED ", rest::binary>>) do
decode_kv_notification("MESH-SAE-AUTH-BLOCKED", rest)
end
def decode_notification(string) do
{:info, String.trim_trailing(string)}
end
defp eap_peer_cert_decode(
binary,
state \\ %{key?: true, in_quote?: false, key: <<>>, value: <<>>},
acc \\ %{}
)
defp eap_peer_cert_decode(<<"=", rest::binary>>, %{key?: true} = state, acc) do
eap_peer_cert_decode(rest, %{state | key?: false}, acc)
end
defp eap_peer_cert_decode(<<"\'", rest::binary>>, %{key?: false, in_quote?: false} = state, acc) do
eap_peer_cert_decode(rest, %{state | in_quote?: true, value: state.value}, acc)
end
defp eap_peer_cert_decode(<<"\'", rest::binary>>, %{key?: false, in_quote?: true} = state, acc) do
eap_peer_cert_decode(rest, %{state | in_quote?: false, value: state.value}, acc)
end
defp eap_peer_cert_decode(<<" ", rest::binary>>, %{key?: false, in_quote?: false} = state, acc) do
eap_peer_cert_decode(
rest,
%{key?: true, in_quote?: false, key: <<>>, value: <<>>},
Map.put(acc, state.key, String.trim(state.value))
)
end
defp eap_peer_cert_decode(<<char::size(1)-binary, rest::binary>>, %{key?: true} = state, acc) do
eap_peer_cert_decode(rest, %{state | key: state.key <> char}, acc)
end
defp eap_peer_cert_decode(<<char::size(1)-binary, rest::binary>>, %{key?: false} = state, acc) do
eap_peer_cert_decode(rest, %{state | value: state.value <> char}, acc)
end
defp eap_peer_cert_decode(<<>>, state, acc) do
Map.put(acc, state.key, String.trim(state.value))
end
defp decode_kv_notification(event, rest) do
info =
Regex.scan(~r(\w+=[\S*]+), rest)
|> Map.new(fn [str] ->
str = String.replace(str, "\'", "")
[key, val] = String.split(str, "=", parts: 2)
clean_val = val |> unquote_string() |> unescape_string()
{key, clean_val}
end)
case Map.pop(info, "bssid") do
{nil, _original} -> {:event, event, info}
{bssid, new_info} -> {:event, event, bssid, new_info}
end
end
@doc """
Decode a key-value response from the wpa_supplicant
"""
@spec decode_kv_response(String.t()) :: %{String.t() => String.t()}
def decode_kv_response(resp) do
resp
|> String.split("\n", trim: true)
|> decode_kv_pairs()
end
defp decode_kv_pairs(pairs) do
Enum.reduce(pairs, %{}, fn pair, acc ->
case String.split(pair, "=", parts: 2) do
[key, value] ->
clean_value = value |> String.trim_trailing() |> unescape_string()
Map.put(acc, key, clean_value)
_ ->
# Skip
acc
end
end)
end
defp unquote_string(<<"\"", _::binary>> = msg), do: String.trim(msg, "\"")
defp unquote_string(<<"\'", _::binary>> = msg), do: String.trim(msg, "\'")
defp unquote_string(other), do: other
defp unescape_string(string) do
unescape_string(string, [])
|> Enum.reverse()
|> :erlang.list_to_binary()
end
defp unescape_string("", acc), do: acc
defp unescape_string(<<?\\, ?x, hex::binary-size(2), rest::binary>>, acc) do
value = String.to_integer(hex, 16)
unescape_string(rest, [value | acc])
end
defp unescape_string(<<other, rest::binary>>, acc) do
unescape_string(rest, [other | acc])
end
@doc """
Parse WiFi access point flags
"""
@spec parse_flags(String.t() | nil) :: [VintageNetWiFi.AccessPoint.flag()]
def parse_flags(flags) when is_binary(flags) do
flags
|> String.split(["]", "["], trim: true)
|> Enum.flat_map(&parse_flag/1)
end
def parse_flags(nil), do: []
defp parse_flag("WPA2-PSK-CCMP"), do: [:wpa2_psk_ccmp]
defp parse_flag("WPA2-EAP-CCMP"), do: [:wpa2_eap_ccmp]
defp parse_flag("WPA2-EAP-CCMP+TKIP"), do: [:wpa2_eap_ccmp_tkip]
defp parse_flag("WPA2-PSK-CCMP+TKIP"), do: [:wpa2_psk_ccmp_tkip]
defp parse_flag("WPA2-PSK+SAE-CCMP"), do: [:wpa2_psk_sae_ccmp]
defp parse_flag("WPA2-SAE-CCMP"), do: [:wpa2_sae_ccmp]
defp parse_flag("WPA2--CCMP"), do: [:wpa2_ccmp]
defp parse_flag("WPA-PSK-CCMP"), do: [:wpa_psk_ccmp]
defp parse_flag("WPA-PSK-CCMP+TKIP"), do: [:wpa_psk_ccmp_tkip]
defp parse_flag("WPA-EAP-CCMP"), do: [:wpa_eap_ccmp]
defp parse_flag("WPA-EAP-CCMP+TKIP"), do: [:wpa_eap_ccmp_tkip]
defp parse_flag("IBSS"), do: [:ibss]
defp parse_flag("MESH"), do: [:mesh]
defp parse_flag("ESS"), do: [:ess]
defp parse_flag("P2P"), do: [:p2p]
defp parse_flag("WPS"), do: [:wps]
defp parse_flag("RSN--CCMP"), do: [:rsn_ccmp]
defp parse_flag(other) do
Logger.warn("[wpa_supplicant] Unknown flag: #{inspect(other)}")
[]
end
end
| 34.666667 | 217 | 0.655381 |
9e950cd4a5acd9b4cc45b3daf9f77a88d9dcda68 | 934 | exs | Elixir | test/doumi/datetime_helper_test.exs | nallwhy/doumi | 6324c340e0ad1974000f7ce2903fc0cccfae12f4 | [
"MIT"
] | 1 | 2020-08-25T23:43:51.000Z | 2020-08-25T23:43:51.000Z | test/doumi/datetime_helper_test.exs | nallwhy/doumi | 6324c340e0ad1974000f7ce2903fc0cccfae12f4 | [
"MIT"
] | null | null | null | test/doumi/datetime_helper_test.exs | nallwhy/doumi | 6324c340e0ad1974000f7ce2903fc0cccfae12f4 | [
"MIT"
] | null | null | null | defmodule Doumi.DateTimeHelperTest do
use ExUnit.Case, async: true
alias Doumi.DateTimeHelper
test "now_s/0 returns current datetime with second precision" do
assert %{microsecond: {_, 0}} = DateTimeHelper.now_s()
end
test "now_ms/0 returns current datetime with millisecond precision" do
assert %{microsecond: {_, 3}} = DateTimeHelper.now_ms()
end
test "now_us/0 returns current datetime with microsecond precision" do
assert %{microsecond: {_, 6}} = DateTimeHelper.now_us()
end
test "to_unix/1" do
now = DateTime.utc_now()
assert DateTimeHelper.to_unix(now) == DateTime.to_unix(now, :millisecond)
end
test "from_unix/1" do
now_unix = DateTime.utc_now() |> DateTime.to_unix(:millisecond)
{:ok, datetime0} = DateTimeHelper.from_unix(now_unix)
{:ok, datetime1} = DateTime.from_unix(now_unix, :millisecond)
assert DateTime.compare(datetime0, datetime1) == :eq
end
end
| 29.1875 | 77 | 0.718415 |
9e952e98fd37d112019a2130894304f8ff0cf5fb | 6,585 | ex | Elixir | apps/core/test/support/ops_factories/medication_request_factory.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 8 | 2019-06-14T11:34:49.000Z | 2021-08-05T19:14:24.000Z | apps/core/test/support/ops_factories/medication_request_factory.ex | edenlabllc/ehealth.api.public | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 1 | 2019-07-08T15:20:22.000Z | 2019-07-08T15:20:22.000Z | apps/core/test/support/ops_factories/medication_request_factory.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 6 | 2018-05-11T13:59:32.000Z | 2022-01-19T20:15:22.000Z | defmodule Core.OPSFactories.MedicationRequestFactory do
@moduledoc false
alias Ecto.UUID
defmacro __using__(_opts) do
quote do
def medication_request_factory do
%{
id: UUID.generate(),
status: "ACTIVE",
inserted_by: UUID.generate(),
updated_by: UUID.generate(),
is_active: true,
person_id: UUID.generate(),
employee_id: UUID.generate(),
division_id: UUID.generate(),
medication_id: UUID.generate(),
created_at: NaiveDateTime.utc_now() |> NaiveDateTime.to_date(),
started_at: NaiveDateTime.utc_now() |> NaiveDateTime.to_date(),
ended_at: NaiveDateTime.utc_now() |> NaiveDateTime.to_date(),
dispense_valid_from: Date.utc_today(),
dispense_valid_to: Date.utc_today(),
medical_program_id: UUID.generate(),
medication_qty: 0,
medication_request_requests_id: UUID.generate(),
request_number: to_string(:rand.uniform()),
legal_entity_id: UUID.generate(),
inserted_at: NaiveDateTime.utc_now(),
updated_at: NaiveDateTime.utc_now(),
verification_code: "",
rejected_at: nil,
rejected_by: nil,
reject_reason: nil,
intent: "order",
category: "community",
context: build(:medical_events_context),
dosage_instruction: medical_events_dosage_instruction()
}
end
def medical_events_context_factory do
%{
identifier: %{
type: %{
coding: [
%{
system: "eHealth/resources",
code: "encounter"
}
]
},
value: UUID.generate()
}
}
end
defp medical_events_dosage_instruction do
[
%{
"sequence" => 1,
"text" =>
"0.25mg PO every 6-12 hours as needed for menses from Jan 15-20, 2015. Do not exceed more than 4mg per day",
"additional_instruction" => [
%{
"coding" => [
%{
"system" => "eHealth/SNOMED/additional_dosage_instructions",
"code" => "311504000"
}
]
}
],
"patient_instruction" =>
"0.25mg PO every 6-12 hours as needed for menses from Jan 15-20, 2015. Do not exceed more than 4mg per day",
"timing" => %{
"event" => [
"2017-04-20T19:14:13Z"
],
"repeat" => %{
"bounds_duration" => %{
"value" => 10,
"unit" => "days",
"system" => "eHealth/ucum/units",
"code" => "d"
},
"count" => 2,
"count_max" => 4,
"duration" => 4,
"duration_max" => 6,
"duration_unit" => "d",
"frequency" => 1,
"frequency_max" => 2,
"period" => 4,
"period_max" => 6,
"period_unit" => "d",
"day_of_week" => [
"mon"
],
"time_of_day" => [
"2017-04-20T19:14:13Z"
],
"when" => [
"WAKE"
],
"offset" => 4
},
"code" => %{
"coding" => [
%{
"system" => "TIMING_ABBREVIATION",
"code" => "patient"
}
]
}
},
"as_needed_boolean" => true,
"site" => %{
"coding" => [
%{
"system" => "eHealth/SNOMED/anatomical_structure_administration_site_codes",
"code" => "344001"
}
]
},
"route" => %{
"coding" => [
%{
"system" => "eHealth/SNOMED/route_codes",
"code" => "46713006"
}
]
},
"method" => %{
"coding" => [
%{
"system" => "eHealth/SNOMED/administration_methods",
"code" => "419747000"
}
]
},
"dose_and_rate" => %{
"type" => %{
"coding" => [
%{
"system" => "eHealth/dose_and_rate",
"code" => "'ordered'"
}
]
},
"dose_range" => %{
"low" => %{
"value" => 13,
"unit" => "mg",
"system" => "eHealth/ucum/units",
"code" => "mg"
},
"high" => %{
"value" => 13,
"unit" => "mg",
"system" => "eHealth/ucum/units",
"code" => "mg"
}
},
"rate_ratio" => %{
"numerator" => %{
"value" => 13,
"unit" => "mg",
"system" => "eHealth/ucum/units",
"code" => "mg"
},
"denominator" => %{
"value" => 13,
"unit" => "mg",
"system" => "eHealth/ucum/units",
"code" => "mg"
}
}
},
"max_dose_per_period" => %{
"numerator" => %{
"value" => 13,
"unit" => "mg",
"system" => "eHealth/ucum/units",
"code" => "mg"
},
"denominator" => %{
"value" => 13,
"unit" => "mg",
"system" => "eHealth/ucum/units",
"code" => "mg"
}
},
"max_dose_per_administration" => %{
"value" => 13,
"unit" => "mg",
"system" => "eHealth/ucum/units",
"code" => "mg"
},
"max_dose_per_lifetime" => %{
"value" => 13,
"unit" => "mg",
"system" => "eHealth/ucum/units",
"code" => "mg"
}
}
]
end
end
end
end
| 31.061321 | 123 | 0.364465 |
9e9531cb7127e8a86bc61e88e34ace7d18981a29 | 1,899 | ex | Elixir | apps/meeple_web/lib/meeple_web/live/board_live/map.ex | grrrisu/meeple | 428762a58a94306a6643b09c08d72fb2883a0309 | [
"MIT"
] | null | null | null | apps/meeple_web/lib/meeple_web/live/board_live/map.ex | grrrisu/meeple | 428762a58a94306a6643b09c08d72fb2883a0309 | [
"MIT"
] | 13 | 2021-12-24T23:44:10.000Z | 2022-03-04T20:56:28.000Z | apps/meeple_web/lib/meeple_web/live/board_live/map.ex | grrrisu/meeple | 428762a58a94306a6643b09c08d72fb2883a0309 | [
"MIT"
] | null | null | null | defmodule MeepleWeb.BoardLive.Map do
use MeepleWeb, :live_component
require Logger
alias Meeple.Board
alias MeepleWeb.BoardLive.{Field, FieldCard}
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign_dimensions()
|> assign(
field_detail: nil,
detail_x: 0,
detail_y: 0
)}
end
def render(assigns) do
~H"""
<div id="map"
class="grid place-content-center relative border-t border-l border-b-2 border-r-2 border-gray-900"
style={css_grid_template(@width, @height)}>
<%= for field <- @fields do %>
<Field.field field={field} target={@myself} />
<% end %>
<.pawns pawns={@pawns} width={@width} height={@height}/>
<.live_component module={FieldCard} id="field-card" field={@field_detail} x={@detail_x} y={@detail_y} pawn={@selected_pawn}/>
</div>
"""
end
def css_grid_template(width, height) do
"grid-template-columns: repeat(#{width}, 75px); grid-template-rows: repeat(#{height}, 75px)"
end
def pawn_x(x), do: x * 75
def pawn_y(y, height), do: (height - 1 - y) * 75
def pawns(assigns) do
~H"""
<%= for pawn <- @pawns do %>
<div
class="absolute m-3 transition-position duration-[1000ms]"
style={"width: 25px; height: 25px; top: #{pawn_y(pawn.y, @height)}px; left: #{pawn_x(pawn.x)}px "}>
<img src="/images/ui/human_token.svg" class="w-full"/>
</div>
<% end %>
"""
end
def handle_event("show", %{"x" => x, "y" => y}, socket) do
Logger.debug("show [#{x}, #{y}]")
field = Board.get_field(x, y, socket.assigns.fog_of_war)
{:noreply,
assign(socket,
field_detail: field,
detail_x: x,
detail_y: y
)}
end
defp assign_dimensions(socket) do
{width, height} = Board.map_dimensions()
assign(socket, width: width, height: height)
end
end
| 27.128571 | 131 | 0.598736 |
9e954746f04cf0710846936ba8882b244d35984d | 333 | exs | Elixir | priv/repo/migrations/20160318123924_add_login_logs.exs | van-mronov/ex_money | 39010f02fd822657e3b5694e08b872bd2ab72c26 | [
"0BSD"
] | 184 | 2015-11-23T20:51:50.000Z | 2022-03-30T01:01:39.000Z | priv/repo/migrations/20160318123924_add_login_logs.exs | van-mronov/ex_money | 39010f02fd822657e3b5694e08b872bd2ab72c26 | [
"0BSD"
] | 15 | 2015-11-26T16:00:20.000Z | 2018-05-25T20:13:39.000Z | priv/repo/migrations/20160318123924_add_login_logs.exs | van-mronov/ex_money | 39010f02fd822657e3b5694e08b872bd2ab72c26 | [
"0BSD"
] | 21 | 2015-11-26T21:34:40.000Z | 2022-03-26T02:56:42.000Z | defmodule ExMoney.Repo.Migrations.AddLoginLogs do
use Ecto.Migration
def change do
create table(:login_logs) do
add :login_id, references(:logins, on_delete: :delete_all)
add :callback, :string
add :event, :string
add :description, :string
add :params, :map
timestamps
end
end
end
| 20.8125 | 64 | 0.666667 |
9e95714d04190b8bfa707913186492f1d99dfd01 | 278 | ex | Elixir | example/lib/kantele/character/views/registration_view.ex | fugufish/kalevala | 34d9e63fac0e51ae5c0f40da340c9f3eaaed6b94 | [
"MIT"
] | 125 | 2020-02-09T17:05:27.000Z | 2022-03-31T03:31:00.000Z | example/lib/kantele/character/views/registration_view.ex | fugufish/kalevala | 34d9e63fac0e51ae5c0f40da340c9f3eaaed6b94 | [
"MIT"
] | 19 | 2020-02-20T02:36:38.000Z | 2021-08-03T16:24:19.000Z | example/lib/kantele/character/views/registration_view.ex | fugufish/kalevala | 34d9e63fac0e51ae5c0f40da340c9f3eaaed6b94 | [
"MIT"
] | 8 | 2020-04-07T05:06:20.000Z | 2021-11-20T06:43:14.000Z | defmodule Kantele.Character.RegistrationView do
use Kalevala.Character.View
alias Kalevala.Character.Conn.EventText
def render("password", _assigns) do
%EventText{
topic: "Registration.PromptPassword",
data: %{},
text: "Password: "
}
end
end
| 19.857143 | 47 | 0.68705 |
9e95998e172a4de71314132090754008f5339902 | 53 | ex | Elixir | lib/phoenix_inline_svg.ex | sparta-developers/phoenix_inline_svg | abb6484e7efc12fff87a0cca7df15aa0e2857702 | [
"MIT"
] | 58 | 2016-07-19T13:45:57.000Z | 2022-03-04T15:45:35.000Z | lib/phoenix_inline_svg.ex | sparta-developers/phoenix_inline_svg | abb6484e7efc12fff87a0cca7df15aa0e2857702 | [
"MIT"
] | 44 | 2016-07-20T22:27:03.000Z | 2021-05-06T22:06:28.000Z | lib/phoenix_inline_svg.ex | sparta-developers/phoenix_inline_svg | abb6484e7efc12fff87a0cca7df15aa0e2857702 | [
"MIT"
] | 33 | 2017-01-27T20:15:25.000Z | 2022-03-02T16:32:07.000Z | defmodule PhoenixInlineSvg do
@moduledoc false
end
| 13.25 | 29 | 0.830189 |
9e959f9c54992a49825fd9bd5bbb515b9fe9fa15 | 2,054 | ex | Elixir | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1beta1_workload_fedramp_high_settings.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1beta1_workload_fedramp_high_settings.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1beta1_workload_fedramp_high_settings.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.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1WorkloadFedrampHighSettings do
@moduledoc """
Settings specific to resources needed for FedRAMP High.
## Attributes
* `kmsSettings` (*type:* `GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1WorkloadKMSSettings.t`, *default:* `nil`) - Required. Input only. Immutable. Settings used to create a CMEK crypto key.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kmsSettings =>
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1WorkloadKMSSettings.t()
| nil
}
field(:kmsSettings,
as:
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1WorkloadKMSSettings
)
end
defimpl Poison.Decoder,
for:
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1WorkloadFedrampHighSettings do
def decode(value, options) do
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1WorkloadFedrampHighSettings.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1WorkloadFedrampHighSettings do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.813559 | 224 | 0.772152 |
9e95afe6d3a9455fd91537725e1421d5b351b94a | 923 | ex | Elixir | lib/extensions/persistent_session/plug.ex | randaalex/pow | 2a8c8db4652f7cb2c58d3a897e02b1d47e76f27b | [
"MIT"
] | 1 | 2021-06-25T10:36:01.000Z | 2021-06-25T10:36:01.000Z | lib/extensions/persistent_session/plug.ex | randaalex/pow | 2a8c8db4652f7cb2c58d3a897e02b1d47e76f27b | [
"MIT"
] | null | null | null | lib/extensions/persistent_session/plug.ex | randaalex/pow | 2a8c8db4652f7cb2c58d3a897e02b1d47e76f27b | [
"MIT"
] | 1 | 2020-07-13T01:11:17.000Z | 2020-07-13T01:11:17.000Z | defmodule PowPersistentSession.Plug do
@moduledoc """
Plug helper methods.
"""
alias Plug.Conn
alias Pow.Config
@doc """
Create a new persistent session in the connection for user.
"""
@spec create(Conn.t(), map()) :: Conn.t()
def create(conn, user) do
{plug, config} = pow_persistent_session(conn)
plug.create(conn, user, config)
end
@doc """
Deletes the persistent session in the connection.
"""
@spec delete(Conn.t()) :: Conn.t()
def delete(conn) do
{plug, config} = pow_persistent_session(conn)
plug.delete(conn, config)
end
defp pow_persistent_session(conn) do
conn.private[:pow_persistent_session] || raise_no_plug_error()
end
@spec raise_no_plug_error :: no_return
defp raise_no_plug_error do
Config.raise_error("PowPersistentSession plug module not installed. Please add the PowPersistentSession.Plug.Cookie plug to your endpoint.")
end
end
| 24.945946 | 144 | 0.707476 |
9e95f152b8a928c557d6048ef626c3cb52460a1d | 55 | ex | Elixir | web/views/user_view.ex | tedstrauss/sonar | 65de7a9a78eae9fd4e02f5abdf00f9fdec19b081 | [
"MIT"
] | 1 | 2020-07-17T14:02:31.000Z | 2020-07-17T14:02:31.000Z | web/views/user_view.ex | tedstrauss/sonar | 65de7a9a78eae9fd4e02f5abdf00f9fdec19b081 | [
"MIT"
] | null | null | null | web/views/user_view.ex | tedstrauss/sonar | 65de7a9a78eae9fd4e02f5abdf00f9fdec19b081 | [
"MIT"
] | 1 | 2019-12-02T17:51:36.000Z | 2019-12-02T17:51:36.000Z | defmodule Sonar.UserView do
use Sonar.Web, :view
end
| 13.75 | 27 | 0.763636 |
9e95fce30b8d713ff1e95dc947a482738f9f36da | 1,869 | ex | Elixir | lib/happy_with.ex | CrowdHailer/happy_with | e3cf8fd58af1ff99d9279a1e2e4b511cfb1c22a1 | [
"Apache-2.0"
] | 29 | 2016-09-25T21:32:29.000Z | 2021-02-12T15:19:01.000Z | lib/happy_with.ex | CrowdHailer/happy_with | e3cf8fd58af1ff99d9279a1e2e4b511cfb1c22a1 | [
"Apache-2.0"
] | 3 | 2017-01-18T09:06:37.000Z | 2018-04-15T17:52:21.000Z | lib/happy_with.ex | CrowdHailer/happy_with | e3cf8fd58af1ff99d9279a1e2e4b511cfb1c22a1 | [
"Apache-2.0"
] | 3 | 2017-02-08T09:12:30.000Z | 2017-12-14T08:20:25.000Z | defmodule HappyWith do
@doc ~S"""
Rewrites the given block and else clauses into Elixir's standard `with` form.
iex> import HappyWith
iex> happy_with do
...> {:ok, name} <- {:ok, "joSE"}
...> lower = String.downcase(name)
...> lower
...> end
"jose"
You can also provide else clauses to the `with` form.
iex> import HappyWith
iex> happy_with do
...> {:ok, name} <- {:error, :nobody}
...> _never_reached = String.downcase(name)
...> else
...> {:error, _} -> "luis"
...> end
"luis"
You can also use tags a feature from the [happy](http://github.com/vic/happy) project.
iex> import HappyWith
iex> happy_with do
...> @something {:ok, name} when is_binary(name) and length(name) > 3 <- {:error, :nobody}
...> _never_reached = String.downcase(name)
...> else
...> {:something, {:error, _}} -> "could not fetch name"
...> end
"could not fetch name"
"""
defmacro happy_with([do: {:__block__, _, body}, else: elses]), do: rewrite(body, elses)
defmacro happy_with([do: {:__block__, _, body}]), do: rewrite(body, nil)
defp rewrite(body, elses) when length(body) > 1 do
exprs = Enum.slice(body, 0..-2) |> rewrite_tags
do_last = [do: Enum.at(body, -1)]
else_clauses = elses && [else: elses] || []
{:with, [], exprs ++ [do_last ++ else_clauses]}
end
defp rewrite(body, _elses), do: body
defp rewrite_tags(exprs) do
exprs |> Enum.map(fn
{:@, _, [{name, _, [{:<-, _, [{:when, _, [pattern, guard]}, expr]}]}]} when is_atom(name) ->
{:<-, [], [{:when, [], [{name, pattern}, guard]}, {name, expr}]}
{:@, _, [{name, _, [{:<-, _, [pattern, expr]}]}]} when is_atom(name) ->
{:<-, [], [{name, pattern}, {name, expr}]}
expr -> expr
end)
end
end
| 31.15 | 98 | 0.542536 |
9e96001d82ec807893e99a26ba8c1ec045026790 | 1,016 | ex | Elixir | lib/phx_api/application.ex | trevligare/phx_api | ea622cfe15b2c3248374a70aaa65edca53cc3171 | [
"MIT"
] | null | null | null | lib/phx_api/application.ex | trevligare/phx_api | ea622cfe15b2c3248374a70aaa65edca53cc3171 | [
"MIT"
] | null | null | null | lib/phx_api/application.ex | trevligare/phx_api | ea622cfe15b2c3248374a70aaa65edca53cc3171 | [
"MIT"
] | null | null | null | defmodule PhxApi.Application do
use Application
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec
# Define workers and child supervisors to be supervised
children = [
# Start the Ecto repository
supervisor(PhxApi.Repo, []),
# Start the endpoint when the application starts
supervisor(PhxApiWeb.Endpoint, []),
# Start your own worker by calling: PhxApi.Worker.start_link(arg1, arg2, arg3)
# worker(PhxApi.Worker, [arg1, arg2, arg3]),
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: PhxApi.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
PhxApiWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 31.75 | 84 | 0.711614 |
9e9633885f0bbdda9201f6a2ab24686bc8e054b3 | 532 | ex | Elixir | lib/epi_locator_web/plugs/put_request_id_on_session.ex | RatioPBC/epi-locator | 58c90500c4e0071ce365d76ec9812f9051d6a9f9 | [
"Apache-2.0"
] | null | null | null | lib/epi_locator_web/plugs/put_request_id_on_session.ex | RatioPBC/epi-locator | 58c90500c4e0071ce365d76ec9812f9051d6a9f9 | [
"Apache-2.0"
] | 6 | 2021-10-19T01:55:57.000Z | 2022-02-15T01:04:19.000Z | lib/epi_locator_web/plugs/put_request_id_on_session.ex | RatioPBC/epi-locator | 58c90500c4e0071ce365d76ec9812f9051d6a9f9 | [
"Apache-2.0"
] | 2 | 2022-01-21T08:38:50.000Z | 2022-01-21T08:42:04.000Z | defmodule EpiLocatorWeb.Plugs.PutRequestIdOnSession do
@moduledoc """
Plug that puts the request_id on the session.
This is done so that a liveview can read the request_id value regardless of
whether it's disconnected, i.e., a regular stateless connection, or connected,
i.e., a websocket connection.
"""
import Plug.Conn
def init(default), do: default
@spec call(Plug.Conn.t(), any) :: Plug.Conn.t()
def call(conn, _default) do
conn |> put_session(:request_id, Logger.metadata()[:request_id])
end
end
| 28 | 80 | 0.721805 |
9e96459223ff3e09f07416fa6036497016587fb1 | 1,294 | exs | Elixir | elixir/change/change_test.exs | macborowy/exercism | c5d45e074e81b946a82a340b2730e0d2732b7e0a | [
"MIT"
] | null | null | null | elixir/change/change_test.exs | macborowy/exercism | c5d45e074e81b946a82a340b2730e0d2732b7e0a | [
"MIT"
] | null | null | null | elixir/change/change_test.exs | macborowy/exercism | c5d45e074e81b946a82a340b2730e0d2732b7e0a | [
"MIT"
] | null | null | null | if !System.get_env("EXERCISM_TEST_EXAMPLES") do
Code.load_file("change.exs")
end
ExUnit.start
ExUnit.configure exclude: :pending, trace: true
defmodule ChangeTest do
use ExUnit.Case
test "returns :error on empty list" do
assert Change.generate(1, []) == :error
end
# @tag :pending
test "generates the correct change when only one coin type is needed" do
change = %{1 => 5, 10 => 0}
assert Change.generate(5, [1, 10]) == {:ok, change}
end
# @tag :pending
test "generates the correct change when multiple coin types are needed" do
change = %{1 => 3, 5 => 1, 10 => 1}
assert Change.generate(18, [1, 5, 10]) == {:ok, change}
end
# @tag :pending
test "returns :error when it is not possible to generate change" do
assert Change.generate(3, [5, 10, 25]) == :error
end
# @tag :pending
test "generates the same change given any coin order" do
change = %{1 => 3, 5 => 1, 10 => 1}
assert Change.generate(18, [1, 5, 10]) == {:ok, change}
assert Change.generate(18, [10, 5, 1]) == {:ok, change}
end
# @tag :pending
test "generates the correct change for large values with many coins" do
change = %{1 => 3, 5 => 1, 10 => 0, 25 => 1, 100 => 1}
assert Change.generate(133, [1, 5, 10, 25, 100]) == {:ok, change}
end
end
| 28.755556 | 76 | 0.625966 |
9e9672a5eb0ae249b9b692446d358a8c6ab79a9a | 2,263 | ex | Elixir | apps/admin_app/lib/admin_app_web.ex | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | 1 | 2021-04-08T22:29:19.000Z | 2021-04-08T22:29:19.000Z | apps/admin_app/lib/admin_app_web.ex | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | null | null | null | apps/admin_app/lib/admin_app_web.ex | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | null | null | null | defmodule AdminAppWeb 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 AdminAppWeb, :controller
use AdminAppWeb, :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, log: false, namespace: AdminAppWeb
import Plug.Conn
import AdminAppWeb.Gettext
alias AdminAppWeb.Router.Helpers, as: Routes
def action(conn, _) do
args = [conn, conn.params]
controller = conn.private.phoenix_controller
action = conn.private.phoenix_action
actions = controller.module_info(:exports) |> Keyword.keys()
case Enum.member?(actions, action) do
true ->
apply(__MODULE__, action_name(conn), args)
false ->
conn |> render(AdminAppWeb.ErrorView, "404.html") |> halt
end
end
end
end
def view do
quote do
use Phoenix.View,
root: "lib/admin_app_web/templates",
namespace: AdminAppWeb
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_flash: 2, view_module: 1]
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
import AdminAppWeb.ErrorHelpers
import AdminAppWeb.Gettext
import AdminAppWeb.InputHelpers
import AdminAppWeb.PaginationHelpers
import AdminAppWeb.DataHelpers
alias AdminAppWeb.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, log_join: false, log_handle_in: false
import AdminAppWeb.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
| 25.426966 | 69 | 0.673884 |
9e9679198da896a27da377ccd52efc0688876b74 | 3,333 | exs | Elixir | test/advisory_locks_test.exs | LeartS/eventstore | f0431bfefcaa1a6fa8251eb6dd0ae8def1d82961 | [
"MIT"
] | null | null | null | test/advisory_locks_test.exs | LeartS/eventstore | f0431bfefcaa1a6fa8251eb6dd0ae8def1d82961 | [
"MIT"
] | null | null | null | test/advisory_locks_test.exs | LeartS/eventstore | f0431bfefcaa1a6fa8251eb6dd0ae8def1d82961 | [
"MIT"
] | null | null | null | defmodule EventStore.AdvisoryLocksTest do
use EventStore.StorageCase
alias EventStore.{AdvisoryLocks, Config, Wait}
alias EventStore.Storage
@locks TestEventStore.EventStore.AdvisoryLocks
@conn TestEventStore.EventStore.AdvisoryLocks.Postgrex
setup do
postgrex_config = Config.parsed(TestEventStore, :eventstore) |> Config.default_postgrex_opts()
conn = start_supervised!({Postgrex, postgrex_config})
[conn: conn]
end
describe "acquire lock" do
test "should acquire lock when available" do
assert {:ok, lock} = AdvisoryLocks.try_advisory_lock(@locks, 1)
assert is_reference(lock)
end
test "should acquire lock when same process already has lock" do
assert {:ok, lock1} = AdvisoryLocks.try_advisory_lock(@locks, 1)
assert {:ok, lock2} = AdvisoryLocks.try_advisory_lock(@locks, 1)
assert {:ok, lock3} = AdvisoryLocks.try_advisory_lock(@locks, 1)
assert is_reference(lock1)
assert is_reference(lock2)
assert is_reference(lock3)
end
test "should fail to acquire lock when already taken", %{conn: conn, schema: schema} do
:ok = Storage.Lock.try_acquire_exclusive_lock(conn, 1, schema: schema)
assert {:error, :lock_already_taken} = AdvisoryLocks.try_advisory_lock(@locks, 1)
end
end
describe "release lock" do
test "should release lock when process terminates", %{conn: conn, schema: schema} do
reply_to = self()
pid =
spawn_link(fn ->
{:ok, _lock} = AdvisoryLocks.try_advisory_lock(@locks, 1)
send(reply_to, :lock_acquired)
# Wait until shutdown
receive do
:shutdown -> :ok
end
end)
assert_receive :lock_acquired
assert {:error, :lock_already_taken} =
Storage.Lock.try_acquire_exclusive_lock(conn, 1, schema: schema)
send(pid, :shutdown)
# Wait for lock to be released after process terminates
Wait.until(fn ->
assert :ok = Storage.Lock.try_acquire_exclusive_lock(conn, 1, schema: schema)
end)
end
end
describe "disconnect" do
test "should send `lock_released` message" do
{:ok, lock} = AdvisoryLocks.try_advisory_lock(@locks, 1)
connection_down()
assert_receive({AdvisoryLocks, :lock_released, ^lock, :shutdown})
end
end
describe "acquire same lock on different schemas" do
setup do
postgrex_config = Config.parsed(TestEventStore, :eventstore)
public_schema =
postgrex_config
|> Keyword.put(:schema, "public")
|> Config.default_postgrex_opts()
conn1 = start_supervised!({Postgrex, public_schema}, id: :conn1)
example_schema =
postgrex_config
|> Keyword.put(:schema, "example")
|> Config.default_postgrex_opts()
conn2 = start_supervised!({Postgrex, example_schema}, id: :conn2)
[conn1: conn1, conn2: conn2, schema1: "public", schema2: "example"]
end
test "should acquire lock", %{conn1: conn1, conn2: conn2, schema1: schema1, schema2: schema2} do
:ok = Storage.Lock.try_acquire_exclusive_lock(conn1, 1, schema: schema1)
:ok = Storage.Lock.try_acquire_exclusive_lock(conn2, 1, schema: schema2)
end
end
defp connection_down do
send(@locks, {:DOWN, @conn, nil, :shutdown})
end
end
| 29.495575 | 100 | 0.673267 |
9e9692218f60d4d98a4bc1d5defa928f5d1e39f7 | 504 | exs | Elixir | test/type_test.exs | PokemonTCG/pokemon-tcg-sdk-elixir | f8866044f4a5439408e04b7a68e893a8bbc1712c | [
"MIT"
] | 7 | 2016-09-01T14:33:45.000Z | 2021-10-01T03:42:06.000Z | test/type_test.exs | PokemonTCG/pokemon-tcg-sdk-elixir | f8866044f4a5439408e04b7a68e893a8bbc1712c | [
"MIT"
] | 1 | 2016-09-06T02:03:22.000Z | 2016-09-08T01:03:11.000Z | test/type_test.exs | PokemonTCG/pokemon-tcg-sdk-elixir | f8866044f4a5439408e04b7a68e893a8bbc1712c | [
"MIT"
] | 3 | 2017-11-21T16:01:51.000Z | 2021-10-01T03:42:07.000Z | defmodule Pokemon.TypeTest do
use ExUnit.Case
use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney
setup_all do
ExVCR.Config.cassette_library_dir("fixture/vcr_cassettes", "fixture/custom_cassettes")
end
test "resource returns types" do
assert Pokemon.Type.resource === "types"
end
test "test_all_returns_all_types" do
use_cassette "all_types" do
types = Pokemon.Type.all
assert Enum.count(types) > 5
assert Enum.member?(types, "Water") === true
end
end
end
| 24 | 90 | 0.710317 |
9e96bd58590eae7fcdf1b2ac7a6ccadc348146dc | 67 | ex | Elixir | lib/peepchat/repo.ex | nihonjinrxs/peep-stack-tutorial-app | 8c10b2b589d645ba5a3e31f86754828579e139c9 | [
"MIT"
] | 1 | 2020-12-23T18:28:54.000Z | 2020-12-23T18:28:54.000Z | lib/peepchat/repo.ex | AbdullahDahmash/peep-stack-api-tutorial | 3e6d98be33fbee0ae79022e6a74940e0ea70cc96 | [
"MIT"
] | null | null | null | lib/peepchat/repo.ex | AbdullahDahmash/peep-stack-api-tutorial | 3e6d98be33fbee0ae79022e6a74940e0ea70cc96 | [
"MIT"
] | null | null | null | defmodule Peepchat.Repo do
use Ecto.Repo, otp_app: :peepchat
end
| 16.75 | 35 | 0.776119 |
9e96c69505008acb817e2cdb01b209cf602ea807 | 2,407 | exs | Elixir | mix.exs | polvalente/joken | bccf3c6d203afd3611437af8369b2b87a5be24a0 | [
"Apache-2.0"
] | null | null | null | mix.exs | polvalente/joken | bccf3c6d203afd3611437af8369b2b87a5be24a0 | [
"Apache-2.0"
] | null | null | null | mix.exs | polvalente/joken | bccf3c6d203afd3611437af8369b2b87a5be24a0 | [
"Apache-2.0"
] | null | null | null | defmodule Joken.Mixfile do
use Mix.Project
@version "2.1.0"
def project do
[
app: :joken,
version: @version,
name: "Joken",
elixir: "~> 1.5",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
consolidate_protocols: Mix.env() != :test,
description: description(),
package: package(),
deps: deps(),
source_ref: "v#{@version}",
source_url: "https://github.com/joken-elixir/joken",
docs: docs_config(),
dialyzer: [plt_add_deps: :apps_direct, plt_add_apps: [:jason]],
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
]
]
end
def application do
[
extra_applications: [:logger, :crypto]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp deps do
[
{:jose, "~> 1.9"},
{:jason, "~> 1.1", only: [:dev, :test]},
{:benchee, "~> 1.0", only: :dev},
# Docs
{:ex_doc, "~> 0.19", only: :dev, runtime: false},
# Dialyzer
{:dialyxir, "~> 1.0.0-rc4", only: :dev, runtime: false},
# Credo
{:credo, "~> 1.0", only: [:dev, :test], runtime: false},
# Test
{:junit_formatter, "~> 3.0", only: :test},
{:stream_data, "~> 0.4", only: :test},
{:excoveralls, "~> 0.10", only: :test}
]
end
defp description do
"""
JWT (JSON Web Token) library for Elixir
"""
end
defp package do
[
files: ["lib", "mix.exs", "README.md", "LICENSE.txt", "CHANGELOG.md"],
maintainers: ["Bryan Joseph", "Victor Nascimento"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/joken-elixir/joken",
"Docs" => "http://hexdocs.pm/joken"
}
]
end
defp docs_config do
[
extra_section: "GUIDES",
extras: [
"guides/introduction.md",
"guides/configuration.md",
"guides/signer.md",
"guides/assymetric_cryptography_signers.md",
"guides/testing.md",
"guides/common_use_cases.md",
"guides/migration_from_1.md",
"guides/custom_header_arguments.md",
{"CHANGELOG.md", [title: "Changelog"]}
],
main: "introduction"
]
end
end
| 24.313131 | 76 | 0.544246 |
9e96ec3899932c1f10eab91b15d4b21c544d1296 | 91 | exs | Elixir | apps/nerves_hub_device/test/nerves_hub_device_web/channels/device_channel_test.exs | Gazler/nerves_hub_web | 9a636a17310382819eaa6cee590e053cb47f0dcc | [
"Apache-2.0"
] | 1 | 2020-08-04T14:13:24.000Z | 2020-08-04T14:13:24.000Z | apps/nerves_hub_device/test/nerves_hub_device_web/channels/device_channel_test.exs | Eaftos/nerves_hub_web | ac03bd044b97265bf3ba3edd8da249d300fa3668 | [
"Apache-2.0"
] | 1 | 2020-09-08T15:15:50.000Z | 2020-09-08T16:13:28.000Z | apps/nerves_hub_device/test/nerves_hub_device_web/channels/device_channel_test.exs | Eaftos/nerves_hub_web | ac03bd044b97265bf3ba3edd8da249d300fa3668 | [
"Apache-2.0"
] | null | null | null | defmodule NervesHubDeviceWeb.DeviceChannelTest do
use NervesHubDeviceWeb.ChannelCase
end
| 22.75 | 49 | 0.89011 |
9e96f78191f430455564aeeef4392d6766659f31 | 995 | exs | Elixir | test/get_trail_status_test.exs | fmcgeough/ex_aws_cloud_trail | 30346e5c11acf9dc5d133635b8025fe659e9f957 | [
"MIT"
] | null | null | null | test/get_trail_status_test.exs | fmcgeough/ex_aws_cloud_trail | 30346e5c11acf9dc5d133635b8025fe659e9f957 | [
"MIT"
] | null | null | null | test/get_trail_status_test.exs | fmcgeough/ex_aws_cloud_trail | 30346e5c11acf9dc5d133635b8025fe659e9f957 | [
"MIT"
] | null | null | null | defmodule GetTrailStatusTest do
use ExUnit.Case
# Returned data from get_trail_status looks like this:
#
# {:ok,
# %{
# "IsLogging" => true,
# "LatestDeliveryAttemptSucceeded" => "2019-01-28T19:56:09Z",
# "LatestDeliveryAttemptTime" => "2019-01-28T19:56:09Z",
# "LatestDeliveryTime" => 1548705369.96,
# "LatestNotificationAttemptSucceeded" => "",
# "LatestNotificationAttemptTime" => "",
# "StartLoggingTime" => 1442928080.135,
# "StopLoggingTime" => 1442928012.831,
# "TimeLoggingStarted" => "2015-09-22T13:21:20Z",
# "TimeLoggingStopped" => "2015-09-22T13:20:12Z"
# }}
test "normal op" do
arn = "arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail"
op = ExAws.CloudTrail.get_trail_status(arn)
assert op.headers == [
{"x-amz-target", "CloudTrail_20131101.GetTrailStatus"},
{"content-type", "application/x-amz-json-1.1"}
]
assert op.data == %{"Name" => arn}
end
end
| 31.09375 | 68 | 0.625126 |
9e972f31681bc62bf7165d0bdb68b145f29c01b6 | 1,900 | ex | Elixir | clients/my_business_verifications/lib/google_api/my_business_verifications/v1/model/email_verification_data.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/my_business_verifications/lib/google_api/my_business_verifications/v1/model/email_verification_data.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/my_business_verifications/lib/google_api/my_business_verifications/v1/model/email_verification_data.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.MyBusinessVerifications.V1.Model.EmailVerificationData do
@moduledoc """
Display data for verifications through email.
## Attributes
* `domain` (*type:* `String.t`, *default:* `nil`) - Domain name in the email address. e.g. "gmail.com" in [email protected]
* `isUserNameEditable` (*type:* `boolean()`, *default:* `nil`) - Whether client is allowed to provide a different user name.
* `user` (*type:* `String.t`, *default:* `nil`) - User name in the email address. e.g. "foo" in [email protected]
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:domain => String.t() | nil,
:isUserNameEditable => boolean() | nil,
:user => String.t() | nil
}
field(:domain)
field(:isUserNameEditable)
field(:user)
end
defimpl Poison.Decoder, for: GoogleApi.MyBusinessVerifications.V1.Model.EmailVerificationData do
def decode(value, options) do
GoogleApi.MyBusinessVerifications.V1.Model.EmailVerificationData.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.MyBusinessVerifications.V1.Model.EmailVerificationData do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.849057 | 128 | 0.721579 |
9e978131bfd6ffdee2b9907493b616b6f85f8d0a | 1,144 | ex | Elixir | lib/format_parser/font.ex | ahtung/format_parser.ex | b4c858f9f3dedd8e62ac17b633d951eb247b7c1f | [
"Apache-2.0"
] | 21 | 2018-02-17T18:49:37.000Z | 2020-03-13T11:14:30.000Z | lib/format_parser/font.ex | ahtung/format_parser.ex | b4c858f9f3dedd8e62ac17b633d951eb247b7c1f | [
"Apache-2.0"
] | 20 | 2018-02-15T07:17:56.000Z | 2021-01-13T13:08:49.000Z | lib/format_parser/font.ex | dunyakirkali/format_parser.ex | 418a6ff5d83be4bcaaa057b4f7eb652c1add2ae6 | [
"Apache-2.0"
] | 1 | 2020-01-28T09:39:00.000Z | 2020-01-28T09:39:00.000Z | defmodule FormatParser.Font do
alias __MODULE__
@moduledoc """
A Font struct and functions.
The Font struct contains the fields format and nature.
"""
defstruct [:format, nature: :font]
@doc """
Parses a file and extracts some information from it.
Takes a `binary file` as argument.
Returns a struct which contains all information that has been extracted from the file if the file is recognized.
Returns the following tuple if file not recognized: `{:error, file}`.
"""
def parse({:error, file}) when is_binary(file) do
parse_font(file)
end
def parse(file) when is_binary(file) do
parse_font(file)
end
def parse(result) do
result
end
defp parse_font(file) do
case file do
<<0x4D, 0x5A, x::binary>> -> parse_fon(x)
<<0x00, 0x01, 0x00, 0x00, 0x00, x::binary>> -> parse_ttf(x)
<<"OTTO", 0x00, x::binary>> -> parse_otf(x)
_ -> {:error, file}
end
end
defp parse_otf(<<_::binary>>) do
%Font{format: :otf}
end
defp parse_ttf(<<_x::binary>>) do
%Font{format: :ttf}
end
defp parse_fon(<<_::binary>>) do
%Font{format: :fon}
end
end
| 20.8 | 114 | 0.645105 |
9e978378dd86608d5b9ef8c22eae6a6e0b94d050 | 1,320 | ex | Elixir | lib/timber_phoenix/application.ex | treble37/timber-elixir-phoenix | 4023b69576a4d2e9029bdee6bd5ce7265973821a | [
"0BSD"
] | 3 | 2019-03-05T21:59:33.000Z | 2020-01-05T13:00:23.000Z | lib/timber_phoenix/application.ex | treble37/timber-elixir-phoenix | 4023b69576a4d2e9029bdee6bd5ce7265973821a | [
"0BSD"
] | 9 | 2018-12-21T21:19:03.000Z | 2020-04-27T09:35:02.000Z | lib/timber_phoenix/application.ex | treble37/timber-elixir-phoenix | 4023b69576a4d2e9029bdee6bd5ce7265973821a | [
"0BSD"
] | 6 | 2019-02-24T20:14:41.000Z | 2020-05-15T01:00:38.000Z | defmodule Timber.Phoenix.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 = [
# Starts a worker by calling: Timber.Phoenix.Worker.start_link(arg)
# {Timber.Phoenix.Worker, arg},
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Timber.Phoenix.Supervisor]
transform_deprecated_configuration()
Supervisor.start_link(children, opts)
end
defp transform_deprecated_configuration do
case Application.fetch_env(:timber_phoenix, :controller_actions_blacklist) do
{:ok, value} ->
new_config = """
config :timber_phoenix, parsed_controller_actions_blacklist: MapSet.new(
#{inspect(value)}
)
"""
IO.warn(
":controller_actions_blacklist is deprecated. Please place the blacklist " <>
"in a MapSet under the :parsed_controller_actions_blacklist key. Config should be:\n\n" <>
new_config
)
Timber.Phoenix.put_parsed_blacklist(MapSet.new(value))
:ok
:error ->
:ok
end
end
end
| 28.085106 | 102 | 0.669697 |
9e978e37eeb162666289d5cb64c4f2fa4328e3d4 | 1,347 | ex | Elixir | exercise1/lib/exercise1.ex | aspiringastro/programming-elixir | ec2167268c06bbb72b2bda26caa469333daccb63 | [
"MIT"
] | null | null | null | exercise1/lib/exercise1.ex | aspiringastro/programming-elixir | ec2167268c06bbb72b2bda26caa469333daccb63 | [
"MIT"
] | null | null | null | exercise1/lib/exercise1.ex | aspiringastro/programming-elixir | ec2167268c06bbb72b2bda26caa469333daccb63 | [
"MIT"
] | null | null | null | defmodule Exercise1 do
@moduledoc """
Documentation for Exercise1.
"""
@doc """
Hello world.
## Examples
iex> Exercise1.hello()
:world
"""
def hello do
:world
end
@doc """
iex> Exercise1.list_concat([1,2,3], [4,5,6])
[1,2,3,4,5,6]
"""
def list_concat(list1, list2) do
# list1 ++ list2
list_concat(list1, list2, [])
end
defp list_concat([item | rest], list2, acc) do
IO.inspect(%{item: item, rest: rest, list2: list2, acc: acc}, label: "pre-one")
list_concat(rest, list2, [item | acc])
|> IO.inspect(label: "one")
end
defp list_concat([], [item | rest], acc) do
IO.inspect(%{item: item, rest: rest, acc: acc}, label: "pre-two")
list_concat([], rest, [item | acc])
|> IO.inspect(label: "two")
end
defp list_concat([], [], acc) do
IO.inspect(%{acc: acc}, label: "pre-final")
acc
|> Enum.reverse
|> IO.inspect(label: "final")
end
@doc """
iex> Exercise1.sum([1,2,3,4,5,6,7,8,9])
45
"""
def sum(list) do
sum(list, 0)
end
defp sum([item | rest], acc) when is_number(item) do
sum(rest, acc + item)
end
defp sum([], acc) do
acc
end
@doc """
iex> Exercise1.pair_tuple_to_list({1,2})
[1,2]
"""
def pair_tuple_to_list({t1, t2}) do
[t1, t2]
end
end
| 17.050633 | 83 | 0.548627 |
9e97a28b706a3aa86ee5d949df9036f3828f62b7 | 15,099 | ex | Elixir | clients/container/lib/google_api/container/v1/model/cluster.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/container/lib/google_api/container/v1/model/cluster.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/container/lib/google_api/container/v1/model/cluster.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Container.V1.Model.Cluster do
@moduledoc """
A Google Kubernetes Engine cluster.
## Attributes
- addonsConfig (AddonsConfig): Configurations for the various addons available to run in the cluster. Defaults to: `null`.
- clusterIpv4Cidr (String.t): The IP address range of the container pods in this cluster, in [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation (e.g. `10.96.0.0/14`). Leave blank to have one automatically chosen or specify a `/14` block in `10.0.0.0/8`. Defaults to: `null`.
- conditions ([StatusCondition]): Which conditions caused the current cluster state. Defaults to: `null`.
- createTime (String.t): [Output only] The time the cluster was created, in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) text format. Defaults to: `null`.
- currentMasterVersion (String.t): [Output only] The current software version of the master endpoint. Defaults to: `null`.
- currentNodeCount (integer()): [Output only] The number of nodes currently in the cluster. Deprecated. Call Kubernetes API directly to retrieve node information. Defaults to: `null`.
- currentNodeVersion (String.t): [Output only] Deprecated, use [NodePools.version](/kubernetes-engine/docs/reference/rest/v1/projects.zones.clusters.nodePools) instead. The current version of the node software components. If they are currently at multiple versions because they're in the process of being upgraded, this reflects the minimum version of all nodes. Defaults to: `null`.
- defaultMaxPodsConstraint (MaxPodsConstraint): The default constraint on the maximum number of pods that can be run simultaneously on a node in the node pool of this cluster. Only honored if cluster created with IP Alias support. Defaults to: `null`.
- description (String.t): An optional description of this cluster. Defaults to: `null`.
- enableKubernetesAlpha (boolean()): Kubernetes alpha features are enabled on this cluster. This includes alpha API groups (e.g. v1alpha1) and features that may not be production ready in the kubernetes version of the master and nodes. The cluster has no SLA for uptime and master/node upgrades are disabled. Alpha enabled clusters are automatically deleted thirty days after creation. Defaults to: `null`.
- enableTpu (boolean()): Enable the ability to use Cloud TPUs in this cluster. Defaults to: `null`.
- endpoint (String.t): [Output only] The IP address of this cluster's master endpoint. The endpoint can be accessed from the internet at `https://username:password@endpoint/`. See the `masterAuth` property of this resource for username and password information. Defaults to: `null`.
- expireTime (String.t): [Output only] The time the cluster will be automatically deleted in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) text format. Defaults to: `null`.
- initialClusterVersion (String.t): The initial Kubernetes version for this cluster. Valid versions are those found in validMasterVersions returned by getServerConfig. The version can be upgraded over time; such upgrades are reflected in currentMasterVersion and currentNodeVersion. Users may specify either explicit versions offered by Kubernetes Engine or version aliases, which have the following behavior: - \"latest\": picks the highest valid Kubernetes version - \"1.X\": picks the highest valid patch+gke.N patch in the 1.X version - \"1.X.Y\": picks the highest valid gke.N patch in the 1.X.Y version - \"1.X.Y-gke.N\": picks an explicit Kubernetes version - \"\",\"-\": picks the default Kubernetes version Defaults to: `null`.
- initialNodeCount (integer()): The number of nodes to create in this cluster. You must ensure that your Compute Engine <a href=\"/compute/docs/resource-quotas\">resource quota</a> is sufficient for this number of instances. You must also have available firewall and routes quota. For requests, this field should only be used in lieu of a \"node_pool\" object, since this configuration (along with the \"node_config\") will be used to create a \"NodePool\" object with an auto-generated name. Do not use this and a node_pool at the same time. This field is deprecated, use node_pool.initial_node_count instead. Defaults to: `null`.
- instanceGroupUrls ([String.t]): Deprecated. Use node_pools.instance_group_urls. Defaults to: `null`.
- ipAllocationPolicy (IpAllocationPolicy): Configuration for cluster IP allocation. Defaults to: `null`.
- labelFingerprint (String.t): The fingerprint of the set of labels for this cluster. Defaults to: `null`.
- legacyAbac (LegacyAbac): Configuration for the legacy ABAC authorization mode. Defaults to: `null`.
- location (String.t): [Output only] The name of the Google Compute Engine [zone](/compute/docs/regions-zones/regions-zones#available) or [region](/compute/docs/regions-zones/regions-zones#available) in which the cluster resides. Defaults to: `null`.
- locations ([String.t]): The list of Google Compute Engine [zones](/compute/docs/zones#available) in which the cluster's nodes should be located. Defaults to: `null`.
- loggingService (String.t): The logging service the cluster should use to write logs. Currently available options: * `logging.googleapis.com` - the Google Cloud Logging service. * `none` - no logs will be exported from the cluster. * if left as an empty string,`logging.googleapis.com` will be used. Defaults to: `null`.
- maintenancePolicy (MaintenancePolicy): Configure the maintenance policy for this cluster. Defaults to: `null`.
- masterAuth (MasterAuth): The authentication information for accessing the master endpoint. If unspecified, the defaults are used: For clusters before v1.12, if master_auth is unspecified, `username` will be set to \"admin\", a random password will be generated, and a client certificate will be issued. Defaults to: `null`.
- masterAuthorizedNetworksConfig (MasterAuthorizedNetworksConfig): The configuration options for master authorized networks feature. Defaults to: `null`.
- monitoringService (String.t): The monitoring service the cluster should use to write metrics. Currently available options: * `monitoring.googleapis.com` - the Google Cloud Monitoring service. * `none` - no metrics will be exported from the cluster. * if left as an empty string, `monitoring.googleapis.com` will be used. Defaults to: `null`.
- name (String.t): The name of this cluster. The name must be unique within this project and zone, and can be up to 40 characters with the following restrictions: * Lowercase letters, numbers, and hyphens only. * Must start with a letter. * Must end with a number or a letter. Defaults to: `null`.
- network (String.t): The name of the Google Compute Engine [network](/compute/docs/networks-and-firewalls#networks) to which the cluster is connected. If left unspecified, the `default` network will be used. Defaults to: `null`.
- networkConfig (NetworkConfig): Configuration for cluster networking. Defaults to: `null`.
- networkPolicy (NetworkPolicy): Configuration options for the NetworkPolicy feature. Defaults to: `null`.
- nodeConfig (NodeConfig): Parameters used in creating the cluster's nodes. For requests, this field should only be used in lieu of a \"node_pool\" object, since this configuration (along with the \"initial_node_count\") will be used to create a \"NodePool\" object with an auto-generated name. Do not use this and a node_pool at the same time. For responses, this field will be populated with the node configuration of the first node pool. (For configuration of each node pool, see `node_pool.config`) If unspecified, the defaults are used. This field is deprecated, use node_pool.config instead. Defaults to: `null`.
- nodeIpv4CidrSize (integer()): [Output only] The size of the address space on each node for hosting containers. This is provisioned from within the `container_ipv4_cidr` range. Defaults to: `null`.
- nodePools ([NodePool]): The node pools associated with this cluster. This field should not be set if \"node_config\" or \"initial_node_count\" are specified. Defaults to: `null`.
- privateClusterConfig (PrivateClusterConfig): Configuration for private cluster. Defaults to: `null`.
- resourceLabels (%{optional(String.t) => String.t}): The resource labels for the cluster to use to annotate any related Google Compute Engine resources. Defaults to: `null`.
- selfLink (String.t): [Output only] Server-defined URL for the resource. Defaults to: `null`.
- servicesIpv4Cidr (String.t): [Output only] The IP address range of the Kubernetes services in this cluster, in [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation (e.g. `1.2.3.4/29`). Service addresses are typically put in the last `/16` from the container CIDR. Defaults to: `null`.
- status (String.t): [Output only] The current status of this cluster. Defaults to: `null`.
- Enum - one of [STATUS_UNSPECIFIED, PROVISIONING, RUNNING, RECONCILING, STOPPING, ERROR, DEGRADED]
- statusMessage (String.t): [Output only] Additional information about the current status of this cluster, if available. Defaults to: `null`.
- subnetwork (String.t): The name of the Google Compute Engine [subnetwork](/compute/docs/subnetworks) to which the cluster is connected. Defaults to: `null`.
- tpuIpv4CidrBlock (String.t): [Output only] The IP address range of the Cloud TPUs in this cluster, in [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation (e.g. `1.2.3.4/29`). Defaults to: `null`.
- zone (String.t): [Output only] The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. This field is deprecated, use location instead. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:addonsConfig => GoogleApi.Container.V1.Model.AddonsConfig.t(),
:clusterIpv4Cidr => any(),
:conditions => list(GoogleApi.Container.V1.Model.StatusCondition.t()),
:createTime => any(),
:currentMasterVersion => any(),
:currentNodeCount => any(),
:currentNodeVersion => any(),
:defaultMaxPodsConstraint => GoogleApi.Container.V1.Model.MaxPodsConstraint.t(),
:description => any(),
:enableKubernetesAlpha => any(),
:enableTpu => any(),
:endpoint => any(),
:expireTime => any(),
:initialClusterVersion => any(),
:initialNodeCount => any(),
:instanceGroupUrls => list(any()),
:ipAllocationPolicy => GoogleApi.Container.V1.Model.IpAllocationPolicy.t(),
:labelFingerprint => any(),
:legacyAbac => GoogleApi.Container.V1.Model.LegacyAbac.t(),
:location => any(),
:locations => list(any()),
:loggingService => any(),
:maintenancePolicy => GoogleApi.Container.V1.Model.MaintenancePolicy.t(),
:masterAuth => GoogleApi.Container.V1.Model.MasterAuth.t(),
:masterAuthorizedNetworksConfig =>
GoogleApi.Container.V1.Model.MasterAuthorizedNetworksConfig.t(),
:monitoringService => any(),
:name => any(),
:network => any(),
:networkConfig => GoogleApi.Container.V1.Model.NetworkConfig.t(),
:networkPolicy => GoogleApi.Container.V1.Model.NetworkPolicy.t(),
:nodeConfig => GoogleApi.Container.V1.Model.NodeConfig.t(),
:nodeIpv4CidrSize => any(),
:nodePools => list(GoogleApi.Container.V1.Model.NodePool.t()),
:privateClusterConfig => GoogleApi.Container.V1.Model.PrivateClusterConfig.t(),
:resourceLabels => map(),
:selfLink => any(),
:servicesIpv4Cidr => any(),
:status => any(),
:statusMessage => any(),
:subnetwork => any(),
:tpuIpv4CidrBlock => any(),
:zone => any()
}
field(:addonsConfig, as: GoogleApi.Container.V1.Model.AddonsConfig)
field(:clusterIpv4Cidr)
field(:conditions, as: GoogleApi.Container.V1.Model.StatusCondition, type: :list)
field(:createTime)
field(:currentMasterVersion)
field(:currentNodeCount)
field(:currentNodeVersion)
field(:defaultMaxPodsConstraint, as: GoogleApi.Container.V1.Model.MaxPodsConstraint)
field(:description)
field(:enableKubernetesAlpha)
field(:enableTpu)
field(:endpoint)
field(:expireTime)
field(:initialClusterVersion)
field(:initialNodeCount)
field(:instanceGroupUrls, type: :list)
field(:ipAllocationPolicy, as: GoogleApi.Container.V1.Model.IpAllocationPolicy)
field(:labelFingerprint)
field(:legacyAbac, as: GoogleApi.Container.V1.Model.LegacyAbac)
field(:location)
field(:locations, type: :list)
field(:loggingService)
field(:maintenancePolicy, as: GoogleApi.Container.V1.Model.MaintenancePolicy)
field(:masterAuth, as: GoogleApi.Container.V1.Model.MasterAuth)
field(
:masterAuthorizedNetworksConfig,
as: GoogleApi.Container.V1.Model.MasterAuthorizedNetworksConfig
)
field(:monitoringService)
field(:name)
field(:network)
field(:networkConfig, as: GoogleApi.Container.V1.Model.NetworkConfig)
field(:networkPolicy, as: GoogleApi.Container.V1.Model.NetworkPolicy)
field(:nodeConfig, as: GoogleApi.Container.V1.Model.NodeConfig)
field(:nodeIpv4CidrSize)
field(:nodePools, as: GoogleApi.Container.V1.Model.NodePool, type: :list)
field(:privateClusterConfig, as: GoogleApi.Container.V1.Model.PrivateClusterConfig)
field(:resourceLabels, type: :map)
field(:selfLink)
field(:servicesIpv4Cidr)
field(:status)
field(:statusMessage)
field(:subnetwork)
field(:tpuIpv4CidrBlock)
field(:zone)
end
defimpl Poison.Decoder, for: GoogleApi.Container.V1.Model.Cluster do
def decode(value, options) do
GoogleApi.Container.V1.Model.Cluster.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Container.V1.Model.Cluster do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 84.825843 | 802 | 0.736936 |
9e97b627d32441af11dd34dfc0cf6fb6d9537b2a | 53,718 | ex | Elixir | lib/aws/ses.ex | ahsandar/aws-elixir | 25de8b6c3a1401bde737cfc26b0679b14b058f23 | [
"Apache-2.0"
] | null | null | null | lib/aws/ses.ex | ahsandar/aws-elixir | 25de8b6c3a1401bde737cfc26b0679b14b058f23 | [
"Apache-2.0"
] | null | null | null | lib/aws/ses.ex | ahsandar/aws-elixir | 25de8b6c3a1401bde737cfc26b0679b14b058f23 | [
"Apache-2.0"
] | null | null | null | # WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
# See https://github.com/aws-beam/aws-codegen for more details.
defmodule AWS.SES do
@moduledoc """
Amazon Simple Email Service
This document contains reference information for the [Amazon Simple Email
Service](https://aws.amazon.com/ses/) (Amazon SES) API, version 2010-12-01.
This document is best used in conjunction with the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/Welcome.html).
<note> For a list of Amazon SES endpoints to use in service requests, see
[Regions and Amazon
SES](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html) in
the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/Welcome.html).
</note>
"""
@doc """
Creates a receipt rule set by cloning an existing one. All receipt rules
and configurations are copied to the new receipt rule set and are
completely independent of the source rule set.
For information about setting up rule sets, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rule-set.html).
You can execute this operation no more than once per second.
"""
def clone_receipt_rule_set(client, input, options \\ []) do
request(client, "CloneReceiptRuleSet", input, options)
end
@doc """
Creates a configuration set.
Configuration sets enable you to publish email sending events. For
information about using configuration sets, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html).
You can execute this operation no more than once per second.
"""
def create_configuration_set(client, input, options \\ []) do
request(client, "CreateConfigurationSet", input, options)
end
@doc """
Creates a configuration set event destination.
<note> When you create or update an event destination, you must provide
one, and only one, destination. The destination can be CloudWatch, Amazon
Kinesis Firehose, or Amazon Simple Notification Service (Amazon SNS).
</note> An event destination is the AWS service to which Amazon SES
publishes the email sending events associated with a configuration set. For
information about using configuration sets, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html).
You can execute this operation no more than once per second.
"""
def create_configuration_set_event_destination(client, input, options \\ []) do
request(client, "CreateConfigurationSetEventDestination", input, options)
end
@doc """
Creates an association between a configuration set and a custom domain for
open and click event tracking.
By default, images and links used for tracking open and click events are
hosted on domains operated by Amazon SES. You can configure a subdomain of
your own to handle these events. For information about using custom
domains, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/configure-custom-open-click-domains.html).
"""
def create_configuration_set_tracking_options(client, input, options \\ []) do
request(client, "CreateConfigurationSetTrackingOptions", input, options)
end
@doc """
Creates a new custom verification email template.
For more information about custom verification email templates, see [Using
Custom Verification Email
Templates](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html)
in the *Amazon SES Developer Guide*.
You can execute this operation no more than once per second.
"""
def create_custom_verification_email_template(client, input, options \\ []) do
request(client, "CreateCustomVerificationEmailTemplate", input, options)
end
@doc """
Creates a new IP address filter.
For information about setting up IP address filters, see the [Amazon SES
Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-ip-filters.html).
You can execute this operation no more than once per second.
"""
def create_receipt_filter(client, input, options \\ []) do
request(client, "CreateReceiptFilter", input, options)
end
@doc """
Creates a receipt rule.
For information about setting up receipt rules, see the [Amazon SES
Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rules.html).
You can execute this operation no more than once per second.
"""
def create_receipt_rule(client, input, options \\ []) do
request(client, "CreateReceiptRule", input, options)
end
@doc """
Creates an empty receipt rule set.
For information about setting up receipt rule sets, see the [Amazon SES
Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rule-set.html).
You can execute this operation no more than once per second.
"""
def create_receipt_rule_set(client, input, options \\ []) do
request(client, "CreateReceiptRuleSet", input, options)
end
@doc """
Creates an email template. Email templates enable you to send personalized
email to one or more destinations in a single API operation. For more
information, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html).
You can execute this operation no more than once per second.
"""
def create_template(client, input, options \\ []) do
request(client, "CreateTemplate", input, options)
end
@doc """
Deletes a configuration set. Configuration sets enable you to publish email
sending events. For information about using configuration sets, see the
[Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html).
You can execute this operation no more than once per second.
"""
def delete_configuration_set(client, input, options \\ []) do
request(client, "DeleteConfigurationSet", input, options)
end
@doc """
Deletes a configuration set event destination. Configuration set event
destinations are associated with configuration sets, which enable you to
publish email sending events. For information about using configuration
sets, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html).
You can execute this operation no more than once per second.
"""
def delete_configuration_set_event_destination(client, input, options \\ []) do
request(client, "DeleteConfigurationSetEventDestination", input, options)
end
@doc """
Deletes an association between a configuration set and a custom domain for
open and click event tracking.
By default, images and links used for tracking open and click events are
hosted on domains operated by Amazon SES. You can configure a subdomain of
your own to handle these events. For information about using custom
domains, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/configure-custom-open-click-domains.html).
<note> Deleting this kind of association will result in emails sent using
the specified configuration set to capture open and click events using the
standard, Amazon SES-operated domains.
</note>
"""
def delete_configuration_set_tracking_options(client, input, options \\ []) do
request(client, "DeleteConfigurationSetTrackingOptions", input, options)
end
@doc """
Deletes an existing custom verification email template.
For more information about custom verification email templates, see [Using
Custom Verification Email
Templates](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html)
in the *Amazon SES Developer Guide*.
You can execute this operation no more than once per second.
"""
def delete_custom_verification_email_template(client, input, options \\ []) do
request(client, "DeleteCustomVerificationEmailTemplate", input, options)
end
@doc """
Deletes the specified identity (an email address or a domain) from the list
of verified identities.
You can execute this operation no more than once per second.
"""
def delete_identity(client, input, options \\ []) do
request(client, "DeleteIdentity", input, options)
end
@doc """
Deletes the specified sending authorization policy for the given identity
(an email address or a domain). This API returns successfully even if a
policy with the specified name does not exist.
<note> This API is for the identity owner only. If you have not verified
the identity, this API will return an error.
</note> Sending authorization is a feature that enables an identity owner
to authorize other senders to use its identities. For information about
using sending authorization, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html).
You can execute this operation no more than once per second.
"""
def delete_identity_policy(client, input, options \\ []) do
request(client, "DeleteIdentityPolicy", input, options)
end
@doc """
Deletes the specified IP address filter.
For information about managing IP address filters, see the [Amazon SES
Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-ip-filters.html).
You can execute this operation no more than once per second.
"""
def delete_receipt_filter(client, input, options \\ []) do
request(client, "DeleteReceiptFilter", input, options)
end
@doc """
Deletes the specified receipt rule.
For information about managing receipt rules, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rules.html).
You can execute this operation no more than once per second.
"""
def delete_receipt_rule(client, input, options \\ []) do
request(client, "DeleteReceiptRule", input, options)
end
@doc """
Deletes the specified receipt rule set and all of the receipt rules it
contains.
<note> The currently active rule set cannot be deleted.
</note> For information about managing receipt rule sets, see the [Amazon
SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rule-sets.html).
You can execute this operation no more than once per second.
"""
def delete_receipt_rule_set(client, input, options \\ []) do
request(client, "DeleteReceiptRuleSet", input, options)
end
@doc """
Deletes an email template.
You can execute this operation no more than once per second.
"""
def delete_template(client, input, options \\ []) do
request(client, "DeleteTemplate", input, options)
end
@doc """
Deprecated. Use the `DeleteIdentity` operation to delete email addresses
and domains.
"""
def delete_verified_email_address(client, input, options \\ []) do
request(client, "DeleteVerifiedEmailAddress", input, options)
end
@doc """
Returns the metadata and receipt rules for the receipt rule set that is
currently active.
For information about setting up receipt rule sets, see the [Amazon SES
Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rule-set.html).
You can execute this operation no more than once per second.
"""
def describe_active_receipt_rule_set(client, input, options \\ []) do
request(client, "DescribeActiveReceiptRuleSet", input, options)
end
@doc """
Returns the details of the specified configuration set. For information
about using configuration sets, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html).
You can execute this operation no more than once per second.
"""
def describe_configuration_set(client, input, options \\ []) do
request(client, "DescribeConfigurationSet", input, options)
end
@doc """
Returns the details of the specified receipt rule.
For information about setting up receipt rules, see the [Amazon SES
Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rules.html).
You can execute this operation no more than once per second.
"""
def describe_receipt_rule(client, input, options \\ []) do
request(client, "DescribeReceiptRule", input, options)
end
@doc """
Returns the details of the specified receipt rule set.
For information about managing receipt rule sets, see the [Amazon SES
Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rule-sets.html).
You can execute this operation no more than once per second.
"""
def describe_receipt_rule_set(client, input, options \\ []) do
request(client, "DescribeReceiptRuleSet", input, options)
end
@doc """
Returns the email sending status of the Amazon SES account for the current
region.
You can execute this operation no more than once per second.
"""
def get_account_sending_enabled(client, input, options \\ []) do
request(client, "GetAccountSendingEnabled", input, options)
end
@doc """
Returns the custom email verification template for the template name you
specify.
For more information about custom verification email templates, see [Using
Custom Verification Email
Templates](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html)
in the *Amazon SES Developer Guide*.
You can execute this operation no more than once per second.
"""
def get_custom_verification_email_template(client, input, options \\ []) do
request(client, "GetCustomVerificationEmailTemplate", input, options)
end
@doc """
Returns the current status of Easy DKIM signing for an entity. For domain
name identities, this operation also returns the DKIM tokens that are
required for Easy DKIM signing, and whether Amazon SES has successfully
verified that these tokens have been published.
This operation takes a list of identities as input and returns the
following information for each:
<ul> <li> Whether Easy DKIM signing is enabled or disabled.
</li> <li> A set of DKIM tokens that represent the identity. If the
identity is an email address, the tokens represent the domain of that
address.
</li> <li> Whether Amazon SES has successfully verified the DKIM tokens
published in the domain's DNS. This information is only returned for domain
name identities, not for email addresses.
</li> </ul> This operation is throttled at one request per second and can
only get DKIM attributes for up to 100 identities at a time.
For more information about creating DNS records using DKIM tokens, go to
the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim-dns-records.html).
"""
def get_identity_dkim_attributes(client, input, options \\ []) do
request(client, "GetIdentityDkimAttributes", input, options)
end
@doc """
Returns the custom MAIL FROM attributes for a list of identities (email
addresses : domains).
This operation is throttled at one request per second and can only get
custom MAIL FROM attributes for up to 100 identities at a time.
"""
def get_identity_mail_from_domain_attributes(client, input, options \\ []) do
request(client, "GetIdentityMailFromDomainAttributes", input, options)
end
@doc """
Given a list of verified identities (email addresses and/or domains),
returns a structure describing identity notification attributes.
This operation is throttled at one request per second and can only get
notification attributes for up to 100 identities at a time.
For more information about using notifications with Amazon SES, see the
[Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/notifications.html).
"""
def get_identity_notification_attributes(client, input, options \\ []) do
request(client, "GetIdentityNotificationAttributes", input, options)
end
@doc """
Returns the requested sending authorization policies for the given identity
(an email address or a domain). The policies are returned as a map of
policy names to policy contents. You can retrieve a maximum of 20 policies
at a time.
<note> This API is for the identity owner only. If you have not verified
the identity, this API will return an error.
</note> Sending authorization is a feature that enables an identity owner
to authorize other senders to use its identities. For information about
using sending authorization, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html).
You can execute this operation no more than once per second.
"""
def get_identity_policies(client, input, options \\ []) do
request(client, "GetIdentityPolicies", input, options)
end
@doc """
Given a list of identities (email addresses and/or domains), returns the
verification status and (for domain identities) the verification token for
each identity.
The verification status of an email address is "Pending" until the email
address owner clicks the link within the verification email that Amazon SES
sent to that address. If the email address owner clicks the link within 24
hours, the verification status of the email address changes to "Success".
If the link is not clicked within 24 hours, the verification status changes
to "Failed." In that case, if you still want to verify the email address,
you must restart the verification process from the beginning.
For domain identities, the domain's verification status is "Pending" as
Amazon SES searches for the required TXT record in the DNS settings of the
domain. When Amazon SES detects the record, the domain's verification
status changes to "Success". If Amazon SES is unable to detect the record
within 72 hours, the domain's verification status changes to "Failed." In
that case, if you still want to verify the domain, you must restart the
verification process from the beginning.
This operation is throttled at one request per second and can only get
verification attributes for up to 100 identities at a time.
"""
def get_identity_verification_attributes(client, input, options \\ []) do
request(client, "GetIdentityVerificationAttributes", input, options)
end
@doc """
Provides the sending limits for the Amazon SES account.
You can execute this operation no more than once per second.
"""
def get_send_quota(client, input, options \\ []) do
request(client, "GetSendQuota", input, options)
end
@doc """
Provides sending statistics for the current AWS Region. The result is a
list of data points, representing the last two weeks of sending activity.
Each data point in the list contains statistics for a 15-minute period of
time.
You can execute this operation no more than once per second.
"""
def get_send_statistics(client, input, options \\ []) do
request(client, "GetSendStatistics", input, options)
end
@doc """
Displays the template object (which includes the Subject line, HTML part
and text part) for the template you specify.
You can execute this operation no more than once per second.
"""
def get_template(client, input, options \\ []) do
request(client, "GetTemplate", input, options)
end
@doc """
Provides a list of the configuration sets associated with your Amazon SES
account in the current AWS Region. For information about using
configuration sets, see [Monitoring Your Amazon SES Sending
Activity](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html)
in the *Amazon SES Developer Guide.*
You can execute this operation no more than once per second. This operation
will return up to 1,000 configuration sets each time it is run. If your
Amazon SES account has more than 1,000 configuration sets, this operation
will also return a NextToken element. You can then execute the
`ListConfigurationSets` operation again, passing the `NextToken` parameter
and the value of the NextToken element to retrieve additional results.
"""
def list_configuration_sets(client, input, options \\ []) do
request(client, "ListConfigurationSets", input, options)
end
@doc """
Lists the existing custom verification email templates for your account in
the current AWS Region.
For more information about custom verification email templates, see [Using
Custom Verification Email
Templates](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html)
in the *Amazon SES Developer Guide*.
You can execute this operation no more than once per second.
"""
def list_custom_verification_email_templates(client, input, options \\ []) do
request(client, "ListCustomVerificationEmailTemplates", input, options)
end
@doc """
Returns a list containing all of the identities (email addresses and
domains) for your AWS account in the current AWS Region, regardless of
verification status.
You can execute this operation no more than once per second.
"""
def list_identities(client, input, options \\ []) do
request(client, "ListIdentities", input, options)
end
@doc """
Returns a list of sending authorization policies that are attached to the
given identity (an email address or a domain). This API returns only a
list. If you want the actual policy content, you can use
`GetIdentityPolicies`.
<note> This API is for the identity owner only. If you have not verified
the identity, this API will return an error.
</note> Sending authorization is a feature that enables an identity owner
to authorize other senders to use its identities. For information about
using sending authorization, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html).
You can execute this operation no more than once per second.
"""
def list_identity_policies(client, input, options \\ []) do
request(client, "ListIdentityPolicies", input, options)
end
@doc """
Lists the IP address filters associated with your AWS account in the
current AWS Region.
For information about managing IP address filters, see the [Amazon SES
Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-ip-filters.html).
You can execute this operation no more than once per second.
"""
def list_receipt_filters(client, input, options \\ []) do
request(client, "ListReceiptFilters", input, options)
end
@doc """
Lists the receipt rule sets that exist under your AWS account in the
current AWS Region. If there are additional receipt rule sets to be
retrieved, you will receive a `NextToken` that you can provide to the next
call to `ListReceiptRuleSets` to retrieve the additional entries.
For information about managing receipt rule sets, see the [Amazon SES
Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rule-sets.html).
You can execute this operation no more than once per second.
"""
def list_receipt_rule_sets(client, input, options \\ []) do
request(client, "ListReceiptRuleSets", input, options)
end
@doc """
Lists the email templates present in your Amazon SES account in the current
AWS Region.
You can execute this operation no more than once per second.
"""
def list_templates(client, input, options \\ []) do
request(client, "ListTemplates", input, options)
end
@doc """
Deprecated. Use the `ListIdentities` operation to list the email addresses
and domains associated with your account.
"""
def list_verified_email_addresses(client, input, options \\ []) do
request(client, "ListVerifiedEmailAddresses", input, options)
end
@doc """
Adds or updates the delivery options for a configuration set.
"""
def put_configuration_set_delivery_options(client, input, options \\ []) do
request(client, "PutConfigurationSetDeliveryOptions", input, options)
end
@doc """
Adds or updates a sending authorization policy for the specified identity
(an email address or a domain).
<note> This API is for the identity owner only. If you have not verified
the identity, this API will return an error.
</note> Sending authorization is a feature that enables an identity owner
to authorize other senders to use its identities. For information about
using sending authorization, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html).
You can execute this operation no more than once per second.
"""
def put_identity_policy(client, input, options \\ []) do
request(client, "PutIdentityPolicy", input, options)
end
@doc """
Reorders the receipt rules within a receipt rule set.
<note> All of the rules in the rule set must be represented in this
request. That is, this API will return an error if the reorder request
doesn't explicitly position all of the rules.
</note> For information about managing receipt rule sets, see the [Amazon
SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rule-sets.html).
You can execute this operation no more than once per second.
"""
def reorder_receipt_rule_set(client, input, options \\ []) do
request(client, "ReorderReceiptRuleSet", input, options)
end
@doc """
Generates and sends a bounce message to the sender of an email you received
through Amazon SES. You can only use this API on an email up to 24 hours
after you receive it.
<note> You cannot use this API to send generic bounces for mail that was
not received by Amazon SES.
</note> For information about receiving email through Amazon SES, see the
[Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email.html).
You can execute this operation no more than once per second.
"""
def send_bounce(client, input, options \\ []) do
request(client, "SendBounce", input, options)
end
@doc """
Composes an email message to multiple destinations. The message body is
created using an email template.
In order to send email using the `SendBulkTemplatedEmail` operation, your
call to the API must meet the following requirements:
<ul> <li> The call must refer to an existing email template. You can create
email templates using the `CreateTemplate` operation.
</li> <li> The message must be sent from a verified email address or
domain.
</li> <li> If your account is still in the Amazon SES sandbox, you may only
send to verified addresses or domains, or to email addresses associated
with the Amazon SES Mailbox Simulator. For more information, see [Verifying
Email Addresses and
Domains](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html)
in the *Amazon SES Developer Guide.*
</li> <li> The maximum message size is 10 MB.
</li> <li> Each `Destination` parameter must include at least one recipient
email address. The recipient address can be a To: address, a CC: address,
or a BCC: address. If a recipient email address is invalid (that is, it is
not in the format *UserName@[SubDomain.]Domain.TopLevelDomain*), the entire
message will be rejected, even if the message contains other recipients
that are valid.
</li> <li> The message may not include more than 50 recipients, across the
To:, CC: and BCC: fields. If you need to send an email message to a larger
audience, you can divide your recipient list into groups of 50 or fewer,
and then call the `SendBulkTemplatedEmail` operation several times to send
the message to each group.
</li> <li> The number of destinations you can contact in a single call to
the API may be limited by your account's maximum sending rate.
</li> </ul>
"""
def send_bulk_templated_email(client, input, options \\ []) do
request(client, "SendBulkTemplatedEmail", input, options)
end
@doc """
Adds an email address to the list of identities for your Amazon SES account
in the current AWS Region and attempts to verify it. As a result of
executing this operation, a customized verification email is sent to the
specified address.
To use this operation, you must first create a custom verification email
template. For more information about creating and using custom verification
email templates, see [Using Custom Verification Email
Templates](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html)
in the *Amazon SES Developer Guide*.
You can execute this operation no more than once per second.
"""
def send_custom_verification_email(client, input, options \\ []) do
request(client, "SendCustomVerificationEmail", input, options)
end
@doc """
Composes an email message and immediately queues it for sending. In order
to send email using the `SendEmail` operation, your message must meet the
following requirements:
<ul> <li> The message must be sent from a verified email address or domain.
If you attempt to send email using a non-verified address or domain, the
operation will result in an "Email address not verified" error.
</li> <li> If your account is still in the Amazon SES sandbox, you may only
send to verified addresses or domains, or to email addresses associated
with the Amazon SES Mailbox Simulator. For more information, see [Verifying
Email Addresses and
Domains](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html)
in the *Amazon SES Developer Guide.*
</li> <li> The maximum message size is 10 MB.
</li> <li> The message must include at least one recipient email address.
The recipient address can be a To: address, a CC: address, or a BCC:
address. If a recipient email address is invalid (that is, it is not in the
format *UserName@[SubDomain.]Domain.TopLevelDomain*), the entire message
will be rejected, even if the message contains other recipients that are
valid.
</li> <li> The message may not include more than 50 recipients, across the
To:, CC: and BCC: fields. If you need to send an email message to a larger
audience, you can divide your recipient list into groups of 50 or fewer,
and then call the `SendEmail` operation several times to send the message
to each group.
</li> </ul> <important> For every message that you send, the total number
of recipients (including each recipient in the To:, CC: and BCC: fields) is
counted against the maximum number of emails you can send in a 24-hour
period (your *sending quota*). For more information about sending quotas in
Amazon SES, see [Managing Your Amazon SES Sending
Limits](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/manage-sending-limits.html)
in the *Amazon SES Developer Guide.*
</important>
"""
def send_email(client, input, options \\ []) do
request(client, "SendEmail", input, options)
end
@doc """
Composes an email message and immediately queues it for sending.
This operation is more flexible than the `SendEmail` API operation. When
you use the `SendRawEmail` operation, you can specify the headers of the
message as well as its content. This flexibility is useful, for example,
when you want to send a multipart MIME email (such a message that contains
both a text and an HTML version). You can also use this operation to send
messages that include attachments.
The `SendRawEmail` operation has the following requirements:
<ul> <li> You can only send email from [verified email addresses or
domains](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html).
If you try to send email from an address that isn't verified, the operation
results in an "Email address not verified" error.
</li> <li> If your account is still in the [Amazon SES
sandbox](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/request-production-access.html),
you can only send email to other verified addresses in your account, or to
addresses that are associated with the [Amazon SES mailbox
simulator](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/mailbox-simulator.html).
</li> <li> The maximum message size, including attachments, is 10 MB.
</li> <li> Each message has to include at least one recipient address. A
recipient address includes any address on the To:, CC:, or BCC: lines.
</li> <li> If you send a single message to more than one recipient address,
and one of the recipient addresses isn't in a valid format (that is, it's
not in the format *UserName@[SubDomain.]Domain.TopLevelDomain*), Amazon SES
rejects the entire message, even if the other addresses are valid.
</li> <li> Each message can include up to 50 recipient addresses across the
To:, CC:, or BCC: lines. If you need to send a single message to more than
50 recipients, you have to split the list of recipient addresses into
groups of less than 50 recipients, and send separate messages to each
group.
</li> <li> Amazon SES allows you to specify 8-bit Content-Transfer-Encoding
for MIME message parts. However, if Amazon SES has to modify the contents
of your message (for example, if you use open and click tracking), 8-bit
content isn't preserved. For this reason, we highly recommend that you
encode all content that isn't 7-bit ASCII. For more information, see [MIME
Encoding](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html#send-email-mime-encoding)
in the *Amazon SES Developer Guide*.
</li> </ul> Additionally, keep the following considerations in mind when
using the `SendRawEmail` operation:
<ul> <li> Although you can customize the message headers when using the
`SendRawEmail` operation, Amazon SES will automatically apply its own
`Message-ID` and `Date` headers; if you passed these headers when creating
the message, they will be overwritten by the values that Amazon SES
provides.
</li> <li> If you are using sending authorization to send on behalf of
another user, `SendRawEmail` enables you to specify the cross-account
identity for the email's Source, From, and Return-Path parameters in one of
two ways: you can pass optional parameters `SourceArn`, `FromArn`, and/or
`ReturnPathArn` to the API, or you can include the following X-headers in
the header of your raw email:
<ul> <li> `X-SES-SOURCE-ARN`
</li> <li> `X-SES-FROM-ARN`
</li> <li> `X-SES-RETURN-PATH-ARN`
</li> </ul> <important> Don't include these X-headers in the DKIM
signature. Amazon SES removes these before it sends the email.
</important> If you only specify the `SourceIdentityArn` parameter, Amazon
SES sets the From and Return-Path addresses to the same identity that you
specified.
For more information about sending authorization, see the [Using Sending
Authorization with Amazon
SES](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html)
in the *Amazon SES Developer Guide.*
</li> <li> For every message that you send, the total number of recipients
(including each recipient in the To:, CC: and BCC: fields) is counted
against the maximum number of emails you can send in a 24-hour period (your
*sending quota*). For more information about sending quotas in Amazon SES,
see [Managing Your Amazon SES Sending
Limits](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/manage-sending-limits.html)
in the *Amazon SES Developer Guide.*
</li> </ul>
"""
def send_raw_email(client, input, options \\ []) do
request(client, "SendRawEmail", input, options)
end
@doc """
Composes an email message using an email template and immediately queues it
for sending.
In order to send email using the `SendTemplatedEmail` operation, your call
to the API must meet the following requirements:
<ul> <li> The call must refer to an existing email template. You can create
email templates using the `CreateTemplate` operation.
</li> <li> The message must be sent from a verified email address or
domain.
</li> <li> If your account is still in the Amazon SES sandbox, you may only
send to verified addresses or domains, or to email addresses associated
with the Amazon SES Mailbox Simulator. For more information, see [Verifying
Email Addresses and
Domains](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html)
in the *Amazon SES Developer Guide.*
</li> <li> The maximum message size is 10 MB.
</li> <li> Calls to the `SendTemplatedEmail` operation may only include one
`Destination` parameter. A destination is a set of recipients who will
receive the same version of the email. The `Destination` parameter can
include up to 50 recipients, across the To:, CC: and BCC: fields.
</li> <li> The `Destination` parameter must include at least one recipient
email address. The recipient address can be a To: address, a CC: address,
or a BCC: address. If a recipient email address is invalid (that is, it is
not in the format *UserName@[SubDomain.]Domain.TopLevelDomain*), the entire
message will be rejected, even if the message contains other recipients
that are valid.
</li> </ul> <important> If your call to the `SendTemplatedEmail` operation
includes all of the required parameters, Amazon SES accepts it and returns
a Message ID. However, if Amazon SES can't render the email because the
template contains errors, it doesn't send the email. Additionally, because
it already accepted the message, Amazon SES doesn't return a message
stating that it was unable to send the email.
For these reasons, we highly recommend that you set up Amazon SES to send
you notifications when Rendering Failure events occur. For more
information, see [Sending Personalized Email Using the Amazon SES
API](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html)
in the *Amazon Simple Email Service Developer Guide*.
</important>
"""
def send_templated_email(client, input, options \\ []) do
request(client, "SendTemplatedEmail", input, options)
end
@doc """
Sets the specified receipt rule set as the active receipt rule set.
<note> To disable your email-receiving through Amazon SES completely, you
can call this API with RuleSetName set to null.
</note> For information about managing receipt rule sets, see the [Amazon
SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rule-sets.html).
You can execute this operation no more than once per second.
"""
def set_active_receipt_rule_set(client, input, options \\ []) do
request(client, "SetActiveReceiptRuleSet", input, options)
end
@doc """
Enables or disables Easy DKIM signing of email sent from an identity. If
Easy DKIM signing is enabled for a domain, then Amazon SES uses DKIM to
sign all email that it sends from addresses on that domain. If Easy DKIM
signing is enabled for an email address, then Amazon SES uses DKIM to sign
all email it sends from that address.
<note> For email addresses (for example, `[email protected]`), you can only
enable DKIM signing if the corresponding domain (in this case,
`example.com`) has been set up to use Easy DKIM.
</note> You can enable DKIM signing for an identity at any time after you
start the verification process for the identity, even if the verification
process isn't complete.
You can execute this operation no more than once per second.
For more information about Easy DKIM signing, go to the [Amazon SES
Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html).
"""
def set_identity_dkim_enabled(client, input, options \\ []) do
request(client, "SetIdentityDkimEnabled", input, options)
end
@doc """
Given an identity (an email address or a domain), enables or disables
whether Amazon SES forwards bounce and complaint notifications as email.
Feedback forwarding can only be disabled when Amazon Simple Notification
Service (Amazon SNS) topics are specified for both bounces and complaints.
<note> Feedback forwarding does not apply to delivery notifications.
Delivery notifications are only available through Amazon SNS.
</note> You can execute this operation no more than once per second.
For more information about using notifications with Amazon SES, see the
[Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/notifications.html).
"""
def set_identity_feedback_forwarding_enabled(client, input, options \\ []) do
request(client, "SetIdentityFeedbackForwardingEnabled", input, options)
end
@doc """
Given an identity (an email address or a domain), sets whether Amazon SES
includes the original email headers in the Amazon Simple Notification
Service (Amazon SNS) notifications of a specified type.
You can execute this operation no more than once per second.
For more information about using notifications with Amazon SES, see the
[Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/notifications.html).
"""
def set_identity_headers_in_notifications_enabled(client, input, options \\ []) do
request(client, "SetIdentityHeadersInNotificationsEnabled", input, options)
end
@doc """
Enables or disables the custom MAIL FROM domain setup for a verified
identity (an email address or a domain).
<important> To send emails using the specified MAIL FROM domain, you must
add an MX record to your MAIL FROM domain's DNS settings. If you want your
emails to pass Sender Policy Framework (SPF) checks, you must also add or
update an SPF record. For more information, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/mail-from-set.html).
</important> You can execute this operation no more than once per second.
"""
def set_identity_mail_from_domain(client, input, options \\ []) do
request(client, "SetIdentityMailFromDomain", input, options)
end
@doc """
Sets an Amazon Simple Notification Service (Amazon SNS) topic to use when
delivering notifications. When you use this operation, you specify a
verified identity, such as an email address or domain. When you send an
email that uses the chosen identity in the Source field, Amazon SES sends
notifications to the topic you specified. You can send bounce, complaint,
or delivery notifications (or any combination of the three) to the Amazon
SNS topic that you specify.
You can execute this operation no more than once per second.
For more information about feedback notification, see the [Amazon SES
Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/notifications.html).
"""
def set_identity_notification_topic(client, input, options \\ []) do
request(client, "SetIdentityNotificationTopic", input, options)
end
@doc """
Sets the position of the specified receipt rule in the receipt rule set.
For information about managing receipt rules, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rules.html).
You can execute this operation no more than once per second.
"""
def set_receipt_rule_position(client, input, options \\ []) do
request(client, "SetReceiptRulePosition", input, options)
end
@doc """
Creates a preview of the MIME content of an email when provided with a
template and a set of replacement data.
You can execute this operation no more than once per second.
"""
def test_render_template(client, input, options \\ []) do
request(client, "TestRenderTemplate", input, options)
end
@doc """
Enables or disables email sending across your entire Amazon SES account in
the current AWS Region. You can use this operation in conjunction with
Amazon CloudWatch alarms to temporarily pause email sending across your
Amazon SES account in a given AWS Region when reputation metrics (such as
your bounce or complaint rates) reach certain thresholds.
You can execute this operation no more than once per second.
"""
def update_account_sending_enabled(client, input, options \\ []) do
request(client, "UpdateAccountSendingEnabled", input, options)
end
@doc """
Updates the event destination of a configuration set. Event destinations
are associated with configuration sets, which enable you to publish email
sending events to Amazon CloudWatch, Amazon Kinesis Firehose, or Amazon
Simple Notification Service (Amazon SNS). For information about using
configuration sets, see [Monitoring Your Amazon SES Sending
Activity](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html)
in the *Amazon SES Developer Guide.*
<note> When you create or update an event destination, you must provide
one, and only one, destination. The destination can be Amazon CloudWatch,
Amazon Kinesis Firehose, or Amazon Simple Notification Service (Amazon
SNS).
</note> You can execute this operation no more than once per second.
"""
def update_configuration_set_event_destination(client, input, options \\ []) do
request(client, "UpdateConfigurationSetEventDestination", input, options)
end
@doc """
Enables or disables the publishing of reputation metrics for emails sent
using a specific configuration set in a given AWS Region. Reputation
metrics include bounce and complaint rates. These metrics are published to
Amazon CloudWatch. By using CloudWatch, you can create alarms when bounce
or complaint rates exceed certain thresholds.
You can execute this operation no more than once per second.
"""
def update_configuration_set_reputation_metrics_enabled(client, input, options \\ []) do
request(client, "UpdateConfigurationSetReputationMetricsEnabled", input, options)
end
@doc """
Enables or disables email sending for messages sent using a specific
configuration set in a given AWS Region. You can use this operation in
conjunction with Amazon CloudWatch alarms to temporarily pause email
sending for a configuration set when the reputation metrics for that
configuration set (such as your bounce on complaint rate) exceed certain
thresholds.
You can execute this operation no more than once per second.
"""
def update_configuration_set_sending_enabled(client, input, options \\ []) do
request(client, "UpdateConfigurationSetSendingEnabled", input, options)
end
@doc """
Modifies an association between a configuration set and a custom domain for
open and click event tracking.
By default, images and links used for tracking open and click events are
hosted on domains operated by Amazon SES. You can configure a subdomain of
your own to handle these events. For information about using custom
domains, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/configure-custom-open-click-domains.html).
"""
def update_configuration_set_tracking_options(client, input, options \\ []) do
request(client, "UpdateConfigurationSetTrackingOptions", input, options)
end
@doc """
Updates an existing custom verification email template.
For more information about custom verification email templates, see [Using
Custom Verification Email
Templates](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html)
in the *Amazon SES Developer Guide*.
You can execute this operation no more than once per second.
"""
def update_custom_verification_email_template(client, input, options \\ []) do
request(client, "UpdateCustomVerificationEmailTemplate", input, options)
end
@doc """
Updates a receipt rule.
For information about managing receipt rules, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rules.html).
You can execute this operation no more than once per second.
"""
def update_receipt_rule(client, input, options \\ []) do
request(client, "UpdateReceiptRule", input, options)
end
@doc """
Updates an email template. Email templates enable you to send personalized
email to one or more destinations in a single API operation. For more
information, see the [Amazon SES Developer
Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html).
You can execute this operation no more than once per second.
"""
def update_template(client, input, options \\ []) do
request(client, "UpdateTemplate", input, options)
end
@doc """
Returns a set of DKIM tokens for a domain identity.
<important> When you execute the `VerifyDomainDkim` operation, the domain
that you specify is added to the list of identities that are associated
with your account. This is true even if you haven't already associated the
domain with your account by using the `VerifyDomainIdentity` operation.
However, you can't send email from the domain until you either successfully
[verify
it](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-domains.html)
or you successfully [set up DKIM for
it](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html).
</important> You use the tokens that are generated by this operation to
create CNAME records. When Amazon SES detects that you've added these
records to the DNS configuration for a domain, you can start sending email
from that domain. You can start sending email even if you haven't added the
TXT record provided by the VerifyDomainIdentity operation to the DNS
configuration for your domain. All email that you send from the domain is
authenticated using DKIM.
To create the CNAME records for DKIM authentication, use the following
values:
<ul> <li> **Name**: *token*._domainkey.*example.com*
</li> <li> **Type**: CNAME
</li> <li> **Value**: *token*.dkim.amazonses.com
</li> </ul> In the preceding example, replace *token* with one of the
tokens that are generated when you execute this operation. Replace
*example.com* with your domain. Repeat this process for each token that's
generated by this operation.
You can execute this operation no more than once per second.
"""
def verify_domain_dkim(client, input, options \\ []) do
request(client, "VerifyDomainDkim", input, options)
end
@doc """
Adds a domain to the list of identities for your Amazon SES account in the
current AWS Region and attempts to verify it. For more information about
verifying domains, see [Verifying Email Addresses and
Domains](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html)
in the *Amazon SES Developer Guide.*
You can execute this operation no more than once per second.
"""
def verify_domain_identity(client, input, options \\ []) do
request(client, "VerifyDomainIdentity", input, options)
end
@doc """
Deprecated. Use the `VerifyEmailIdentity` operation to verify a new email
address.
"""
def verify_email_address(client, input, options \\ []) do
request(client, "VerifyEmailAddress", input, options)
end
@doc """
Adds an email address to the list of identities for your Amazon SES account
in the current AWS region and attempts to verify it. As a result of
executing this operation, a verification email is sent to the specified
address.
You can execute this operation no more than once per second.
"""
def verify_email_identity(client, input, options \\ []) do
request(client, "VerifyEmailIdentity", input, options)
end
@spec request(AWS.Client.t(), binary(), map(), list()) ::
{:ok, Poison.Parser.t() | nil, Poison.Response.t()}
| {:error, Poison.Parser.t()}
| {:error, HTTPoison.Error.t()}
defp request(client, action, input, options) do
client = %{client | service: "ses"}
host = build_host("email", client)
url = build_url(host, client)
headers = [
{"Host", host},
{"Content-Type", "application/x-www-form-urlencoded"}
]
input = Map.merge(input, %{"Action" => action, "Version" => "2010-12-01"})
payload = AWS.Util.encode_query(input)
headers = AWS.Request.sign_v4(client, "POST", url, headers, payload)
case HTTPoison.post(url, payload, headers, options) do
{:ok, %HTTPoison.Response{status_code: 200, body: ""} = response} ->
{:ok, nil, response}
{:ok, %HTTPoison.Response{status_code: 200, body: body} = response} ->
{:ok, AWS.Util.decode_xml(body), response}
{:ok, %HTTPoison.Response{body: body}} ->
error = AWS.Util.decode_xml(body)
{:error, error}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, %HTTPoison.Error{reason: reason}}
end
end
defp build_host(_endpoint_prefix, %{region: "local"}) do
"localhost"
end
defp build_host(endpoint_prefix, %{region: region, endpoint: endpoint}) do
"#{endpoint_prefix}.#{region}.#{endpoint}"
end
defp build_url(host, %{:proto => proto, :port => port}) do
"#{proto}://#{host}:#{port}/"
end
end
| 41.545244 | 112 | 0.749004 |
9e97dcab050970ab881869b6f9c69d66a613bea3 | 14,501 | ex | Elixir | lib/elixir/lib/process.ex | bellthoven/elixir | 14610cb09b8d093d9513f97b7f4da82bdcbdd46d | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/process.ex | bellthoven/elixir | 14610cb09b8d093d9513f97b7f4da82bdcbdd46d | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/process.ex | bellthoven/elixir | 14610cb09b8d093d9513f97b7f4da82bdcbdd46d | [
"Apache-2.0"
] | null | null | null | defmodule Process do
@moduledoc """
Conveniences for working with processes and the process dictionary.
Besides the functions available in this module, the `Kernel` module
exposes and auto-imports some basic functionality related to processes
available through the functions:
* `Kernel.spawn/1` and `Kernel.spawn/3`
* `Kernel.spawn_link/1` and `Kernel.spawn_link/3`
* `Kernel.spawn_monitor/1` and `Kernel.spawn_monitor/3`
* `Kernel.self/0`
* `Kernel.send/2`
"""
@doc """
Returns `true` if the process exists and is alive (i.e. it is not exiting
and has not exited yet). Otherwise, returns `false`.
`pid` must refer to a process at the local node.
Inlined by the compiler.
"""
@spec alive?(pid) :: boolean
def alive?(pid) do
:erlang.is_process_alive(pid)
end
@doc """
Returns all key-values in the dictionary.
Inlined by the compiler.
"""
@spec get :: [{term, term}]
def get do
:erlang.get()
end
@doc """
Returns the value for the given `key`.
"""
@spec get(term) :: term
@spec get(term, default :: term) :: term
def get(key, default \\ nil) do
case :erlang.get(key) do
:undefined ->
default
value ->
value
end
end
@doc """
Returns all keys in the process dictionary.
Inlined by the compiler.
"""
@spec get_keys() :: [term]
def get_keys() do
:erlang.get_keys()
end
@doc """
Returns all keys that have the given `value`.
Inlined by the compiler.
"""
@spec get_keys(term) :: [term]
def get_keys(value) do
:erlang.get_keys(value)
end
@doc """
Stores the given key-value in the process dictionary.
The return value is the value that was previously stored under the key `key`
(or `nil` in case no value was stored under `key`).
"""
@spec put(term, term) :: term | nil
def put(key, value) do
nillify :erlang.put(key, value)
end
@doc """
Deletes the given `key` from the dictionary.
"""
@spec delete(term) :: term | nil
def delete(key) do
nillify :erlang.erase(key)
end
@doc """
Sends an exit signal with the given reason to the pid.
The following behaviour applies if reason is any term except `:normal` or `:kill`:
1. If pid is not trapping exits, pid will exit with the given reason.
2. If pid is trapping exits, the exit signal is transformed into a message
`{:EXIT, from, reason}` and delivered to the message queue of pid.
3. If reason is the atom `:normal`, pid will not exit (unless it is the calling
process's pid, in which case it will exit with the reason `:normal`).
If it is trapping exits, the exit signal is transformed into a message
`{:EXIT, from, :normal}` and delivered to its message queue.
4. If reason is the atom `:kill`, that is if `exit(pid, :kill)` is called,
an untrappable exit signal is sent to pid which will unconditionally
exit with exit reason `:killed`.
Inlined by the compiler.
## Examples
Process.exit(pid, :kill)
"""
@spec exit(pid, term) :: true
def exit(pid, reason) do
:erlang.exit(pid, reason)
end
@doc """
Sends a message to the given process.
If the option `:noconnect` is used and sending the message would require an
auto-connection to another node the message is not sent and `:noconnect` is
returned.
If the option `:nosuspend` is used and sending the message would cause the
sender to be suspended the message is not sent and `:nosuspend` is returned.
Otherwise the message is sent and `:ok` is returned.
## Examples
iex> Process.send({:name, :node_does_not_exist}, :hi, [:noconnect])
:noconnect
"""
@spec send(dest, msg, [option]) :: :ok | :noconnect | :nosuspend when
dest: pid | port | atom | {atom, node},
msg: any,
option: :noconnect | :nosuspend
def send(dest, msg, options) do
:erlang.send(dest, msg, options)
end
@doc """
Sends `msg` to `dest` after `time` milliseconds.
If `dest` is a pid, it must be the pid of a local process, dead or alive.
If `dest` is an atom, it must be the name of a registered process
which is looked up at the time of delivery. No error is given if the name does
not refer to a process.
This function returns a timer reference, which can be read or canceled with
`read_timer/1` and `cancel_timer/1`.
Finally, the timer will be automatically canceled if the given `dest` is a pid
which is not alive or when the given pid exits. Note that timers will not be
automatically canceled when `dest` is an atom (as the atom resolution is done
on delivery).
"""
@spec send_after(pid | atom, term, non_neg_integer) :: reference
def send_after(dest, msg, time) do
:erlang.send_after(time, dest, msg)
end
@doc """
Cancels a timer created by `send_after/3`.
When the result is an integer, it represents the time in milli-seconds
left until the timer will expire.
When the result is `false`, a timer corresponding to `timer_ref` could
not be found. This can be either because the timer expired, already has
been canceled, or because `timer_ref` never corresponded to a timer.
If the timer has expired, the timeout message has been sent, but it does
not tell you whether or not it has arrived at its destination yet.
Inlined by the compiler.
"""
@spec cancel_timer(reference) :: non_neg_integer | false
def cancel_timer(timer_ref) do
:erlang.cancel_timer(timer_ref)
end
@doc """
Reads a timer created by `send_after/3`.
When the result is an integer, it represents the time in milli-seconds
left until the timer will expire.
When the result is `false`, a timer corresponding to `timer_ref` could
not be found. This can be either because the timer expired, already has
been canceled, or because `timer_ref` never corresponded to a timer.
If the timer has expired, the timeout message has been sent, but it does
not tell you whether or not it has arrived at its destination yet.
Inlined by the compiler.
"""
@spec read_timer(reference) :: non_neg_integer | false
def read_timer(timer_ref) do
:erlang.read_timer(timer_ref)
end
@type spawn_opt :: :link | :monitor | {:priority, :low | :normal | :high} |
{:fullsweep_after, non_neg_integer} |
{:min_heap_size, non_neg_integer} |
{:min_bin_vheap_size, non_neg_integer}
@type spawn_opts :: [spawn_opt]
@doc """
Spawns the given module and function passing the given args
according to the given options.
The result depends on the given options. In particular,
if `:monitor` is given as an option, it will return a tuple
containing the pid and the monitoring reference, otherwise
just the spawned process pid.
It also accepts extra options, for the list of available options
check [`:erlang.spawn_opt/4`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-4).
Inlined by the compiler.
"""
@spec spawn((() -> any), spawn_opts) :: pid | {pid, reference}
def spawn(fun, opts) do
:erlang.spawn_opt(fun, opts)
end
@doc """
Spawns the given module and function passing the given args
according to the given options.
The result depends on the given options. In particular,
if `:monitor` is given as an option, it will return a tuple
containing the pid and the monitoring reference, otherwise
just the spawned process pid.
It also accepts extra options, for the list of available options
check [`:erlang.spawn_opt/4`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-4).
Inlined by the compiler.
"""
@spec spawn(module, atom, list, spawn_opts) :: pid | {pid, reference}
def spawn(mod, fun, args, opts) do
:erlang.spawn_opt(mod, fun, args, opts)
end
@doc """
The calling process starts monitoring the item given.
It returns the monitor reference.
See [the need for monitoring](http://elixir-lang.org/getting-started/mix-otp/genserver.html#the-need-for-monitoring)
for an example.
See [`:erlang.monitor/2`](http://www.erlang.org/doc/man/erlang.html#monitor-2) for more info.
Inlined by the compiler.
"""
@spec monitor(pid | {reg_name :: atom, node :: atom} | reg_name :: atom) :: reference
def monitor(item) do
:erlang.monitor(:process, item)
end
@doc """
If `monitor_ref` is a reference which the calling process
obtained by calling `monitor/1`, this monitoring is turned off.
If the monitoring is already turned off, nothing happens.
See [`:erlang.demonitor/2`](http://www.erlang.org/doc/man/erlang.html#demonitor-2) for more info.
Inlined by the compiler.
"""
@spec demonitor(reference) :: true
@spec demonitor(reference, options :: [:flush | :info]) :: boolean
def demonitor(monitor_ref, options \\ []) do
:erlang.demonitor(monitor_ref, options)
end
@doc """
Returns a list of process identifiers corresponding to all the
processes currently existing on the local node.
Note that a process that is exiting, exists but is not alive, i.e.,
`alive?/1` will return `false` for a process that is exiting,
but its process identifier will be part of the result returned.
See [`:erlang.processes/0`](http://www.erlang.org/doc/man/erlang.html#processes-0) for more info.
"""
@spec list :: [pid]
def list do
:erlang.processes()
end
@doc """
Creates a link between the calling process and another process
(or port) `pid`, if there is not such a link already.
See [`:erlang.link/1`](http://www.erlang.org/doc/man/erlang.html#link-1) for more info.
Inlined by the compiler.
"""
@spec link(pid | port) :: true
def link(pid) do
:erlang.link(pid)
end
@doc """
Removes the link, if there is one, between the calling process and
the process or port referred to by `pid`. Returns `true` and does not
fail, even if there is no link or `id` does not exist
See [`:erlang.unlink/1`](http://www.erlang.org/doc/man/erlang.html#unlink-1) for more info.
Inlined by the compiler.
"""
@spec unlink(pid | port) :: true
def unlink(pid) do
:erlang.unlink(pid)
end
@doc """
Associates the name with a pid or a port identifier. `name`, which must
be an atom, can be used instead of the pid / port identifier with the
`Kernel.send/2` function.
`Process.register/2` will fail with `ArgumentError` if the pid supplied
is no longer alive, (check with `alive?/1`) or if the name is
already registered (check with `whereis/1`).
"""
@spec register(pid | port, atom) :: true
def register(pid, name) when not name in [nil, false, true] do
:erlang.register(name, pid)
end
@doc """
Removes the registered name, associated with a pid or a port identifier.
See [`:erlang.unregister/1`](http://www.erlang.org/doc/man/erlang.html#unregister-1) for more info.
"""
@spec unregister(atom) :: true
def unregister(name) do
:erlang.unregister(name)
end
@doc """
Returns the pid or port identifier with the registered name.
Returns `nil` if the name is not registered.
See [`:erlang.whereis/1`](http://www.erlang.org/doc/man/erlang.html#whereis-1) for more info.
"""
@spec whereis(atom) :: pid | port | nil
def whereis(name) do
nillify :erlang.whereis(name)
end
@doc """
Returns the pid of the group leader for the process which evaluates the function.
"""
@spec group_leader :: pid
def group_leader do
:erlang.group_leader
end
@doc """
Sets the group leader of `pid` to `leader`. Typically, this is used when a processes
started from a certain shell should have a group leader other than `:init`.
"""
@spec group_leader(pid, leader :: pid) :: true
def group_leader(pid, leader) do
:erlang.group_leader(leader, pid)
end
@doc """
Returns a list of names which have been registered using `register/2`.
"""
@spec registered :: [atom]
def registered do
:erlang.registered()
end
@typep process_flag :: :trap_exit | :error_handler | :min_heap_size |
:min_bin_vheap_size | :priority | :save_calls |
:sensitive
@doc """
Sets certain flags for the process which calls this function.
Returns the old value of the flag.
See [`:erlang.process_flag/2`](http://www.erlang.org/doc/man/erlang.html#process_flag-2) for more info.
"""
@spec flag(process_flag, term) :: term
def flag(flag, value) do
:erlang.process_flag(flag, value)
end
@doc """
Sets certain flags for the process `pid`, in the same manner as `flag/2`.
Returns the old value of the flag. The allowed values for `flag` are
only a subset of those allowed in `flag/2`, namely: `save_calls`.
See [`:erlang.process_flag/3`](http://www.erlang.org/doc/man/erlang.html#process_flag-3) for more info.
"""
@spec flag(pid, :save_calls, non_neg_integer) :: non_neg_integer
def flag(pid, flag, value) do
:erlang.process_flag(pid, flag, value)
end
@doc """
Returns information about the process identified by `pid` or `nil` if the process
is not alive.
Use this only for debugging information.
See [`:erlang.process_info/1`](http://www.erlang.org/doc/man/erlang.html#process_info-1) for more info.
"""
@spec info(pid) :: Keyword.t
def info(pid) do
nillify :erlang.process_info(pid)
end
@doc """
Returns information about the process identified by `pid`
or `nil` if the process is not alive.
See [`:erlang.process_info/2`](http://www.erlang.org/doc/man/erlang.html#process_info-2) for more info.
"""
@spec info(pid, atom | [atom]) :: {atom, term} | [{atom, term}] | nil
def info(pid, spec)
def info(pid, :registered_name) do
case :erlang.process_info(pid, :registered_name) do
:undefined -> nil
[] -> {:registered_name, []}
other -> other
end
end
def info(pid, spec) when is_atom(spec) or is_list(spec) do
nillify :erlang.process_info(pid, spec)
end
@doc """
Puts the calling process into a wait state
where its memory allocation has been reduced as much as possible,
which is useful if the process does not expect to receive any messages
in the near future.
See [`:erlang.hibernate/3`](http://www.erlang.org/doc/man/erlang.html#hibernate-3) for more info.
Inlined by the compiler.
"""
@spec hibernate(module, atom, list) :: no_return
def hibernate(mod, fun, args) do
:erlang.hibernate(mod, fun, args)
end
@compile {:inline, nillify: 1}
defp nillify(:undefined), do: nil
defp nillify(other), do: other
end
| 31.184946 | 118 | 0.682436 |
9e9817e369ed933c755de46fc7a4e020c5892796 | 333 | ex | Elixir | lib/hex.ex | joshchernoff/hagrid | 53e6b6a8af5be670532725900af8df0623a098c5 | [
"Unlicense"
] | 2 | 2018-07-14T20:32:19.000Z | 2019-12-03T20:01:56.000Z | lib/hex.ex | joshchernoff/hagrid | 53e6b6a8af5be670532725900af8df0623a098c5 | [
"Unlicense"
] | null | null | null | lib/hex.ex | joshchernoff/hagrid | 53e6b6a8af5be670532725900af8df0623a098c5 | [
"Unlicense"
] | null | null | null | defmodule HexApi do
@api "https://hex.pm/api/packages"
def search query do
query
|> build_request
|> HTTPoison.get
|> parse
end
def build_request query do
@api <> "?limit=10&sort=downloads&search=" <> query
end
defp parse {:ok, %HTTPoison.Response{body: body}} do
Poison.decode(body)
end
end
| 17.526316 | 55 | 0.645646 |
9e984281d77fa1e9bf664cf31d657e4415e7806d | 3,454 | exs | Elixir | test/live_component_events_test.exs | alexandrubagu/surface | b8ef74444e53f8325fb793fa1399966c2a4b1e7a | [
"MIT"
] | null | null | null | test/live_component_events_test.exs | alexandrubagu/surface | b8ef74444e53f8325fb793fa1399966c2a4b1e7a | [
"MIT"
] | null | null | null | test/live_component_events_test.exs | alexandrubagu/surface | b8ef74444e53f8325fb793fa1399966c2a4b1e7a | [
"MIT"
] | 1 | 2020-04-21T18:49:15.000Z | 2020-04-21T18:49:15.000Z | defmodule Surface.EventsTest do
use ExUnit.Case
use Phoenix.ConnTest
import Phoenix.LiveViewTest
import ComponentTestHelper
@endpoint Endpoint
defmodule LiveDiv do
use Surface.LiveComponent
def render(assigns) do
~H"""
<div>Live div</div>
"""
end
end
defmodule Button do
use Surface.LiveComponent
property click, :event, default: "click"
def render(assigns) do
~H"""
<button :on-phx-click={{ @click }}>Click me!</button>
"""
end
def handle_event("click", _, socket) do
{:noreply, socket}
end
end
defmodule Panel do
use Surface.LiveComponent
property buttonClick, :event, default: "click"
def render(assigns) do
~H"""
<div>
<Button id="button_id" click={{ @buttonClick }}/>
</div>
"""
end
def handle_event("click", _, socket) do
{:noreply, socket}
end
end
defmodule ButtonWithInvalidEvent do
use Surface.LiveComponent
property click, :event
def render(assigns) do
~H"""
<button phx-click={{ @click }}/>
"""
end
end
defmodule View do
use Surface.LiveView
def render(assigns) do
~H"""
<div>
<Panel id="panel_id" buttonClick="click"/>
</div>
"""
end
def handle_event("click", _, socket) do
{:noreply, socket}
end
end
test "handle event in the parent liveview" do
{:ok, _view, html} = live_isolated(build_conn(), View)
assert_html(
html =~ """
<button data-phx-component="1" phx-click="click">Click me!</button>
"""
)
end
test "handle event in parent component" do
code = """
<div>
<Panel id="panel_id"/>
</div>
"""
assert render_live(code) =~ """
<button data-phx-component="1" phx-click="click" phx-target="0"\
"""
end
test "handle event locally" do
code = """
<div>
<Button id="button_id"/>
</div>
"""
assert render_live(code) =~ """
<button data-phx-component="0" phx-click="click" phx-target="0"\
"""
end
test "override target" do
code = """
<div>
<Button id="button_id" click={{ %{name: "ok", target: "#comp"} }}/>
</div>
"""
assert render_live(code) =~ """
phx-click="ok" phx-target="#comp"\
"""
end
test "override target with keyword list notation" do
code = """
<div>
<Button id="button_id" click={{ "ok", target: "#comp" }}/>
</div>
"""
assert render_live(code) =~ """
phx-click="ok" phx-target="#comp"\
"""
end
test "passing event as nil does not render phx-*" do
code = """
<div>
<Button id="button_id" click={{ nil }}/>
</div>
"""
html = render_live(code)
assert html =~ "<button"
refute html =~ "phx-click"
refute html =~ "phx-target"
end
test "raise error when passing an :event into a phx-* binding" do
code = """
<div>
<ButtonWithInvalidEvent id="button_id" click={{ "ok" }}/>
</div>
"""
message = """
invalid value for "phx-click". LiveView bindings only accept values \
of type :string. If you want to pass an :event, please use directive \
:on-phx-click instead. Expected a :string, got: %{name: "ok", target: :live_view}\
"""
assert_raise(RuntimeError, message, fn ->
render_live(code)
end)
end
end
| 20.19883 | 86 | 0.56022 |
9e9847faa38c82f1dd3194e321246ead8e960a55 | 452 | ex | Elixir | lib/bpmn/activity/task/user.ex | Around25/hashiru-bpmn | 56271b700b71ecef409f932dbacb02392f403be9 | [
"Apache-2.0"
] | 13 | 2017-09-19T17:49:59.000Z | 2021-09-21T18:20:15.000Z | lib/bpmn/activity/task/user.ex | Around25/hashiru-bpmn | 56271b700b71ecef409f932dbacb02392f403be9 | [
"Apache-2.0"
] | 7 | 2017-10-17T16:44:37.000Z | 2017-11-14T23:40:40.000Z | lib/bpmn/activity/task/user.ex | Around25/hashiru-bpmn | 56271b700b71ecef409f932dbacb02392f403be9 | [
"Apache-2.0"
] | 3 | 2017-10-21T08:23:26.000Z | 2021-09-10T14:27:07.000Z | defmodule Bpmn.Activity.Task.User do
@moduledoc """
Handle passing the token through an event element.
"""
@doc """
Receive the token for the element and decide if the business logic should be executed
"""
def tokenIn(elem, context), do: execute(elem, context)
defp tokenOut(elem, context), do: {:not_implemented}
@doc """
Execute the start event business logic
"""
def execute(elem, context), do: tokenOut(elem, context)
end | 26.588235 | 87 | 0.70354 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.