hexsha stringlengths 40 40 | size int64 2 991k | ext stringclasses 2 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 208 | max_stars_repo_name stringlengths 6 106 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses list | max_stars_count int64 1 33.5k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 208 | max_issues_repo_name stringlengths 6 106 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses list | max_issues_count int64 1 16.3k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 208 | max_forks_repo_name stringlengths 6 106 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses list | max_forks_count int64 1 6.91k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 991k | avg_line_length float64 1 36k | max_line_length int64 1 977k | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
03dafab613ae90adfa1678c8a19b30c34655c82a | 1,236 | ex | Elixir | lib/datum/ellipsoid.ex | danielzfranklin/coord | bf2fd85302128698367f4781d78baac9e534f071 | [
"Apache-2.0",
"MIT"
] | null | null | null | lib/datum/ellipsoid.ex | danielzfranklin/coord | bf2fd85302128698367f4781d78baac9e534f071 | [
"Apache-2.0",
"MIT"
] | null | null | null | lib/datum/ellipsoid.ex | danielzfranklin/coord | bf2fd85302128698367f4781d78baac9e534f071 | [
"Apache-2.0",
"MIT"
] | null | null | null | defmodule Coord.Datum.Ellipsoid do
@moduledoc """
Specified the shape of the surface of a `Coord.Datum`. See the typedoc for
`t:Coord.Datum.Ellipsoid.t/0` for the specifics of how to create an instance.
## Concept
An ellipsoid is a surface that approximates the shape of the earth. It is
constructed by flattening a sphere. WGS84 is defined by an ellipsoid with
specific parameters. Other datum either use different parameters of different
shapes altogether.
Source: <https://en.wikipedia.org/wiki/Reference_ellipsoid>
"""
@typedoc """
Assumes an oblate sphereoid datum surface like WGS84. Other types of surfaces are not currently
supported.
Keys:
* `:a`: equatorial radius of the sphereoid in meters
* `:b`: the polar semi-minor axis in meters (equals a * (1 − f))
* `:f`: flattening (also known as ellipticity or oblateness)
For example, the function `Coord.Datum.wgs84/0` creates an instance of an `Coord.Datum.Ellipsoid`
that looks like this:
```
%Coord.Datum.Ellipsoid{a: 6_378_137, b: 6_356_752.314245, f: 1 / 298.257223563}
```
"""
@type t :: %__MODULE__{
a: integer(),
b: float(),
f: float()
}
defstruct a: nil, b: nil, f: nil
end
| 30.9 | 99 | 0.687702 |
03db1dd0cabb6ad1322da23f8b785b1c8ecf2193 | 342 | ex | Elixir | apps/language_server/lib/language_server/protocol/document_symbol.ex | wingyplus/elixir-ls | b3f00a5332d7886816df8056a3a8297c4eb447b2 | [
"Apache-2.0"
] | null | null | null | apps/language_server/lib/language_server/protocol/document_symbol.ex | wingyplus/elixir-ls | b3f00a5332d7886816df8056a3a8297c4eb447b2 | [
"Apache-2.0"
] | null | null | null | apps/language_server/lib/language_server/protocol/document_symbol.ex | wingyplus/elixir-ls | b3f00a5332d7886816df8056a3a8297c4eb447b2 | [
"Apache-2.0"
] | null | null | null | defmodule ElixirLS.LanguageServer.Protocol.DocumentSymbol do
@moduledoc """
Corresponds to the LSP interface of the same name.
For details see https://microsoft.github.io/language-server-protocol/specification#textDocument_documentSymbol
"""
@derive Jason.Encoder
defstruct [:name, :kind, :range, :selectionRange, :children]
end
| 34.2 | 112 | 0.780702 |
03db3198a1fd82ef86eaacb98529a7afd5283a2d | 90 | exs | Elixir | misc_util_math.exs | sebmaldo/Getting-Started-with-Elixir | 87754e36e39f7e375aeb2c038339a111f23cb3b9 | [
"MIT"
] | null | null | null | misc_util_math.exs | sebmaldo/Getting-Started-with-Elixir | 87754e36e39f7e375aeb2c038339a111f23cb3b9 | [
"MIT"
] | null | null | null | misc_util_math.exs | sebmaldo/Getting-Started-with-Elixir | 87754e36e39f7e375aeb2c038339a111f23cb3b9 | [
"MIT"
] | null | null | null | defmodule ModulePlayground.Misc.Util.Math do
def add(a,b) do
a + b
end
end | 18 | 44 | 0.633333 |
03db49cb798ecb085afaeca1b9e321372ce5f0ec | 326 | ex | Elixir | ping/lib/ping.ex | enilsen16/elixir | b4d1d45858a25e4beb39e07de8685f3d93d6a520 | [
"MIT"
] | null | null | null | ping/lib/ping.ex | enilsen16/elixir | b4d1d45858a25e4beb39e07de8685f3d93d6a520 | [
"MIT"
] | null | null | null | ping/lib/ping.ex | enilsen16/elixir | b4d1d45858a25e4beb39e07de8685f3d93d6a520 | [
"MIT"
] | null | null | null | defmodule Ping do
def main do
{:ok, %HTTPoison.Response{body: body}} = HTTPoison.get "http://www.imdb.com/title/tt3219604/?ref_=tt_rec_tti"
body
|> Floki.find("#title_recs a")
|> Floki.attribute("href")
|> Enum.filter(fn(x) -> String.starts_with?(x, "/title/") end )
|> List.first
end
end
| 27.166667 | 113 | 0.616564 |
03db6ea58387b99747c9ba3232e7dfbfbe259086 | 3,442 | exs | Elixir | config/runtime.exs | ricardopadua/introduction_phoenix_liveview | 3e320b4ea7f80b079dfcd9ac2d5714b1204ce4ed | [
"Apache-2.0"
] | null | null | null | config/runtime.exs | ricardopadua/introduction_phoenix_liveview | 3e320b4ea7f80b079dfcd9ac2d5714b1204ce4ed | [
"Apache-2.0"
] | null | null | null | config/runtime.exs | ricardopadua/introduction_phoenix_liveview | 3e320b4ea7f80b079dfcd9ac2d5714b1204ce4ed | [
"Apache-2.0"
] | null | null | null | import Config
# config/runtime.exs is executed for all environments, including
# during releases. It is executed after compilation and before the
# system starts, so it is typically used to load production configuration
# and secrets from environment variables or elsewhere. Do not define
# any compile-time configuration in here, as it won't be applied.
# The block below contains prod specific runtime configuration.
# Start the phoenix server if environment is set and running in a release
if System.get_env("PHX_SERVER") && System.get_env("RELEASE_NAME") do
config :introduction_phoenix_liveview, IntroductionPhoenixLiveviewWeb.Endpoint, server: true
end
if config_env() == :prod do
database_url =
System.get_env("DATABASE_URL") ||
raise """
environment variable DATABASE_URL is missing.
For example: ecto://USER:PASS@HOST/DATABASE
"""
maybe_ipv6 = if System.get_env("ECTO_IPV6"), do: [:inet6], else: []
config :introduction_phoenix_liveview, IntroductionPhoenixLiveview.Repo,
# ssl: true,
url: database_url,
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
socket_options: maybe_ipv6
# The secret key base is used to sign/encrypt cookies and other secrets.
# A default value is used in config/dev.exs and config/test.exs but you
# want to use a different value for prod and you most likely don't want
# to check this value into version control, so we use an environment
# variable instead.
secret_key_base =
System.get_env("SECRET_KEY_BASE") ||
raise """
environment variable SECRET_KEY_BASE is missing.
You can generate one by calling: mix phx.gen.secret
"""
host = System.get_env("PHX_HOST") || "example.com"
port = String.to_integer(System.get_env("PORT") || "4000")
config :introduction_phoenix_liveview, IntroductionPhoenixLiveviewWeb.Endpoint,
url: [host: host, port: 443],
http: [
# Enable IPv6 and bind on all interfaces.
# Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
# See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html
# for details about using IPv6 vs IPv4 and loopback vs public addresses.
ip: {0, 0, 0, 0, 0, 0, 0, 0},
port: port
],
secret_key_base: secret_key_base
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start each relevant endpoint:
#
# config :introduction_phoenix_liveview, IntroductionPhoenixLiveviewWeb.Endpoint, server: true
#
# Then you can assemble a release by calling `mix release`.
# See `mix help release` for more information.
# ## Configuring the mailer
#
# In production you need to configure the mailer to use a different adapter.
# Also, you may need to configure the Swoosh API client of your choice if you
# are not using SMTP. Here is an example of the configuration:
#
# config :introduction_phoenix_liveview, IntroductionPhoenixLiveview.Mailer,
# adapter: Swoosh.Adapters.Mailgun,
# api_key: System.get_env("MAILGUN_API_KEY"),
# domain: System.get_env("MAILGUN_DOMAIN")
#
# For this example you need include a HTTP client required by Swoosh API client.
# Swoosh supports Hackney and Finch out of the box:
#
# config :swoosh, :api_client, Swoosh.ApiClient.Hackney
#
# See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details.
end
| 40.023256 | 100 | 0.717025 |
03db75aab594f97b0ed81166e02cc8f1f111dc63 | 95 | ex | Elixir | Elixir/HelloWorld.ex | godslayer201/Hello-World | 0b0dec4f8d18d2db348ee4fd0fad8233dd9074a4 | [
"MIT"
] | null | null | null | Elixir/HelloWorld.ex | godslayer201/Hello-World | 0b0dec4f8d18d2db348ee4fd0fad8233dd9074a4 | [
"MIT"
] | null | null | null | Elixir/HelloWorld.ex | godslayer201/Hello-World | 0b0dec4f8d18d2db348ee4fd0fad8233dd9074a4 | [
"MIT"
] | null | null | null | # Hello World
defmodule ModuleName do
def hello do
IO.puts "Hello World"
end
end
| 13.571429 | 26 | 0.663158 |
03db789745b7f11f0d4bdffb1b9d6b674b091c4b | 1,465 | exs | Elixir | test/configuration_test.exs | niccolox/publicsuffix-elixir | 34adba7a6f6accc6c3fe95db7b169367b0bfd56e | [
"MIT"
] | 42 | 2016-04-21T21:14:04.000Z | 2021-07-18T11:00:25.000Z | test/configuration_test.exs | niccolox/publicsuffix-elixir | 34adba7a6f6accc6c3fe95db7b169367b0bfd56e | [
"MIT"
] | 21 | 2016-05-11T23:27:55.000Z | 2021-07-08T01:46:54.000Z | test/configuration_test.exs | niccolox/publicsuffix-elixir | 34adba7a6f6accc6c3fe95db7b169367b0bfd56e | [
"MIT"
] | 18 | 2016-05-19T20:19:59.000Z | 2021-07-07T23:17:32.000Z | defmodule PublicSuffix.ConfigurationTest do
use ExUnit.Case
@data_file_name "public_suffix_list.dat"
@cached_data_dir Path.expand("../data", __DIR__)
setup do
temp_dir = "tmp/#{:test_server.temp_name('public_suffix-test')}"
File.mkdir_p!(temp_dir)
cached_file_name = Path.join(@cached_data_dir, @data_file_name)
backup_file_name = Path.join(temp_dir, @data_file_name)
File.cp!(cached_file_name, backup_file_name)
modified_rules =
cached_file_name
|> File.read!
|> Kernel.<>("\npublicsuffix.elixir")
File.write!(cached_file_name, modified_rules)
on_exit fn ->
# restore things...
recompile_lib
File.cp!(backup_file_name, cached_file_name)
File.rm_rf!(temp_dir)
end
end
test "compiles using a newly fetched copy of the rules file if so configured" do
recompile_lib
assert get_public_suffix("foo.publicsuffix.elixir") == "publicsuffix.elixir"
recompile_lib [{"PUBLIC_SUFFIX_DOWNLOAD_DATA_ON_COMPILE", "true"}]
assert get_public_suffix("foo.publicsuffix.elixir") == "elixir"
end
defp get_public_suffix(domain) do
expression = "#{inspect domain} |> PublicSuffix.public_suffix |> IO.puts"
assert {result, 0} = System.cmd "mix", ["run", "-e", expression]
result |> String.strip |> String.split("\n") |> List.last
end
defp recompile_lib(env \\ []) do
assert {_output, 0} = System.cmd "mix", ["compile", "--force"], env: env
end
end
| 31.170213 | 82 | 0.69215 |
03db9b5d6c67ab9241d0f759b04b1385fae9c9b0 | 1,884 | ex | Elixir | lib/hexpm_web/views/blog_view.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 691 | 2017-03-08T09:15:45.000Z | 2022-03-23T22:04:47.000Z | lib/hexpm_web/views/blog_view.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 491 | 2017-03-07T12:58:42.000Z | 2022-03-29T23:32:54.000Z | lib/hexpm_web/views/blog_view.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 200 | 2017-03-12T23:03:39.000Z | 2022-03-05T17:55:52.000Z | defmodule HexpmWeb.BlogView do
use HexpmWeb, :view
alias Hexpm.Utils
skip_slugs = ~w()
all_templates =
Phoenix.Template.find_all(@phoenix_root)
|> Enum.map(&Phoenix.Template.template_path_to_name(&1, @phoenix_root))
|> Enum.flat_map(fn
<<n1, n2, n3, "-", slug::binary>> = template
when n1 in ?0..?9 and n2 in ?0..?9 and n3 in ?0..?9 ->
[{Path.rootname(slug), template}]
_other ->
[]
end)
|> Enum.reject(fn {slug, _template} -> slug in skip_slugs end)
|> Enum.sort_by(&elem(&1, 1), &>=/2)
def render("index.html", _assigns) do
render_template("index.html", posts: posts())
end
def render("index.xml", _assigns) do
render_template("index.xml", posts: posts())
end
def render(other, _assigns) do
content_tag(:div, render_template(other, %{}), class: "show-post")
end
def all_templates() do
unquote(all_templates)
end
defp posts() do
Enum.map(all_templates(), fn {slug, template} ->
content = render(template, %{})
content = Phoenix.HTML.safe_to_string(content)
%{
slug: slug,
title: title(content),
subtitle: subtitle(content),
paragraph: first_paragraph(content),
published: published(content)
}
end)
end
defp first_paragraph(content) do
regex_run(~r[<p>(.*)</p>]sU, content)
end
defp title(content) do
regex_run(~r[<h2>(.*)</h2>]sU, content)
end
defp subtitle(content) do
regex_run(~r[<div class="subtitle">(.*)</div>]sU, content)
end
defp published(content) do
{:ok, datetime, _utc_offset} =
~r[<time datetime="(.+)">(.+)</time>]sU
|> regex_run(content)
|> DateTime.from_iso8601()
Utils.datetime_to_rfc2822(datetime)
end
defp regex_run(regex, string) do
regex
|> Regex.run(string)
|> Enum.at(1)
|> String.trim()
end
end
| 23.259259 | 75 | 0.610403 |
03dbb9afe18d4b4993ea516b0d43f643b05f25d2 | 446 | exs | Elixir | elixir/sublist/sublist.exs | dtcristo/exercism-solutions | 312922ff1bedc51e9273f746eb90af71644cb971 | [
"MIT"
] | 1 | 2017-08-24T07:34:14.000Z | 2017-08-24T07:34:14.000Z | elixir/sublist/sublist.exs | dtcristo/exercism-solutions | 312922ff1bedc51e9273f746eb90af71644cb971 | [
"MIT"
] | null | null | null | elixir/sublist/sublist.exs | dtcristo/exercism-solutions | 312922ff1bedc51e9273f746eb90af71644cb971 | [
"MIT"
] | null | null | null | defmodule Sublist do
@doc """
Returns whether the first list is a sublist or a superlist of the second list
and if not whether it is equal or unequal to the second list.
"""
def compare(l, l), do: :equal
def compare([], _), do: :sublist
def compare(_, []), do: :superlist
def compare(a, b), do: :unequal
def compare([a|as], [b|bs]) do
cond do
(a == b) -> compare(as, bs)
true -> :unequal
end
end
end
| 21.238095 | 79 | 0.607623 |
03dbd10a409f5b6b699a2cc826f318c4ae5ce9fb | 4,476 | exs | Elixir | test/absinthe/middleware/dataloader_test.exs | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | 1 | 2019-10-10T02:57:52.000Z | 2019-10-10T02:57:52.000Z | test/absinthe/middleware/dataloader_test.exs | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | 2 | 2020-07-21T05:23:37.000Z | 2020-08-26T04:56:12.000Z | test/absinthe/middleware/dataloader_test.exs | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | 1 | 2018-11-16T02:34:40.000Z | 2018-11-16T02:34:40.000Z | defmodule Absinthe.Middleware.DataloaderTest do
use Absinthe.Case, async: true
defmodule Schema do
use Absinthe.Schema
import Absinthe.Resolution.Helpers
@organizations 1..3
|> Map.new(
&{&1,
%{
id: &1,
name: "Organization: ##{&1}"
}}
)
@users 1..3
|> Enum.map(
&%{
id: &1,
name: "User: ##{&1}",
organization_id: &1
}
)
def organizations(), do: @organizations
defp batch_load({:organization_id, %{pid: test_pid}}, sources) do
send(test_pid, :loading)
Map.new(sources, fn src ->
{src, Map.fetch!(@organizations, src.organization_id)}
end)
end
def dataloader() do
source = Dataloader.KV.new(&batch_load/2)
Dataloader.add_source(Dataloader.new(), :test, source)
end
def context(ctx) do
ctx
|> Map.put_new(:loader, dataloader())
|> Map.merge(%{
test_pid: self()
})
end
def plugins do
[Absinthe.Middleware.Dataloader] ++ Absinthe.Plugin.defaults()
end
object :organization do
field :id, :integer
field :name, :string
end
object :user do
field :name, :string
field :foo_organization, :organization do
resolve dataloader(:test, fn _, _, %{context: %{test_pid: pid}} ->
{:organization_id, %{pid: pid}}
end)
end
field :bar_organization, :organization do
resolve dataloader(:test, :organization_id, args: %{pid: self()})
end
end
query do
field :users, list_of(:user) do
resolve fn _, _, _ -> {:ok, @users} end
end
field :organization, :organization do
arg :id, non_null(:integer)
resolve fn _, %{id: id}, %{context: %{loader: loader, test_pid: test_pid}} ->
loader
|> Dataloader.load(:test, {:organization_id, %{pid: test_pid}}, %{organization_id: id})
|> Dataloader.put(
:test,
{:organization_id, %{pid: self()}},
%{organization_id: 123},
%{}
)
|> on_load(fn loader ->
{:ok,
Dataloader.get(loader, :test, {:organization_id, %{pid: test_pid}}, %{
organization_id: id
})}
end)
end
end
end
end
test "can resolve a field using the normal dataloader helper" do
doc = """
{
users {
organization: barOrganization {
name
}
}
}
"""
expected_data = %{
"users" => [
%{"organization" => %{"name" => "Organization: #1"}},
%{"organization" => %{"name" => "Organization: #2"}},
%{"organization" => %{"name" => "Organization: #3"}}
]
}
assert {:ok, %{data: data}} = Absinthe.run(doc, Schema)
assert expected_data == data
assert_receive(:loading)
refute_receive(:loading)
end
test "can resolve batched fields cross-query that have different data requirements" do
doc = """
{
users {
organization: fooOrganization {
name
}
}
organization(id: 1) {
id
}
}
"""
expected_data = %{
"users" => [
%{"organization" => %{"name" => "Organization: #1"}},
%{"organization" => %{"name" => "Organization: #2"}},
%{"organization" => %{"name" => "Organization: #3"}}
],
"organization" => %{"id" => 1}
}
assert {:ok, %{data: data}} = Absinthe.run(doc, Schema)
assert expected_data == data
assert_receive(:loading)
refute_receive(:loading)
end
test "using a cached field doesn't explode" do
doc = """
{
organization(id: 1) {
id
}
}
"""
expected_data = %{"organization" => %{"id" => 1}}
org = Schema.organizations()[1]
# Get the dataloader, and warm the cache for the organization key we're going
# to try to access via graphql.
dataloader =
Schema.dataloader()
|> Dataloader.put(:test, {:organization_id, %{pid: self()}}, %{organization_id: 1}, org)
context = %{
loader: dataloader
}
assert {:ok, %{data: data}} = Absinthe.run(doc, Schema, context: context)
assert expected_data == data
refute_receive(:loading)
end
end
| 24.326087 | 97 | 0.514969 |
03dbfdf0db0aa06dea06e3835b7c2fa979b0ad4c | 1,759 | exs | Elixir | mix.exs | sidharth-shridhar/Bitcoin-Miner-Simulation | 2789dc8fe5f65269789540f675fac682e431e518 | [
"MIT"
] | 1 | 2021-12-16T08:31:24.000Z | 2021-12-16T08:31:24.000Z | mix.exs | hojason117/BitcoinSimulator | f85e623eec1923a2c0d418388f440cc06b6a5283 | [
"MIT"
] | null | null | null | mix.exs | hojason117/BitcoinSimulator | f85e623eec1923a2c0d418388f440cc06b6a5283 | [
"MIT"
] | null | null | null | defmodule BitcoinSimulator.MixProject do
use Mix.Project
def project do
[
app: :bitcoin_simulator,
version: "0.1.0",
elixir: "~> 1.5",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix, :gettext] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
aliases: aliases(),
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {BitcoinSimulator.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:phoenix, "~> 1.4.0"},
{:phoenix_pubsub, "~> 1.1"},
# {:phoenix_ecto, "~> 4.0"},
# {:ecto_sql, "~> 3.0"},
# {:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.11"},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:gettext, "~> 0.11"},
{:jason, "~> 1.0"},
{:plug_cowboy, "~> 2.0", override: true},
{:timex, "~> 3.1"},
{:drab, "~> 0.10.0"}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to create, migrate and run the seeds file at once:
#
# $ mix ecto.setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
# "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
# "ecto.reset": ["ecto.drop", "ecto.setup"],
# test: ["ecto.create --quiet", "ecto.migrate", "test"]
]
end
end
| 27.061538 | 81 | 0.571916 |
03dc3cb26aa72fbff6ef901dc0a492230aee06a6 | 8,153 | ex | Elixir | web/router.ex | aman-io/exq_ui | 28a02575481a5ddf77a0ea302d711c55c7420bab | [
"Apache-2.0"
] | null | null | null | web/router.ex | aman-io/exq_ui | 28a02575481a5ddf77a0ea302d711c55c7420bab | [
"Apache-2.0"
] | null | null | null | web/router.ex | aman-io/exq_ui | 28a02575481a5ddf77a0ea302d711c55c7420bab | [
"Apache-2.0"
] | null | null | null | defmodule ExqUi.RouterPlug do
require Logger
require EEx
alias ExqUi.RouterPlug.Router
def init(options) do
enq_opts =
if options[:exq_opts] do
options[:exq_opts]
else
[name: Exq.Api.Server.server_name(ExqUi)]
end
Keyword.put(options, :exq_opts, enq_opts)
end
def call(conn, opts) do
namespace_opt = opts[:namespace] || "exq"
conn = Plug.Conn.assign(conn, :namespace, namespace_opt)
conn = Plug.Conn.assign(conn, :exq_name, opts[:exq_opts][:name])
case namespace_opt do
"" ->
Router.call(conn, Router.init(opts))
_ ->
namespace(conn, opts, namespace_opt)
end
end
def namespace(%Plug.Conn{path_info: [ns | path]} = conn, opts, ns) do
Router.call(%Plug.Conn{conn | path_info: path}, Router.init(opts))
end
def namespace(conn, _opts, _ns), do: conn
defmodule Router do
import Plug.Conn
use Plug.Router
plug(Plug.Static, at: "/", from: :exq_ui)
plug(ExqUi.JsonApi, on: "api")
plug(:match)
plug(:dispatch)
get "/api/stats/all" do
{:ok, processed} = Exq.Api.stats(conn.assigns[:exq_name], "processed")
{:ok, failed} = Exq.Api.stats(conn.assigns[:exq_name], "failed")
{:ok, busy} = Exq.Api.busy(conn.assigns[:exq_name])
{:ok, scheduled} = Exq.Api.scheduled_size(conn.assigns[:exq_name])
{:ok, retrying} = Exq.Api.retry_size(conn.assigns[:exq_name])
{:ok, dead} = Exq.Api.failed_size(conn.assigns[:exq_name])
{:ok, queues} = Exq.Api.queue_size(conn.assigns[:exq_name])
queue_sizes =
for {_q, size} <- queues do
size
end
qtotal = "#{Enum.sum(queue_sizes)}"
{:ok, json} =
Jason.encode(%{
stat: %{
id: "all",
processed: processed || 0,
failed: failed || 0,
busy: busy || 0,
scheduled: scheduled || 0,
dead: dead || 0,
retrying: retrying || 0,
enqueued: qtotal
}
})
conn |> send_resp(200, json) |> halt
end
get "/api/realtimes" do
{:ok, failures, successes} = Exq.Api.realtime_stats(conn.assigns[:exq_name])
f =
for {date, count} <- failures do
%{id: "f#{date}", timestamp: date, count: count}
end
s =
for {date, count} <- successes do
%{id: "s#{date}", timestamp: date, count: count}
end
all = %{realtimes: f ++ s}
{:ok, json} = Jason.encode(all)
conn |> send_resp(200, json) |> halt
end
get "/api/scheduled" do
{:ok, jobs} = Exq.Api.scheduled_with_scores(conn.assigns[:exq_name])
{:ok, json} =
Jason.encode(%{scheduled: Enum.map(map_score_to_jobs(jobs), &Map.from_struct/1)})
conn |> send_resp(200, json) |> halt
end
get "/api/retries" do
{:ok, retries} = Exq.Api.retries(conn.assigns[:exq_name])
retries = retries |> map_jid_to_id |> convert_results_to_times(:failed_at)
{:ok, json} = Jason.encode(%{retries: Enum.map(retries, &Map.from_struct/1)})
conn |> send_resp(200, json) |> halt
end
get "/api/retries/:id" do
{:ok, retry} = Exq.Api.find_retry(conn.assigns[:exq_name], id)
retry = retry |> map_jid_to_id |> convert_results_to_times(:failed_at)
{:ok, json} = Jason.encode(%{retry: Map.from_struct(retry)})
conn |> send_resp(200, json) |> halt
end
get "/api/failures" do
{:ok, failures} = Exq.Api.failed(conn.assigns[:exq_name])
failures = failures |> map_jid_to_id |> convert_results_to_times(:failed_at)
{:ok, json} = Jason.encode(%{failures: failures})
conn |> send_resp(200, json) |> halt
end
delete "/api/failures/:id" do
:ok = Exq.Api.remove_failed(conn.assigns[:exq_name], id)
conn |> send_resp(204, "") |> halt
end
delete "/api/retries/:id" do
:ok = Exq.Api.remove_retry(conn.assigns[:exq_name], id)
conn |> send_resp(204, "") |> halt
end
delete "/api/scheduled/:id" do
:ok = Exq.Api.remove_scheduled(conn.assigns[:exq_name], id)
conn |> send_resp(204, "") |> halt
end
delete "/api/failures" do
:ok = Exq.Api.clear_failed(conn.assigns[:exq_name])
conn |> send_resp(204, "") |> halt
end
delete "/api/retries" do
:ok = Exq.Api.clear_retries(conn.assigns[:exq_name])
conn |> send_resp(204, "") |> halt
end
delete "/api/scheduled" do
:ok = Exq.Api.clear_scheduled(conn.assigns[:exq_name])
conn |> send_resp(204, "") |> halt
end
post "/api/failures/:_id/retry" do
# TODO
conn |> send_resp(200, "") |> halt
end
put "/api/retries/:id" do
:ok = Exq.Api.retry_job(conn.assigns[:exq_name], id)
conn |> send_resp(204, "") |> halt
end
get "/api/processes" do
{:ok, processes} = Exq.Api.processes(conn.assigns[:exq_name])
process_jobs =
for p <- processes do
process = Map.delete(p, "job")
pjob = Jason.decode!(p.job)
process =
Map.put(process, :job_id, pjob["jid"])
|> Map.put(:started_at, score_to_time(p.started_at))
|> Map.put(:id, "#{process.host}:#{process.pid}")
pjob = Map.put(pjob, :id, pjob["jid"])
[process, pjob]
end
processes = for [process, _job] <- process_jobs, do: process
jobs = for [_process, job] <- process_jobs, do: job
{:ok, json} =
Jason.encode(%{processes: Enum.map(processes, &Map.from_struct/1), jobs: jobs})
conn |> send_resp(200, json) |> halt
end
get "/api/queues" do
{:ok, queues} = Exq.Api.queue_size(conn.assigns[:exq_name])
job_counts = for {q, size} <- queues, do: %{id: q, size: size}
{:ok, json} = Jason.encode(%{queues: job_counts})
conn |> send_resp(200, json) |> halt
end
get "/api/queues/:id" do
{:ok, jobs} = Exq.Api.jobs(conn.assigns[:exq_name], id)
jobs_structs = map_jid_to_id(jobs)
job_ids = for j <- jobs_structs, do: j[:id]
{:ok, json} =
Jason.encode(%{
queue: %{id: id, job_ids: job_ids, partial: false},
jobs: map_jid_to_id(jobs)
})
conn |> send_resp(200, json) |> halt
end
delete "/api/queues/:id" do
Exq.Api.remove_queue(conn.assigns[:exq_name], id)
conn |> send_resp(204, "") |> halt
end
delete "/api/processes" do
:ok = Exq.Api.clear_processes(conn.assigns[:exq_name])
conn |> send_resp(204, "") |> halt
end
# precompile index.html into render_index/1 function
index_path = Path.join([Application.app_dir(:exq_ui), "priv/static/index.html"])
EEx.function_from_file(:defp, :render_index, index_path, [:assigns])
match _ do
base =
case conn.assigns[:namespace] do
"" -> ""
namespace -> "#{namespace}/"
end
conn
|> put_resp_header("content-type", "text/html")
|> send_resp(200, render_index(base: base))
|> halt
end
def map_jid_to_id(jobs) when is_list(jobs) do
for job <- jobs do
map_jid_to_id(job)
end
end
def map_jid_to_id(job), do: Map.put(job, :id, job.jid)
def convert_results_to_times(jobs, score_key) when is_list(jobs) do
for job <- jobs do
convert_results_to_times(job, score_key)
end
end
def convert_results_to_times(job, score_key) do
Map.put(job, score_key, score_to_time(Map.get(job, score_key)))
end
def score_to_time(score) when is_float(score) do
round(score * 1_000_000)
|> DateTime.from_unix!(:microseconds)
|> DateTime.to_iso8601()
end
def score_to_time(score) do
if String.contains?(score, ".") do
score_to_time(String.to_float(score))
else
String.to_integer(score)
|> DateTime.from_unix!()
|> DateTime.to_iso8601()
end
end
def map_score_to_jobs(jobs) do
Enum.map(jobs, fn {job, score} ->
job
|> Map.put(:scheduled_at, score_to_time(score))
|> Map.put(:id, job.jid)
end)
end
end
end
| 28.211073 | 89 | 0.583589 |
03dc442dd3c19b9e39e3eb26108ae02bd7a01600 | 1,791 | ex | Elixir | lib/nostrum/shard/intents.ex | phereford/nostrum | 3d273671f51d839eedac4d6e52ba9cf70720ac01 | [
"MIT"
] | 637 | 2017-03-07T11:25:35.000Z | 2022-03-31T13:37:51.000Z | lib/nostrum/shard/intents.ex | phereford/nostrum | 3d273671f51d839eedac4d6e52ba9cf70720ac01 | [
"MIT"
] | 372 | 2017-03-07T20:42:03.000Z | 2022-03-30T22:46:46.000Z | lib/nostrum/shard/intents.ex | phereford/nostrum | 3d273671f51d839eedac4d6e52ba9cf70720ac01 | [
"MIT"
] | 149 | 2017-03-07T12:11:58.000Z | 2022-03-19T22:11:51.000Z | defmodule Nostrum.Shard.Intents do
@moduledoc false
import Bitwise
@privileged_intents [
:guild_members,
:guild_presences
]
@spec intent_values :: [{atom, integer()}, ...]
def intent_values do
[
guilds: 1 <<< 0,
guild_members: 1 <<< 1,
guild_bans: 1 <<< 2,
guild_emojis: 1 <<< 3,
guild_integrations: 1 <<< 4,
guild_webhooks: 1 <<< 5,
guild_invites: 1 <<< 6,
guild_voice_states: 1 <<< 7,
guild_presences: 1 <<< 8,
guild_messages: 1 <<< 9,
guild_message_reactions: 1 <<< 10,
guild_message_typing: 1 <<< 11,
direct_messages: 1 <<< 12,
direct_message_reactions: 1 <<< 13,
direct_message_typing: 1 <<< 14
]
end
@spec get_enabled_intents :: integer()
def get_enabled_intents do
# If no intents are passed in config, default to non-privileged being enabled.
enabled_intents = Application.get_env(:nostrum, :gateway_intents, :nonprivileged)
case enabled_intents do
:all ->
get_intent_value(Keyword.keys(intent_values()))
:nonprivileged ->
get_intent_value(Keyword.keys(intent_values()) -- @privileged_intents)
intents ->
get_intent_value(intents)
end
end
@spec get_intent_value([atom()]) :: integer
def get_intent_value(enabled_intents) do
Enum.reduce(enabled_intents, 0, fn intent, intents ->
case intent_values()[intent] do
nil -> raise "Invalid intent specified: #{intent}"
value -> intents ||| value
end
end)
end
@spec has_intent?(atom()) :: boolean
def has_intent?(requested_intent) do
enabled_integer = get_enabled_intents()
intent_integer = intent_values()[requested_intent]
(enabled_integer &&& intent_integer) == intent_integer
end
end
| 26.731343 | 85 | 0.644891 |
03dc49785f241ddb5f634e775e9ddddb65e47b5e | 60 | exs | Elixir | test/logger_graylog_backend_test.exs | rranelli/logger_graylog_backend | d2b0abae68190a0a95ef219fda8282ef02608605 | [
"Apache-2.0"
] | 4 | 2019-08-20T15:02:09.000Z | 2021-04-19T09:47:45.000Z | test/logger_graylog_backend_test.exs | rranelli/logger_graylog_backend | d2b0abae68190a0a95ef219fda8282ef02608605 | [
"Apache-2.0"
] | 1 | 2019-03-29T06:51:50.000Z | 2019-03-29T20:52:05.000Z | test/logger_graylog_backend_test.exs | rranelli/logger_graylog_backend | d2b0abae68190a0a95ef219fda8282ef02608605 | [
"Apache-2.0"
] | 5 | 2019-03-28T19:32:39.000Z | 2022-03-06T10:03:27.000Z | defmodule LoggerGraylogBackendTest do
use ExUnit.Case
end
| 15 | 37 | 0.85 |
03dc4fd01a76b84ecb674a2eaba412e48ec9dbf2 | 683 | ex | Elixir | lib/types/primitive_type.ex | dragonwasrobot/json_schema | 00363b64ebadbb885ff8eb01433cb0f36d54caaa | [
"MIT"
] | 3 | 2019-01-07T20:11:40.000Z | 2021-02-03T22:24:07.000Z | lib/types/primitive_type.ex | dragonwasrobot/json_schema | 00363b64ebadbb885ff8eb01433cb0f36d54caaa | [
"MIT"
] | 13 | 2018-07-27T12:39:01.000Z | 2022-03-28T20:16:15.000Z | lib/types/primitive_type.ex | dragonwasrobot/json_schema | 00363b64ebadbb885ff8eb01433cb0f36d54caaa | [
"MIT"
] | null | null | null | defmodule JsonSchema.Types.PrimitiveType do
@moduledoc """
Represents a custom `primitive` type definition in a JSON schema.
JSON Schema:
"name": {
"description": "A name",
"type": "string"
}
Resulting in the Elixir representation:
%PrimitiveType{name: "name",
description: "A name",
path: URI.parse("#/name"),
type: "string"}
"""
use TypedStruct
typedstruct do
field :name, String.t(), enforce: true
field :description, String.t() | nil, default: nil
field :path, String.t() | URI.t(), enforce: true
field :type, String.t(), enforce: true
end
end
| 23.551724 | 67 | 0.573939 |
03dc7c5a0e8ee4e5d383db3b762da24283131602 | 522 | ex | Elixir | lib/fake_server/agents/env_agent.ex | JacksonIsaac/fake_server | a646287b252d1ce4da4b61eac50e897a6423b7ed | [
"Apache-2.0"
] | null | null | null | lib/fake_server/agents/env_agent.ex | JacksonIsaac/fake_server | a646287b252d1ce4da4b61eac50e897a6423b7ed | [
"Apache-2.0"
] | null | null | null | lib/fake_server/agents/env_agent.ex | JacksonIsaac/fake_server | a646287b252d1ce4da4b61eac50e897a6423b7ed | [
"Apache-2.0"
] | null | null | null | defmodule FakeServer.Agents.EnvAgent do
@moduledoc false
alias FakeServer.Env
def start_link do
Agent.start_link(fn -> [] end, name: __MODULE__)
end
def stop do
Agent.stop(__MODULE__)
end
def save_env(server_id, %Env{} = env) do
Agent.update(__MODULE__, &Keyword.put(&1, server_id, env))
env
end
def get_env(server_id) do
Agent.get(__MODULE__, &Keyword.get(&1, server_id))
end
def delete_env(server_id) do
Agent.get(__MODULE__, &Keyword.delete(&1, server_id))
end
end
| 19.333333 | 62 | 0.691571 |
03dcce40ec7fa0ba507700554577b3b6c9f16322 | 1,773 | ex | Elixir | clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/device_identifier.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/device_identifier.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/device_identifier.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.AndroidDeviceProvisioning.V1.Model.DeviceIdentifier do
@moduledoc """
DeviceIdentifiers identifies an unique device.
## Attributes
- imei (String): IMEI Defaults to: `null`.
- manufacturer (String): Manufacturer name to match `android.os.Build.MANUFACTURER` (required). Allowed values listed in [manufacturer names](/zero-touch/resources/manufacturer-names). Defaults to: `null`.
- meid (String): MEID Defaults to: `null`.
- serialNumber (String): Serial number (optional) Defaults to: `null`.
"""
defstruct [
:"imei",
:"manufacturer",
:"meid",
:"serialNumber"
]
end
defimpl Poison.Decoder, for: GoogleApi.AndroidDeviceProvisioning.V1.Model.DeviceIdentifier do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.AndroidDeviceProvisioning.V1.Model.DeviceIdentifier do
def encode(value, options) do
GoogleApi.AndroidDeviceProvisioning.V1.Deserializer.serialize_non_nil(value, options)
end
end
| 34.096154 | 217 | 0.751833 |
03dd04f815718e58330207bea154cb2d25b38e60 | 1,201 | ex | Elixir | lib/changelog_web/views/admin/person_view.ex | lawik/changelog.com | 3f0b6ceb6ba723df9b21164114fbc208509e9c12 | [
"MIT"
] | null | null | null | lib/changelog_web/views/admin/person_view.ex | lawik/changelog.com | 3f0b6ceb6ba723df9b21164114fbc208509e9c12 | [
"MIT"
] | null | null | null | lib/changelog_web/views/admin/person_view.ex | lawik/changelog.com | 3f0b6ceb6ba723df9b21164114fbc208509e9c12 | [
"MIT"
] | null | null | null | defmodule ChangelogWeb.Admin.PersonView do
use ChangelogWeb, :admin_view
alias Changelog.Person
alias ChangelogWeb.PersonView
alias ChangelogWeb.Admin.{EpisodeView, NewsItemView}
def avatar_url(person), do: PersonView.avatar_url(person)
def episode_count(person), do: Person.episode_count(person)
def list_of_links(person) do
[
%{value: person.email, icon: "envelope", url: "mailto:#{person.email}"},
%{
value: person.twitter_handle,
icon: "twitter",
url: SharedHelpers.twitter_url(person.twitter_handle)
},
%{
value: person.github_handle,
icon: "github",
url: SharedHelpers.github_url(person.github_handle)
},
%{
value: person.linkedin_handle,
icon: "linkedin",
url: SharedHelpers.linkedin_url(person.linkedin_handle)
},
%{value: person.website, icon: "share", url: person.website}
]
|> Enum.reject(fn x -> x.value == nil end)
|> Enum.map(fn x ->
~s{<a href="#{x.url}" class="ui icon button" target="_blank"><i class="#{x.icon} icon"></i></a>}
end)
|> Enum.join("")
end
def post_count(person), do: Person.post_count(person)
end
| 30.025 | 102 | 0.637802 |
03dd079c6d9c069f7d651505f806c722f44549b5 | 6,348 | exs | Elixir | packages/elixir/.credo.exs | venomnert/riptide | 39a50047bb51cd30a93ff7022bb01385c28a4f03 | [
"MIT"
] | 11 | 2020-01-20T16:42:00.000Z | 2021-09-18T11:36:45.000Z | packages/elixir/.credo.exs | venomnert/riptide | 39a50047bb51cd30a93ff7022bb01385c28a4f03 | [
"MIT"
] | 16 | 2020-04-05T19:26:14.000Z | 2020-05-21T14:50:59.000Z | packages/elixir/.credo.exs | venomnert/riptide | 39a50047bb51cd30a93ff7022bb01385c28a4f03 | [
"MIT"
] | 2 | 2020-10-16T11:01:57.000Z | 2021-01-20T21:11:52.000Z | # This file contains the configuration for Credo and you are probably reading
# this after creating it with `mix credo.gen.config`.
#
# If you find anything wrong or unclear in this file, please report an
# issue on GitHub: https://github.com/rrrene/credo/issues
#
%{
#
# You can have as many configs as you like in the `configs:` field.
configs: [
%{
#
# Run any exec using `mix credo -C <name>`. If no exec name is given
# "default" is used.
#
name: "default",
#
# These are the files included in the analysis:
files: %{
#
# You can give explicit globs or simply directories.
# In the latter case `**/*.{ex,exs}` will be used.
#
included: ["lib/", "src/", "test/", "web/", "apps/"],
excluded: [~r"/_build/", ~r"/deps/", ~r"/node_modules/"]
},
#
# If you create your own checks, you must specify the source files for
# them here, so they can be loaded by Credo before running the analysis.
#
requires: [],
#
# If you want to enforce a style guide and need a more traditional linting
# experience, you can change `strict` to `true` below:
#
strict: false,
#
# If you want to use uncolored output by default, you can change `color`
# to `false` below:
#
color: true,
#
# You can customize the parameters of any check by adding a second element
# to the tuple.
#
# To disable a check put `false` as second element:
#
# {Credo.Check.Design.DuplicatedCode, false}
#
checks: [
#
## Consistency Checks
#
{Credo.Check.Consistency.ExceptionNames, []},
{Credo.Check.Consistency.LineEndings, []},
{Credo.Check.Consistency.ParameterPatternMatching, []},
{Credo.Check.Consistency.SpaceAroundOperators, []},
{Credo.Check.Consistency.SpaceInParentheses, []},
{Credo.Check.Consistency.TabsOrSpaces, []},
#
## Design Checks
#
# You can customize the priority of any check
# Priority values are: `low, normal, high, higher`
#
{Credo.Check.Design.AliasUsage, [priority: :low]},
# For some checks, you can also set other parameters
#
# If you don't want the `setup` and `test` macro calls in ExUnit tests
# or the `schema` macro in Ecto schemas to trigger DuplicatedCode, just
# set the `excluded_macros` parameter to `[:schema, :setup, :test]`.
#
{Credo.Check.Design.DuplicatedCode, [excluded_macros: []]},
# You can also customize the exit_status of each check.
# If you don't want TODO comments to cause `mix credo` to fail, just
# set this value to 0 (zero).
#
{Credo.Check.Design.TagTODO, [exit_status: 2]},
{Credo.Check.Design.TagFIXME, []},
#
## Readability Checks
#
{Credo.Check.Readability.AliasOrder, []},
{Credo.Check.Readability.FunctionNames, []},
{Credo.Check.Readability.LargeNumbers, []},
{Credo.Check.Readability.MaxLineLength, [priority: :low, max_length: 120]},
{Credo.Check.Readability.ModuleAttributeNames, []},
{Credo.Check.Readability.ModuleDoc, false},
{Credo.Check.Readability.ModuleNames, []},
{Credo.Check.Readability.ParenthesesOnZeroArityDefs, []},
{Credo.Check.Readability.ParenthesesInCondition, []},
{Credo.Check.Readability.PredicateFunctionNames, []},
{Credo.Check.Readability.PreferImplicitTry, []},
{Credo.Check.Readability.RedundantBlankLines, []},
{Credo.Check.Readability.StringSigils, []},
{Credo.Check.Readability.TrailingBlankLine, []},
{Credo.Check.Readability.TrailingWhiteSpace, []},
{Credo.Check.Readability.VariableNames, []},
{Credo.Check.Readability.Semicolons, []},
{Credo.Check.Readability.SpaceAfterCommas, []},
#
## Refactoring Opportunities
#
{Credo.Check.Refactor.DoubleBooleanNegation, []},
{Credo.Check.Refactor.CondStatements, false},
{Credo.Check.Refactor.CyclomaticComplexity, false},
{Credo.Check.Refactor.FunctionArity, []},
{Credo.Check.Refactor.LongQuoteBlocks, []},
{Credo.Check.Refactor.MapInto, []},
{Credo.Check.Refactor.MatchInCondition, []},
{Credo.Check.Refactor.NegatedConditionsInUnless, []},
{Credo.Check.Refactor.NegatedConditionsWithElse, []},
{Credo.Check.Refactor.Nesting, false},
{Credo.Check.Refactor.PipeChainStart,
[excluded_argument_types: [:atom, :binary, :fn, :keyword], excluded_functions: []]},
{Credo.Check.Refactor.UnlessWithElse, []},
#
## Warnings
#
{Credo.Check.Warning.BoolOperationOnSameValues, []},
{Credo.Check.Warning.ExpensiveEmptyEnumCheck, []},
{Credo.Check.Warning.IExPry, []},
{Credo.Check.Warning.IoInspect, []},
{Credo.Check.Warning.LazyLogging, []},
{Credo.Check.Warning.OperationOnSameValues, []},
{Credo.Check.Warning.OperationWithConstantResult, []},
{Credo.Check.Warning.UnusedEnumOperation, []},
{Credo.Check.Warning.UnusedFileOperation, []},
{Credo.Check.Warning.UnusedKeywordOperation, []},
{Credo.Check.Warning.UnusedListOperation, []},
{Credo.Check.Warning.UnusedPathOperation, []},
{Credo.Check.Warning.UnusedRegexOperation, []},
{Credo.Check.Warning.UnusedStringOperation, []},
{Credo.Check.Warning.UnusedTupleOperation, []},
{Credo.Check.Warning.RaiseInsideRescue, []},
#
# Controversial and experimental checks (opt-in, just remove `, false`)
#
{Credo.Check.Refactor.ABCSize, false},
{Credo.Check.Refactor.AppendSingleItem, false},
{Credo.Check.Refactor.VariableRebinding, false},
{Credo.Check.Warning.MapGetUnsafePass, false},
{Credo.Check.Consistency.MultiAliasImportRequireUse, false},
#
# Deprecated checks (these will be deleted after a grace period)
#
{Credo.Check.Readability.Specs, false}
#
# Custom checks can be created using `mix credo.gen.check`.
#
]
}
]
}
| 39.185185 | 93 | 0.614052 |
03dd18ddcbb4b11984ac56c6723fa372393f57d9 | 703 | exs | Elixir | apps/alert_processor/priv/repo/migrations/20170726172307_add_versions.exs | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | null | null | null | apps/alert_processor/priv/repo/migrations/20170726172307_add_versions.exs | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | 21 | 2021-03-12T17:05:30.000Z | 2022-02-16T21:48:35.000Z | apps/alert_processor/priv/repo/migrations/20170726172307_add_versions.exs | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | 1 | 2021-12-09T15:09:53.000Z | 2021-12-09T15:09:53.000Z | defmodule Repo.Migrations.AddVersions do
use Ecto.Migration
def change do
create table(:versions) do
add :event, :string, null: false, size: 10
add :item_type, :string, null: false
add :item_id, :binary_id
add :item_changes, :map, null: false
add :originator_id, references(:users, type: :binary_id)
add :origin, :string, size: 50
add :meta, :map
add :inserted_at, :utc_datetime, null: false
end
create index(:versions, [:originator_id])
create index(:versions, [:item_id, :item_type])
create index(:versions, [:event, :item_type])
create index(:versions, [:item_type, :inserted_at])
end
end
| 30.565217 | 62 | 0.631579 |
03dd26665d0e5da03ee07abfcd0bfe0f04332d9b | 2,645 | exs | Elixir | priv/repo/migrations/20200920134049_change_owner_for_followers_chat.exs | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | 328 | 2020-07-23T22:13:49.000Z | 2022-03-31T21:22:28.000Z | priv/repo/migrations/20200920134049_change_owner_for_followers_chat.exs | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | 362 | 2020-07-23T22:38:38.000Z | 2022-03-24T02:11:16.000Z | priv/repo/migrations/20200920134049_change_owner_for_followers_chat.exs | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | 72 | 2020-07-23T22:50:46.000Z | 2022-02-02T11:59:32.000Z | defmodule Glimesh.Repo.Migrations.ChangeOwnerForFollowersChat do
use Ecto.Migration
import Ecto.Query
def up do
rename table(:user_moderators), to: table(:channel_moderators)
rename table(:user_moderation_log), to: table(:channel_moderation_log)
alter table(:chat_messages) do
add :channel_id, references(:channels)
end
alter table(:channel_moderators) do
add :channel_id, references(:channels)
end
alter table(:channel_moderation_log) do
add :channel_id, references(:channels)
end
flush()
from(cm in "chat_messages",
join: c in Glimesh.Streams.Channel,
on: c.user_id == cm.streamer_id,
update: [set: [channel_id: c.id]]
)
|> Glimesh.Repo.update_all([])
from(cm in "channel_moderators",
join: c in Glimesh.Streams.Channel,
on: c.user_id == cm.streamer_id,
update: [set: [channel_id: c.id]]
)
|> Glimesh.Repo.update_all([])
from(cml in "channel_moderation_log",
join: c in Glimesh.Streams.Channel,
on: c.user_id == cml.streamer_id,
update: [set: [channel_id: c.id]]
)
|> Glimesh.Repo.update_all([])
alter table(:chat_messages) do
remove :streamer_id
end
alter table(:channel_moderators) do
remove :streamer_id
end
alter table(:channel_moderation_log) do
remove :streamer_id
end
end
def down do
rename table(:channel_moderators), to: table(:user_moderators)
rename table(:channel_moderation_log), to: table(:user_moderation_log)
alter table(:chat_messages) do
add :streamer_id, references(:users)
end
alter table(:user_moderators) do
add :streamer_id, references(:users)
end
alter table(:user_moderation_log) do
add :streamer_id, references(:users)
end
flush()
from(cm in "chat_messages",
join: c in Glimesh.Streams.Channel,
on: c.id == cm.channel_id,
update: [set: [streamer_id: c.user_id]]
)
|> Glimesh.Repo.update_all([])
from(cm in "user_moderators",
join: c in Glimesh.Streams.Channel,
on: c.id == cm.channel_id,
update: [set: [streamer_id: c.user_id]]
)
|> Glimesh.Repo.update_all([])
from(cml in "user_moderation_log",
join: c in Glimesh.Streams.Channel,
on: c.id == cml.channel_id,
update: [set: [streamer_id: c.user_id]]
)
|> Glimesh.Repo.update_all([])
alter table(:chat_messages) do
remove :channel_id
end
alter table(:user_moderators) do
remove :channel_id
end
alter table(:user_moderation_log) do
remove :channel_id
end
end
end
| 24.266055 | 74 | 0.650284 |
03dd58ddcc09b2202b4a96565d7c49905ff5564e | 2,141 | exs | Elixir | test/changelog_web/controllers/home_controller_test.exs | theafricanengineer/changelog.com | 4954d0df516c0a325667ec6c1fbbf02d68c9b953 | [
"MIT"
] | null | null | null | test/changelog_web/controllers/home_controller_test.exs | theafricanengineer/changelog.com | 4954d0df516c0a325667ec6c1fbbf02d68c9b953 | [
"MIT"
] | null | null | null | test/changelog_web/controllers/home_controller_test.exs | theafricanengineer/changelog.com | 4954d0df516c0a325667ec6c1fbbf02d68c9b953 | [
"MIT"
] | null | null | null | defmodule ChangelogWeb.HomeControllerTest do
use ChangelogWeb.ConnCase
alias Changelog.Person
@tag :as_user
test "renders the home page", %{conn: conn} do
conn = get(conn, home_path(conn, :show))
assert html_response(conn, 200)
end
@tag :as_user
test "renders the account form", %{conn: conn} do
conn = get(conn, home_path(conn, :account))
assert html_response(conn, 200) =~ "form"
end
@tag :as_user
test "renders the profile form", %{conn: conn} do
conn = get(conn, home_path(conn, :profile))
assert html_response(conn, 200) =~ "form"
end
@tag :as_inserted_user
test "updates person and redirects to home page", %{conn: conn} do
conn = put(conn, home_path(conn, :update), from: "account", person: %{name: "New Name"})
assert redirected_to(conn) == home_path(conn, :show)
end
@tag :as_inserted_user
test "does not update with invalid attributes", %{conn: conn} do
conn = put(conn, home_path(conn, :update), from: "profile", person: %{name: ""})
assert html_response(conn, 200) =~ ~r/problem/
end
test "opting out of notifications", %{conn: conn} do
person = insert(:person)
{:ok, token} = Person.encoded_id(person)
conn = get(conn, home_path(conn, :opt_out, token, "email_on_authored_news"))
assert conn.status == 200
refute Repo.get(Person, person.id).settings.email_on_authored_news
end
@tag :as_inserted_user
test "signed in and opting out of notifications", %{conn: conn} do
person = conn.assigns.current_user
{:ok, token} = Person.encoded_id(person)
conn = get(conn, home_path(conn, :opt_out, token, "email_on_submitted_news"))
assert conn.status == 200
refute Repo.get(Person, person.id).settings.email_on_submitted_news
end
test "requires user on all actions except email links", %{conn: conn} do
Enum.each([
get(conn, home_path(conn, :show)),
get(conn, home_path(conn, :profile)),
get(conn, home_path(conn, :account)),
put(conn, home_path(conn, :update), person: %{}),
], fn conn ->
assert html_response(conn, 302)
assert conn.halted
end)
end
end
| 32.439394 | 92 | 0.67305 |
03dd70b86b8536be4b87f9f27e98f6703abbcf7d | 416 | ex | Elixir | lib/thin_notion_api/types/search_params.ex | CodingZeal/thin_notion_api | e1f4081348300ab6c48adae8ebb4b2995cde59d1 | [
"MIT"
] | 1 | 2022-01-15T00:50:09.000Z | 2022-01-15T00:50:09.000Z | lib/thin_notion_api/types/search_params.ex | CodingZeal/thin_notion_api | e1f4081348300ab6c48adae8ebb4b2995cde59d1 | [
"MIT"
] | null | null | null | lib/thin_notion_api/types/search_params.ex | CodingZeal/thin_notion_api | e1f4081348300ab6c48adae8ebb4b2995cde59d1 | [
"MIT"
] | null | null | null | defmodule ThinNotionApi.Types.SearchParams do
@typedoc """
Parameters for using the search API.
"""
@type t :: %__MODULE__{
query: String.t(),
sort: ThinNotionApi.Types.SearchSortParams.t(),
filter: ThinNotionApi.Types.SearchFilterParams.t(),
start_cursor: String.t(),
page_size: integer()
}
@derive Jason.Encoder
defstruct [:query, :sort, :filter, :start_cursor, :page_size]
end
| 24.470588 | 63 | 0.692308 |
03dd8333819e9ab191e422ab9562df7c4614bcaf | 2,508 | ex | Elixir | ch4/todo_list/lib/todo_list.ex | TheEndIsNear/ElixirInAction | 9b18ebd4845723935e03ec2a0c3cf869aa955541 | [
"MIT"
] | null | null | null | ch4/todo_list/lib/todo_list.ex | TheEndIsNear/ElixirInAction | 9b18ebd4845723935e03ec2a0c3cf869aa955541 | [
"MIT"
] | null | null | null | ch4/todo_list/lib/todo_list.ex | TheEndIsNear/ElixirInAction | 9b18ebd4845723935e03ec2a0c3cf869aa955541 | [
"MIT"
] | null | null | null | defmodule TodoList do
@moduledoc """
"""
defstruct auto_id: 1, entries: %{}
@doc """
Creates a new TodoList
"""
def new(), do: %TodoList{}
@doc """
Add a new entry to a todo list
"""
def add_entry(todo_list, entry) do
entry = Map.put(entry, :id, todo_list.auto_id)
new_entries =
Map.put(
todo_list.entries,
todo_list.auto_id,
entry
)
%TodoList{todo_list | entries: new_entries, auto_id: todo_list.auto_id + 1}
end
@doc """
List all entries for a given date
"""
def entries(todo_list, date) do
todo_list.entries
|> Stream.filter(fn {_, entry} -> entry.date == date end)
|> Enum.map(fn {_, entry} -> entry end)
end
@doc """
Update an entry based upon an entry id, and a function for updating the entry
"""
def update_entry(todo_list, entry_id, updater_fun) do
case Map.fetch(todo_list.entries, entry_id) do
:error ->
todo_list
{:ok, old_entry} ->
old_entry_id = old_entry.id
new_entry = %{id: ^old_entry_id} = updater_fun.(old_entry)
new_entries = Map.put(todo_list.entries, new_entry.id, new_entry)
%TodoList{todo_list | entries: new_entries}
end
end
def update_entry(todo_list, %{} = new_entry) do
update_entry(todo_list, new_entry.id, fn _ -> new_entry end)
end
@doc """
Deletes an entry from the todo list, based on the id given
"""
def delete_entry(todo_list, entry_id) do
Map.delete(todo_list, entry_id)
end
defimpl String.Chars, for: TodoList do
def to_string(_) do
"#TodoList"
end
end
defimpl Collectable, for: TodoList do
def into(original) do
{original, &into_callback/2}
end
defp into_callback(todo_list, {:cont, entry}) do
TodoList.add_entry(todo_list, entry)
end
defp into_callback(todo_list, :done), do: todo_list
defp into_callback(todo_list, :halt), do: :ok
end
end
defmodule TodoList.CsvImporter do
def import(filename) do
File.stream!(filename)
|> Stream.map(&String.replace(&1, "\n", ""))
|> Stream.map(&String.split(&1, ","))
|> Stream.map(&parse_date/1)
|> Stream.map(&create_map/1)
|> Enum.into(TodoList.new())
end
defp parse_date([date|tail]) do
[year, month, day] =
date
|> String.split("/")
|> Enum.map(&String.to_integer/1)
{:ok, date} = Date.new(year, month, day)
[ date | tail]
end
defp create_map([date | [task]]) do
%{date: date, title: task}
end
end
| 23.439252 | 79 | 0.627592 |
03dd8cfaa81ae2f0767cb0eab3f6ead64ef47e94 | 1,544 | ex | Elixir | test/support/data_case.ex | CableClub/cable-club-core | 70c67c7a105dea83f2c1a1e2ee75a1ee97713bfb | [
"Apache-2.0"
] | null | null | null | test/support/data_case.ex | CableClub/cable-club-core | 70c67c7a105dea83f2c1a1e2ee75a1ee97713bfb | [
"Apache-2.0"
] | null | null | null | test/support/data_case.ex | CableClub/cable-club-core | 70c67c7a105dea83f2c1a1e2ee75a1ee97713bfb | [
"Apache-2.0"
] | null | null | null | defmodule CableClub.DataCase do
@moduledoc """
This module defines the setup for tests requiring
access to the application's data layer.
You may define functions here to be used as helpers in
your tests.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use CableClub.DataCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
alias CableClub.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import CableClub.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(CableClub.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(CableClub.Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transforms changeset errors into a map of messages.
assert {:error, changeset} = Accounts.create_user(%{password: "short"})
assert "password is too short" in errors_on(changeset).password
assert %{password: ["password is too short"]} = errors_on(changeset)
"""
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
| 27.571429 | 77 | 0.691062 |
03dd8db30a11e5589bb4d19638085f05dfd42d3b | 1,775 | ex | Elixir | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_property.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_property.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_property.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.Vision.V1.Model.GoogleCloudVisionV1p4beta1Property do
@moduledoc """
A `Property` consists of a user-supplied name/value pair.
## Attributes
- name (String.t): Name of the property. Defaults to: `null`.
- uint64Value (String.t): Value of numeric properties. Defaults to: `null`.
- value (String.t): Value of the property. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:name => any(),
:uint64Value => any(),
:value => any()
}
field(:name)
field(:uint64Value)
field(:value)
end
defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1Property do
def decode(value, options) do
GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1Property.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1Property do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.87037 | 92 | 0.731268 |
03dd905d67a25a0f8f7a1ff5f86c8c744588fde2 | 1,407 | ex | Elixir | lib/brando_admin/components/children_button.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 4 | 2020-10-30T08:40:38.000Z | 2022-01-07T22:21:37.000Z | lib/brando_admin/components/children_button.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 1,162 | 2020-07-05T11:20:15.000Z | 2022-03-31T06:01:49.000Z | lib/brando_admin/components/children_button.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | null | null | null | defmodule BrandoAdmin.Components.ChildrenButton do
use Surface.LiveComponent
prop entry, :any, required: true
prop fields, :list, required: true
data count, :integer
data active, :boolean
def mount(socket) do
{:ok, assign(socket, :active, false)}
end
def update(assigns, socket) do
entry = assigns.entry
fields = assigns.fields
count = Enum.reduce(fields, 0, fn x, acc -> Enum.count(Map.get(entry, x)) + acc end)
singular = entry.__struct__.__naming__().singular
{:ok,
socket
|> assign(assigns)
|> assign(
count: count,
singular: singular
)}
end
def render(assigns) do
~F"""
<div class="children-button">
<button
:on-click="toggle"
type="button"
data-testid="children-button"
class={active: @active}
phx-page-loading>
{#if @active}
Close
{#else}
+ {@count}
{/if}
</button>
</div>
"""
end
def handle_event(
"toggle",
_,
%{assigns: %{fields: child_fields, singular: singular, entry: %{id: id}}} = socket
) do
id = "list-row-#{singular}-#{id}"
send_update(BrandoAdmin.Components.Content.List.Row,
id: id,
show_children: !socket.assigns.active,
child_fields: child_fields
)
{:noreply, assign(socket, :active, !socket.assigns.active)}
end
end
| 21.984375 | 90 | 0.585643 |
03ddacc8b38009604932120f7ef1a7647c949824 | 2,945 | ex | Elixir | apps/core/lib/core/api/helpers/microservice_base.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 8 | 2019-06-14T11:34:49.000Z | 2021-08-05T19:14:24.000Z | apps/core/lib/core/api/helpers/microservice_base.ex | edenlabllc/ehealth.api.public | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 1 | 2019-07-08T15:20:22.000Z | 2019-07-08T15:20:22.000Z | apps/core/lib/core/api/helpers/microservice_base.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 6 | 2018-05-11T13:59:32.000Z | 2022-01-19T20:15:22.000Z | defmodule Core.API.Helpers.MicroserviceBase do
@moduledoc false
defmacro __using__(_) do
quote do
use Confex, otp_app: :core
use HTTPoison.Base
alias Core.API.Helpers.ResponseDecoder
require Logger
def process_request_url(url), do: config()[:endpoint] <> url
def process_request_options(options), do: Keyword.merge(config()[:hackney_options], options)
@filter_request_headers ["content-length", "Content-Length", "authorization"]
@filter_log_headers ["api-key", "authorization"]
def process_request_headers(headers) do
headers
|> Keyword.drop(@filter_request_headers)
|> Enum.concat([{"Content-Type", "application/json"}])
end
defp process_log_headers(headers) do
headers
|> Keyword.drop(@filter_log_headers)
|> Enum.into(%{})
end
def request!(method, url, body \\ "", headers \\ [], options \\ []) do
with {:ok, _} <- check_params(options) do
method
|> super(url, body, headers, options)
|> log_response()
|> ResponseDecoder.check_response()
end
end
def request(method, url, body \\ "", headers \\ [], options \\ []) do
with {:ok, params} <- check_params(options) do
query_string = if Enum.empty?(params), do: "", else: "?#{URI.encode_query(params)}"
Logger.info(
"Microservice #{method} request to #{config()[:endpoint]} on #{process_request_url(url)}#{query_string}.
Body: #{body} and headers: #{inspect(process_log_headers(headers))}"
)
method
|> super(url, body, headers, options)
|> log_response()
end
end
defp check_params(options) do
params = Keyword.get(options, :params, [])
errors =
Enum.reduce(params, [], fn
{k, v}, errors_list when is_list(v) ->
errors_list ++ error_description(k)
{k, v}, errors_list ->
try do
to_string(v)
errors_list
rescue
error ->
errors_list ++ error_description(k)
end
end)
if length(errors) > 0, do: {:error, errors}, else: {:ok, params}
end
defp log_response(%{request: request, status_code: code, body: body} = response) when code >= 300 do
Logger.warn(
"Failed microservice #{request.method} request to #{config()[:endpoint]} with response: #{inspect(body)}"
)
response
end
defp log_response(response), do: response
defp error_description(value_name) do
[
{
%{
description: "Request parameter #{value_name} is not valid",
params: [],
rule: :invalid
},
"$.#{value_name}"
}
]
end
end
end
end
| 29.158416 | 116 | 0.550764 |
03ddc21208b48921d4ba7b4457a3abeb9fc63675 | 1,099 | exs | Elixir | clients/dataproc/mix.exs | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/dataproc/mix.exs | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/dataproc/mix.exs | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | defmodule GoogleApi.Dataproc.V1.Mixfile do
use Mix.Project
def project do
[app: :google_api_dataproc,
version: "0.0.1",
elixir: "~> 1.4",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/dataproc"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:tesla, "~> 0.8"},
{:poison, ">= 1.0.0"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
Manages Hadoop-based clusters and jobs on Google Cloud Platform.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/dataproc",
"Homepage" => "https://cloud.google.com/dataproc/"
}
]
end
end
| 23.382979 | 108 | 0.585987 |
03ddc71bdc353dbb413bb8ef5d8ed70b5a318f5c | 4,519 | exs | Elixir | apps/definition_kafka/test/kafka/topic/destination_test.exs | rucker/hindsight | 876a5d344c5d8eebbea37684ee07e0a91e4430f0 | [
"Apache-2.0"
] | 12 | 2020-01-27T19:43:02.000Z | 2021-07-28T19:46:29.000Z | apps/definition_kafka/test/kafka/topic/destination_test.exs | rucker/hindsight | 876a5d344c5d8eebbea37684ee07e0a91e4430f0 | [
"Apache-2.0"
] | 81 | 2020-01-28T18:07:23.000Z | 2021-11-22T02:12:13.000Z | apps/definition_kafka/test/kafka/topic/destination_test.exs | rucker/hindsight | 876a5d344c5d8eebbea37684ee07e0a91e4430f0 | [
"Apache-2.0"
] | 10 | 2020-02-13T21:24:09.000Z | 2020-05-21T18:39:35.000Z | defmodule Kafka.Topic.DestinationTest do
use ExUnit.Case
use Divo
require Temp.Env
import AssertAsync
@endpoints [localhost: 9092]
@moduletag integration: true, divo: true
setup do
test = self()
handler = fn event, measurements, metadata, config ->
send(test, {:telemetry_event, event, measurements, metadata, config})
end
:telemetry.attach(__MODULE__, [:destination, :kafka, :write], handler, %{})
on_exit(fn -> :telemetry.detach(__MODULE__) end)
Process.flag(:trap_exit, true)
:ok
end
describe "start_link/2" do
test "creates topic in Kafka" do
topic = Kafka.Topic.new!(endpoints: @endpoints, name: "create-me")
{:ok, pid} = Destination.start_link(topic, context([]))
assert_async debug: true do
assert Elsa.topic?(@endpoints, topic.name)
end
assert_down(pid)
end
test "creates topic with configurable number of partitions" do
topic = Kafka.Topic.new!(endpoints: @endpoints, name: "partitioned", partitions: 3)
{:ok, pid} = Destination.start_link(topic, context([]))
assert_async debug: true do
assert Elsa.topic?(@endpoints, topic.name)
assert Elsa.Util.partition_count(@endpoints, topic.name) == 3
end
assert_down(pid)
end
end
describe "write/2" do
test "produces messages to Kafka" do
topic = Kafka.Topic.new!(endpoints: @endpoints, name: "write-me")
{:ok, pid} = Destination.start_link(topic, context([]))
assert :ok = Destination.write(topic, pid, ["one", "two", "three"])
assert_async debug: true do
assert Elsa.topic?(@endpoints, topic.name)
{:ok, _, messages} = Elsa.fetch(@endpoints, topic.name)
assert ["one", "two", "three"] == Enum.map(messages, & &1.value)
end
assert_down(pid)
end
test "encodes maps to JSON before producing to Kafka" do
topic = Kafka.Topic.new!(endpoints: @endpoints, name: "write-maps")
{:ok, pid} = Destination.start_link(topic, context([]))
assert :ok = Destination.write(topic, pid, [%{one: 1}, %{two: 2}])
assert_async debug: true do
assert Elsa.topic?(@endpoints, topic.name)
{:ok, _, messages} = Elsa.fetch(@endpoints, topic.name)
assert [{"", ~s|{"one":1}|}, {"", ~s|{"two":2}|}] ==
Enum.map(messages, &{&1.key, &1.value})
end
assert_down(pid)
end
test "keys message off topic's key_path field" do
topic = Kafka.Topic.new!(endpoints: @endpoints, name: "key-me", key_path: ["a", "b"])
{:ok, pid} = Destination.start_link(topic, context([]))
input = [%{"a" => %{"b" => "1"}}, %{"a" => %{"b" => "2"}}]
assert :ok = Destination.write(topic, pid, input)
assert_async debug: true do
assert Elsa.topic?(@endpoints, topic.name)
{:ok, _, messages} = Elsa.fetch(@endpoints, topic.name)
# TODO keys can only be binary?
assert [{"1", ~s|{"a":{"b":"1"}}|}, {"2", ~s|{"a":{"b":"2"}}|}] =
Enum.map(messages, &{&1.key, &1.value})
end
assert_down(pid)
end
end
describe "stop/1" do
test "stops the destination topic process" do
topic = Kafka.Topic.new!(endpoints: @endpoints, name: "stop-me")
{:ok, pid} = Destination.start_link(topic, context([]))
assert_async debug: true do
assert Elsa.topic?(@endpoints, topic.name)
end
assert :ok = Destination.stop(topic, pid)
refute Process.alive?(pid)
end
end
describe "delete/1" do
test "deletes topic from Kafka" do
{:ok, topic} = Kafka.Topic.new(endpoints: @endpoints, name: "delete-me")
Elsa.create_topic(@endpoints, topic.name)
assert_async debug: true do
assert Elsa.topic?(@endpoints, topic.name)
end
assert :ok = Destination.delete(topic)
assert_async debug: true do
refute Elsa.topic?(@endpoints, topic.name)
end
end
test "returns error tuple if topic cannot be deleted" do
topic = Kafka.Topic.new!(endpoints: @endpoints, name: "never-existed")
assert {:error, {:unknown_topic_or_partition, _}} = Destination.delete(topic)
end
end
defp assert_down(pid) do
ref = Process.monitor(pid)
Process.exit(pid, :kill)
assert_receive {:DOWN, ^ref, _, _, _}
end
defp context(overrides) do
[dictionary: Dictionary.from_list([]), dataset_id: "foo", subset_id: "bar"]
|> Keyword.merge(overrides)
|> Destination.Context.new!()
end
end
| 29.535948 | 91 | 0.614295 |
03ddf9fe0f2b898da731dcdd9d979f5d02e9d526 | 1,415 | exs | Elixir | mix.exs | joakimk/exqueue | bc2c4fdf311174ea92ff1cf3c0a1860137132ed7 | [
"MIT",
"Unlicense"
] | 366 | 2015-07-04T22:05:44.000Z | 2021-11-15T10:13:46.000Z | mix.exs | joakimk/exqueue | bc2c4fdf311174ea92ff1cf3c0a1860137132ed7 | [
"MIT",
"Unlicense"
] | 47 | 2015-07-05T13:40:56.000Z | 2019-10-04T03:16:56.000Z | mix.exs | joakimk/exqueue | bc2c4fdf311174ea92ff1cf3c0a1860137132ed7 | [
"MIT",
"Unlicense"
] | 33 | 2015-07-05T12:50:55.000Z | 2021-01-28T03:42:41.000Z | defmodule Toniq.Mixfile do
use Mix.Project
def project do
[
app: :toniq,
version: "1.2.3",
elixir: "~> 1.0",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
description: description(),
package: package(),
deps: deps()
]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[applications: [:logger, :uuid, :exredis], mod: {Toniq, []}]
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
[
{:exredis, ">= 0.1.1"},
{:uuid, "~> 1.0"},
{:ex_doc, ">= 0.0.0", only: :dev},
{:mix_test_watch, "~> 0.5", only: :dev, runtime: false},
{:retry, "~> 0.5.0", only: :test}
]
end
defp description do
"""
Simple and reliable background job processing library for Elixir.
Has persistence, retries, delayed jobs, concurrency limiting, error handling and is heroku friendly.
"""
end
defp package do
[
files: ["lib", "mix.exs", "README.md"],
maintainers: ["Joakim Kolsjö"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/joakimk/toniq"}
]
end
end
| 23.583333 | 104 | 0.571025 |
03de5258ee5513d7a52b92825de738015f4f66c9 | 1,448 | ex | Elixir | lib/json_api_query_builder/include.ex | mbuhot/json_api_query_builder | c67bc3bf81c27c6ccb69278d09eba337aa81589c | [
"MIT"
] | 8 | 2017-12-13T14:37:37.000Z | 2020-05-22T13:50:45.000Z | lib/json_api_query_builder/include.ex | mbuhot/json_api_query_builder | c67bc3bf81c27c6ccb69278d09eba337aa81589c | [
"MIT"
] | null | null | null | lib/json_api_query_builder/include.ex | mbuhot/json_api_query_builder | c67bc3bf81c27c6ccb69278d09eba337aa81589c | [
"MIT"
] | null | null | null | defmodule JsonApiQueryBuilder.Include do
@moduledoc """
Related resource include operations for JsonApiQueryBuilder
"""
@doc """
Applies related resource inclusion from a parsed JSON-API request to an `Ecto.Queryable.t` as preloads.
The given callback will be invoked for each included relationship with a new JSON-API style request.
"""
@spec include(Ecto.Queryable.t, map, function) :: Ecto.Queryable.t
def include(query, params = %{"include" => include}, callback) do
includes = group_includes(include)
Enum.reduce(includes, query, fn
{relationship, related_includes}, query ->
related_params = %{
"include" => related_includes,
"filter" => (get_in(params, ["filter", relationship]) || %{}),
"fields" => params["fields"]
}
callback.(query, relationship, related_params)
end)
end
def include(query, _params, _callback), do: query
@doc """
Groups the `include` string by leading path segment.
## Example
iex> JsonApiQueryBuilder.Include.group_includes("a,a.b,a.b.c,a.d,e")
[{"a", "b,b.c,d"}, {"e", ""}]
"""
@spec group_includes(String.t) :: [{String.t, String.t}]
def group_includes(includes) do
includes
|> String.split(",", trim: true)
|> Enum.map(&String.split(&1, ".", parts: 2))
|> Enum.group_by(&hd/1, &Enum.drop(&1, 1))
|> Enum.map(fn {k, v} -> {k, Enum.join(List.flatten(v), ",")} end)
end
end | 33.674419 | 105 | 0.635359 |
03de67e084b8e0b75105d5929cca5701eb60e039 | 2,255 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/resource_policy_snapshot_schedule_policy_schedule.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/compute/lib/google_api/compute/v1/model/resource_policy_snapshot_schedule_policy_schedule.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/compute/lib/google_api/compute/v1/model/resource_policy_snapshot_schedule_policy_schedule.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.Compute.V1.Model.ResourcePolicySnapshotSchedulePolicySchedule do
@moduledoc """
A schedule for disks where the schedueled operations are performed.
## Attributes
* `dailySchedule` (*type:* `GoogleApi.Compute.V1.Model.ResourcePolicyDailyCycle.t`, *default:* `nil`) -
* `hourlySchedule` (*type:* `GoogleApi.Compute.V1.Model.ResourcePolicyHourlyCycle.t`, *default:* `nil`) -
* `weeklySchedule` (*type:* `GoogleApi.Compute.V1.Model.ResourcePolicyWeeklyCycle.t`, *default:* `nil`) -
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:dailySchedule => GoogleApi.Compute.V1.Model.ResourcePolicyDailyCycle.t() | nil,
:hourlySchedule => GoogleApi.Compute.V1.Model.ResourcePolicyHourlyCycle.t() | nil,
:weeklySchedule => GoogleApi.Compute.V1.Model.ResourcePolicyWeeklyCycle.t() | nil
}
field(:dailySchedule, as: GoogleApi.Compute.V1.Model.ResourcePolicyDailyCycle)
field(:hourlySchedule, as: GoogleApi.Compute.V1.Model.ResourcePolicyHourlyCycle)
field(:weeklySchedule, as: GoogleApi.Compute.V1.Model.ResourcePolicyWeeklyCycle)
end
defimpl Poison.Decoder,
for: GoogleApi.Compute.V1.Model.ResourcePolicySnapshotSchedulePolicySchedule do
def decode(value, options) do
GoogleApi.Compute.V1.Model.ResourcePolicySnapshotSchedulePolicySchedule.decode(value, options)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Compute.V1.Model.ResourcePolicySnapshotSchedulePolicySchedule do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41 | 110 | 0.759645 |
03defd0074dd2e7eaa4fbbd6b64776a8fa226ae5 | 7,003 | exs | Elixir | test/nerves_new_test.exs | TORIFUKUKaiou/nerves_bootstrap | 8d4142779fa5f2a3719118490c8cd3401c6eb374 | [
"Apache-2.0"
] | null | null | null | test/nerves_new_test.exs | TORIFUKUKaiou/nerves_bootstrap | 8d4142779fa5f2a3719118490c8cd3401c6eb374 | [
"Apache-2.0"
] | null | null | null | test/nerves_new_test.exs | TORIFUKUKaiou/nerves_bootstrap | 8d4142779fa5f2a3719118490c8cd3401c6eb374 | [
"Apache-2.0"
] | null | null | null | Code.require_file("mix_helper.exs", __DIR__)
defmodule Nerves.NewTest do
use ExUnit.Case
import MixHelper
@app_name "my_device"
setup do
# The shell asks to install deps.
# We will politely say not to.
send(self(), {:mix_shell_input, :yes?, false})
:ok
end
test "new project default targets", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name])
assert_file("#{@app_name}/README.md")
assert_file("#{@app_name}/mix.exs", fn file ->
assert file =~ "@app :#{@app_name}"
assert file =~ "{:nerves_system_rpi, \"~> 1.12\", runtime: false, targets: :rpi"
assert file =~ "{:nerves_system_rpi0, \"~> 1.12\", runtime: false, targets: :rpi0"
assert file =~ "{:nerves_system_rpi2, \"~> 1.12\", runtime: false, targets: :rpi2"
assert file =~ "{:nerves_system_rpi3, \"~> 1.12\", runtime: false, targets: :rpi3"
assert file =~ "{:nerves_system_rpi3a, \"~> 1.12\", runtime: false, targets: :rpi3a"
assert file =~ "{:nerves_system_rpi4, \"~> 1.12\", runtime: false, targets: :rpi4"
assert file =~ "{:nerves_system_bbb, \"~> 2.7\", runtime: false, targets: :bbb"
assert file =~ "{:nerves_system_x86_64, \"~> 1.12\", runtime: false, targets: :x86_64"
end)
end)
end
test "new project single target", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name, "--target", "rpi"])
assert_file("#{@app_name}/README.md")
assert_file("#{@app_name}/mix.exs", fn file ->
assert file =~ "@app :#{@app_name}"
assert file =~ "{:nerves_system_rpi, \"~> 1.12\", runtime: false, targets: :rpi"
refute file =~ "{:nerves_system_rpi0, \"~> 1.12\", runtime: false, targets: :rpi0"
end)
end)
end
test "new project multiple target", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name, "--target", "rpi", "--target", "rpi3"])
assert_file("#{@app_name}/README.md")
assert_file("#{@app_name}/mix.exs", fn file ->
assert file =~ "@app :#{@app_name}"
assert file =~ "{:nerves_system_rpi, \"~> 1.12\", runtime: false, targets: :rpi"
assert file =~ "{:nerves_system_rpi3, \"~> 1.12\", runtime: false, targets: :rpi3"
refute file =~ "{:nerves_system_rpi0, \"~> 1.12\", runtime: false, targets: :rpi0"
end)
end)
end
test "new project cookie set", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name, "--cookie", "foo"])
assert_file("#{@app_name}/mix.exs", fn file ->
assert file =~ ~s{cookie: "foo"}
end)
end)
end
test "new project provides a default cookie", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name])
assert_file("#{@app_name}/mix.exs", fn file ->
assert file =~ "cookie: \"\#{@app}_cookie\""
end)
end)
end
test "new project enables heart", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name])
assert_file("#{@app_name}/rel/vm.args.eex", fn file ->
assert file =~ "-heart -env HEART_BEAT_TIMEOUT"
end)
end)
end
test "new project enables embedded mode", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name])
assert_file("#{@app_name}/rel/vm.args.eex", fn file ->
assert file =~ "-mode embedded"
end)
end)
end
test "new project adds runtime_tools", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name])
assert_file("#{@app_name}/mix.exs", fn file ->
assert file =~ ~r/extra_applications:.*runtime_tools/
end)
end)
end
test "new project includes ring_logger", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name])
assert_file("#{@app_name}/mix.exs", fn file ->
assert file =~ ~r/:ring_logger/
end)
assert_file("#{@app_name}/config/config.exs", fn file ->
assert file =~ ~r/RingLogger/
end)
end)
end
test "new project includes toolshed", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name])
assert_file("#{@app_name}/mix.exs", fn file ->
assert file =~ ~r/:toolshed/
end)
end)
end
test "new project sets build_embedded", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name])
assert_file("#{@app_name}/mix.exs", fn file ->
assert file =~ ~r/build_embedded:/
end)
end)
end
test "new project with nerves_pack", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name, "--nerves-pack"])
assert_file("#{@app_name}/mix.exs", fn file ->
assert file =~ ~r/:nerves_pack/
end)
assert_file("#{@app_name}/config/target.exs", fn file ->
assert file =~ ~r"nerves_ssh"
assert file =~ ~r"vintage_net"
assert file =~ ~r"mdns_lite"
end)
end)
end
test "new project with implicit nerves_pack", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name])
assert_file("#{@app_name}/mix.exs", fn file ->
assert file =~ ~r/:nerves_pack/
end)
assert_file("#{@app_name}/config/target.exs", fn file ->
assert file =~ ~r"nerves_ssh"
assert file =~ ~r"vintage_net"
assert file =~ ~r"mdns_lite"
end)
end)
end
test "new project without nerves pack", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name, "--no-nerves-pack"])
assert_file("#{@app_name}/mix.exs", fn file ->
refute file =~ ~r"nerves_pack"
end)
assert_file("#{@app_name}/config/config.exs", fn file ->
refute file =~ ~r"nerves_pack"
refute file =~ ~r"nerves_ssh"
end)
end)
end
test "new projects cannot use reserved names", context do
in_tmp(context.test, fn ->
assert_raise(Mix.Error, "New projects cannot be named 'nerves'", fn ->
Mix.Tasks.Nerves.New.run(["nerves"])
end)
end)
end
test "new project sets source_date_epoch time", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name, "--source-date-epoch", "1234"])
assert_file("#{@app_name}/config/config.exs", fn file ->
assert file =~ ~r/source_date_epoch: "1234"/
end)
end)
end
test "new project generates source_date_epoch time", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name])
assert_file("#{@app_name}/config/config.exs", fn file ->
assert file =~ ~r/source_date_epoch: /
end)
end)
end
test "new project generates sample erlinit config", context do
in_tmp(context.test, fn ->
Mix.Tasks.Nerves.New.run([@app_name])
assert_file("#{@app_name}/config/target.exs", fn file ->
assert file =~ ~r"erlinit"
end)
end)
end
end
| 29.92735 | 94 | 0.600885 |
03df20560d4256c1ba5ce5073b2367b9f3c8df37 | 112 | exs | Elixir | ps/servy/test/servy_test.exs | mdeilman/ElixirCode | d0560c7b135b4cb146dccb8202b9e4dede199a1b | [
"Apache-2.0"
] | null | null | null | ps/servy/test/servy_test.exs | mdeilman/ElixirCode | d0560c7b135b4cb146dccb8202b9e4dede199a1b | [
"Apache-2.0"
] | 1 | 2020-02-26T14:55:23.000Z | 2020-02-26T14:55:23.000Z | ps/servy/test/servy_test.exs | mdeilman/ElixirCode | d0560c7b135b4cb146dccb8202b9e4dede199a1b | [
"Apache-2.0"
] | null | null | null | defmodule ServyTest do
use ExUnit.Case
doctest Servy
test "the truth" do
assert 1 + 1 == 2
end
end
| 12.444444 | 22 | 0.660714 |
03df49793ee3e653bbe585c6ae80be87db19fb2e | 1,789 | ex | Elixir | lib/blue_heron/hci/commands/controller_and_baseband/write_scan_enable.ex | amclain/blue_heron | e1802097ef6a845e28a8be56076f3b81ebb56206 | [
"Apache-2.0"
] | 45 | 2020-10-17T13:34:15.000Z | 2022-03-08T09:40:43.000Z | lib/blue_heron/hci/commands/controller_and_baseband/write_scan_enable.ex | amclain/blue_heron | e1802097ef6a845e28a8be56076f3b81ebb56206 | [
"Apache-2.0"
] | 20 | 2020-10-15T15:05:54.000Z | 2022-03-27T15:54:36.000Z | lib/blue_heron/hci/commands/controller_and_baseband/write_scan_enable.ex | amclain/blue_heron | e1802097ef6a845e28a8be56076f3b81ebb56206 | [
"Apache-2.0"
] | 11 | 2020-10-23T17:18:57.000Z | 2022-03-15T20:01:49.000Z | defmodule BlueHeron.HCI.Command.ControllerAndBaseband.WriteScanEnable do
use BlueHeron.HCI.Command.ControllerAndBaseband, ocf: 0x001A
@moduledoc """
This command writes the value for the Scan_Enable configuration parameter.
* OGF: `#{inspect(@ogf, base: :hex)}`
* OCF: `#{inspect(@ocf, base: :hex)}`
* Opcode: `#{inspect(@opcode)}`
Bluetooth Spec v5.2, Vol 4, Part E, section 7.3.18
The Scan_Enable parameter controls whether or not the BR/EDR Controller will
periodically scan for page attempts and/or inquiry requests from other BR/EDR
Controllers. If Page Scan is enabled, then the device will enter page scan
mode based on the value of the Page_Scan_Interval and Page_Scan_Window
parameters. If Inquiry Scan is enabled, then the BR/EDR Controller will enter
Inquiry Scan mode based on the value of the Inquiry_Scan_Interval and
Inquiry_Scan_Window parameters.
## Command Parameters
* `scan_enable`:
* `0x00` - No scans enabled. **Default**.
* `0x01` - Inquiry Scan enabled. Page Scan disabled.
* `0x02` - Inquiry Scan disabled. Page Scan enabled.
* `0x03` - Inquiry Scan enabled. Page Scan enabled.
## Return Parameters
* `:status` - see `BlueHeron.ErrorCode`
"""
defparameters scan_enable: 0x00
defimpl BlueHeron.HCI.Serializable do
def serialize(%{opcode: opcode, scan_enable: scan_enable}) do
<<opcode::binary, 1, scan_enable>>
end
end
@impl BlueHeron.HCI.Command
def deserialize(<<@opcode::binary, 1, scan_enable>>) do
new(scan_enable: scan_enable)
end
@impl BlueHeron.HCI.Command
def deserialize_return_parameters(<<status>>) do
%{status: status}
end
@impl true
def serialize_return_parameters(%{status: status}) do
<<BlueHeron.ErrorCode.to_code!(status)>>
end
end
| 32.527273 | 79 | 0.723309 |
03df7848a3016f7fadf64556f4169db9366a737f | 689 | exs | Elixir | patterns/content-based-router/elixir/contentBasedRouter/mix.exs | thetonymaster/thetonymaster.github.io | 2e24d46dd377fed6ab6d1609e5afe24b4953a0f2 | [
"MIT"
] | null | null | null | patterns/content-based-router/elixir/contentBasedRouter/mix.exs | thetonymaster/thetonymaster.github.io | 2e24d46dd377fed6ab6d1609e5afe24b4953a0f2 | [
"MIT"
] | null | null | null | patterns/content-based-router/elixir/contentBasedRouter/mix.exs | thetonymaster/thetonymaster.github.io | 2e24d46dd377fed6ab6d1609e5afe24b4953a0f2 | [
"MIT"
] | null | null | null | defmodule ContentBasedRouter.Mixfile do
use Mix.Project
def project do
[app: :contentBasedRouter,
version: "0.0.1",
elixir: "~> 1.1",
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: [:logger]]
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
[]
end
end
| 20.878788 | 77 | 0.62119 |
03df80bb598a3b2a0e1a9182eab8f7c5337029c7 | 1,733 | ex | Elixir | lib/shopix_web.ex | gsarwate/shopix | 21d0e85294ee92cb7573d1b5a5746af6824b9355 | [
"MIT"
] | 196 | 2019-05-05T15:59:32.000Z | 2022-03-15T02:37:19.000Z | lib/shopix_web.ex | gsarwate/shopix | 21d0e85294ee92cb7573d1b5a5746af6824b9355 | [
"MIT"
] | 105 | 2019-05-04T19:04:40.000Z | 2021-07-28T11:21:45.000Z | lib/shopix_web.ex | gsarwate/shopix | 21d0e85294ee92cb7573d1b5a5746af6824b9355 | [
"MIT"
] | 26 | 2019-05-05T19:40:52.000Z | 2021-11-16T00:32:46.000Z | defmodule ShopixWeb do
@moduledoc """
A module that keeps using definitions for controllers,
views and so on.
This can be used in your application as:
use ShopixWeb, :controller
use ShopixWeb, :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 controller do
quote do
use Phoenix.Controller, namespace: ShopixWeb
import Plug.Conn
import ShopixWeb.Router.Helpers
import ShopixWeb.Gettext
import ShopixWeb.StringHelpers
end
end
def view do
quote do
use Phoenix.View,
root: "lib/shopix_web/templates",
namespace: ShopixWeb
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
import ShopixWeb.Router.Helpers
import ShopixWeb.ErrorHelpers
import ShopixWeb.TranslationHelpers
import ShopixWeb.ImageHelpers
import ShopixWeb.Gettext
import ShopixWeb.StringHelpers
import ShopixWeb.DateHelpers
import Scrivener.HTML
import Bootform
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 ShopixWeb.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.106667 | 88 | 0.688979 |
03df9fb4b1b2c1ca461eb1de8c59e0b353f4f9c1 | 2,332 | ex | Elixir | lib/toolshed/log.ex | fhunleth/toolbag | 6eda196a2c0506ccad01fb437aa30b81def55eda | [
"Apache-2.0"
] | 51 | 2018-10-20T00:48:39.000Z | 2021-02-26T13:42:03.000Z | lib/toolshed/log.ex | fhunleth/toolbag | 6eda196a2c0506ccad01fb437aa30b81def55eda | [
"Apache-2.0"
] | 27 | 2021-02-27T15:57:22.000Z | 2022-03-18T03:12:59.000Z | lib/toolshed/log.ex | fhunleth/toolbag | 6eda196a2c0506ccad01fb437aa30b81def55eda | [
"Apache-2.0"
] | 11 | 2018-11-02T00:00:57.000Z | 2021-02-24T19:03:34.000Z | defmodule Toolshed.Log do
@moduledoc """
Utilities for attaching and detaching to the log
These utilities configure Elixir's console backend to attach
to the current group leader. This makes it work over `ssh` sessions
and play well with the IEx prompt.
"""
@doc """
Attach the current session to the Elixir logger
This forwards incoming log messages to the terminal. Call `detach/0` to stop
the messages.
Behind the scenes, this uses Elixir's built-in console logger and can be
configured similarly. See the [Logger console backend
documentation](https://hexdocs.pm/logger/Logger.html#module-console-backend)
for details. The following are useful options:
* `:level` - the minimum log level to report. E.g., specify `level: :warning`
to only see warnings and errors.
* `:metadata` - a list of metadata keys to show or `:all`
Unspecified options use either the console backend's default or those found
in the application environment for the `:console` Logger backend.
"""
@spec log_attach(keyword()) :: {:error, any} | {:ok, :undefined | pid}
def log_attach(options \\ []) do
case Process.get(__MODULE__) do
nil ->
all_options = Keyword.put(options, :device, Process.group_leader())
backend = {Logger.Backends.Console, all_options}
{:ok, pid} = GenServer.start(Toolshed.Log.Watcher, {Process.group_leader(), backend})
Process.put(__MODULE__, {pid, backend})
Logger.add_backend({Logger.Backends.Console, all_options})
_other ->
{:error, :detach_first}
end
end
@doc """
Detach the current session from the Elixir logger
"""
@spec log_detach :: :ok | {:error, :not_attached | :not_found}
def log_detach() do
case Process.get(__MODULE__) do
nil ->
{:error, :not_attached}
{pid, backend} ->
Process.delete(__MODULE__)
GenServer.stop(pid)
Logger.remove_backend(backend)
end
end
defmodule Watcher do
@moduledoc false
use GenServer
@impl GenServer
def init({watch_pid, backend}) do
Process.monitor(watch_pid)
{:ok, backend}
end
@impl GenServer
def handle_info({:DOWN, _ref, :process, _pid, _reason}, backend) do
_ = Logger.remove_backend(backend)
{:stop, :normal, backend}
end
end
end
| 29.518987 | 93 | 0.675815 |
03dfe5900828c8b1c40e8ada03ccf19e1b8b18fe | 557 | ex | Elixir | lib/lle_cymraeg_web/views/person_view.ex | danielcavanagh/lle-cymraeg | 01aebc939254e0dd76427cb460722b830c232e82 | [
"MIT"
] | null | null | null | lib/lle_cymraeg_web/views/person_view.ex | danielcavanagh/lle-cymraeg | 01aebc939254e0dd76427cb460722b830c232e82 | [
"MIT"
] | null | null | null | lib/lle_cymraeg_web/views/person_view.ex | danielcavanagh/lle-cymraeg | 01aebc939254e0dd76427cb460722b830c232e82 | [
"MIT"
] | null | null | null | defmodule LleCymraegWeb.PersonView do
use LleCymraegWeb, :view
alias LleCymraegWeb.PersonView
def render("index.json", %{people: people}) do
%{data: render_many(people, PersonView, "person.json")}
end
def render("show.json", %{person: person}) do
%{data: render_one(person, PersonView, "person.json")}
end
def render("person.json", %{person: person}) do
%{id: person.id,
name: person.name,
dob: person.dob,
bio: person.bio,
is_public?: person.is_public?,
travel_time: person.travel_time}
end
end
| 25.318182 | 59 | 0.666068 |
03e014103f7419659e9d52d1282d9da5f854e9ea | 803 | exs | Elixir | test/ex_raja_ongkir/request_test.exs | giraphme/ex_raja_ongkir | 6c7e7a811879d0adfd7eb574d0bbc665f1b7084d | [
"MIT"
] | null | null | null | test/ex_raja_ongkir/request_test.exs | giraphme/ex_raja_ongkir | 6c7e7a811879d0adfd7eb574d0bbc665f1b7084d | [
"MIT"
] | 1 | 2018-04-24T08:27:20.000Z | 2018-04-24T08:27:20.000Z | test/ex_raja_ongkir/request_test.exs | giraphme/ex_raja_ongkir | 6c7e7a811879d0adfd7eb574d0bbc665f1b7084d | [
"MIT"
] | null | null | null | defmodule ExRajaOngkir.RequestTest do
use ExUnit.Case
describe "ExRajaOngkir.Request.take_result/1" do
test "It get the result from RajaOngkir response" do
expected_result = "This is result"
mock_response = %HTTPotion.Response{
body: %{"rajaongkir" => %{"results" => expected_result, "status" => %{"code" => 200}}}
}
assert {:ok, expected_result} == ExRajaOngkir.Request.take_result(mock_response)
end
test "It fail to get the result because the request was failed" do
expected_result = "This is result"
mock_response = %HTTPotion.Response{
body: %{"rajaongkir" => %{"results" => expected_result, "status" => %{"code" => 500}}}
}
assert {:error, _} = ExRajaOngkir.Request.take_result(mock_response)
end
end
end
| 30.884615 | 94 | 0.656289 |
03e05653da8f6756686fadf1d3c8c5724e91afe1 | 3,022 | exs | Elixir | test/ex_doc/cli_test.exs | henrik/ex_doc | f09796782121f935e70cc51405d4773130fd70ca | [
"Apache-2.0",
"CC-BY-4.0"
] | 1 | 2021-03-13T14:49:36.000Z | 2021-03-13T14:49:36.000Z | test/ex_doc/cli_test.exs | henrik/ex_doc | f09796782121f935e70cc51405d4773130fd70ca | [
"Apache-2.0",
"CC-BY-4.0"
] | 25 | 2015-02-03T02:21:01.000Z | 2021-04-01T13:13:56.000Z | test/ex_doc/cli_test.exs | henrik/ex_doc | f09796782121f935e70cc51405d4773130fd70ca | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | defmodule ExDoc.CLITest do
use ExUnit.Case, async: true
import ExUnit.CaptureIO
@ebin "_build/test/lib/ex_doc/ebin"
defp run(args) do
ExDoc.CLI.main(args, &{&1, &2, &3})
end
test "minimum command-line options" do
assert {"ExDoc", "1.2.3", [app: :ex_doc, source_beam: @ebin]} ==
run(["ExDoc", "1.2.3", @ebin])
end
test "version" do
assert capture_io(fn ->
run(["--version"])
end) == "ExDoc v#{ExDoc.version()}\n"
assert capture_io(fn ->
run(["-v"])
end) == "ExDoc v#{ExDoc.version()}\n"
end
test "too many arguments" do
fun = fn ->
run(["ExDoc", "1.2.3", "/", "kaboom"])
end
assert catch_exit(capture_io(fun)) == {:shutdown, 1}
end
test "too few arguments" do
fun = fn ->
run(["ExDoc"])
end
assert catch_exit(capture_io(fun)) == {:shutdown, 1}
end
test "arguments that are not aliased" do
File.write!("not_aliased.exs", ~s([key: "val"]))
args = ~w(
ExDoc 1.2.3 #{@ebin}
--config not_aliased.exs
--output html
--formatter html
--source-root ./
--source-url http://example.com/username/project
--source-ref abcdefg
--main Main
--homepage-url http://example.com
--logo logo.png
--canonical http://example.com/project
)
{project, version, opts} = run(args)
assert project == "ExDoc"
assert version == "1.2.3"
assert Enum.sort(opts) == [
app: :ex_doc,
canonical: "http://example.com/project",
formatter: "html",
homepage_url: "http://example.com",
key: "val",
logo: "logo.png",
main: "Main",
output: "html",
source_beam: "#{@ebin}",
source_ref: "abcdefg",
source_root: "./",
source_url: "http://example.com/username/project"
]
after
File.rm!("not_aliased.exs")
end
describe ".exs config" do
test "loading" do
File.write!("test.exs", ~s([extras: ["README.md"]]))
{project, version, opts} =
run(["ExDoc", "--extra-section", "Guides", "1.2.3", @ebin, "-c", "test.exs"])
assert project == "ExDoc"
assert version == "1.2.3"
assert Enum.sort(opts) == [
app: :ex_doc,
extra_section: "Guides",
extras: ["README.md"],
source_beam: @ebin
]
after
File.rm!("test.exs")
end
test "missing" do
assert_raise File.Error,
fn -> run(["ExDoc", "1.2.3", @ebin, "-c", "test.exs"]) end
end
test "invalid" do
File.write!("test.exs", ~s(%{"extras" => "README.md"}))
assert_raise RuntimeError,
~S(expected a keyword list from config file: "test.exs"),
fn ->
run(["ExDoc", "1.2.3", @ebin, "-c", "test.exs"])
end
after
File.rm!("test.exs")
end
end
end
| 25.394958 | 85 | 0.50728 |
03e067ec264145fba5993a0c645564976993eed5 | 129 | ex | Elixir | lib/rain_machine/zone.ex | unsilo/rain_machine | a1acf1b7ed54021699c137cabb5ed127d0aa30a3 | [
"MIT"
] | null | null | null | lib/rain_machine/zone.ex | unsilo/rain_machine | a1acf1b7ed54021699c137cabb5ed127d0aa30a3 | [
"MIT"
] | null | null | null | lib/rain_machine/zone.ex | unsilo/rain_machine | a1acf1b7ed54021699c137cabb5ed127d0aa30a3 | [
"MIT"
] | null | null | null | defmodule RainMachine.Zone do
defstruct name: nil, last_water: nil, next_water: nil, total_water: nil, uid: nil, state: 0
end
| 25.8 | 93 | 0.751938 |
03e0aefb56a0c4582ef911c3c4d53d05a3b0e781 | 7,949 | exs | Elixir | test/invoices/invoice_creation_test.exs | fstromback/bitpal | 2c50e6700d7383b4f025b3734ba37257c69ce47e | [
"BSD-3-Clause-Clear"
] | null | null | null | test/invoices/invoice_creation_test.exs | fstromback/bitpal | 2c50e6700d7383b4f025b3734ba37257c69ce47e | [
"BSD-3-Clause-Clear"
] | null | null | null | test/invoices/invoice_creation_test.exs | fstromback/bitpal | 2c50e6700d7383b4f025b3734ba37257c69ce47e | [
"BSD-3-Clause-Clear"
] | null | null | null | defmodule InvoiceCreationTest do
use BitPal.IntegrationCase, db: true, async: false
alias BitPal.Addresses
alias BitPal.ExchangeRate
alias BitPal.Invoices
alias BitPalSchemas.Address
test "invoice registration" do
# we don't have to provide fiat_amount
assert {:ok, invoice} =
Invoices.register(%{
amount: Money.parse!(1.2, "BCH"),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
invoice = Repo.preload(invoice, :currency)
assert invoice.id != nil
assert invoice.amount == Money.parse!(1.2, "BCH")
assert invoice.fiat_amount == Money.parse!(2.4, "USD")
assert invoice.status == :draft
assert invoice.currency_id == "BCH"
assert invoice.currency.id == "BCH"
assert invoice.address_id == nil
assert invoice.exchange_rate == %ExchangeRate{
rate: Decimal.from_float(2.0),
pair: {:BCH, :USD}
}
assert in_db = Invoices.fetch!(invoice.id)
assert in_db.id == invoice.id
# it's fine to skip fiat_amount + exchange_rate
assert {:ok, invoice} = Invoices.register(%{amount: Money.parse!(1.2, "BCH")})
assert Money.to_decimal(invoice.amount) == Decimal.from_float(1.2)
assert invoice.fiat_amount == nil
assert invoice.exchange_rate == nil
# but we must have either amount or exchange_rate, otherwise we don't
# know how much crypto to ask for
assert {:error, changeset} = Invoices.register(%{fiat_amount: Money.parse!(1.2, "BCH")})
assert "must provide either amount or exchange rate" in errors_on(changeset).amount
# only exchange rate isn't enough either
assert {:error, changeset} =
Invoices.register(%{
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert "must provide amount in either crypto or fiat" in errors_on(changeset).amount
# other invalid inputs
assert {:error, changeset} =
Invoices.register(%{
amount: Money.parse!(-2.5, "BCH"),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert "cannot be negative" in errors_on(changeset).amount
assert {:error, changeset} =
Invoices.register(%{
amount: "BORK",
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert "is invalid" in errors_on(changeset).amount
end
test "address assigning" do
assert {:ok, invoice} =
Invoices.register(%{
amount: Money.parse!(1.2, "BCH"),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert {:ok, address} = Addresses.register(:BCH, "bch:0", Addresses.next_address_index("BCH"))
assert {:ok, invoice} = Invoices.assign_address(invoice, address)
assert invoice.address == address
assert {:error, _} =
Invoices.assign_address(invoice, %Address{
id: "not-in-db",
generation_index: 1,
currency_id: "BCH"
})
end
test "ensuring addresses" do
assert {:ok, inv} =
Invoices.register(%{
amount: Money.parse!(1.2, "BCH"),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert {:ok, one = %{address_id: "one"}} =
Invoices.ensure_address(inv, fn _ ->
"one"
end)
assert {:ok, ^one} =
Invoices.ensure_address(one, fn _ ->
"xxx"
end)
assert {:error, _} =
Invoices.ensure_address(inv, fn _ ->
"one"
end)
assert {:ok, %{address_id: "two"}} =
Invoices.ensure_address(inv, fn _ ->
"two"
end)
ind = Addresses.next_address_index(:BCH)
assert {:ok, _} =
Invoices.register(%{
amount: Money.parse!(1.2, "BCH"),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert {:ok, %{address_id: "three"}} =
Invoices.ensure_address(inv, fn _ ->
"three"
end)
assert Addresses.next_address_index(:BCH) != ind
end
test "amount calculations" do
# fiat amount will be calculated from amount + exchange_rate
assert {:ok, invoice} =
Invoices.register(%{
amount: Money.parse!(1.2, "BCH"),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert Money.to_decimal(invoice.fiat_amount) == Decimal.from_float(2.4)
# amount will be calculated from fiat_amount + exchange_rate
assert {:ok, invoice} =
Invoices.register(%{
fiat_amount: Money.parse!(2.4, :USD),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert Money.to_decimal(invoice.amount) == Decimal.from_float(1.2)
# exchange_rate will be calculated from amount + fiat_amount
assert {:ok, invoice} =
Invoices.register(%{
amount: Money.parse!(1.2, "BCH"),
fiat_amount: Money.parse!(2.4, :USD)
})
assert invoice.exchange_rate == %ExchangeRate{
rate: Decimal.new(2),
pair: {:BCH, :USD}
}
# if we provide them all, they must match
assert {:ok, _} =
Invoices.register(%{
amount: Money.parse!(1.2, "BCH"),
fiat_amount: Money.parse!(2.4, :USD),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert {:error, _} =
Invoices.register(%{
amount: Money.parse!(3000, "BCH"),
fiat_amount: Money.parse!(2.4, :USD),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert {:error, _} =
Invoices.register(%{
amount: Money.parse!(1.2, "BCH"),
fiat_amount: Money.parse!(2.4, :USD),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "EUR"})
})
end
test "large amounts" do
assert {:ok, invoice} =
Invoices.register(%{
amount: Money.parse!(127_000_000_000.000_000_01, :DGC),
exchange_rate: ExchangeRate.new!(Decimal.new(2_000_000), {"DGC", "USD"})
})
assert invoice = Invoices.fetch!(invoice.id)
assert Money.to_decimal(invoice.amount) == Decimal.from_float(127_000_000_000.000_000_01)
assert Money.to_decimal(invoice.fiat_amount) ==
Decimal.from_float(254_000_000_000_000_000.000_000_02)
end
@tag backends: true
test "register via finalize" do
assert {:ok, _} =
BitPal.register_and_finalize(%{
amount: Money.parse!(1.2, "BCH"),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert {:ok, invoice} =
Invoices.register(%{
amount: Money.parse!(1.2, "BCH"),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert {:ok, _} = BitPal.finalize(invoice)
assert {:error, _} =
BitPal.finalize(%Invoice{
amount: Money.parse!(1.2, "BCH"),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
assert {:error, _} =
BitPal.finalize(%Invoice{
id: Ecto.UUID.bingenerate(),
amount: Money.parse!(1.2, "BCH"),
exchange_rate: ExchangeRate.new!(Decimal.from_float(2.0), {"BCH", "USD"})
})
Process.sleep(200)
end
end
| 33.682203 | 98 | 0.561203 |
03e0b8f58c8f7075fcc683da3483e404f30507e0 | 1,023 | ex | Elixir | lib/origami/application.ex | OrigamiApp/server | efbf185a33694b47fc94376c8ddc4b30f8e3d620 | [
"Apache-2.0"
] | null | null | null | lib/origami/application.ex | OrigamiApp/server | efbf185a33694b47fc94376c8ddc4b30f8e3d620 | [
"Apache-2.0"
] | null | null | null | lib/origami/application.ex | OrigamiApp/server | efbf185a33694b47fc94376c8ddc4b30f8e3d620 | [
"Apache-2.0"
] | null | null | null | defmodule Origami.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(Origami.Repo, []),
# Start the endpoint when the application starts
supervisor(OrigamiWeb.Endpoint, []),
# Start your own worker by calling: Origami.Worker.start_link(arg1, arg2, arg3)
# worker(Origami.Worker, [arg1, arg2, arg3]),
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Origami.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
OrigamiWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 31.96875 | 85 | 0.713587 |
03e0ca7028755bbe160a0a2d0265886939fd13a9 | 3,208 | ex | Elixir | lib/day06.ex | hvnsweeting/adventofcode2018 | 8e5a85ebb7b102361b844b0f92522c18148a672a | [
"BSD-3-Clause"
] | 1 | 2022-01-10T02:34:18.000Z | 2022-01-10T02:34:18.000Z | lib/day06.ex | hvnsweeting/adventofcode2018 | 8e5a85ebb7b102361b844b0f92522c18148a672a | [
"BSD-3-Clause"
] | null | null | null | lib/day06.ex | hvnsweeting/adventofcode2018 | 8e5a85ebb7b102361b844b0f92522c18148a672a | [
"BSD-3-Clause"
] | 1 | 2019-12-02T09:42:17.000Z | 2019-12-02T09:42:17.000Z | defmodule Day06 do
def hello() do
:hello
end
def manhattan_distance({x1, y1}, {x2, y2}) do
abs(x1 - x2) + abs(y1 - y2)
end
def string_to_coordinate(string) do
string
|> String.split("\n", trim: true)
|> Enum.map(&String.trim/1)
|> Enum.map(fn s -> String.split(s, ", ") end)
|> Enum.map(fn [x, y] -> {String.to_integer(x), String.to_integer(y)} end)
end
def smallest_grid(coordinates) do
{min_x, _} = coordinates |> Enum.min_by(fn {x, _} -> x end)
{_, min_y} = coordinates |> Enum.min_by(fn {_, y} -> y end)
{max_x, _} = coordinates |> Enum.max_by(fn {x, _} -> x end)
{_, max_y} = coordinates |> Enum.max_by(fn {_, y} -> y end)
{{min_x, min_y}, {max_x, max_y}}
end
def boundery?({x, y}, max_min) do
{{min_x, min_y}, {max_x, max_y}} = max_min
x == min_x || x == max_x || (y == min_y || y == max_y)
end
def boundery_indexes(coordinates) do
{{min_x, min_y}, {max_x, max_y}} = smallest_grid(coordinates)
coordinates
|> Enum.map(
&boundery?(
&1,
{{min_x, min_y}, {max_x, max_y}}
)
)
end
def generate_grid_coords({top_left, bottom_right}) do
{top_left_x, top_left_y} = top_left
{bottom_right_x, bottom_right_y} = bottom_right
for x <- top_left_x..bottom_right_x, y <- top_left_y..bottom_right_y, do: {x, y}
end
def solve_part1(input) do
coords = input |> string_to_coordinate
max_min = smallest_grid(coords)
boundary = coords |> boundery_indexes
grid_coords =
smallest_grid(coords)
|> IO.inspect()
|> generate_grid_coords
coords_closest_index =
grid_coords
|> Enum.map(fn {x, y} ->
{{x, y}, for(c <- coords, do: manhattan_distance(c, {x, y}))}
end)
|> Enum.filter(fn {_, v} ->
Enum.filter(v, &(&1 == Enum.min(v))) |> length == 1
end)
|> Enum.map(fn {coord, distances} ->
{coord, Enum.find_index(distances, &(&1 == Enum.min(distances)))}
end)
# those have points on edge of grid closest to it
index_of_input_points_that_has_infinite_area =
coords_closest_index
|> Enum.map(fn {{x, y}, index} -> if boundery?({x, y}, max_min), do: index, else: nil end)
|> Enum.reject(fn x -> x == nil end)
|> Enum.uniq()
|> IO.inspect()
coords_closest_index
|> Enum.group_by(fn {_, nearest_index} -> nearest_index end)
|> Enum.map(fn {index, nearest_coords} -> {index, length(nearest_coords)} end)
|> Enum.reject(fn {idx, count} ->
Enum.member?(index_of_input_points_that_has_infinite_area, idx)
end)
|> Enum.max_by(fn {_k, v} -> v end)
|> elem(1)
end
def total_distance(coordinates, location) do
Enum.sum(
coordinates
|> Enum.map(&manhattan_distance(&1, location))
)
end
def find_region(coordinates, dist_limit \\ 32) do
locations = coordinates |> smallest_grid |> generate_grid_coords
Enum.count(
Enum.map(
locations,
&total_distance(coordinates, &1)
),
&(&1 < dist_limit)
)
end
def solve_part2(inputstring, dist_limit \\ 10000) do
inputstring
|> string_to_coordinate
|> find_region(dist_limit)
end
end
| 27.895652 | 96 | 0.601621 |
03e0d7ffd543a1d4997199adecdaf8f43adc6f45 | 1,717 | ex | Elixir | clients/sheets/lib/google_api/sheets/v4/model/data_source_refresh_daily_schedule.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/sheets/lib/google_api/sheets/v4/model/data_source_refresh_daily_schedule.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/sheets/lib/google_api/sheets/v4/model/data_source_refresh_daily_schedule.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Sheets.V4.Model.DataSourceRefreshDailySchedule do
@moduledoc """
A schedule for data to refresh every day in a given time interval.
## Attributes
* `startTime` (*type:* `GoogleApi.Sheets.V4.Model.TimeOfDay.t`, *default:* `nil`) - The start time of a time interval in which a data source refresh is scheduled. Only `hours` part is used. The time interval size defaults to that in the Sheets editor.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:startTime => GoogleApi.Sheets.V4.Model.TimeOfDay.t()
}
field(:startTime, as: GoogleApi.Sheets.V4.Model.TimeOfDay)
end
defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.DataSourceRefreshDailySchedule do
def decode(value, options) do
GoogleApi.Sheets.V4.Model.DataSourceRefreshDailySchedule.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.DataSourceRefreshDailySchedule do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.531915 | 255 | 0.75364 |
03e0fb0c3928f18a1d0e99174fbc1d63199525c9 | 428 | ex | Elixir | lib/hologram/compiler/js_encoders/relaxed_boolean_and_operator.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 40 | 2022-01-19T20:27:36.000Z | 2022-03-31T18:17:41.000Z | lib/hologram/compiler/js_encoders/relaxed_boolean_and_operator.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 42 | 2022-02-03T22:52:43.000Z | 2022-03-26T20:57:32.000Z | lib/hologram/compiler/js_encoders/relaxed_boolean_and_operator.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 3 | 2022-02-10T04:00:37.000Z | 2022-03-08T22:07:45.000Z | alias Hologram.Compiler.{Context, JSEncoder, Opts}
alias Hologram.Compiler.IR.RelaxedBooleanAndOperator
defimpl JSEncoder, for: RelaxedBooleanAndOperator do
def encode(%{left: left, right: right}, %Context{} = context, %Opts{} = opts) do
left = JSEncoder.encode(left, context, opts)
right = JSEncoder.encode(right, context, opts)
"Hologram.Interpreter.$relaxed_boolean_and_operator(#{left}, #{right})"
end
end
| 35.666667 | 82 | 0.742991 |
03e0fc43d004a58aba02428e51af20f7c88a0399 | 2,347 | ex | Elixir | lib/sanbase/tag/tag.ex | santiment/sanbase2 | 9ef6e2dd1e377744a6d2bba570ea6bd477a1db31 | [
"MIT"
] | 81 | 2017-11-20T01:20:22.000Z | 2022-03-05T12:04:25.000Z | lib/sanbase/tag/tag.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 359 | 2017-10-15T14:40:53.000Z | 2022-01-25T13:34:20.000Z | lib/sanbase/tag/tag.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 16 | 2017-11-19T13:57:40.000Z | 2022-02-07T08:13:02.000Z | defmodule Sanbase.Tag do
use Ecto.Schema
import Ecto.Changeset
import Ecto.Query
alias __MODULE__
alias Sanbase.Repo
alias Sanbase.Insight.Post
alias Sanbase.Alert.UserTrigger
@posts_join_through_table "posts_tags"
@user_triggers_join_through_table "user_triggers_tags"
schema "tags" do
field(:name, :string)
many_to_many(:posts, Post, join_through: @posts_join_through_table)
many_to_many(:user_triggers, UserTrigger, join_through: @user_triggers_join_through_table)
end
def changeset(%Tag{} = tag, attrs \\ %{}) do
tag
|> cast(attrs, [:name])
|> validate_required([:name])
|> unique_constraint(:name, name: :tags_name_index)
end
def by_names(names) when is_list(names) do
from(t in __MODULE__, where: t.name in ^names)
|> Repo.all()
end
def all(), do: Repo.all(__MODULE__)
@doc ~s"""
Given a changeset and a map of params, containing `tags`. The tags are added with
`put_assoc` that works on the whole list of tags.
"""
@spec put_tags(Ecto.Changeset.t(), map()) :: Ecto.Changeset.t()
def put_tags(%Ecto.Changeset{} = changeset, %{tags: tags})
when is_list(tags) and length(tags) > 10 do
Ecto.Changeset.add_error(changeset, :tags, "Cannot add more than 10 tags for a record")
end
def put_tags(%Ecto.Changeset{} = changeset, %{tags: tags}) when is_list(tags) do
tags =
tags
|> Enum.filter(&is_binary/1)
|> Enum.map(fn tag -> %{name: tag} end)
Repo.insert_all(__MODULE__, tags, on_conflict: :nothing, conflict_target: [:name])
tag_names = tags |> Enum.map(& &1.name)
tag_structures = by_names(tag_names)
# The `by_names` functions can return the tags in a different order if any new
# tags were inserted. Sort the tags in their original order before passing them
# to put_assoc
tags =
tag_names
|> Enum.map(fn name -> Enum.find(tag_structures, &(&1.name == name)) end)
changeset
|> put_assoc(:tags, tags)
end
def put_tags(%Ecto.Changeset{} = changeset, _), do: changeset
def drop_tags(%Post{id: id}) do
from(pt in @posts_join_through_table, where: pt.post_id == ^id)
|> Repo.delete_all()
end
def drop_tags(%UserTrigger{id: id}) do
from(pt in @user_triggers_join_through_table, where: pt.user_trigger_id == ^id)
|> Repo.delete_all()
end
end
| 29.708861 | 94 | 0.681721 |
03e1170b5d0162efedcdae4c79dd2bfeb6a294b3 | 572 | ex | Elixir | apps/tai/lib/tai/events/stream_channel_invalid.ex | chrism2671/tai-1 | 847827bd23908adfad4a82c83d5295bdbc022796 | [
"MIT"
] | null | null | null | apps/tai/lib/tai/events/stream_channel_invalid.ex | chrism2671/tai-1 | 847827bd23908adfad4a82c83d5295bdbc022796 | [
"MIT"
] | null | null | null | apps/tai/lib/tai/events/stream_channel_invalid.ex | chrism2671/tai-1 | 847827bd23908adfad4a82c83d5295bdbc022796 | [
"MIT"
] | 1 | 2020-05-03T23:32:11.000Z | 2020-05-03T23:32:11.000Z | defmodule Tai.Events.StreamChannelInvalid do
@type venue_id :: Tai.Venue.id()
@type t :: %Tai.Events.StreamChannelInvalid{
venue: venue_id,
name: atom,
available: [atom]
}
@enforce_keys ~w(venue name available)a
defstruct ~w(venue name available)a
end
defimpl Tai.LogEvent, for: Tai.Events.StreamChannelInvalid do
def to_data(event) do
keys =
event
|> Map.keys()
|> Enum.filter(&(&1 != :__struct__))
event
|> Map.take(keys)
|> Map.put(:available, event.available |> inspect())
end
end
| 22.88 | 61 | 0.625874 |
03e137fdd1726356e8dadcd2837d6cb4a5106aa3 | 636 | ex | Elixir | test/support/test_case.ex | gustavoarmoa/changelog.com | e898a9979a237ae66962714821ed8633a4966f37 | [
"MIT"
] | 1 | 2019-11-02T08:32:25.000Z | 2019-11-02T08:32:25.000Z | test/support/test_case.ex | sdrees/changelog.com | 955cdcf93d74991062f19a03e34c9f083ade1705 | [
"MIT"
] | null | null | null | test/support/test_case.ex | sdrees/changelog.com | 955cdcf93d74991062f19a03e34c9f083ade1705 | [
"MIT"
] | null | null | null | defmodule Changelog.TestCase do
@moduledoc """
Functions in this module are imported in all test modules
"""
def fixtures_path() do
Path.dirname(__ENV__.file) <> "/../fixtures"
end
def stub_audio_file(episode) do
%Changelog.Episode{episode | audio_file: %{file_name: "test.mp3"}}
end
@doc """
Helper for retrying a test for `timeout` milliseconds before failing
"""
def wait_for_passing(timeout, function) when timeout > 0 do
function.()
rescue
_ ->
Process.sleep(100)
wait_for_passing(timeout - 100, function)
end
def wait_for_passing(_timeout, function), do: function.()
end
| 24.461538 | 70 | 0.688679 |
03e13e34c3c9f983a6c1c3fabe0fef2d4fbb8ac5 | 3,617 | ex | Elixir | lib/rethinkdb/pseudotypes.ex | point/rethinkdb-elixir | 0549902e5060e75b0942716befc16db984a14b76 | [
"MIT"
] | null | null | null | lib/rethinkdb/pseudotypes.ex | point/rethinkdb-elixir | 0549902e5060e75b0942716befc16db984a14b76 | [
"MIT"
] | null | null | null | lib/rethinkdb/pseudotypes.ex | point/rethinkdb-elixir | 0549902e5060e75b0942716befc16db984a14b76 | [
"MIT"
] | null | null | null | defmodule RethinkDB.Pseudotypes do
@moduledoc false
defmodule Binary do
@moduledoc false
defstruct data: nil
def parse(%{"$reql_type$" => "BINARY", "data" => data}, opts) do
case Dict.get(opts, :binary_format) do
:raw ->
%__MODULE__{data: data}
_ ->
:base64.decode(data)
end
end
end
defmodule Geometry do
@moduledoc false
defmodule Point do
@moduledoc false
defstruct coordinates: []
end
defmodule Line do
@moduledoc false
defstruct coordinates: []
end
defmodule Polygon do
@moduledoc false
defstruct coordinates: []
end
def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => [x,y], "type" => "Point"}) do
%Point{coordinates: {x,y}}
end
def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => coords, "type" => "LineString"}) do
%Line{coordinates: Enum.map(coords, &List.to_tuple/1)}
end
def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => coords, "type" => "Polygon"}) do
%Polygon{coordinates: (for points <- coords, do: Enum.map points, &List.to_tuple/1)}
end
end
defmodule Time do
@moduledoc false
defstruct epoch_time: nil, timezone: nil
def parse(%{"$reql_type$" => "TIME", "epoch_time" => epoch_time, "timezone" => timezone}, opts) do
case Dict.get(opts, :time_format) do
:raw ->
%__MODULE__{epoch_time: epoch_time, timezone: timezone}
_ ->
{:ok, _, seconds} = Calendar.ISO.parse_utc_datetime("1970-01-01T00:00:00.000" <> timezone)
zone_abbr = case seconds do
0 -> "UTC"
_ -> timezone
end
negative = seconds < 0
seconds = abs(seconds)
time_zone = case {div(seconds,3600),rem(seconds,3600)} do
{0,0} -> "Etc/UTC"
{hours,0} ->
"Etc/GMT" <> if negative do "+" else "-" end <> Integer.to_string(hours)
{hours,seconds} ->
"Etc/GMT" <> if negative do "+" else "-" end <> Integer.to_string(hours) <> ":" <>
String.pad_leading(Integer.to_string(seconds), 2, "0")
end
epoch_time * 1000
|> trunc()
|> DateTime.from_unix!(:millisecond)
|> struct(utc_offset: seconds, zone_abbr: zone_abbr, time_zone: time_zone)
end
end
end
def convert_reql_pseudotypes(nil, opts), do: nil
def convert_reql_pseudotypes(%{"$reql_type$" => "BINARY"} = data, opts) do
Binary.parse(data, opts)
end
def convert_reql_pseudotypes(%{"$reql_type$" => "GEOMETRY"} = data, opts) do
Geometry.parse(data)
end
def convert_reql_pseudotypes(%{"$reql_type$" => "GROUPED_DATA"} = data, opts) do
parse_grouped_data(data)
end
def convert_reql_pseudotypes(%{"$reql_type$" => "TIME"} = data, opts) do
Time.parse(data, opts)
end
def convert_reql_pseudotypes(list, opts) when is_list(list) do
Enum.map(list, fn data -> convert_reql_pseudotypes(data, opts) end)
end
def convert_reql_pseudotypes(map, opts) when is_map(map) do
Enum.map(map, fn {k, v} ->
{k, convert_reql_pseudotypes(v, opts)}
end) |> Enum.into(%{})
end
def convert_reql_pseudotypes(string, opts), do: string
def parse_grouped_data(%{"$reql_type$" => "GROUPED_DATA", "data" => data}) do
Enum.map(data, fn ([k, data]) ->
{k, data}
end) |> Enum.into(%{})
end
def create_grouped_data(data) when is_map(data) do
data = data |> Enum.map(fn {k,v} -> [k, v] end)
%{"$reql_type$" => "GROUPED_DATA", "data" => data}
end
end
| 32.881818 | 102 | 0.592203 |
03e14f8b891ab8542caec552de74da380cf8a69a | 3,695 | exs | Elixir | test/bits_test.exs | EntropyString/Elixir | fb90c6dddd8dd7026c4762d138bea7ce0c81fe8a | [
"MIT"
] | 23 | 2017-09-06T23:56:04.000Z | 2021-08-17T17:29:19.000Z | test/bits_test.exs | EntropyString/Elixir | fb90c6dddd8dd7026c4762d138bea7ce0c81fe8a | [
"MIT"
] | null | null | null | test/bits_test.exs | EntropyString/Elixir | fb90c6dddd8dd7026c4762d138bea7ce0c81fe8a | [
"MIT"
] | 4 | 2017-09-15T16:27:28.000Z | 2019-10-04T11:41:24.000Z | defmodule EntropypString.Bits.Test do
use ExUnit.Case, async: true
import EntropyString, only: [bits: 2]
test "bits for zero entropy" do
assert bits(0, 0) == 0
assert bits(100, 0) == 0
assert bits(0, 100) == 0
assert bits(0, -1) == 0
assert bits(-1, 0) == 0
end
test "bits for integer total and risk" do
assert round(bits(10, 1000)) == 15
assert round(bits(10, 10000)) == 19
assert round(bits(10, 100_000)) == 22
assert round(bits(100, 1000)) == 22
assert round(bits(100, 10000)) == 26
assert round(bits(100, 100_000)) == 29
assert round(bits(1000, 1000)) == 29
assert round(bits(1000, 10000)) == 32
assert round(bits(1000, 100_000)) == 36
assert round(bits(10000, 1000)) == 36
assert round(bits(10000, 10000)) == 39
assert round(bits(10000, 100_000)) == 42
assert round(bits(100_000, 1000)) == 42
assert round(bits(100_000, 10000)) == 46
assert round(bits(100_000, 100_000)) == 49
end
test "bits powers" do
assert round(bits(1.0e5, 1.0e3)) == 42
assert round(bits(1.0e5, 1.0e4)) == 46
assert round(bits(1.0e5, 1.0e5)) == 49
end
test "preshing 32-bit" do
assert round(bits(30084, 1.0e01)) == 32
assert round(bits(9292, 1.0e02)) == 32
assert round(bits(2932, 1.0e03)) == 32
assert round(bits(927, 1.0e04)) == 32
assert round(bits(294, 1.0e05)) == 32
assert round(bits(93, 1.0e06)) == 32
assert round(bits(30, 1.0e07)) == 32
assert round(bits(10, 1.0e08)) == 32
end
test "preshing 64-bit" do
assert round(bits(1.97e09, 1.0e01)) == 64
assert round(bits(6.09e08, 1.0e02)) == 64
assert round(bits(1.92e08, 1.0e03)) == 64
assert round(bits(6.07e07, 1.0e04)) == 64
assert round(bits(1.92e07, 1.0e05)) == 64
assert round(bits(6.07e06, 1.0e06)) == 64
assert round(bits(1.92e06, 1.0e07)) == 64
assert round(bits(607_401, 1.0e08)) == 64
assert round(bits(192_077, 1.0e09)) == 64
assert round(bits(60704, 1.0e10)) == 64
assert round(bits(19208, 1.0e11)) == 64
assert round(bits(6074, 1.0e12)) == 64
assert round(bits(1921, 1.0e13)) == 64
assert round(bits(608, 1.0e14)) == 64
assert round(bits(193, 1.0e15)) == 64
assert round(bits(61, 1.0e16)) == 64
assert round(bits(20, 1.0e17)) == 64
assert round(bits(7, 1.0e18)) == 64
end
test "preshing 160-bit" do
assert round(bits(1.42e24, 2)) == 160
assert round(bits(5.55e23, 10)) == 160
assert round(bits(1.71e23, 100)) == 160
assert round(bits(5.41e22, 1000)) == 160
assert round(bits(1.71e22, 1.0e04)) == 160
assert round(bits(5.41e21, 1.0e05)) == 160
assert round(bits(1.71e21, 1.0e06)) == 160
assert round(bits(5.41e20, 1.0e07)) == 160
assert round(bits(1.71e20, 1.0e08)) == 160
assert round(bits(5.41e19, 1.0e09)) == 160
assert round(bits(1.71e19, 1.0e10)) == 160
assert round(bits(5.41e18, 1.0e11)) == 160
assert round(bits(1.71e18, 1.0e12)) == 160
assert round(bits(5.41e17, 1.0e13)) == 160
assert round(bits(1.71e17, 1.0e14)) == 160
assert round(bits(5.41e16, 1.0e15)) == 160
assert round(bits(1.71e16, 1.0e16)) == 160
assert round(bits(5.41e15, 1.0e17)) == 160
assert round(bits(1.71e15, 1.0e18)) == 160
end
test "NaN entropy bits" do
assert bits(-1, 100) == NaN
assert bits(100, -1) == NaN
assert bits(-1, -1) == NaN
end
test "module entropy total/risk" do
defmodule(TotalRiskId, do: use(EntropyString, total: 10_000_000, risk: 10.0e12))
assert round(TotalRiskId.bits()) == 89
end
test "module entropy bits" do
defmodule(BitsId, do: use(EntropyString, bits: 96))
assert BitsId.bits() == 96
end
end
| 32.991071 | 84 | 0.615968 |
03e197910f3b2905745e0c1a3f09fd9ecd4e961b | 404 | exs | Elixir | test/mix/tasks/cc_cedict_entries_test.exs | bchase/cc_cedict-elixir | 37ad788b91746ff0aa7248b0596c9d7fcb8dd902 | [
"MIT"
] | null | null | null | test/mix/tasks/cc_cedict_entries_test.exs | bchase/cc_cedict-elixir | 37ad788b91746ff0aa7248b0596c9d7fcb8dd902 | [
"MIT"
] | null | null | null | test/mix/tasks/cc_cedict_entries_test.exs | bchase/cc_cedict-elixir | 37ad788b91746ff0aa7248b0596c9d7fcb8dd902 | [
"MIT"
] | null | null | null | defmodule CCCEDICT.EntryStreamConsumer do
def take_one(entries_stream) do
[entry] = Enum.take entries_stream, 1
entry
end
end
defmodule CCCEDICT.EntriesMixTaskTest do
use ExUnit.Case, async: true
test "module receives entries stream" do
consumer = "CCCEDICT.EntryStreamConsumer.take_one"
entry = Mix.Tasks.CCCEDICT.Entries.run([consumer])
assert entry.trad == "%"
end
end
| 23.764706 | 54 | 0.740099 |
03e1ccfbd5690cb2f47bdc0b01d79ed746d59a8b | 1,659 | ex | Elixir | clients/iap/lib/google_api/iap/v1/model/csm_settings.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/iap/lib/google_api/iap/v1/model/csm_settings.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/iap/lib/google_api/iap/v1/model/csm_settings.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.IAP.V1.Model.CsmSettings do
@moduledoc """
Configuration for RCTokens generated for CSM workloads protected by IAP. RCTokens are IAP generated JWTs that can be verified at the application. The RCToken is primarily used for ISTIO deployments, and can be scoped to a single mesh by configuring the audience field accordingly
## Attributes
* `rctokenAud` (*type:* `String.t`, *default:* `nil`) - Audience claim set in the generated RCToken. This value is not validated by IAP.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:rctokenAud => String.t()
}
field(:rctokenAud)
end
defimpl Poison.Decoder, for: GoogleApi.IAP.V1.Model.CsmSettings do
def decode(value, options) do
GoogleApi.IAP.V1.Model.CsmSettings.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.IAP.V1.Model.CsmSettings do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.297872 | 281 | 0.746835 |
03e1cfab4552e5782ed0d2222b794c9a0e32d335 | 3,889 | exs | Elixir | apps/ewallet/test/ewallet/web/v1/serializers/export_serializer_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 322 | 2018-02-28T07:38:44.000Z | 2020-05-27T23:09:55.000Z | apps/ewallet/test/ewallet/web/v1/serializers/export_serializer_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 643 | 2018-02-28T12:05:20.000Z | 2020-05-22T08:34:38.000Z | apps/ewallet/test/ewallet/web/v1/serializers/export_serializer_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 63 | 2018-02-28T10:57:06.000Z | 2020-05-27T23:10:38.000Z | # Copyright 2018-2019 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule EWallet.Web.V1.ExportSerializerTest do
use EWallet.Web.SerializerCase, :v1
alias Ecto.Association.NotLoaded
alias EWallet.Web.Paginator
alias EWallet.Web.V1.ExportSerializer
alias Utils.Helpers.{Assoc, DateFormatter}
describe "serialize/1 for a single export" do
test "serializes into correct V1 export format" do
export = build(:export)
expected = %{
object: "export",
id: export.id,
filename: export.filename,
schema: export.schema,
status: export.status,
completion: export.completion,
download_url: export.url,
adapter: export.adapter,
user_id: Assoc.get(export, [:user, :id]),
key_id: Assoc.get(export, [:key, :id]),
params: export.params,
pid: export.pid,
failure_reason: nil,
created_at: DateFormatter.to_iso8601(export.inserted_at),
updated_at: DateFormatter.to_iso8601(export.updated_at)
}
assert ExportSerializer.serialize(export) == expected
end
test "serializes to nil if the export is not loaded" do
assert ExportSerializer.serialize(%NotLoaded{}) == nil
end
test "serializes nil to nil" do
assert ExportSerializer.serialize(nil) == nil
end
end
describe "serialize/1 for an export list" do
test "serialize into list of V1 export" do
export_1 = build(:export)
export_2 = build(:export)
paginator = %Paginator{
data: [export_1, export_2],
pagination: %{
current_page: 9,
per_page: 7,
is_first_page: false,
is_last_page: true
}
}
expected = %{
object: "list",
data: [
%{
object: "export",
id: export_1.id,
filename: export_1.filename,
schema: export_1.schema,
status: export_1.status,
completion: export_1.completion,
download_url: export_1.url,
adapter: export_1.adapter,
user_id: Assoc.get(export_1, [:user, :id]),
key_id: Assoc.get(export_1, [:key, :id]),
params: export_1.params,
pid: export_1.pid,
failure_reason: nil,
created_at: DateFormatter.to_iso8601(export_1.inserted_at),
updated_at: DateFormatter.to_iso8601(export_1.updated_at)
},
%{
object: "export",
id: export_2.id,
filename: export_2.filename,
schema: export_2.schema,
status: export_2.status,
completion: export_2.completion,
download_url: export_2.url,
adapter: export_2.adapter,
user_id: Assoc.get(export_2, [:user, :id]),
key_id: Assoc.get(export_2, [:key, :id]),
params: export_2.params,
pid: export_2.pid,
failure_reason: nil,
created_at: DateFormatter.to_iso8601(export_2.inserted_at),
updated_at: DateFormatter.to_iso8601(export_2.updated_at)
}
],
pagination: %{
current_page: 9,
per_page: 7,
is_first_page: false,
is_last_page: true
}
}
assert ExportSerializer.serialize(paginator) == expected
end
end
end
| 32.140496 | 74 | 0.613782 |
03e1d20de28f06bbff57acedecb65655b81931c5 | 1,782 | ex | Elixir | clients/sheets/lib/google_api/sheets/v4/model/insert_range_request.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/sheets/lib/google_api/sheets/v4/model/insert_range_request.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/sheets/lib/google_api/sheets/v4/model/insert_range_request.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Sheets.V4.Model.InsertRangeRequest do
@moduledoc """
Inserts cells into a range, shifting the existing cells over or down.
## Attributes
- range (GridRange): The range to insert new cells into. Defaults to: `null`.
- shiftDimension (String): The dimension which will be shifted when inserting cells. If ROWS, existing cells will be shifted down. If COLUMNS, existing cells will be shifted right. Defaults to: `null`.
- Enum - one of [DIMENSION_UNSPECIFIED, ROWS, COLUMNS]
"""
defstruct [
:"range",
:"shiftDimension"
]
end
defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.InsertRangeRequest do
import GoogleApi.Sheets.V4.Deserializer
def decode(value, options) do
value
|> deserialize(:"range", :struct, GoogleApi.Sheets.V4.Model.GridRange, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.InsertRangeRequest do
def encode(value, options) do
GoogleApi.Sheets.V4.Deserializer.serialize_non_nil(value, options)
end
end
| 34.941176 | 203 | 0.750842 |
03e1db72255f861578f2d36c7470ffa33f388d0e | 7,785 | ex | Elixir | lib/nostrum/struct/channel.ex | defnorep/nostrum | daf869afc0f98fd132460296a2c999fea033fd63 | [
"MIT"
] | null | null | null | lib/nostrum/struct/channel.ex | defnorep/nostrum | daf869afc0f98fd132460296a2c999fea033fd63 | [
"MIT"
] | null | null | null | lib/nostrum/struct/channel.ex | defnorep/nostrum | daf869afc0f98fd132460296a2c999fea033fd63 | [
"MIT"
] | null | null | null | defmodule Nostrum.Struct.Channel do
@moduledoc ~S"""
Struct representing a Discord guild channel.
A `Nostrum.Struct.Channel` represents all 5 types of channels. Each
channel has a field `:type` with any of the following values:
* `0` - GUILD_TEXT
* `1` - DM
* `2` - GUILD_VOICE
* `3` - GROUP_DM
* `4` - GUILD_CATEGORY
More information can be found on the
[Discord API Channel Documentation](https://discordapp.com/developers/docs/resources/channel#channel-object).
## Mentioning Channels in Messages
A `Nostrum.Struct.Channel` can be mentioned in message content using the `String.Chars`
protocol or `mention/1`.
```Elixir
channel = %Nostrum.Struct.Channel{id: 381889573426429952}
Nostrum.Api.create_message!(184046599834435585, "#{channel}")
%Nostrum.Struct.Message{content: "<#381889573426429952>"}
channel = %Nostrum.Struct.Channel{id: 280085880452939778}
Nostrum.Api.create_message!(280085880452939778, "#{Nostrum.Struct.Channel.mention(channel)}")
%Nostrum.Struct.Message{content: "<#280085880452939778>"}
```
"""
alias Nostrum.Struct.Overwrite
alias Nostrum.Struct.Snowflake
alias Nostrum.Struct.User
alias Nostrum.Util
defstruct [
:id,
:type,
:guild_id,
:position,
:permission_overwrites,
:name,
:topic,
:nsfw,
:last_message_id,
:bitrate,
:user_limit,
:recipients,
:icon,
:owner_id,
:application_id,
:parent_id,
:last_pin_timestamp
]
defimpl String.Chars do
def to_string(channel), do: @for.mention(channel)
end
@typedoc "The channel's id"
@type id :: Snowflake.t()
@typedoc "The id of the channel's guild"
@type guild_id :: Snowflake.t()
@typedoc "The ordered position of the channel"
@type position :: integer
@typedoc "The list of overwrites"
@type permission_overwrites :: [Overwrite.t()]
@typedoc "The name of the channel"
@type name :: String.t()
@typedoc "Current channel topic"
@type topic :: String.t()
@typedoc "If the channel is nsfw"
@type nsfw :: boolean
@typedoc "Id of the last message sent"
@type last_message_id :: Snowflake.t() | nil
@typedoc "The bitrate of the voice channel"
@type bitrate :: integer
@typedoc "The user limit of the voice channel"
@type user_limit :: integer
@typedoc "The recipients of the DM"
@type recipients :: [User.t()]
@typedoc "The icon hash of the channel"
@type icon :: String.t() | nil
@typedoc "The id of the DM creator"
@type owner_id :: Snowflake.t()
@typedoc "The application id of the group DM creator if it is bot-created"
@type application_id :: Snowflake.t() | nil
@typedoc "The id of the parent category for a channel"
@type parent_id :: Snowflake.t() | nil
@typedoc "When the last pinned message was pinned"
@type last_pin_timestamp :: String.t() | nil
@typedoc """
A `Nostrum.Struct.Channel` that represents a text channel in a guild.
"""
@type guild_text_channel :: %__MODULE__{
id: id,
type: 0,
guild_id: guild_id,
position: position,
permission_overwrites: permission_overwrites,
name: name,
topic: topic,
nsfw: nsfw,
last_message_id: last_message_id,
bitrate: nil,
user_limit: nil,
recipients: nil,
icon: nil,
owner_id: nil,
application_id: nil,
parent_id: parent_id,
last_pin_timestamp: last_pin_timestamp
}
@typedoc """
A `Nostrum.Struct.Channel` that represents a DM channel.
"""
@type dm_channel :: %__MODULE__{
id: id,
type: 1,
guild_id: nil,
position: nil,
permission_overwrites: nil,
name: nil,
topic: nil,
nsfw: nil,
last_message_id: last_message_id,
bitrate: nil,
user_limit: nil,
recipients: recipients,
icon: nil,
owner_id: nil,
application_id: nil,
parent_id: nil,
last_pin_timestamp: nil
}
@typedoc """
A `Nostrum.Struct.Channel` that represents a voice channel in a guild.
"""
@type guild_voice_channel :: %__MODULE__{
id: id,
type: 2,
guild_id: guild_id,
position: position,
permission_overwrites: permission_overwrites,
name: name,
topic: nil,
nsfw: nsfw,
last_message_id: nil,
bitrate: bitrate,
user_limit: user_limit,
recipients: nil,
icon: nil,
owner_id: nil,
application_id: nil,
parent_id: parent_id,
last_pin_timestamp: nil
}
@typedoc """
A `Nostrum.Struct.Channel` that represents a group DM channel.
"""
@type group_dm_channel :: %__MODULE__{
id: id,
type: 3,
guild_id: nil,
position: nil,
permission_overwrites: nil,
name: name,
topic: nil,
nsfw: nil,
last_message_id: last_message_id,
bitrate: nil,
user_limit: nil,
recipients: recipients,
icon: icon,
owner_id: owner_id,
application_id: application_id,
parent_id: nil,
last_pin_timestamp: nil
}
@typedoc """
A `Nostrum.Struct.Channel` that represents a channel category in a guild.
"""
@type channel_category :: %__MODULE__{
id: id,
type: 4,
guild_id: guild_id,
position: position,
permission_overwrites: permission_overwrites,
name: name,
topic: nil,
nsfw: nsfw,
last_message_id: nil,
bitrate: nil,
user_limit: nil,
recipients: nil,
icon: nil,
owner_id: nil,
application_id: nil,
parent_id: parent_id,
last_pin_timestamp: nil
}
@typedoc """
A `Nostrum.Struct.Channel` that represents a channel in a guild.
"""
@type guild_channel ::
guild_text_channel
| guild_voice_channel
| channel_category
@typedoc """
A `Nostrum.Struct.Channel` that represents a text channel.
"""
@type text_channel ::
guild_text_channel
| dm_channel
| group_dm_channel
@typedoc """
A `Nostrum.Struct.Channel` that represents a voice channel.
"""
@type voice_channel :: guild_voice_channel
@type t ::
guild_text_channel
| dm_channel
| guild_voice_channel
| group_dm_channel
| channel_category
@doc ~S"""
Formats a `Nostrum.Struct.Channel` into a mention.
## Examples
```Elixir
iex> channel = %Nostrum.Struct.Channel{id: 381889573426429952}
...> Nostrum.Struct.Channel.mention(channel)
"<#381889573426429952>"
```
"""
@spec mention(t) :: String.t()
def mention(%__MODULE__{id: id}), do: "<##{id}>"
@doc false
def p_encode do
%__MODULE__{
permission_overwrites: [Overwrite.p_encode()]
}
end
@doc false
def to_struct(map) do
new =
map
|> Map.new(fn {k, v} -> {Util.maybe_to_atom(k), v} end)
|> Map.update(:id, nil, &Util.cast(&1, Snowflake))
|> Map.update(:guild_id, nil, &Util.cast(&1, Snowflake))
|> Map.update(:permission_overwrites, nil, &Util.cast(&1, {:list, {:struct, Overwrite}}))
|> Map.update(:last_message_id, nil, &Util.cast(&1, Snowflake))
|> Map.update(:recipients, nil, &Util.cast(&1, {:list, {:struct, User}}))
|> Map.update(:owner_id, nil, &Util.cast(&1, Snowflake))
|> Map.update(:application_id, nil, &Util.cast(&1, Snowflake))
|> Map.update(:parent_id, nil, &Util.cast(&1, Snowflake))
struct(__MODULE__, new)
end
end
| 26.752577 | 111 | 0.608606 |
03e24578da43a7bd642beef4a4d1912beeb5a964 | 286 | exs | Elixir | test/tesla/adapter/ibrowse_test.exs | chingor13/tesla | 640fd5e860491992c4aeba9ba125be711942a237 | [
"MIT"
] | null | null | null | test/tesla/adapter/ibrowse_test.exs | chingor13/tesla | 640fd5e860491992c4aeba9ba125be711942a237 | [
"MIT"
] | null | null | null | test/tesla/adapter/ibrowse_test.exs | chingor13/tesla | 640fd5e860491992c4aeba9ba125be711942a237 | [
"MIT"
] | null | null | null | defmodule IbrowseTest do
use ExUnit.Case
use Tesla.Adapter.TestCase.Basic, adapter: :ibrowse
use Tesla.Adapter.TestCase.StreamRequestBody, adapter: :ibrowse
use Tesla.Adapter.TestCase.SSL, adapter: :ibrowse
setup do
Application.ensure_started(:ibrowse)
:ok
end
end
| 23.833333 | 65 | 0.762238 |
03e2473c2b379bc91416ff50162823f4dfdf41e1 | 512 | ex | Elixir | test/support/conn_case.ex | aarongraham/surface_bulma | 0b8ab633465681b8c3b58c767034cb557e09c8af | [
"MIT"
] | 30 | 2021-02-05T18:50:38.000Z | 2022-03-12T22:42:29.000Z | test/support/conn_case.ex | aarongraham/surface_bulma | 0b8ab633465681b8c3b58c767034cb557e09c8af | [
"MIT"
] | 19 | 2021-01-15T19:14:24.000Z | 2022-02-05T14:57:18.000Z | test/support/conn_case.ex | aarongraham/surface_bulma | 0b8ab633465681b8c3b58c767034cb557e09c8af | [
"MIT"
] | 17 | 2021-02-01T20:57:51.000Z | 2022-03-20T17:06:57.000Z | defmodule SurfaceBulma.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
It also imports other functionality to make it easier
to test components.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing
use Surface.LiveViewTest
# The default endpoint for testing
@endpoint Endpoint
end
end
setup _tags do
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 19.692308 | 55 | 0.701172 |
03e2a0e14d8aba263bb47c512ac0e4afc2f382c4 | 1,110 | ex | Elixir | lib/resty/resource/builder.ex | kkvesper/resty | a7680b9b10487b5ffb02bfa2a5c89b67312a2411 | [
"MIT"
] | null | null | null | lib/resty/resource/builder.ex | kkvesper/resty | a7680b9b10487b5ffb02bfa2a5c89b67312a2411 | [
"MIT"
] | null | null | null | lib/resty/resource/builder.ex | kkvesper/resty | a7680b9b10487b5ffb02bfa2a5c89b67312a2411 | [
"MIT"
] | 1 | 2019-01-10T13:15:23.000Z | 2019-01-10T13:15:23.000Z | defmodule Resty.Resource.Builder do
@moduledoc false
def build(module, attributes, filter_unknown \\ true) do
attributes = attributes |> Enum.into(%{})
attributes =
case filter_unknown do
true -> remove_unknown(attributes, module.known_attributes())
false -> attributes
end
struct(module, attributes)
end
defp remove_unknown(atrributes_to_filter, known_attributes) do
remove_unknown(atrributes_to_filter, known_attributes, %{})
end
defp remove_unknown(_, [], filtered_attributes), do: filtered_attributes
defp remove_unknown(data, [attribute | next_attributes], filtered_attributes) do
attribute_string_key = attribute |> to_string()
value =
case Map.get(data, attribute, :no_val) do
:no_val -> Map.get(data, attribute_string_key, :no_val)
value -> value
end
updated_filtered_attributes =
case value do
:no_val -> filtered_attributes
value -> Map.put(filtered_attributes, attribute, value)
end
remove_unknown(data, next_attributes, updated_filtered_attributes)
end
end
| 27.75 | 82 | 0.702703 |
03e2a1033dd8e46d14eb1639c44d462fa0d9ab23 | 1,258 | exs | Elixir | mix.exs | gmcintire/xgps | 56cf4c83dfc05aa22b1d7b7d1d2456cf5acfa7a2 | [
"MIT"
] | null | null | null | mix.exs | gmcintire/xgps | 56cf4c83dfc05aa22b1d7b7d1d2456cf5acfa7a2 | [
"MIT"
] | null | null | null | mix.exs | gmcintire/xgps | 56cf4c83dfc05aa22b1d7b7d1d2456cf5acfa7a2 | [
"MIT"
] | null | null | null | defmodule XGPS.Mixfile do
use Mix.Project
def project do
[
app: :xgps,
name: XGPS,
version: "0.4.1",
elixir: "~> 1.6",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
source_url: "https://github.com/gmcintire/xgps",
deps: deps(),
description: description(),
package: package()
]
end
def application do
[applications: [:logger, :gen_stage], mod: {XGPS, []}]
end
defp deps do
[
{:circuits_uart, "~> 1.3"},
{:mix_test_watch, "~> 1.0.2"},
{:gen_stage, "~> 1.0.0"},
{:ex_doc, ">= 0.0.0", only: :dev},
{:credo, "~> 1.3", only: [:dev, :test]}
]
end
defp description do
"""
An OTP application for reading and parsing GPS data written in Elixir.
Will attach to an serial port, and provide positions to subscribers.
Distributes positions using GenStage.
"""
end
defp package do
# These are the default files included in the package
[
name: :xgps,
files: ["lib", "mix.exs", "README*", "LICENSE*", "simulator_positions.txt"],
maintainers: ["Roy Veshovda"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/royveshovda/xgps"}
]
end
end
| 24.192308 | 82 | 0.569157 |
03e303de588bd43bb78cdd8ec8a86ff8f53f2fac | 500 | ex | Elixir | lib/elxr_yt_wb_scrpr.ex | mingyar/elixir-youtube-web-scraper | 14e7238847281ab4880cb2b60c3eb39eac647858 | [
"MIT"
] | 1 | 2021-05-24T05:28:33.000Z | 2021-05-24T05:28:33.000Z | lib/elxr_yt_wb_scrpr.ex | mingyar/elxr_yt_wb_scrpr | 14e7238847281ab4880cb2b60c3eb39eac647858 | [
"MIT"
] | null | null | null | lib/elxr_yt_wb_scrpr.ex | mingyar/elxr_yt_wb_scrpr | 14e7238847281ab4880cb2b60c3eb39eac647858 | [
"MIT"
] | null | null | null | defmodule ElxrYtWbScrpr do
use Hound.Helpers
def last_video_from() do
IO.puts "starting"
Hound.start_session
navigate_to "https://www.youtube.com/channel/UC0l2QTnO1P2iph-86HHilMQ/videos"
Process.sleep(5000)
last_video = page_source()
|> Floki.find("#video-title")
|> Floki.attribute("href")
|> Enum.at(0)
navigate_to "https://www.youtube.com/#{last_video}"
Process.sleep(10000)
Hound.end_session
end
end
| 29.411765 | 81 | 0.63 |
03e3056ab360104c565561b6e0d9a8786d495ba1 | 71 | ex | Elixir | web/views/layout_view.ex | KazuCocoa/react_phoenix | 7cd2fe0bdcddf8a0fdd876517232893783bf21e5 | [
"MIT"
] | null | null | null | web/views/layout_view.ex | KazuCocoa/react_phoenix | 7cd2fe0bdcddf8a0fdd876517232893783bf21e5 | [
"MIT"
] | null | null | null | web/views/layout_view.ex | KazuCocoa/react_phoenix | 7cd2fe0bdcddf8a0fdd876517232893783bf21e5 | [
"MIT"
] | null | null | null | defmodule ReactPhoenix.LayoutView do
use ReactPhoenix.Web, :view
end
| 17.75 | 36 | 0.816901 |
03e3229afaf373c49118be94c4c4cc743854230e | 1,246 | ex | Elixir | 06_retirement_calculator/lib/retirement_calculator.ex | mkchandler/elixir-school | cc08bd723db00cc35cd2d6b07abe519e5d102ca0 | [
"MIT"
] | 1 | 2015-12-15T04:46:41.000Z | 2015-12-15T04:46:41.000Z | 06_retirement_calculator/lib/retirement_calculator.ex | mkchandler/elixir-school | cc08bd723db00cc35cd2d6b07abe519e5d102ca0 | [
"MIT"
] | null | null | null | 06_retirement_calculator/lib/retirement_calculator.ex | mkchandler/elixir-school | cc08bd723db00cc35cd2d6b07abe519e5d102ca0 | [
"MIT"
] | null | null | null | defmodule RetirementCalculator do
def run do
current_age = IO.gets("What is your current age? ")
|> String.strip
|> String.to_integer
retirement_age = IO.gets("What age would you like to retire? ")
|> String.strip
|> String.to_integer
years = years_until_retirement(current_age, retirement_age)
current_year = DateTime.utc_now.year
year = year_of_retirement(current_year, years)
display_message(years, current_year, year)
|> IO.puts
end
def display_message(years, current_year, year) when years > 1 do
"You have #{years} years left until you can retire.\n" <>
"It's #{current_year}, so you can retire in #{year}."
end
def display_message(years, current_year, year) when years == 1 do
"You have #{years} year left until you can retire.\n" <>
"It's #{current_year}, so you can retire in #{year}."
end
def display_message(_, _, _) do
IO.puts("You are ready to retire now!")
end
def years_until_retirement(current_age, retirement_age) do
retirement_age - current_age
end
def year_of_retirement(current_year, years_until_retirement) do
current_year + years_until_retirement
end
end
| 31.15 | 68 | 0.666132 |
03e39f31ce931b0387cbf1a3440dbaa1b5d2dfdf | 12,531 | exs | Elixir | test/taglet_test.exs | ringofhealth/ex_tag | a0aa0a3c8f57311867e33d2290a944a46351d0e2 | [
"Apache-2.0"
] | null | null | null | test/taglet_test.exs | ringofhealth/ex_tag | a0aa0a3c8f57311867e33d2290a944a46351d0e2 | [
"Apache-2.0"
] | null | null | null | test/taglet_test.exs | ringofhealth/ex_tag | a0aa0a3c8f57311867e33d2290a944a46351d0e2 | [
"Apache-2.0"
] | null | null | null | defmodule TagletTest do
alias Ecto.Adapters.SQL
alias TagletPost, as: Post
alias Taglet.{Tagging, Tag}
import Ecto.Query
import Ecto.Query
# import Mix.Ecto, only: [build_repo_priv: 1]
use ExUnit.Case
def build_repo_priv(repo) do
Application.app_dir(
Keyword.fetch!(repo.config(), :otp_app),
source_repo_priv(repo)
)
end
def source_repo_priv(repo) do
repo.config()[:priv] || "priv/#{repo |> Module.split() |> List.last() |> Macro.underscore()}"
end
@repo Taglet.RepoClient.repo()
@tenant_id "example_tenant"
doctest Taglet
setup do
# Regular test
@repo.delete_all(Post)
@repo.delete_all(Tagging)
@repo.delete_all(Tag)
# Multi tenant test
setup_tenant()
on_exit(fn ->
# Regular test
@repo.delete_all(Post)
@repo.delete_all(Tagging)
@repo.delete_all(Tag)
# Multi tenant test
setup_tenant()
end)
:ok
end
# Regular test
test "add/4 with a tag returns the struct with the new tag" do
post = @repo.insert!(%Post{title: "hello world"})
Taglet.add(post, "mytag")
result = Taglet.add(post, "tag1")
assert result.tags == ["mytag", "tag1"]
end
test "add/4 with a tag list returns the struct with the new tags" do
post = @repo.insert!(%Post{title: "hello world"})
Taglet.add(post, "mytag")
result = Taglet.add(post, ["tag1", "tag2"])
assert result.tags == ["mytag", "tag1", "tag2"]
end
test "add/4 with context returns a diferent list for every context" do
post = @repo.insert!(%Post{title: "hello world"})
result1 = Taglet.add(post, "mytag1", "context1")
result2 = Taglet.add(post, "mytag2", "context2")
assert result1.context1 == ["mytag1"]
assert result2.context2 == ["mytag2"]
end
test "add/4 with repeated tag returns the same tags" do
post = @repo.insert!(%Post{title: "hello world"})
Taglet.add(post, "mytag")
result = Taglet.add(post, "mytag")
assert result.tags == ["mytag"]
end
test "add/4 with nil tag returns the same struct" do
post = @repo.insert!(%Post{title: "hello world"})
result = Taglet.add(post, nil)
assert result == post
end
test "remove/4 deletes a tag and returns a list of associated tags" do
post = @repo.insert!(%Post{title: "hello world"})
Taglet.add(post, "mytag")
Taglet.add(post, "mytag2")
Taglet.add(post, "mytag3")
result = Taglet.remove(post, "mytag2")
assert result.tags == ["mytag", "mytag3"]
end
test "remove/4 deletes a tag for a specific context and returns a list of associated tags" do
post = @repo.insert!(%Post{title: "hello world"})
Taglet.add(post, "mytag", "context1")
Taglet.add(post, "mytag2", "context1")
Taglet.add(post, "mytag3", "context2")
result = Taglet.remove(post, "mytag2", "context1")
assert result.context1 == ["mytag"]
end
test "remove/4 does nothing for an unexistent tag" do
post = @repo.insert!(%Post{title: "hello world"})
Taglet.add(post, "mytag")
Taglet.add(post, "mytag2")
Taglet.add(post, "mytag3")
result = Taglet.remove(post, "my2")
assert result.tags == ["mytag", "mytag2", "mytag3"]
end
test "tag_list/2 with struct as param returns a list of associated tags" do
post = @repo.insert!(%Post{title: "hello world"})
Taglet.add(post, "mytag")
Taglet.add(post, "mytag2")
result = Taglet.tag_list(post)
assert result == ["mytag", "mytag2"]
end
test "tag_list/2 with struct returns a list of associated tags for a specific context" do
post = @repo.insert!(%Post{title: "hello world"})
Taglet.add(post, "mytag", "context")
Taglet.add(post, "mytag2", "context")
result = Taglet.tag_list(post, "context")
assert result == ["mytag", "mytag2"]
end
test "tag_list/2 with module as param returns a list of tags related with one context and module" do
post1 = @repo.insert!(%Post{title: "hello world"})
post2 = @repo.insert!(%Post{title: "hello world2"})
Taglet.add(post1, ["tag1", "tag2"])
Taglet.add(post2, ["tag2", "tag3"])
result = Taglet.tag_list(Post)
assert result == ["tag1", "tag2", "tag3"]
end
test "tagged_with/4 returns a list of structs associated to a tag" do
post1 = @repo.insert!(%Post{title: "hello world1"})
post2 = @repo.insert!(%Post{title: "hello world2"})
post3 = @repo.insert!(%Post{title: "hello world3"})
Taglet.add(post1, "tagged1")
Taglet.add(post2, "tagged1")
Taglet.add(post3, "tagged2")
result = Taglet.tagged_with("tagged1", Post)
assert result == [post1, post2]
end
test "tagged_with_any/4 returns a list of structs associated to a tag" do
post1 = @repo.insert!(%Post{title: "hello world1"})
post2 = @repo.insert!(%Post{title: "hello world2"})
post3 = @repo.insert!(%Post{title: "hello world3"})
post4 = @repo.insert!(%Post{title: "hello world4"})
Taglet.add(post1, ["tagged1", "tagged2"])
Taglet.add(post2, "tagged2")
Taglet.add(post3, "tagged3")
Taglet.add(post3, "tagged4")
result = Taglet.tagged_with_any(["tagged2", "tagged2"], Post)
assert result == [post1, post2]
end
test "tagged_with_any_query/4 returns a query of structs associated to a tag" do
post1 = @repo.insert!(%Post{title: "hello world1"})
post2 = @repo.insert!(%Post{title: "hello world2"})
post3 = @repo.insert!(%Post{title: "hello world3"})
post4 = @repo.insert!(%Post{title: "hello world4"})
Taglet.add(post1, ["tagged1", "tagged2"])
Taglet.add(post2, "tagged2")
Taglet.add(post3, "tagged3")
Taglet.add(post3, "tagged4")
query = Post |> where(title: "hello world2")
result = Taglet.tagged_with_any_query(query, ["tagged1", "tagged2"]) |> @repo.all
assert result == [post2]
end
test "tagged_with_query/4 returns a query of structs associated to a tag" do
post1 = @repo.insert!(%Post{title: "hello world1"})
post2 = @repo.insert!(%Post{title: "hello world2"})
post3 = @repo.insert!(%Post{title: "hello world3"})
Taglet.add(post1, "tagged1")
Taglet.add(post2, ["tagged1", "tagged2"])
Taglet.add(post3, "tagged2")
query = Post |> where(title: "hello world2")
result = Taglet.tagged_with_query(query, ["tagged1", "tagged2"]) |> @repo.all
assert result == [post2]
end
# Multi tenant test
test "[multi tenant] add/4 with a tag returns the struct with the new tag" do
post = @repo.insert!(%Post{title: "hello world"})
Taglet.add(post, "mytag")
result = Taglet.add(post, "tag1")
assert result.tags == ["mytag", "tag1"]
end
test "[multi tenant] add/4 with a tag list returns the struct with the new tags" do
post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id)
Taglet.add(post, "mytag", prefix: @tenant_id)
result = Taglet.add(post, ["tag1", "tag2"], prefix: @tenant_id)
assert result.tags == ["mytag", "tag1", "tag2"]
end
test "[multi tenant] add/4 with context returns a diferent list for every context" do
post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id)
result1 = Taglet.add(post, "mytag1", "context1", prefix: @tenant_id)
result2 = Taglet.add(post, "mytag2", "context2", prefix: @tenant_id)
assert result1.context1 == ["mytag1"]
assert result2.context2 == ["mytag2"]
end
test "[multi tenant] add/4 with repeated tag returns the same tags" do
post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id)
Taglet.add(post, "mytag", prefix: @tenant_id)
result = Taglet.add(post, "mytag", prefix: @tenant_id)
assert result.tags == ["mytag"]
end
test "[multi tenant] add/4 with nil tag returns the same struct" do
post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id)
result = Taglet.add(post, nil, prefix: @tenant_id)
assert result == post
end
test "[multi tenant] remove/4 deletes a tag and returns a list of associated tags" do
post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id)
Taglet.add(post, "mytag", "tags", prefix: @tenant_id)
Taglet.add(post, "mytag2", "tags", prefix: @tenant_id)
Taglet.add(post, "mytag3", "tags", prefix: @tenant_id)
result = Taglet.remove(post, "mytag2", "tags", prefix: @tenant_id)
assert result.tags == ["mytag", "mytag3"]
end
test "[multi tenant] remove/4 deletes a tag for a specific context and returns a list of associated tags" do
post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id)
Taglet.add(post, "mytag", "context1", prefix: @tenant_id)
Taglet.add(post, "mytag2", "context1", prefix: @tenant_id)
Taglet.add(post, "mytag3", "context2", prefix: @tenant_id)
result = Taglet.remove(post, "mytag2", "context1", prefix: @tenant_id)
assert result.context1 == ["mytag"]
end
test "[multi tenant] remove/4 does nothing for an unexistent tag" do
post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id)
Taglet.add(post, "mytag", "tags", prefix: @tenant_id)
Taglet.add(post, "mytag2", "tags", prefix: @tenant_id)
Taglet.add(post, "mytag3", "tags", prefix: @tenant_id)
result = Taglet.remove(post, "my2", "tags", prefix: @tenant_id)
assert result.tags() == ["mytag", "mytag2", "mytag3"]
end
test "[multi tenant] tag_list/2 with struct as param returns a list of associated tags" do
post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id)
Taglet.add(post, "mytag", "tags", prefix: @tenant_id)
Taglet.add(post, "mytag2", "tags", prefix: @tenant_id)
result = Taglet.tag_list(post, "tags", prefix: @tenant_id)
assert result == ["mytag", "mytag2"]
end
test "[multi tenant] tag_list/2 with struct returns a list of associated tags for a specific context" do
post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id)
Taglet.add(post, "mytag", "context", prefix: @tenant_id)
Taglet.add(post, "mytag2", "context", prefix: @tenant_id)
result = Taglet.tag_list(post, "context", prefix: @tenant_id)
assert result == ["mytag", "mytag2"]
end
test "[multi tenant] tag_list/2 with module as param returns a list of tags related with one context and module" do
post1 = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id)
post2 = @repo.insert!(%Post{title: "hello world2"}, prefix: @tenant_id)
Taglet.add(post1, ["tag1", "tag2"], "tags", prefix: @tenant_id)
Taglet.add(post2, ["tag2", "tag3"], "tags", prefix: @tenant_id)
result = Taglet.tag_list(Post, "tags", prefix: @tenant_id)
assert result == ["tag1", "tag2", "tag3"]
end
test "[multi tenant] tagged_with/4 returns a list of structs associated to a tag" do
post1 = @repo.insert!(%Post{title: "hello world1"}, prefix: @tenant_id)
post2 = @repo.insert!(%Post{title: "hello world2"}, prefix: @tenant_id)
post3 = @repo.insert!(%Post{title: "hello world3"}, prefix: @tenant_id)
Taglet.add(post1, "tagged1", "tags", prefix: @tenant_id)
Taglet.add(post2, "tagged1", "tags", prefix: @tenant_id)
Taglet.add(post3, "tagged2", "tags", prefix: @tenant_id)
post1 = @repo.get(Post, 1, prefix: @tenant_id)
post2 = @repo.get(Post, 2, prefix: @tenant_id)
result = Taglet.tagged_with("tagged1", Post, "tags", prefix: @tenant_id)
assert result == [post1, post2]
end
test "[multi tenant] tagged_with_query/4 returns a query of structs associated to a tag" do
post1 = @repo.insert!(%Post{title: "hello world1"}, prefix: @tenant_id)
post2 = @repo.insert!(%Post{title: "hello world2"}, prefix: @tenant_id)
post3 = @repo.insert!(%Post{title: "hello world3"}, prefix: @tenant_id)
Taglet.add(post1, "tagged1", "tags", prefix: @tenant_id)
Taglet.add(post2, ["tagged1", "tagged2"], "tags", prefix: @tenant_id)
Taglet.add(post3, "tagged2", "tags", prefix: @tenant_id)
query = Post |> where(title: "hello world2")
post2 = @repo.get(Post, 2, prefix: @tenant_id)
result =
Taglet.tagged_with_query(query, ["tagged1", "tagged2"])
|> @repo.all(prefix: @tenant_id)
assert result == [post2]
end
# Aux functions
defp setup_tenant do
migrations_path = Path.join(build_repo_priv(@repo), "migrations")
# Drop the previous tenant to reset the data
SQL.query(@repo, "DROP SCHEMA \"#{@tenant_id}\" CASCADE", [])
# Create new tenant
SQL.query(@repo, "CREATE SCHEMA \"#{@tenant_id}\"", [])
Ecto.Migrator.run(@repo, migrations_path, :up, prefix: @tenant_id, all: true)
end
end
| 33.867568 | 117 | 0.651185 |
03e3cbf42d306527695282ab5a846a2e8a12820a | 2,603 | exs | Elixir | test/elixir_google_spreadsheets/client_test.exs | trusty/elixir_google_spreadsheets | b7f74d75e61027dc0b12aa5260168563d0777c92 | [
"MIT"
] | 50 | 2016-12-21T06:39:08.000Z | 2022-03-16T04:52:42.000Z | test/elixir_google_spreadsheets/client_test.exs | trusty/elixir_google_spreadsheets | b7f74d75e61027dc0b12aa5260168563d0777c92 | [
"MIT"
] | 36 | 2017-01-31T19:12:19.000Z | 2022-03-10T17:27:58.000Z | test/elixir_google_spreadsheets/client_test.exs | nested-tech/elixir_google_spreadsheets | 45895fe6ac5bc9f256bc2e271be1a3324ce8aded | [
"MIT"
] | 34 | 2017-01-16T04:22:16.000Z | 2022-03-01T01:46:39.000Z | defmodule GSS.ClientTest do
use ExUnit.Case, async: true
alias GSS.{Client.RequestParams, Client}
alias GSS.StubModules.Consumer
describe ".request" do
setup do
{:ok, client} = GenStage.start_link(GSS.Client, :ok)
client
|> send_request(:get, 1)
|> send_request(:post, 2)
|> send_request(:get, 3)
|> send_request(:put, 4)
|> send_request(:get, 5)
[client: client]
end
def send_request(client, method, num) do
request = create_request(method, num)
Task.async(fn -> GenStage.call(client, {:request, request}, 50_000) end)
client
end
def create_request(method, num) do
%RequestParams{method: method, url: "http://url/?n=#{num}"}
end
test "add request events to the queue and release them to read consumer", %{client: client} do
{:ok, _cons} = Consumer.start_link({client, partition: :read})
assert_receive {:received, [event1, event2, event3]}
request1 = create_request(:get, 1)
assert {:request, _, ^request1} = event1
request2 = create_request(:get, 3)
assert {:request, _, ^request2} = event2
request3 = create_request(:get, 5)
assert {:request, _, ^request3} = event3
end
test "add request events to the queue and release them to write consumer", %{client: client} do
{:ok, _cons} = Consumer.start_link({client, partition: :write})
assert_receive {:received, [event1, event2]}
request1 = create_request(:post, 2)
assert {:request, _, ^request1} = event1
request2 = create_request(:put, 4)
assert {:request, _, ^request2} = event2
end
end
describe ".dispatcher_hash/1" do
setup do
request = %RequestParams{url: "http://localhost"}
%{request: request}
end
test "get request to :read partition", %{request: request} do
event = {:request, self(), %{request | method: :get}}
assert {event, :read} == Client.dispatcher_hash(event)
end
test "post request to :write partition", %{request: request} do
event = {:request, self(), %{request | method: :post}}
assert {event, :write} == Client.dispatcher_hash(event)
end
test "put request to :write partition", %{request: request} do
event = {:request, self(), %{request | method: :put}}
assert {event, :write} == Client.dispatcher_hash(event)
end
test "patch request to :write partition", %{request: request} do
event = {:request, self(), %{request | method: :patch}}
assert {event, :write} == Client.dispatcher_hash(event)
end
end
end
| 30.988095 | 99 | 0.629274 |
03e3f5170bf2038cef5c32fc186a09e136e5a822 | 3,887 | ex | Elixir | lib/oban/plugins/lifeline.ex | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"Apache-2.0"
] | null | null | null | lib/oban/plugins/lifeline.ex | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"Apache-2.0"
] | null | null | null | lib/oban/plugins/lifeline.ex | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"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, Repo, Senator}
@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 Senator.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.764286 | 97 | 0.658863 |
03e432735d670ae8d6e1d66e141711126389e217 | 4,292 | ex | Elixir | test/e2e/lib/hologram_e2e_web/pages/page_4.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 40 | 2022-01-19T20:27:36.000Z | 2022-03-31T18:17:41.000Z | test/e2e/lib/hologram_e2e_web/pages/page_4.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 42 | 2022-02-03T22:52:43.000Z | 2022-03-26T20:57:32.000Z | test/e2e/lib/hologram_e2e_web/pages/page_4.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 3 | 2022-02-10T04:00:37.000Z | 2022-03-08T22:07:45.000Z | defmodule HologramE2E.Page4 do
use Hologram.Page
alias HologramE2E.Component4, warn: false
route "/e2e/page-4"
def init(_params, _conn) do
%{
text: "",
value: :p4,
x: 0
}
end
def template do
~H"""
<h1>Page 4</h1><br />
<button id="page-4-button-1" on:click.command="command_1">Command 1</button>
<button id="page-4-button-2" on:click.command={:command_2}>Command 2</button>
<button id="page-4-button-3" on:click.command={:command_3, a: 5, b: 6}>Command 3</button>
<button id="page-4-button-4" on:click.command={:component_4_id, :component_4_command_1}>Component 4 Command 1</button>
<button id="page-4-button-5" on:click.command={:component_4_id, :component_4_command_2, a: 5, b: 6}>Component 4 Command 2</button>
<button id="page-4-button-6" on:click.command="command_4">Command 4</button>
<button id="page-4-button-7" on:click.command={:command_5}>Command 5</button>
<button id="page-4-button-8" on:click.command={:command_6, a: 5, b: 6}>Command 6</button>
<button id="page-4-button-9" on:click.command="command_7">Command 7</button>
<button id="page-4-button-10" on:click.command={:command_8, a: 5, b: 6}>Command 8</button>
<button id="page-4-button-11" on:click.command="command_9">Command 9</button>
<button id="page-4-button-12" on:click.command={:component_4_id, :component_4_command_3}>Component 4 Command 3</button>
<button id="page-4-button-13" on:click.command={:layout, :default_layout_command_1}>Layout 4 Command 1</button>
<button id="page-4-button-14" on:click.command="command_11">Command 11</button>
<button id="page-4-button-15" on:click="action_12">Action 12</button>
<br />
<div id="text-page-4">{@text}</div><br />
<Component4 id="component_4_id" /><br />
"""
end
def action(:action_1_b, _params, state) do
put(state, :text, "text updated by action_1_b, state.value = #{state.value}")
end
def action(:action_2_b, _params, state) do
put(state, :text, "text updated by action_2_b, state.value = #{state.value}")
end
def action(:action_3_b, params, state) do
put(
state,
:text,
"text updated by action_3_b, params.a = #{params.a}, params.b = #{params.b}, state.value = #{state.value}"
)
end
def action(:action_4_b, _params, state) do
put(state, :text, "text updated by action_4_b, state.value = #{state.value}")
end
def action(:action_5_b, _params, state) do
put(state, :text, "text updated by action_5_b, state.value = #{state.value}")
end
def action(:action_6_b, params, state) do
put(
state,
:text,
"text updated by action_6_b, params.a = #{params.a}, params.b = #{params.b}, state.value = #{state.value}"
)
end
def action(:action_9_b, _params, state) do
put(state, :text, "text updated by action_9_b, state.value = #{state.value}")
end
def action(:action_10_b, _params, state) do
put(state, :text, "text updated by action_10_b, state.value = #{state.value}")
end
def action(:action_11_b, _params, state) do
put(state, :text, "text updated by action_11_b, state.value = #{state.value}")
end
def action(:action_12, _params, state) do
{state, :command_12}
end
def action(:action_12_b, _params, state) do
put(state, :text, "text updated by action_12_b, state.value = #{state.value}")
end
def command(:command_1, _params) do
:action_1_b
end
def command(:command_2, _params) do
:action_2_b
end
def command(:command_3, params) do
{:action_3_b, a: params.a * 10, b: params.b * 10}
end
def command(:command_4, _params) do
:action_4_b
end
def command(:command_5, _params) do
:action_5_b
end
def command(:command_6, params) do
{:action_6_b, a: params.a * 10, b: params.b * 10}
end
def command(:command_7, _params) do
{:component_4_id, :component_4_action_3_b}
end
def command(:command_8, params) do
{:component_4_id, :component_4_action_4_b, a: params.a * 10, b: params.b * 10}
end
def command(:command_9, _params) do
:action_9_b
end
def command(:command_10, _params) do
:action_10_b
end
def command(:command_11, _params) do
:action_11_b
end
def command(:command_12, _params) do
:action_12_b
end
end
| 30.225352 | 134 | 0.663094 |
03e4684797a1e93da4cd59ffdab3482563467266 | 501 | exs | Elixir | apps/artemis/priv/repo/migrations/20200221004737_create_event_questions.exs | artemis-platform/artemis_teams | 9930c3d9528e37b76f0525390e32b66eed7eadde | [
"MIT"
] | 2 | 2020-04-23T02:29:18.000Z | 2020-07-07T13:13:17.000Z | apps/artemis/priv/repo/migrations/20200221004737_create_event_questions.exs | chrislaskey/artemis_teams | 9930c3d9528e37b76f0525390e32b66eed7eadde | [
"MIT"
] | 4 | 2020-04-26T20:35:36.000Z | 2020-11-10T22:13:19.000Z | apps/artemis/priv/repo/migrations/20200221004737_create_event_questions.exs | chrislaskey/artemis_teams | 9930c3d9528e37b76f0525390e32b66eed7eadde | [
"MIT"
] | null | null | null | defmodule Artemis.Repo.Migrations.CreateEventQuestions do
use Ecto.Migration
def change do
create table(:event_questions) do
add :active, :boolean
add :description, :text
add :order, :integer
add :title, :string
add :type, :string
add :event_template_id, references(:event_templates, on_delete: :delete_all)
timestamps(type: :utc_datetime)
end
create index(:event_questions, [:title])
create index(:event_questions, [:type])
end
end
| 23.857143 | 82 | 0.684631 |
03e4b1bdb91a72a4ddc96aa6bde1764fde4a8b94 | 780 | ex | Elixir | lib/surface/components/form.ex | zamith/surface | 1597bd2b2490eacea2a7ab659a7c95863e73985b | [
"MIT"
] | null | null | null | lib/surface/components/form.ex | zamith/surface | 1597bd2b2490eacea2a7ab659a7c95863e73985b | [
"MIT"
] | null | null | null | lib/surface/components/form.ex | zamith/surface | 1597bd2b2490eacea2a7ab659a7c95863e73985b | [
"MIT"
] | 1 | 2020-04-21T18:49:15.000Z | 2020-04-21T18:49:15.000Z | defmodule Surface.Components.Form do
use Surface.Component
import Phoenix.HTML.Form
alias Surface.Components.Raw
@doc "Atom or changeset to inform the form data"
property for, :any, required: true
@doc "URL to where the form is submitted"
property action, :string, required: true
@doc "Keyword list with options to be passed down to `form_for/3`"
property opts, :keyword, default: []
@doc "The content of the `<form>`"
slot default
@doc "The form instance initialized by the Form component"
context set form, :form
def init_context(assigns) do
form = form_for(assigns.for, assigns.action, assigns.opts)
{:ok, form: form}
end
def render(assigns) do
~H"""
{{ @form }}
<slot/>
<#Raw></form></#Raw>
"""
end
end
| 21.666667 | 68 | 0.670513 |
03e4bcfc07d3525b132209e81387b9cb4a5627b8 | 1,288 | ex | Elixir | lib/oli_web/plugs/set_user.ex | ChristianMurphy/oli-torus | ffeee4996b66b7c6c6eb3e0082d030b8cc6cea97 | [
"MIT"
] | null | null | null | lib/oli_web/plugs/set_user.ex | ChristianMurphy/oli-torus | ffeee4996b66b7c6c6eb3e0082d030b8cc6cea97 | [
"MIT"
] | null | null | null | lib/oli_web/plugs/set_user.ex | ChristianMurphy/oli-torus | ffeee4996b66b7c6c6eb3e0082d030b8cc6cea97 | [
"MIT"
] | null | null | null | defmodule Oli.Plugs.SetCurrentUser do
import Plug.Conn
alias Oli.Accounts.Author
alias Oli.Accounts.User
alias Oli.Repo
def init(_params) do
end
def call(conn, _params) do
conn
|> set_author
|> set_user
|> set_user_token
end
def set_author(conn) do
pow_config = OliWeb.Pow.PowHelpers.get_pow_config(:author)
if author = Pow.Plug.current_user(conn, pow_config) do
cond do
current_author = Repo.get(Author, author.id) ->
assign(conn, :current_author, current_author)
true ->
assign(conn, :current_author, nil)
end
else
conn
end
end
def set_user(conn) do
pow_config = OliWeb.Pow.PowHelpers.get_pow_config(:user)
if user = Pow.Plug.current_user(conn, pow_config) do
cond do
current_user = Repo.get(User, user.id) |> Repo.preload([:platform_roles, :author]) ->
assign(conn, :current_user, current_user)
true ->
assign(conn, :current_user, nil)
end
else
conn
end
end
defp set_user_token(conn) do
case conn.assigns[:current_user] do
nil ->
conn
user ->
token = Phoenix.Token.sign(conn, "user socket", user.sub)
assign(conn, :user_token, token)
end
end
end
| 21.114754 | 93 | 0.627329 |
03e4e7f5bfad88175ca25c86739cd91134e81cd5 | 1,625 | exs | Elixir | config/config.exs | octosteve/remote_retro | 3385b0db3c2daab934ce12a2f7642a5f10ac5147 | [
"MIT"
] | 523 | 2017-03-15T15:21:11.000Z | 2022-03-14T03:04:18.000Z | config/config.exs | octosteve/remote_retro | 3385b0db3c2daab934ce12a2f7642a5f10ac5147 | [
"MIT"
] | 524 | 2017-03-16T18:31:09.000Z | 2022-02-26T10:02:06.000Z | config/config.exs | octosteve/remote_retro | 3385b0db3c2daab934ce12a2f7642a5f10ac5147 | [
"MIT"
] | 60 | 2017-05-01T18:02:28.000Z | 2022-03-04T21:04:56.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# General application configuration
config :remote_retro,
ecto_repos: [RemoteRetro.Repo],
env: Mix.env()
# Configures the endpoint
config :remote_retro, RemoteRetroWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "btCOS+GDpTLovPJFR8hQ9LbXeshAFCS4DaRCSbwIgFyt2AcKwE9oUfP9i3AsBAGW",
render_errors: [view: RemoteRetroWeb.ErrorView, accepts: ~w(html json)],
pubsub_server: RemoteRetro.PubSub,
live_view: [signing_salt: "FglCNt_sd7C22gLB"]
# Configures Email API
config :remote_retro, RemoteRetro.Mailer, adapter: Bamboo.SendGridAdapter, api_key: System.get_env("SENDGRID_API_KEY")
config :bamboo, :json_library, Jason
config :remote_retro, :auth_controller, RemoteRetroWeb.AuthController
config :remote_retro, :extra_headers, ""
config :oauth2,
serializers: %{
"application/json" => Jason,
}
config :libcluster,
topologies: []
# Configures HoneyBadger error reporting API
config :honeybadger,
api_key: "stubDevValue"
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
config :remote_retro, ecto_repos: [RemoteRetro.Repo]
config :remote_retro, live_dashboard_repos: []
config :phoenix, :json_library, Jason
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"
| 30.660377 | 118 | 0.774769 |
03e50f4ef9e516d9d81e4b9fd3f1a24fc61e964b | 3,824 | ex | Elixir | lib/saxy/xmerl/handler.ex | duffelhq/saxy | fb37f1d9ce919e6085a924c2483c515ee6cb997b | [
"MIT"
] | null | null | null | lib/saxy/xmerl/handler.ex | duffelhq/saxy | fb37f1d9ce919e6085a924c2483c515ee6cb997b | [
"MIT"
] | null | null | null | lib/saxy/xmerl/handler.ex | duffelhq/saxy | fb37f1d9ce919e6085a924c2483c515ee6cb997b | [
"MIT"
] | null | null | null | defmodule Saxy.Xmerl.Handler do
@moduledoc false
import Saxy.Xmerl.Records
@behaviour Saxy.Handler
@impl true
def handle_event(:start_element, element, state) do
{:ok, start_element(element, state)}
end
def handle_event(:end_element, element, state) do
{:ok, end_element(element, state)}
end
def handle_event(:characters, element, state) do
{:ok, characters(element, state)}
end
def handle_event(_event_name, _event_data, state) do
{:ok, state}
end
# Event handlers
defp start_element({name, attributes}, state) do
%{atom_fun: atom_fun, stack: stack, child_count: child_count} = state
element = make_element(name, attributes, stack, child_count, atom_fun)
%{state | stack: [element | stack], child_count: [0 | child_count]}
end
defp end_element(_name, %{stack: [root]} = state) do
%{state | stack: [reverse_element_content(root)]}
end
defp end_element(_name, state) do
%{stack: stack, child_count: child_count} = state
[current | [parent | stack]] = stack
[_ | [count | child_count]] = child_count
current = reverse_element_content(current)
parent = prepend_element_content(parent, current)
%{state | stack: [parent | stack], child_count: [count + 1 | child_count]}
end
defp characters(characters, state) do
%{stack: [current | stack]} = state
text = xmlText(value: String.to_charlist(characters))
current = prepend_element_content(current, text)
%{state | stack: [current | stack]}
end
# Helpers
defp prepend_element_content(xmlElement(content: content) = current, object) do
xmlElement(current, content: [object | content])
end
defp reverse_element_content(xmlElement(content: content) = element) do
xmlElement(element, content: Enum.reverse(content))
end
defp make_element(binary_name, attributes, stack, child_count, atom_fun) do
{namespace, local} = split_name(binary_name)
name = make_name(binary_name, atom_fun)
nsinfo = make_nsinfo(namespace, local)
attributes = make_attributes(attributes, atom_fun)
namespace = make_namespace()
parents = make_parents(stack)
position = determine_element_position(child_count)
content = []
xmlElement(
name: name,
expanded_name: name,
pos: position,
nsinfo: nsinfo,
namespace: namespace,
parents: parents,
attributes: attributes,
content: content
)
end
defp determine_element_position([count | _]), do: count + 1
defp determine_element_position([]), do: 1
defp split_name(name) do
case String.split(name, ":", parts: 2) do
[local] -> {<<>>, local}
[namespace, local] -> {namespace, local}
end
end
defp make_name(name, atom_fun) do
atom_fun.(name)
end
defp make_nsinfo(<<>>, _local), do: []
defp make_nsinfo(namespace, local),
do: {String.to_charlist(namespace), String.to_charlist(local)}
defp make_namespace(), do: xmlNamespace()
defp make_parents(stack, acc \\ [])
defp make_parents([], acc), do: Enum.reverse(acc)
defp make_parents([current | stack], acc) do
xmlElement(name: name, pos: pos) = current
make_parents(stack, [{name, pos} | acc])
end
defp make_attributes(attributes, atom_fun, count \\ 0, acc \\ [])
defp make_attributes([], _atom_fun, _count, acc), do: Enum.reverse(acc)
defp make_attributes([{binary_name, value} | attributes], atom_fun, count, acc) do
{namespace, local} = split_name(binary_name)
name = make_name(binary_name, atom_fun)
attribute =
xmlAttribute(
name: name,
expanded_name: name,
nsinfo: make_nsinfo(namespace, local),
pos: count + 1,
value: String.to_charlist(value)
)
make_attributes(attributes, atom_fun, count + 1, [attribute | acc])
end
end
| 26.555556 | 84 | 0.676778 |
03e53a5f1fc3ec838b376b99049a65488cba88a4 | 2,068 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/targeting_templates_list_response.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/targeting_templates_list_response.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/targeting_templates_list_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.DFAReporting.V34.Model.TargetingTemplatesListResponse do
@moduledoc """
Targeting Template List Response
## Attributes
* `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#targetingTemplatesListResponse".
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Pagination token to be used for the next list operation.
* `targetingTemplates` (*type:* `list(GoogleApi.DFAReporting.V34.Model.TargetingTemplate.t)`, *default:* `nil`) - Targeting template collection.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => String.t(),
:nextPageToken => String.t(),
:targetingTemplates => list(GoogleApi.DFAReporting.V34.Model.TargetingTemplate.t())
}
field(:kind)
field(:nextPageToken)
field(:targetingTemplates, as: GoogleApi.DFAReporting.V34.Model.TargetingTemplate, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.TargetingTemplatesListResponse do
def decode(value, options) do
GoogleApi.DFAReporting.V34.Model.TargetingTemplatesListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.TargetingTemplatesListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.018868 | 166 | 0.744197 |
03e53b583ae4bfa673fc91044f4846293a6e01c7 | 3,002 | exs | Elixir | test/phoenix/pubsub/pg2_test.exs | grindrlabs/phoenix_pubsub | 27a9113dfa8a2e125ae74cfff36e6a322c8b97f4 | [
"MIT"
] | 3 | 2020-06-08T03:47:03.000Z | 2021-09-17T21:48:37.000Z | test/phoenix/pubsub/pg2_test.exs | grindrlabs/phoenix_pubsub | 27a9113dfa8a2e125ae74cfff36e6a322c8b97f4 | [
"MIT"
] | null | null | null | test/phoenix/pubsub/pg2_test.exs | grindrlabs/phoenix_pubsub | 27a9113dfa8a2e125ae74cfff36e6a322c8b97f4 | [
"MIT"
] | null | null | null | # Run shared PubSub adapter tests
Application.put_env(:phoenix, :pubsub_test_adapter, Phoenix.PubSub.PG2)
Code.require_file "../../shared/pubsub_test.exs", __DIR__
# Run distributed elixir specific PubSub tests
defmodule Phoenix.PubSub.PG2Test do
use Phoenix.PubSub.NodeCase
alias Phoenix.PubSub
alias Phoenix.PubSub.PG2
@node1 :"node1@127.0.0.1"
@node2 :"node2@127.0.0.1"
@receive_timeout 500
setup config do
size = config[:pool_size] || 1
if config[:pool_size] do
{:ok, _} = PG2.start_link(config.test, pool_size: size)
else
{:ok, _} = PG2.start_link(config.test, [])
end
{_, {:ok, _}} = start_pubsub(@node1, PG2, config.test, [pool_size: size * 2])
{:ok, %{pubsub: config.test, pool_size: size}}
end
for size <- [1, 8], topic = "#{__MODULE__}:#{size}" do
@tag pool_size: size, topic: topic
test "pool #{size}: direct_broadcast targets a specific node", config do
spy_on_pubsub(@node1, config.pubsub, self(), config.topic)
PubSub.subscribe(config.pubsub, config.topic)
:ok = PubSub.direct_broadcast(@node1, config.pubsub, config.topic, :ping)
assert_receive {@node1, :ping}, @receive_timeout
:ok = PubSub.direct_broadcast!(@node1, config.pubsub, config.topic, :ping)
assert_receive {@node1, :ping}, @receive_timeout
:ok = PubSub.direct_broadcast(@node2, config.pubsub, config.topic, :ping)
refute_receive {@node1, :ping}, @receive_timeout
:ok = PubSub.direct_broadcast!(@node2, config.pubsub, config.topic, :ping)
refute_receive {@node1, :ping}, @receive_timeout
end
@tag pool_size: size, topic: topic
test "pool #{size}: direct_broadcast_from targets a specific node", config do
spy_on_pubsub(@node1, config.pubsub, self(), config.topic)
PubSub.subscribe(config.pubsub, config.topic)
:ok = PubSub.direct_broadcast_from(@node1, config.pubsub, self(), config.topic, :ping)
assert_receive {@node1, :ping}, @receive_timeout
:ok = PubSub.direct_broadcast_from!(@node1, config.pubsub, self(), config.topic, :ping)
assert_receive {@node1, :ping}, @receive_timeout
:ok = PubSub.direct_broadcast_from(@node2, config.pubsub, self(), config.topic, :ping)
refute_receive {@node1, :ping}, @receive_timeout
:ok = PubSub.direct_broadcast_from!(@node2, config.pubsub, self(), config.topic, :ping)
refute_receive {@node1, :ping}, @receive_timeout
end
end
test "pool size defaults to number of schedulers" do
{:ok, pg2_supervisor} = PG2.start_link(:pool_size_count_test, [])
local_supervisor =
pg2_supervisor
|> Supervisor.which_children()
|> Enum.find_value(fn
{Phoenix.PubSub.LocalSupervisor, pid, :supervisor, _} -> pid
_ -> false
end)
%{supervisors: supervisor_count} = Supervisor.count_children(local_supervisor)
assert supervisor_count == :erlang.system_info(:schedulers)
end
end
| 39.5 | 93 | 0.672219 |
03e573b24e7580d296d267036fd63cbf6e86d350 | 322 | exs | Elixir | elixir/elixir-sips/samples/elixiak_playground/mix.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | 2 | 2015-12-09T02:16:51.000Z | 2021-07-26T22:53:43.000Z | elixir/elixir-sips/samples/elixiak_playground/mix.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | null | null | null | elixir/elixir-sips/samples/elixiak_playground/mix.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | 1 | 2016-05-08T18:40:31.000Z | 2016-05-08T18:40:31.000Z | defmodule ElixiakPlayground.Mixfile do
use Mix.Project
def project do
[app: :elixiak_playground,
version: "0.0.1",
elixir: "~> 1.0",
deps: deps]
end
def application do
[applications: [:logger]]
end
defp deps do
[
{:elixiak, github: 'drewkerrigan/elixiak'}
]
end
end
| 15.333333 | 50 | 0.60559 |
03e574f31c79b55a6ef6ea70accf629069c01f59 | 19,538 | ex | Elixir | lib/logger/lib/logger/translator.ex | dogatuncay/elixir | 42875b97f858a31d3cbb8e1090ffb4d6c443ba75 | [
"Apache-2.0"
] | 1 | 2017-05-29T02:02:38.000Z | 2017-05-29T02:02:38.000Z | lib/logger/lib/logger/translator.ex | dogatuncay/elixir | 42875b97f858a31d3cbb8e1090ffb4d6c443ba75 | [
"Apache-2.0"
] | null | null | null | lib/logger/lib/logger/translator.ex | dogatuncay/elixir | 42875b97f858a31d3cbb8e1090ffb4d6c443ba75 | [
"Apache-2.0"
] | null | null | null | defmodule Logger.Translator do
@moduledoc """
Default translation for Erlang log messages.
Logger allows developers to rewrite log messages provided by
OTP applications into a format more compatible with Elixir
log messages by providing a translator.
A translator is simply a tuple containing a module and a function
that can be added and removed via the `Logger.add_translator/1` and
`Logger.remove_translator/1` functions and is invoked for every Erlang
message above the minimum log level with four arguments:
* `min_level` - the current Logger level
* `level` - the level of the message being translated
* `kind` - if the message is a `:report` or `:format`
* `message` - the message to format. If it is `:report`, it is a tuple
with `{report_type, report_data}`, if it is `:format`, it is a
tuple with `{format_message, format_args}`.
The function must return:
* `{:ok, chardata, metadata}` - if the message translation with its metadata
* `{:ok, chardata}` - the translated message
* `:skip` - if the message is not meant to be translated nor logged
* `:none` - if there is no translation, which triggers the next translator
See the function `translate/4` in this module for an example implementation
and the default messages translated by Logger.
"""
@doc """
Built-in translation function.
"""
def translate(min_level, level, kind, message)
def translate(min_level, _level, :report, {:logger, %{label: label} = report}) do
case label do
{:gen_server, :terminate} ->
report_gen_server_terminate(min_level, report)
{:gen_event, :terminate} ->
report_gen_event_terminate(min_level, report)
_ ->
:skip
end
end
def translate(min_level, _level, :report, {{:proc_lib, :crash}, data}) do
report_crash(min_level, data)
end
def translate(min_level, _level, :report, {{:supervisor, :progress}, data}) do
report_supervisor_progress(min_level, data)
end
def translate(min_level, _level, :report, {{:supervisor, _}, data}) do
report_supervisor(min_level, data)
end
def translate(
_min_level,
_level,
:report,
{{:application_controller, :progress}, [application: app, started_at: node]}
) do
{:ok, ["Application ", Atom.to_string(app), " started at " | inspect(node)]}
end
def translate(
_min_level,
_level,
:report,
{{:application_controller, :exit}, [application: app, exited: reason, type: _type]}
) do
{:ok, ["Application ", Atom.to_string(app), " exited: " | Application.format_error(reason)]}
end
def translate(
_min_level,
:error,
:report,
{{Task.Supervisor, :terminating},
%{
name: name,
starter: starter,
function: function,
args: args,
reason: reason
}}
) do
opts = Application.get_env(:logger, :translator_inspect_opts)
{formatted, reason} = format_reason(reason)
metadata = [crash_reason: reason] ++ registered_name(name)
msg =
["Task #{inspect(name)} started from #{inspect(starter)} terminating"] ++
[formatted, "\nFunction: #{inspect(function, opts)}"] ++
["\n Args: #{inspect(args, opts)}"]
{:ok, msg, metadata}
end
def translate(min_level, :error, :format, message) do
case message do
# This is no longer emitted by Erlang/OTP but it may be
# manually emitted by libraries like connection.
# TODO: Remove this translation on Elixir v1.14
{'** Generic server ' ++ _, [name, last, state, reason | client]} ->
opts = Application.get_env(:logger, :translator_inspect_opts)
{formatted, reason} = format_reason(reason)
metadata = [crash_reason: reason] ++ registered_name(name)
msg =
["GenServer #{inspect(name)} terminating", formatted] ++
["\nLast message#{format_from(client)}: #{inspect(last, opts)}"]
if min_level == :debug do
msg = [msg, "\nState: #{inspect(state, opts)}" | format_client(client)]
{:ok, msg, metadata}
else
{:ok, msg, metadata}
end
{'Error in process ' ++ _, [pid, node, {reason, stack}]} ->
reason = Exception.normalize(:error, reason, stack)
msg = [
"Process ",
inspect(pid),
" on node ",
inspect(node),
" raised an exception" | format(:error, reason, stack)
]
{:ok, msg, [crash_reason: exit_reason(:error, reason, stack)]}
{'Error in process ' ++ _, [pid, {reason, stack}]} ->
reason = Exception.normalize(:error, reason, stack)
msg = ["Process ", inspect(pid), " raised an exception" | format(:error, reason, stack)]
{:ok, msg, [crash_reason: exit_reason(:error, reason, stack)]}
_ ->
:none
end
end
def translate(_min_level, :info, :report, {
:std_info,
[application: app, exited: reason, type: _type]
}) do
{:ok, ["Application ", Atom.to_string(app), " exited: " | Application.format_error(reason)]}
end
def translate(min_level, :error, :report, {{:error_logger, :error_report}, data}) do
report_supervisor(min_level, data)
end
def translate(min_level, :error, :report, {:supervisor_report, data}) do
report_supervisor(min_level, data)
end
def translate(min_level, :error, :report, {:crash_report, data}) do
report_crash(min_level, data)
end
def translate(min_level, :info, :report, {:progress, [{:supervisor, _} | _] = data}) do
report_supervisor_progress(min_level, data)
end
def translate(_min_level, :info, :report, {:progress, [application: app, started_at: node]}) do
{:ok, ["Application ", Atom.to_string(app), " started at " | inspect(node)]}
end
## Helpers
def translate(_min_level, _level, _kind, _message) do
:none
end
defp report_gen_server_terminate(min_level, report) do
inspect_opts = Application.get_env(:logger, :translator_inspect_opts)
%{
client_info: client,
last_message: last,
name: name,
reason: reason,
state: state
} = report
{formatted, reason} = format_reason(reason)
metadata = [crash_reason: reason] ++ registered_name(name)
msg =
["GenServer ", inspect(name), " terminating", formatted] ++
["\nLast message", format_last_message_from(client), ": ", inspect(last, inspect_opts)]
if min_level == :debug do
msg = [msg, "\nState: ", inspect(state, inspect_opts) | format_client_info(client)]
{:ok, msg, metadata}
else
{:ok, msg, metadata}
end
end
defp report_gen_event_terminate(min_level, report) do
inspect_opts = Application.get_env(:logger, :translator_inspect_opts)
%{
handler: handler,
last_message: last,
name: name,
reason: reason,
state: state
} = report
reason =
case reason do
{:EXIT, why} -> why
_ -> reason
end
{formatted, reason} = format_reason(reason)
metadata = [crash_reason: reason] ++ registered_name(name)
msg =
[":gen_event handler ", inspect(handler), " installed in ", inspect(name), " terminating"] ++
[formatted, "\nLast message: ", inspect(last, inspect_opts)]
if min_level == :debug do
{:ok, [msg, "\nState: ", inspect(state, inspect_opts)], metadata}
else
{:ok, msg, metadata}
end
end
defp report_supervisor_progress(
min_level,
supervisor: sup,
started: [{:pid, pid}, {:id, id} | started]
) do
msg =
["Child ", inspect(id), " of Supervisor ", sup_name(sup), " started"] ++
["\nPid: ", inspect(pid)] ++ child_info(min_level, started)
{:ok, msg}
end
defp report_supervisor_progress(
min_level,
supervisor: sup,
started: [{:pid, pid} | started]
) do
msg =
["Child of Supervisor ", sup_name(sup), " started", "\nPid: ", inspect(pid)] ++
child_info(min_level, started)
{:ok, msg}
end
defp report_supervisor_progress(_min_level, _other), do: :none
defp report_supervisor(
min_level,
supervisor: sup,
errorContext: context,
reason: reason,
offender: [{:pid, pid}, {:id, id} | offender]
) do
pid_info =
if is_pid(pid) and context != :shutdown do
["\nPid: ", inspect(pid)]
else
[]
end
msg =
["Child ", inspect(id), " of Supervisor ", sup_name(sup)] ++
[?\s, sup_context(context), "\n** (exit) ", offender_reason(reason, context)] ++
pid_info ++ child_info(min_level, offender)
{:ok, msg}
end
defp report_supervisor(
min_level,
supervisor: sup,
errorContext: context,
reason: reason,
offender: [{:nb_children, n}, {:id, id} | offender]
) do
msg =
["Children ", inspect(id), " of Supervisor ", sup_name(sup), ?\s, sup_context(context)] ++
["\n** (exit) ", offender_reason(reason, context), "\nNumber: ", Integer.to_string(n)] ++
child_info(min_level, offender)
{:ok, msg}
end
defp report_supervisor(
min_level,
supervisor: sup,
errorContext: context,
reason: reason,
offender: [{:pid, pid} | offender]
) do
msg =
["Child of Supervisor ", sup_name(sup), ?\s, sup_context(context)] ++
["\n** (exit) ", offender_reason(reason, context), "\nPid: ", inspect(pid)] ++
child_info(min_level, offender)
{:ok, msg}
end
defp report_supervisor(_min_level, _other), do: :none
# If start call raises reason will be of form {:EXIT, reason}
defp offender_reason({:EXIT, reason}, :start_error) do
Exception.format_exit(reason)
end
defp offender_reason(reason, _context) do
Exception.format_exit(reason)
end
defp sup_name({:local, name}), do: inspect(name)
defp sup_name({:global, name}), do: inspect(name)
defp sup_name({:via, _mod, name}), do: inspect(name)
defp sup_name({pid, mod}), do: [inspect(pid), " (", inspect(mod), ?)]
defp sup_name(unknown_name), do: inspect(unknown_name)
defp sup_context(:start_error), do: "failed to start"
defp sup_context(:child_terminated), do: "terminated"
defp sup_context(:shutdown), do: "caused shutdown"
defp sup_context(:shutdown_error), do: "shut down abnormally"
defp child_info(min_level, [{:mfargs, {mod, fun, args}} | debug]) do
["\nStart Call: ", format_mfa(mod, fun, args) | child_debug(min_level, debug)]
end
# Comes from bridge with MFA
defp child_info(min_level, [{:mfa, {mod, fun, args}} | debug]) do
["\nStart Call: ", format_mfa(mod, fun, args) | child_debug(min_level, debug)]
end
# Comes from bridge with Mod
defp child_info(min_level, [{:mod, mod} | debug]) do
["\nStart Module: ", inspect(mod) | child_debug(min_level, debug)]
end
defp child_info(_min_level, _child) do
[]
end
defp child_debug(:debug, restart_type: restart, shutdown: shutdown, child_type: type) do
["\nRestart: ", inspect(restart), "\nShutdown: ", inspect(shutdown)] ++
["\nType: ", inspect(type)]
end
defp child_debug(_min_level, _child) do
[]
end
defp report_crash(min_level, [[{:initial_call, initial_call} | crashed], linked]) do
mfa = initial_call_to_mfa(initial_call)
report_crash(min_level, crashed, [{:initial_call, mfa}], linked)
end
defp report_crash(min_level, [crashed, linked]) do
report_crash(min_level, crashed, [], linked)
end
defp report_crash(min_level, crashed, extra, linked) do
[
{:pid, pid},
{:registered_name, name},
{:error_info, {kind, reason, stack}} | crashed
] = crashed
dictionary = crashed[:dictionary]
reason = Exception.normalize(kind, reason, stack)
case Keyword.get(dictionary, :logger_enabled, true) do
false ->
:skip
true ->
user_metadata = Keyword.get(dictionary, :"$logger_metadata$", %{}) |> Map.to_list()
msg =
["Process ", crash_name(pid, name), " terminating", format(kind, reason, stack)] ++
[crash_info(min_level, extra ++ crashed, [?\n]), crash_linked(min_level, linked)]
extra =
if ancestors = crashed[:ancestors], do: [{:ancestors, ancestors} | extra], else: extra
extra =
if callers = dictionary[:"$callers"], do: [{:callers, callers} | extra], else: extra
extra = [{:crash_reason, exit_reason(kind, reason, stack)} | extra]
{:ok, msg, registered_name(name) ++ extra ++ user_metadata}
end
end
defp initial_call_to_mfa({:supervisor, module, _}), do: {module, :init, 1}
defp initial_call_to_mfa({:supervisor_bridge, module, _}), do: {module, :init, 1}
defp initial_call_to_mfa({mod, fun, args}) when is_list(args), do: {mod, fun, length(args)}
defp initial_call_to_mfa(mfa), do: mfa
defp crash_name(pid, []), do: inspect(pid)
defp crash_name(pid, name), do: [inspect(name), " (", inspect(pid), ?)]
defp crash_info(min_level, [{:initial_call, {mod, fun, args}} | info], prefix) do
[prefix, "Initial Call: ", crash_call(mod, fun, args) | crash_info(min_level, info, prefix)]
end
defp crash_info(min_level, [{:current_function, {mod, fun, args}} | info], prefix) do
[prefix, "Current Call: ", crash_call(mod, fun, args) | crash_info(min_level, info, prefix)]
end
defp crash_info(min_level, [{:current_function, []} | info], prefix) do
crash_info(min_level, info, prefix)
end
defp crash_info(min_level, [{:ancestors, ancestors} | debug], prefix) do
[prefix, "Ancestors: ", inspect(ancestors) | crash_info(min_level, debug, prefix)]
end
defp crash_info(:debug, debug, prefix) do
for {key, value} <- debug do
crash_debug(key, value, prefix)
end
end
defp crash_info(_, _, _) do
[]
end
defp crash_call(mod, fun, arity) when is_integer(arity) do
format_mfa(mod, fun, arity)
end
defp crash_call(mod, fun, args) do
format_mfa(mod, fun, length(args))
end
defp crash_debug(:current_stacktrace, stack, prefix) do
stack_prefix = [prefix | " "]
stacktrace = Enum.map(stack, &[stack_prefix | Exception.format_stacktrace_entry(&1)])
[prefix, "Current Stacktrace:" | stacktrace]
end
defp crash_debug(key, value, prefix) do
[prefix, crash_debug_key(key), ?:, ?\s, inspect(value)]
end
defp crash_debug_key(key) do
case key do
:message_queue_len -> "Message Queue Length"
:messages -> "Messages"
:links -> "Links"
:dictionary -> "Dictionary"
:trap_exit -> "Trapping Exits"
:status -> "Status"
:heap_size -> "Heap Size"
:stack_size -> "Stack Size"
:reductions -> "Reductions"
end
end
defp crash_linked(_min_level, []), do: []
defp crash_linked(min_level, neighbours) do
Enum.reduce(neighbours, "\nNeighbours:", fn {:neighbour, info}, acc ->
[acc | crash_neighbour(min_level, info)]
end)
end
@indent " "
defp crash_neighbour(min_level, [{:pid, pid}, {:registered_name, []} | info]) do
[?\n, @indent, inspect(pid) | crash_info(min_level, info, [?\n, @indent | @indent])]
end
defp crash_neighbour(min_level, [{:pid, pid}, {:registered_name, name} | info]) do
[?\n, @indent, inspect(name), " (", inspect(pid), ")"] ++
crash_info(min_level, info, [?\n, @indent | @indent])
end
defp format_last_message_from({_, {name, _}}), do: [" (from ", inspect(name), ")"]
defp format_last_message_from({from, _}), do: [" (from ", inspect(from), ")"]
defp format_last_message_from(_), do: []
defp format_client_info({from, :dead}),
do: ["\nClient ", inspect(from), " is dead"]
defp format_client_info({from, :remote}),
do: ["\nClient ", inspect(from), " is remote on node ", inspect(node(from))]
defp format_client_info({_, {name, stacktrace}}),
do: ["\nClient ", inspect(name), " is alive\n" | format_stacktrace(stacktrace)]
defp format_client_info(_),
do: []
defp format_reason({maybe_exception, [_ | _] = maybe_stacktrace} = reason) do
try do
format_stacktrace(maybe_stacktrace)
catch
:error, _ ->
{format_stop(reason), {reason, []}}
else
formatted_stacktrace ->
{formatted, reason} = maybe_normalize(maybe_exception, maybe_stacktrace)
{[formatted | formatted_stacktrace], {reason, maybe_stacktrace}}
end
end
defp format_reason(reason) do
{format_stop(reason), {reason, []}}
end
defp format_stop(reason) do
["\n** (stop) " | Exception.format_exit(reason)]
end
# Erlang processes rewrite the :undef error to these reasons when logging
@gen_undef [:"module could not be loaded", :"function not exported"]
defp maybe_normalize(undef, [{mod, fun, args, _info} | _] = stacktrace)
when undef in @gen_undef and is_atom(mod) and is_atom(fun) do
cond do
is_list(args) ->
format_undef(mod, fun, length(args), undef, stacktrace)
is_integer(args) ->
format_undef(mod, fun, args, undef, stacktrace)
true ->
{format_stop(undef), undef}
end
end
defp maybe_normalize(reason, stacktrace) do
# If this is already an exception (even an ErlangError), we format it as an
# exception. Otherwise, we try to normalize it, and if it's normalized as an
# ErlangError we instead format it as an exit.
if is_exception(reason) do
{[?\n | Exception.format_banner(:error, reason, stacktrace)], reason}
else
case Exception.normalize(:error, reason, stacktrace) do
%ErlangError{} ->
{format_stop(reason), reason}
exception ->
{[?\n | Exception.format_banner(:error, exception, stacktrace)], exception}
end
end
end
defp format(kind, payload, stacktrace) do
[?\n, Exception.format_banner(kind, payload, stacktrace) | format_stacktrace(stacktrace)]
end
defp format_stacktrace(stacktrace) do
for entry <- stacktrace do
["\n " | Exception.format_stacktrace_entry(entry)]
end
end
defp registered_name(name) when is_atom(name), do: [registered_name: name]
defp registered_name(_name), do: []
defp format_mfa(mod, fun, :undefined),
do: [inspect(mod), ?., Code.Identifier.inspect_as_function(fun) | "/?"]
defp format_mfa(mod, fun, args),
do: Exception.format_mfa(mod, fun, args)
defp exit_reason(:exit, reason, stack), do: {reason, stack}
defp exit_reason(:error, reason, stack), do: {reason, stack}
defp exit_reason(:throw, value, stack), do: {{:nocatch, value}, stack}
## Deprecated helpers
defp format_from([]), do: ""
defp format_from([from]), do: " (from #{inspect(from)})"
defp format_from([from, stacktrace]) when is_list(stacktrace), do: " (from #{inspect(from)})"
defp format_from([from, node_name]) when is_atom(node_name),
do: " (from #{inspect(from)} on #{inspect(node_name)})"
defp format_client([from]) do
"\nClient #{inspect(from)} is dead"
end
defp format_client([from, stacktrace]) when is_list(stacktrace) do
["\nClient #{inspect(from)} is alive\n" | format_stacktrace(stacktrace)]
end
defp format_client(_) do
[]
end
defp format_undef(mod, fun, arity, undef, stacktrace) do
opts = [module: mod, function: fun, arity: arity, reason: undef]
exception = UndefinedFunctionError.exception(opts)
{[?\n | Exception.format_banner(:error, exception, stacktrace)], exception}
end
end
| 31.820847 | 99 | 0.633535 |
03e57da984b4c4e4f7c6c0c29057fe3b3924dedd | 1,865 | ex | Elixir | clients/datastore/lib/google_api/datastore/v1/model/google_datastore_admin_v1beta1_export_entities_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/datastore/lib/google_api/datastore/v1/model/google_datastore_admin_v1beta1_export_entities_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/datastore/lib/google_api/datastore/v1/model/google_datastore_admin_v1beta1_export_entities_response.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.Datastore.V1.Model.GoogleDatastoreAdminV1beta1ExportEntitiesResponse do
@moduledoc """
The response for
google.datastore.admin.v1beta1.DatastoreAdmin.ExportEntities.
## Attributes
* `outputUrl` (*type:* `String.t`, *default:* `nil`) - Location of the output metadata file. This can be used to begin an import
into Cloud Datastore (this project or another project). See
google.datastore.admin.v1beta1.ImportEntitiesRequest.input_url.
Only present if the operation completed successfully.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:outputUrl => String.t()
}
field(:outputUrl)
end
defimpl Poison.Decoder,
for: GoogleApi.Datastore.V1.Model.GoogleDatastoreAdminV1beta1ExportEntitiesResponse do
def decode(value, options) do
GoogleApi.Datastore.V1.Model.GoogleDatastoreAdminV1beta1ExportEntitiesResponse.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Datastore.V1.Model.GoogleDatastoreAdminV1beta1ExportEntitiesResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.303571 | 132 | 0.756032 |
03e59e248d1e7896f9f8175d460589fb256cd66a | 82 | exs | Elixir | test/views/layout_view_test.exs | aaronvine/elm_recipes | bd68ddca0b22c7c773de1f80aa627bb58b759ccf | [
"MIT"
] | null | null | null | test/views/layout_view_test.exs | aaronvine/elm_recipes | bd68ddca0b22c7c773de1f80aa627bb58b759ccf | [
"MIT"
] | null | null | null | test/views/layout_view_test.exs | aaronvine/elm_recipes | bd68ddca0b22c7c773de1f80aa627bb58b759ccf | [
"MIT"
] | null | null | null | defmodule ElmRecipes.LayoutViewTest do
use ElmRecipes.ConnCase, async: true
end
| 20.5 | 38 | 0.829268 |
03e5c3484e68ea2a2263fd019d4bc39522b27749 | 1,393 | ex | Elixir | apps/admin_api/lib/admin_api/v1/channels/transaction_consumption_channel.ex | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 322 | 2018-02-28T07:38:44.000Z | 2020-05-27T23:09:55.000Z | apps/admin_api/lib/admin_api/v1/channels/transaction_consumption_channel.ex | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 643 | 2018-02-28T12:05:20.000Z | 2020-05-22T08:34:38.000Z | apps/admin_api/lib/admin_api/v1/channels/transaction_consumption_channel.ex | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 63 | 2018-02-28T10:57:06.000Z | 2020-05-27T23:10:38.000Z | # Copyright 2018-2019 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# credo:disable-for-this-file
defmodule AdminAPI.V1.TransactionConsumptionChannel do
@moduledoc """
Represents the transaction consumption channel.
"""
use Phoenix.Channel, async: false
alias EWalletDB.TransactionConsumption
alias EWallet.TransactionConsumptionPolicy
def join(
"transaction_consumption:" <> consumption_id,
_params,
%{
assigns: %{auth: auth}
} = socket
) do
with %TransactionConsumption{} = consumption <-
TransactionConsumption.get(consumption_id, preload: [:account, :wallet]),
{:ok, _} <- TransactionConsumptionPolicy.authorize(:listen, auth, consumption) do
{:ok, socket}
else
_ -> {:error, :forbidden_channel}
end
end
def join(_, _, _), do: {:error, :invalid_parameter}
end
| 33.166667 | 90 | 0.706389 |
03e5c70fda9628f0806139cdb48c8da39ef755c7 | 2,716 | ex | Elixir | lib/mix/lib/mix/tasks/local.hex.ex | liveforeverx/elixir | cf3cf0bd5443b59206e5733602244bc3543f0a53 | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/tasks/local.hex.ex | liveforeverx/elixir | cf3cf0bd5443b59206e5733602244bc3543f0a53 | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/tasks/local.hex.ex | liveforeverx/elixir | cf3cf0bd5443b59206e5733602244bc3543f0a53 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Local.Hex do
use Mix.Task
@hex_s3 "https://s3.amazonaws.com/s3.hex.pm"
@hex_list_url @hex_s3 <> "/installs/list.csv"
@hex_archive_url @hex_s3 <> "/installs/[VERSION]/hex.ez"
@hex_requirement ">= 0.5.0"
@shortdoc "Install hex locally"
@moduledoc """
Install Hex locally.
mix local.hex
## Command line options
* `--force` - forces installation without a shell prompt; primarily
intended for automation in build systems like make
"""
@spec run(OptionParser.argv) :: boolean
def run(args) do
version = get_matching_version()
url = String.replace(@hex_archive_url, "[VERSION]", version)
Mix.Tasks.Archive.Install.run [url, "--shell" | args]
end
@doc false
# Returns true if Hex is loaded or installed, otherwise returns false.
@spec ensure_installed?(atom) :: boolean
def ensure_installed?(app) do
if Code.ensure_loaded?(Hex) do
true
else
shell = Mix.shell
shell.info "Could not find hex, which is needed to build dependency #{inspect app}"
if shell.yes?("Shall I install hex?") do
run ["--force"]
else
false
end
end
end
@doc false
# Returns true if have required Hex, returns false if don't and don't update,
# if update then exits.
@spec ensure_updated?() :: boolean
def ensure_updated?() do
if Code.ensure_loaded?(Hex) do
if Version.match?(Hex.version, @hex_requirement) do
true
else
Mix.shell.info "Mix requires hex #{@hex_requirement} but you have #{Hex.version}"
if Mix.shell.yes?("Shall I abort the current command and update hex?") do
run ["--force"]
exit({:shutdown, 0})
end
false
end
else
false
end
end
@doc false
def start do
try do
Hex.start
catch
kind, reason ->
stacktrace = System.stacktrace
Mix.shell.error "Could not start Hex. Try fetching a new version with " <>
"`mix local.hex` or uninstalling it with `mix archive.uninstall hex.ez`"
:erlang.raise(kind, reason, stacktrace)
end
end
defp get_matching_version do
Mix.Utils.read_path!(@hex_list_url)
|> parse_csv
|> all_eligibile_versions
|> List.last
end
defp parse_csv(body) do
:binary.split(body, "\n", [:global, :trim])
|> Enum.flat_map(fn line ->
[_hex|elixirs] = :binary.split(line, ",", [:global, :trim])
elixirs
end)
|> Enum.uniq
end
defp all_eligibile_versions(versions) do
{:ok, current_version} = Version.parse(System.version)
Enum.filter(versions, &Version.compare(&1, current_version) != :gt)
end
end
| 26.115385 | 96 | 0.627761 |
03e5cad6c4ad24bddaf73a5f5945d85150db432d | 1,660 | exs | Elixir | config/config.exs | drowzy/massa | 624cb02e0039b0624c534636f96fd157b1e34a95 | [
"Apache-2.0"
] | 5 | 2021-04-21T22:26:04.000Z | 2021-11-08T12:00:24.000Z | config/config.exs | drowzy/massa | 624cb02e0039b0624c534636f96fd157b1e34a95 | [
"Apache-2.0"
] | 16 | 2021-11-01T08:19:03.000Z | 2022-03-30T08:17:43.000Z | config/config.exs | drowzy/massa | 624cb02e0039b0624c534636f96fd157b1e34a95 | [
"Apache-2.0"
] | null | null | null | import Config
# Our Logger general configuration
config :logger,
backends: [:console],
truncate: 65536,
compile_time_purge_matching: [
[level_lower_than: :debug]
]
config :protobuf, extensions: :enabled
# Our Console Backend-specific configuration
config :logger, :console,
format: "$date $time [$node]:[$metadata]:[$level]:$levelpad$message\n",
metadata: [:pid]
config :injectx, Injectx,
context: %{
bindings: [
%{
behavior: MassaProxy.Infra.Config,
definitions: [%{module: MassaProxy.Infra.Config.Vapor, default: true, name: nil}]
},
%{
behavior: MassaProxy.Runtime,
definitions: [
%{module: MassaProxy.Runtime.Grpc, default: true, name: nil},
%{module: MassaProxy.Runtime.Wasm, default: false, name: nil}
]
}
]
}
# OpenTracing configs
config :otter,
zipkin_collector_uri: 'http://127.0.0.1:9411/api/v1/spans',
zipkin_tag_host_service: "massa_proxy",
http_client: :hackney
# Proxy configuration
config :massa_proxy,
proxy_port: System.get_env("PROXY_PORT") || 9000,
proxy_http_port: System.get_env("PROXY_HTTP_PORT") || 9001,
user_function_host: System.get_env("USER_FUNCTION_HOST") || "127.0.0.1",
user_function_port: System.get_env("USER_FUNCTION_PORT") || 8080,
user_function_uds_enable: System.get_env("PROXY_UDS_MODE") || false,
user_function_sock_addr: System.get_env("PROXY_UDS_ADDRESS") || "/var/run/cloudstate.sock",
heartbeat_interval: System.get_env("PROXY_HEARTBEAT_INTERVAL") || 240_000
config :massa_proxy, MassaProxy.Infra.Cache.Modules,
primary: [
gc_interval: 3_600_000,
backend: :shards
]
| 29.642857 | 93 | 0.695181 |
03e608b2b5d0fd6ddd728d4a2da7a0f980c88c5f | 656 | ex | Elixir | deps/absinthe/lib/absinthe/language/union_type_definition.ex | JoakimEskils/elixir-absinthe | d81e24ec7c7b1164e6d152101dd50422f192d7e9 | [
"MIT"
] | 3 | 2017-06-22T16:33:58.000Z | 2021-07-07T15:21:09.000Z | lib/absinthe/language/union_type_definition.ex | bruce/absinthe | 19b63d3aaa9fb75aad01ffd5e91d89e0b30d7f91 | [
"MIT"
] | null | null | null | lib/absinthe/language/union_type_definition.ex | bruce/absinthe | 19b63d3aaa9fb75aad01ffd5e91d89e0b30d7f91 | [
"MIT"
] | null | null | null | defmodule Absinthe.Language.UnionTypeDefinition do
@moduledoc false
alias Absinthe.{Blueprint, Language}
defstruct [
name: nil,
directives: [],
types: [],
loc: %{start_line: nil}
]
@type t :: %__MODULE__{
name: String.t,
directives: [Language.Directive.t],
types: [Language.NamedType.t],
loc: Language.loc_t
}
defimpl Blueprint.Draft do
def convert(node, doc) do
%Blueprint.Schema.UnionTypeDefinition{
name: node.name,
types: Absinthe.Blueprint.Draft.convert(node.types, doc),
directives: Absinthe.Blueprint.Draft.convert(node.directives, doc),
}
end
end
end
| 21.16129 | 75 | 0.653963 |
03e631b4419be075f1df755a770a33f47695b0c7 | 216 | ex | Elixir | test/support/phoenix/views/error_view.ex | patrickbiermann/pow | ebc2ac7d6e15961dac4be38091ff75dae0d26554 | [
"MIT"
] | 4 | 2018-05-07T16:37:15.000Z | 2018-07-14T00:44:12.000Z | test/support/phoenix/views/error_view.ex | patrickbiermann/pow | ebc2ac7d6e15961dac4be38091ff75dae0d26554 | [
"MIT"
] | null | null | null | test/support/phoenix/views/error_view.ex | patrickbiermann/pow | ebc2ac7d6e15961dac4be38091ff75dae0d26554 | [
"MIT"
] | 1 | 2020-07-13T01:11:17.000Z | 2020-07-13T01:11:17.000Z | defmodule Pow.Test.Phoenix.ErrorView do
@moduledoc false
def render("500.html", _assigns), do: "500.html"
def render("400.html", _assigns), do: "400.html"
def render("404.html", _assigns), do: "404.html"
end
| 30.857143 | 50 | 0.694444 |
03e637a40a404aac070252785b889efeeef17e82 | 1,778 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_telephony_transfer_call.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_telephony_transfer_call.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_telephony_transfer_call.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2021-03-04T13:43:47.000Z | 2021-03-04T13:43:47.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.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageTelephonyTransferCall do
@moduledoc """
Transfers the call in Telephony Gateway.
## Attributes
* `phoneNumber` (*type:* `String.t`, *default:* `nil`) - Required. The phone number to transfer the call to in [E.164 format](https://en.wikipedia.org/wiki/E.164). We currently only allow transferring to US numbers (+1xxxyyyzzzz).
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:phoneNumber => String.t()
}
field(:phoneNumber)
end
defimpl Poison.Decoder,
for:
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageTelephonyTransferCall do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageTelephonyTransferCall.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageTelephonyTransferCall do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.925926 | 234 | 0.755906 |
03e64a4fe30c00942297dabfd19631fc551fb8d2 | 830 | ex | Elixir | lib/day_02_inventory_management_system_part_two.ex | scmx/advent-of-code-2018-elixir | bad5a125fdc98519c29cbca1e5b7f64d61da5869 | [
"MIT"
] | 2 | 2019-01-16T16:10:31.000Z | 2019-05-14T04:41:15.000Z | lib/day_02_inventory_management_system_part_two.ex | scmx/advent-of-code-2018-elixir | bad5a125fdc98519c29cbca1e5b7f64d61da5869 | [
"MIT"
] | null | null | null | lib/day_02_inventory_management_system_part_two.ex | scmx/advent-of-code-2018-elixir | bad5a125fdc98519c29cbca1e5b7f64d61da5869 | [
"MIT"
] | 1 | 2019-01-02T18:13:23.000Z | 2019-01-02T18:13:23.000Z | defmodule Adventofcode.Day02InventoryManagementSystem.PartTwo do
use Adventofcode
def common_letters(input) do
input
|> String.split("\n")
|> do_common_letters
|> hd
end
def do_common_letters(box_ids) do
for a <- box_ids, b <- box_ids, off_by_one?(a, b) do
common(a, b)
end
end
defp off_by_one?(a, b) do
diff(a, b) == 1
end
defp diff(a, b) do
[a, b]
|> Enum.map(&String.graphemes/1)
|> transpose
|> Enum.reject(fn [a, b] -> a == b end)
|> Enum.count()
end
defp common(a, b) do
[a, b]
|> Enum.map(&String.graphemes/1)
|> transpose
|> Enum.filter(fn [a, b] -> a == b end)
|> Enum.map(&hd/1)
|> Enum.join("")
end
def transpose(list_of_lists) do
list_of_lists
|> List.zip()
|> Enum.map(&Tuple.to_list/1)
end
end
| 18.863636 | 64 | 0.578313 |
03e64dff88fd6fca119058c1c00fe87e2b95bb3e | 1,425 | ex | Elixir | lib/reuse/application.ex | riccardofelluga/reuse-checker | c57b824141ff28a05b8c065b401bbdae178f0259 | [
"MIT"
] | 2 | 2018-09-01T17:38:39.000Z | 2018-09-20T13:47:50.000Z | lib/reuse/application.ex | riccardofelluga/reuse-checker | c57b824141ff28a05b8c065b401bbdae178f0259 | [
"MIT"
] | null | null | null | lib/reuse/application.ex | riccardofelluga/reuse-checker | c57b824141ff28a05b8c065b401bbdae178f0259 | [
"MIT"
] | null | null | null | #
# Copyright (c) 2018 Andrea Janes <ajanes@unibz.it>, Riccardo Felluga <riccardo.felluga@stud-inf.unibz.it>, Max Schweigkofler <maxelia.schweigkofler@stud-inf.unibz.it>
#
# This file is part of the project reuse-checker which is released under the MIT license.
# See file LICENSE or go to https://github.com/riccardofelluga/reuse-checker for full license details.
#
# SPDX-License-Identifier: MIT
#
defmodule Reuse.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, warn: false
# Define workers and child supervisors to be supervised
children = [
# Start the Ecto repository
supervisor(Reuse.Repo, []),
# Start the endpoint when the application starts
supervisor(ReuseWeb.Endpoint, [])
# Start your own worker by calling: Reuse.Worker.start_link(arg1, arg2, arg3)
# worker(Reuse.Worker, [arg1, arg2, arg3]),
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Reuse.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
ReuseWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 34.756098 | 167 | 0.725614 |
03e65807d7dff3a5edb90cab0ccfcf192ef095b9 | 1,283 | exs | Elixir | config/prod.exs | aortbals/chatter | a0ac7af7a8bca66d183b0f51320f269066171199 | [
"MIT"
] | null | null | null | config/prod.exs | aortbals/chatter | a0ac7af7a8bca66d183b0f51320f269066171199 | [
"MIT"
] | null | null | null | config/prod.exs | aortbals/chatter | a0ac7af7a8bca66d183b0f51320f269066171199 | [
"MIT"
] | null | null | null | use Mix.Config
# For production, we configure the host to read the PORT
# from the system environment. Therefore, you will need
# to set PORT=80 before running your server.
#
# You should also configure the url host to something
# meaningful, we use this information when generating URLs.
config :chatter, Chatter.Endpoint,
http: [port: {:system, "PORT"}],
url: [host: "example.com"]
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section:
#
# config:chatter, Chatter.Endpoint,
# ...
# https: [port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables point to a file on
# disk for the key and cert.
# Do not print debug messages in production
config :logger, level: :info
# ## 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 :chatter, Chatter.Endpoint, server: true
#
# Finally import the config/prod.secret.exs
# which should be versioned separately.
import_config "prod.secret.exs"
| 27.891304 | 64 | 0.715511 |
03e671fd44b85f084d8ef167f75b55bef0d9f585 | 1,842 | ex | Elixir | clients/street_view_publish/lib/google_api/street_view_publish/v1/model/lat_lng.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/street_view_publish/lib/google_api/street_view_publish/v1/model/lat_lng.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/street_view_publish/lib/google_api/street_view_publish/v1/model/lat_lng.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.StreetViewPublish.V1.Model.LatLng do
@moduledoc """
An object that represents a latitude/longitude pair. This is expressed as a pair of doubles to represent degrees latitude and degrees longitude. Unless specified otherwise, this object must conform to the WGS84 standard. Values must be within normalized ranges.
## Attributes
* `latitude` (*type:* `float()`, *default:* `nil`) - The latitude in degrees. It must be in the range [-90.0, +90.0].
* `longitude` (*type:* `float()`, *default:* `nil`) - The longitude in degrees. It must be in the range [-180.0, +180.0].
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:latitude => float() | nil,
:longitude => float() | nil
}
field(:latitude)
field(:longitude)
end
defimpl Poison.Decoder, for: GoogleApi.StreetViewPublish.V1.Model.LatLng do
def decode(value, options) do
GoogleApi.StreetViewPublish.V1.Model.LatLng.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.StreetViewPublish.V1.Model.LatLng do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.84 | 263 | 0.725841 |
03e68771a02cbdbdcca8fb78df9685083d77d191 | 40,755 | ex | Elixir | clients/android_enterprise/lib/google_api/android_enterprise/v1/api/enterprises.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/android_enterprise/lib/google_api/android_enterprise/v1/api/enterprises.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/android_enterprise/lib/google_api/android_enterprise/v1/api/enterprises.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"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.AndroidEnterprise.V1.Api.Enterprises do
@moduledoc """
API calls for all endpoints tagged `Enterprises`.
"""
alias GoogleApi.AndroidEnterprise.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Acknowledges notifications that were received from Enterprises.PullNotificationSet to prevent subsequent calls from returning the same notifications.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :notificationSetId (String.t): The notification set ID as returned by Enterprises.PullNotificationSet. This must be provided.
## Returns
{:ok, %{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_acknowledge_notification_set(Tesla.Env.client(), keyword()) ::
{:ok, nil} | {:error, Tesla.Env.t()}
def androidenterprise_enterprises_acknowledge_notification_set(connection, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:notificationSetId => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/enterprises/acknowledgeNotificationSet")
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(decode: false)
end
@doc """
Completes the signup flow, by specifying the Completion token and Enterprise token. This request must not be called multiple times for a given Enterprise Token.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :completionToken (String.t): The Completion token initially returned by GenerateSignupUrl.
- :enterpriseToken (String.t): The Enterprise token appended to the Callback URL.
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.Enterprise{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_complete_signup(Tesla.Env.client(), keyword()) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.Enterprise.t()} | {:error, Tesla.Env.t()}
def androidenterprise_enterprises_complete_signup(connection, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:completionToken => :query,
:enterpriseToken => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/enterprises/completeSignup")
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.Enterprise{})
end
@doc """
Returns a unique token to access an embeddable UI. To generate a web UI, pass the generated token into the managed Google Play javascript API. Each token may only be used to start one UI session. See the javascript API documentation for further information.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- enterprise_id (String.t): The ID of the enterprise.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (AdministratorWebTokenSpec):
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebToken{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_create_web_token(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebToken.t()}
| {:error, Tesla.Env.t()}
def androidenterprise_enterprises_create_web_token(connection, enterprise_id, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/enterprises/{enterpriseId}/createWebToken", %{
"enterpriseId" => URI.encode_www_form(enterprise_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebToken{})
end
@doc """
Deletes the binding between the EMM and enterprise. This is now deprecated. Use this method only to unenroll customers that were previously enrolled with the insert call, then enroll them again with the enroll call.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- enterprise_id (String.t): The ID of the enterprise.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_delete(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, nil} | {:error, Tesla.Env.t()}
def androidenterprise_enterprises_delete(connection, enterprise_id, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/enterprises/{enterpriseId}", %{
"enterpriseId" => URI.encode_www_form(enterprise_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(decode: false)
end
@doc """
Enrolls an enterprise with the calling EMM.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- token (String.t): The token provided by the enterprise to register the EMM.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (Enterprise):
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.Enterprise{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_enroll(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.Enterprise.t()} | {:error, Tesla.Env.t()}
def androidenterprise_enterprises_enroll(connection, token, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/enterprises/enroll")
|> Request.add_param(:query, :token, token)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.Enterprise{})
end
@doc """
Generates a sign-up URL.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :callbackUrl (String.t): The callback URL to which the Admin will be redirected after successfully creating an enterprise. Before redirecting there the system will add a single query parameter to this URL named \"enterpriseToken\" which will contain an opaque token to be used for the CompleteSignup request. Beware that this means that the URL will be parsed, the parameter added and then a new URL formatted, i.e. there may be some minor formatting changes and, more importantly, the URL must be well-formed so that it can be parsed.
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.SignupInfo{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_generate_signup_url(Tesla.Env.client(), keyword()) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.SignupInfo.t()} | {:error, Tesla.Env.t()}
def androidenterprise_enterprises_generate_signup_url(connection, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:callbackUrl => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/enterprises/signupUrl")
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.SignupInfo{})
end
@doc """
Retrieves the name and domain of an enterprise.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- enterprise_id (String.t): The ID of the enterprise.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.Enterprise{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_get(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.Enterprise.t()} | {:error, Tesla.Env.t()}
def androidenterprise_enterprises_get(connection, enterprise_id, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/enterprises/{enterpriseId}", %{
"enterpriseId" => URI.encode_www_form(enterprise_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.Enterprise{})
end
@doc """
Deprecated and unused.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- enterprise_id (String.t): The ID of the enterprise.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.AndroidDevicePolicyConfig{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_get_android_device_policy_config(
Tesla.Env.client(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.AndroidDevicePolicyConfig.t()}
| {:error, Tesla.Env.t()}
def androidenterprise_enterprises_get_android_device_policy_config(
connection,
enterprise_id,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/enterprises/{enterpriseId}/androidDevicePolicyConfig", %{
"enterpriseId" => URI.encode_www_form(enterprise_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.AndroidDevicePolicyConfig{})
end
@doc """
Returns a service account and credentials. The service account can be bound to the enterprise by calling setAccount. The service account is unique to this enterprise and EMM, and will be deleted if the enterprise is unbound. The credentials contain private key data and are not stored server-side. This method can only be called after calling Enterprises.Enroll or Enterprises.CompleteSignup, and before Enterprises.SetAccount; at other times it will return an error. Subsequent calls after the first will generate a new, unique set of credentials, and invalidate the previously generated credentials. Once the service account is bound to the enterprise, it can be managed using the serviceAccountKeys resource.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- enterprise_id (String.t): The ID of the enterprise.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :keyType (String.t): The type of credential to return with the service account. Required.
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.ServiceAccount{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_get_service_account(
Tesla.Env.client(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.ServiceAccount.t()} | {:error, Tesla.Env.t()}
def androidenterprise_enterprises_get_service_account(connection, enterprise_id, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:keyType => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/enterprises/{enterpriseId}/serviceAccount", %{
"enterpriseId" => URI.encode_www_form(enterprise_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.ServiceAccount{})
end
@doc """
Returns the store layout for the enterprise. If the store layout has not been set, returns \"basic\" as the store layout type and no homepage.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- enterprise_id (String.t): The ID of the enterprise.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.StoreLayout{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_get_store_layout(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.StoreLayout.t()} | {:error, Tesla.Env.t()}
def androidenterprise_enterprises_get_store_layout(connection, enterprise_id, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/enterprises/{enterpriseId}/storeLayout", %{
"enterpriseId" => URI.encode_www_form(enterprise_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.StoreLayout{})
end
@doc """
Establishes the binding between the EMM and an enterprise. This is now deprecated; use enroll instead.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- token (String.t): The token provided by the enterprise to register the EMM.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (Enterprise):
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.Enterprise{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_insert(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.Enterprise.t()} | {:error, Tesla.Env.t()}
def androidenterprise_enterprises_insert(connection, token, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/enterprises")
|> Request.add_param(:query, :token, token)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.Enterprise{})
end
@doc """
Looks up an enterprise by domain name. This is only supported for enterprises created via the Google-initiated creation flow. Lookup of the id is not needed for enterprises created via the EMM-initiated flow since the EMM learns the enterprise ID in the callback specified in the Enterprises.generateSignupUrl call.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- domain (String.t): The exact primary domain name of the enterprise to look up.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.EnterprisesListResponse{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.EnterprisesListResponse.t()}
| {:error, Tesla.Env.t()}
def androidenterprise_enterprises_list(connection, domain, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/enterprises")
|> Request.add_param(:query, :domain, domain)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.EnterprisesListResponse{})
end
@doc """
Pulls and returns a notification set for the enterprises associated with the service account authenticated for the request. The notification set may be empty if no notification are pending. A notification set returned needs to be acknowledged within 20 seconds by calling Enterprises.AcknowledgeNotificationSet, unless the notification set is empty. Notifications that are not acknowledged within the 20 seconds will eventually be included again in the response to another PullNotificationSet request, and those that are never acknowledged will ultimately be deleted according to the Google Cloud Platform Pub/Sub system policy. Multiple requests might be performed concurrently to retrieve notifications, in which case the pending notifications (if any) will be split among each caller, if any are pending. If no notifications are present, an empty notification list is returned. Subsequent requests may return more notifications once they become available.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestMode (String.t): The request mode for pulling notifications. Specifying waitForNotifications will cause the request to block and wait until one or more notifications are present, or return an empty notification list if no notifications are present after some time. Speciying returnImmediately will cause the request to immediately return the pending notifications, or an empty list if no notifications are present. If omitted, defaults to waitForNotifications.
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.NotificationSet{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_pull_notification_set(Tesla.Env.client(), keyword()) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.NotificationSet.t()}
| {:error, Tesla.Env.t()}
def androidenterprise_enterprises_pull_notification_set(connection, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestMode => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/enterprises/pullNotificationSet")
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.NotificationSet{})
end
@doc """
Sends a test notification to validate the EMM integration with the Google Cloud Pub/Sub service for this enterprise.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- enterprise_id (String.t): The ID of the enterprise.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.EnterprisesSendTestPushNotificationResponse{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_send_test_push_notification(
Tesla.Env.client(),
String.t(),
keyword()
) ::
{:ok,
GoogleApi.AndroidEnterprise.V1.Model.EnterprisesSendTestPushNotificationResponse.t()}
| {:error, Tesla.Env.t()}
def androidenterprise_enterprises_send_test_push_notification(
connection,
enterprise_id,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/enterprises/{enterpriseId}/sendTestPushNotification", %{
"enterpriseId" => URI.encode_www_form(enterprise_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(
struct: %GoogleApi.AndroidEnterprise.V1.Model.EnterprisesSendTestPushNotificationResponse{}
)
end
@doc """
Sets the account that will be used to authenticate to the API as the enterprise.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- enterprise_id (String.t): The ID of the enterprise.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (EnterpriseAccount):
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.EnterpriseAccount{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_set_account(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.EnterpriseAccount.t()}
| {:error, Tesla.Env.t()}
def androidenterprise_enterprises_set_account(connection, enterprise_id, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/enterprises/{enterpriseId}/account", %{
"enterpriseId" => URI.encode_www_form(enterprise_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.EnterpriseAccount{})
end
@doc """
Deprecated and unused.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- enterprise_id (String.t): The ID of the enterprise.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (AndroidDevicePolicyConfig):
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.AndroidDevicePolicyConfig{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_set_android_device_policy_config(
Tesla.Env.client(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.AndroidDevicePolicyConfig.t()}
| {:error, Tesla.Env.t()}
def androidenterprise_enterprises_set_android_device_policy_config(
connection,
enterprise_id,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/enterprises/{enterpriseId}/androidDevicePolicyConfig", %{
"enterpriseId" => URI.encode_www_form(enterprise_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.AndroidDevicePolicyConfig{})
end
@doc """
Sets the store layout for the enterprise. By default, storeLayoutType is set to \"basic\" and the basic store layout is enabled. The basic layout only contains apps approved by the admin, and that have been added to the available product set for a user (using the setAvailableProductSet call). Apps on the page are sorted in order of their product ID value. If you create a custom store layout (by setting storeLayoutType = \"custom\" and setting a homepage), the basic store layout is disabled.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- enterprise_id (String.t): The ID of the enterprise.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (StoreLayout):
## Returns
{:ok, %GoogleApi.AndroidEnterprise.V1.Model.StoreLayout{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_set_store_layout(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.AndroidEnterprise.V1.Model.StoreLayout.t()} | {:error, Tesla.Env.t()}
def androidenterprise_enterprises_set_store_layout(connection, enterprise_id, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/enterprises/{enterpriseId}/storeLayout", %{
"enterpriseId" => URI.encode_www_form(enterprise_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.AndroidEnterprise.V1.Model.StoreLayout{})
end
@doc """
Unenrolls an enterprise from the calling EMM.
## Parameters
- connection (GoogleApi.AndroidEnterprise.V1.Connection): Connection to server
- enterprise_id (String.t): The ID of the enterprise.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %{}} on success
{:error, info} on failure
"""
@spec androidenterprise_enterprises_unenroll(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, nil} | {:error, Tesla.Env.t()}
def androidenterprise_enterprises_unenroll(connection, enterprise_id, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/enterprises/{enterpriseId}/unenroll", %{
"enterpriseId" => URI.encode_www_form(enterprise_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(decode: false)
end
end
| 44.298913 | 960 | 0.692872 |
03e6b8b86fd28c619373613f74352637acda2008 | 5,042 | exs | Elixir | test/unit/changeset/hash_password_test.exs | lumenlunae/sentinel | 189d9b02aeeea942a41963b42ef8523ef192fd03 | [
"MIT"
] | null | null | null | test/unit/changeset/hash_password_test.exs | lumenlunae/sentinel | 189d9b02aeeea942a41963b42ef8523ef192fd03 | [
"MIT"
] | null | null | null | test/unit/changeset/hash_password_test.exs | lumenlunae/sentinel | 189d9b02aeeea942a41963b42ef8523ef192fd03 | [
"MIT"
] | null | null | null | defmodule HashPasswordTest do
use Sentinel.UnitCase
alias Mix.Config
alias Sentinel.Changeset.HashPassword
setup do
password = "password"
matching = %{
credentials: %{
other: %{
password: password,
password_confirmation: password
}
}
}
mismatch = %{
credentials: %{
other: %{
password: password,
password_confirmation: "wrong password"
}
}
}
no_confirmation = %{
credentials: %{
other: %{
password: password
}
}
}
no_password = %{
credentials: %{
other: %{}
}
}
{:ok,
%{
matching: matching,
mismatch: mismatch,
no_confirmation: no_confirmation,
no_password: no_password
}}
end
test "it should return a valid changeset with a hashed password when password and confirmation are present and match",
%{matching: params} do
assert %Sentinel.Ueberauth{}
|> Ecto.Changeset.cast(%{}, [
:provider,
:uid,
:expires_at,
:hashed_password,
:hashed_password_reset_token,
:user_id
])
|> HashPassword.changeset(params)
|> Map.get(:valid?)
end
test "it should return an invalid changeset without a hashed password when password and confirmation are present and match, and errors are already present",
%{matching: params} do
refute %Sentinel.Ueberauth{}
|> Ecto.Changeset.cast(%{}, [
:provider,
:uid,
:expires_at,
:hashed_password,
:hashed_password_reset_token,
:user_id
])
|> Ecto.Changeset.add_error(:misc, "doesn't matter what this is")
|> HashPassword.changeset(params)
|> Map.get(:changes)
|> Map.get(:hashed_password, false)
end
test "on creation it should return an invalid changeset when password and password confirmation do not match, and invitable is disabled",
%{mismatch: params} do
Application.put_env(:sentinel, :invitable, false)
refute %Sentinel.Ueberauth{}
|> Ecto.Changeset.cast(%{}, [
:provider,
:uid,
:expires_at,
:hashed_password,
:hashed_password_reset_token,
:user_id
])
|> HashPassword.changeset(params)
|> Map.get(:valid?)
end
test "on update it should return a valid changeset when password and password confirmation do not match",
%{mismatch: params} do
assert %Sentinel.Ueberauth{id: 1}
|> Ecto.Changeset.cast(%{}, [
:provider,
:uid,
:expires_at,
:hashed_password,
:hashed_password_reset_token,
:user_id
])
|> HashPassword.changeset(params)
|> Map.get(:valid?)
end
test "it should return a valid changeset when password and password confirmation do not match and invitable module is enabled, and user is being created",
%{mismatch: params} do
Application.put_env(:sentinel, :invitable, true)
assert %Sentinel.Ueberauth{}
|> Ecto.Changeset.cast(%{}, [
:provider,
:uid,
:expires_at,
:hashed_password,
:hashed_password_reset_token,
:user_id
])
|> HashPassword.changeset(params)
|> Map.get(:valid?)
end
test "it should return an invalid changest when password is absent when invitable is disabled",
%{no_password: params} do
Application.put_env(:sentinel, :invitable, false)
refute %Sentinel.Ueberauth{}
|> Ecto.Changeset.cast(%{}, [
:provider,
:uid,
:expires_at,
:hashed_password,
:hashed_password_reset_token,
:user_id
])
|> HashPassword.changeset(params)
|> Map.get(:valid?)
end
test "on update it should return an invalid changest when password is absent an ueberauth struct",
%{no_confirmation: params} do
refute %Sentinel.Ueberauth{id: 1}
|> Ecto.Changeset.cast(%{}, [
:provider,
:uid,
:expires_at,
:hashed_password,
:hashed_password_reset_token,
:user_id
])
|> HashPassword.changeset(params)
|> Map.get(:valid?)
end
test "it should return a valid changeset if changes are unrelated to password", %{
no_password: params
} do
assert %Sentinel.Ueberauth{id: 1}
|> Ecto.Changeset.cast(%{}, [
:provider,
:uid,
:expires_at,
:hashed_password,
:hashed_password_reset_token,
:user_id
])
|> HashPassword.changeset(params)
|> Map.get(:valid?)
end
end
| 28.011111 | 158 | 0.545815 |
03e6c502b4a01361c2acceebbd8dc9fff9399f16 | 2,304 | ex | Elixir | lib/weber/handler/weber_req_handler_result.ex | Mendor/weber | 3c4fceff2bc6cf6ce38138b7e1c042c3f2536221 | [
"MIT"
] | 1 | 2018-02-21T07:56:22.000Z | 2018-02-21T07:56:22.000Z | lib/weber/handler/weber_req_handler_result.ex | Mendor/weber | 3c4fceff2bc6cf6ce38138b7e1c042c3f2536221 | [
"MIT"
] | null | null | null | lib/weber/handler/weber_req_handler_result.ex | Mendor/weber | 3c4fceff2bc6cf6ce38138b7e1c042c3f2536221 | [
"MIT"
] | null | null | null | defmodule Handler.WeberReqHandler.Result do
@moduledoc """
This module provides the handle result
"""
import Weber.Utils
require Weber.Helper.ContentFor
defrecord App,
controller: nil,
views: nil
@doc "Handle response from controller"
def handle_result(res, controller // nil, views // nil) do
app = App.new controller: controller, views: views
request(res, app)
end
defp request({:render, data, headers}, app) do
filename = atom_to_list(app.controller)
|> :string.tokens('.')
|> List.last
|> :lists.append(".html")
|> :erlang.list_to_binary
|> String.downcase
|> :erlang.binary_to_list
{:ok, file_content} = File.read(:lists.nth(1, find_file_path(get_all_files(app.views), filename)))
Weber.Helper.ContentFor.content_for(:layout, app.controller.__layout__)
{:render, 200, (EEx.eval_string add_helpers_imports(file_content), data), headers}
end
defp request({:render_other, filename, headers}, app) do
{:ok, file_content} = File.read(:lists.nth(1, find_file_path(get_all_files(app.views), filename)))
Weber.Helper.ContentFor.content_for(:layout, app.controller.__layout__)
{:render, 200, (EEx.eval_string add_helpers_imports(file_content), []), headers}
end
defp request({:render_inline, data, params, headers}, _app) do
{:render, 200, (EEx.eval_string data, params), headers}
end
defp request({:file, path, headers}, _app) do
{:ok, file_content} = File.read(path)
{:file, 200, file_content, :lists.append([{"Content-Type", :mimetypes.filename(path)}], headers)}
end
defp request({:redirect, location}, _app) do
{:redirect, 301, [{"Location", location}, {"Cache-Control", "no-store"}]}
end
defp request({:nothing, headers}, _app) do
{:nothing, 200, headers}
end
defp request({:text, data, headers}, _app) do
{:text, 200, data, :lists.append([{"Content-Type", "plain/text"}], headers)}
end
defp request({:json, data, headers}, _app) do
{:json, 200, JSON.generate(data), :lists.append([{"Content-Type", "application/json"}], headers)}
end
defp request({:not_found, data, _headers}, _app) do
{:not_found, 404, data, [{"Content-Type", "text/html"}]}
end
end | 34.909091 | 102 | 0.652778 |
03e7093899e05f32738cfbf44f37363c97858b50 | 472 | ex | Elixir | server/lib/chat/application.ex | ludovicm67/poc-chat | dd710b36d6dee7b009bdc98f8cb911ed601583d3 | [
"MIT"
] | null | null | null | server/lib/chat/application.ex | ludovicm67/poc-chat | dd710b36d6dee7b009bdc98f8cb911ed601583d3 | [
"MIT"
] | null | null | null | server/lib/chat/application.ex | ludovicm67/poc-chat | dd710b36d6dee7b009bdc98f8cb911ed601583d3 | [
"MIT"
] | null | null | null | defmodule Chat.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
port = Application.fetch_env!(:chat, :port)
children = [
{Task.Supervisor, name: Chat.TaskSupervisor},
{Task, fn -> Chat.accept(port) end}
]
opts = [strategy: :one_for_one, name: Chat.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 23.6 | 58 | 0.688559 |
03e714d5d15e5ab232d3751fe78e4a9512119898 | 585 | exs | Elixir | test/test_helper.exs | securingsincity/molasses | a9758184c026fa69038a204c113934506929e9e7 | [
"MIT"
] | 76 | 2016-12-06T17:56:26.000Z | 2022-01-11T21:17:56.000Z | test/test_helper.exs | securingsincity/molasses | a9758184c026fa69038a204c113934506929e9e7 | [
"MIT"
] | 13 | 2017-01-05T10:22:51.000Z | 2017-02-05T03:05:25.000Z | test/test_helper.exs | securingsincity/molasses | a9758184c026fa69038a204c113934506929e9e7 | [
"MIT"
] | 4 | 2017-01-05T10:10:17.000Z | 2021-05-31T05:22:11.000Z | ExUnit.start()
defmodule Molasses.Test.Repo do
use Ecto.Repo, otp_app: :molasses
end
Mix.Task.run "ecto.drop", ["--quiet", "-r", "Molasses.Test.Repo"]
Mix.Task.run "ecto.create", ["--quiet", "-r", "Molasses.Test.Repo"]
Molasses.Test.Repo.start_link
# Ecto.Adapters.SQL.begin_test_transaction(Molasses.Test.Repo)
Mix.Task.run "ecto.migrate", ["--quiet", "-r", "Molasses.Test.Repo"]
Code.require_file "./support/router.exs", __DIR__
Code.require_file "./support/endpoint.exs", __DIR__
Code.require_file "./support/view.exs", __DIR__
{:ok, _pid} = Molasses.Test.Endpoint.start_link | 32.5 | 68 | 0.724786 |
03e725fd751d84c980170d31d9bae824a49c169b | 2,489 | ex | Elixir | DL-5TM/DL-5TM.ex | Realscrat/decentlab-decoders | 3ca5006cd85e3772a15a1b3fff3922c50979eeb6 | [
"MIT"
] | 13 | 2020-01-18T22:08:44.000Z | 2022-02-06T14:19:57.000Z | DL-5TM/DL-5TM.ex | Realscrat/decentlab-decoders | 3ca5006cd85e3772a15a1b3fff3922c50979eeb6 | [
"MIT"
] | 4 | 2019-05-10T07:17:41.000Z | 2021-10-20T16:24:04.000Z | DL-5TM/DL-5TM.ex | Realscrat/decentlab-decoders | 3ca5006cd85e3772a15a1b3fff3922c50979eeb6 | [
"MIT"
] | 15 | 2019-06-04T06:13:32.000Z | 2022-02-15T07:28:52.000Z |
# https://www.decentlab.com/products/legacy-soil-moisture-and-temperature-sensor-for-lorawan
defmodule DecentlabDecoder do
@protocol_version 2
defp sensor_defs do
[
%{
length: 2,
values: [
%{
:name => "Dielectric permittivity",
:convert => fn x -> Enum.at(x, 0) / 50 end,
:unit => nil
},
%{
:name => "Volumetric water content",
:convert => fn x -> 0.0000043 * :math.pow(Enum.at(x, 0)/50, 3) - 0.00055 * :math.pow(Enum.at(x, 0)/50, 2) + 0.0292 * (Enum.at(x, 0)/50) - 0.053 end,
:unit => "m³⋅m⁻³"
},
%{
:name => "Soil temperature",
:convert => fn x -> (Enum.at(x, 1) - 400) / 10 end,
:unit => "°C"
}
]
},
%{
length: 1,
values: [
%{
:name => "Battery voltage",
:convert => fn x -> Enum.at(x, 0) / 1000 end,
:unit => "V"
}
]
}
]
end
def decode(msg, :hex) do
{:ok, bytes} = Base.decode16(msg, case: :mixed)
decode(bytes)
end
def decode(msg) when is_binary(msg), do: decode_binary(msg)
def decode(msg), do: to_string(msg) |> decode
defp decode_binary(<<@protocol_version, device_id::size(16), flags::binary-size(2), bytes::binary>>) do
bytes
|> bytes_to_words()
|> sensor(flags, sensor_defs())
|> Map.put("Device ID", device_id)
|> Map.put("Protocol version", @protocol_version)
end
defp bytes_to_words(<<>>), do: []
defp bytes_to_words(<<word::size(16), rest::binary>>), do: [word | bytes_to_words(rest)]
defp sensor(words, <<flags::size(15), 1::size(1)>>, [%{length: len, values: value_defs} | rest]) do
{x, rest_words} = Enum.split(words, len)
value(value_defs, x)
|> Map.merge(sensor(rest_words, <<0::size(1), flags::size(15)>>, rest))
end
defp sensor(words, <<flags::size(15), 0::size(1)>>, [_cur | rest]) do
sensor(words, <<0::size(1), flags::size(15)>>, rest)
end
defp sensor([], _flags, []), do: %{}
defp value([], _x), do: %{}
defp value([%{convert: nil} | rest], x), do: value(rest, x)
defp value([%{name: name, unit: unit, convert: convert} | rest], x) do
value(rest, x)
|> Map.put(name, %{"unit" => unit, "value" => convert.(x)})
end
end
IO.inspect(DecentlabDecoder.decode("02023b0003003702710c60", :hex))
IO.inspect(DecentlabDecoder.decode("02023b00020c60", :hex))
| 27.054348 | 160 | 0.53636 |
03e74ea51c504b281c2ce01620a27e1090b86931 | 100 | ex | Elixir | web/commands/product_category.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 356 | 2016-03-16T12:37:28.000Z | 2021-12-18T03:22:39.000Z | web/commands/product_category.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 30 | 2016-03-16T09:19:10.000Z | 2021-01-12T08:10:52.000Z | web/commands/product_category.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 72 | 2016-03-16T13:32:14.000Z | 2021-03-23T11:27:43.000Z | defmodule Nectar.Command.ProductCategory do
use Nectar.Command, model: Nectar.ProductCategory
end
| 25 | 51 | 0.84 |
03e76afdb6aaaaa92268b930cac5e5667fbb9b27 | 1,847 | ex | Elixir | lib/podder/podcasts/podcasts.ex | chattes/podder | 612c5a98c8aacfd5922fa499d513519db2af38ed | [
"MIT"
] | null | null | null | lib/podder/podcasts/podcasts.ex | chattes/podder | 612c5a98c8aacfd5922fa499d513519db2af38ed | [
"MIT"
] | null | null | null | lib/podder/podcasts/podcasts.ex | chattes/podder | 612c5a98c8aacfd5922fa499d513519db2af38ed | [
"MIT"
] | null | null | null | defmodule Podder.Podcasts do
use GenServer
require Logger
alias Elixir.Registry
@moduledoc """
Documentation for Podder.
"""
@doc """
Hello world.
## Examples
iex> Podder.hello()
:world
"""
def init(%{pod_name: name}) do
new_state = %{pod_name: name}
fetch_podcast = Task.async(fn -> Podder.ListenProvider.API.fetch_podcast(name) end)
new_state =
with {:ok, result} <- Task.await(fetch_podcast) do
Map.merge(new_state, result)
else
_ -> new_state
end
schedule_work()
{:ok, new_state}
end
def init(_), do: {:error, "Cannot Initialise Server pod_name is not passed."}
def handle_call(:fetch, _from, state) do
new_state = Map.put(state, "fetched", 1)
{:reply, new_state, new_state}
end
def handle_call(:get_state, _from, state) do
{:reply, state, state}
end
def handle_info(:work, state) do
%{pod_name: name} = state
new_state = state
fetch_podcast = Task.async(fn -> Podder.ListenProvider.API.fetch_podcast(name) end)
new_state =
with {:ok, result} <- Task.await(fetch_podcast) do
Map.merge(%{pod_name: name}, result)
else
_ -> new_state
end
schedule_work()
{:noreply, new_state}
end
defp schedule_work do
Process.send_after(self(), :work, 1000 * 60 * 60 * 24)
end
@doc """
Client Implementation
"""
def start_link(%{name: name, state: state}) do
IO.puts("Start GEN SERVER")
GenServer.start_link(__MODULE__, state, name: via_tuple(name))
end
def fetch_episodes(pid) do
GenServer.call(pid, :fetch)
end
def get_episodes(pid) do
GenServer.call(pid, :get_state)
end
def whereis(name: name), do: Registry.whereis_name({Podder.Registry, name})
defp via_tuple(name), do: {:via, Registry, {Podder.Registry, name}}
end
| 21.729412 | 87 | 0.643205 |
03e79deffd33113adc3908b0288d9c8f1bf76aad | 1,763 | exs | Elixir | test/sitemapper/sitemap_generator_test.exs | cbx/sitemapper | dd9078b9d572aab45ce4be375185b92b456b088f | [
"MIT"
] | null | null | null | test/sitemapper/sitemap_generator_test.exs | cbx/sitemapper | dd9078b9d572aab45ce4be375185b92b456b088f | [
"MIT"
] | null | null | null | test/sitemapper/sitemap_generator_test.exs | cbx/sitemapper | dd9078b9d572aab45ce4be375185b92b456b088f | [
"MIT"
] | null | null | null | defmodule Sitemapper.SitemapGeneratorTest do
use ExUnit.Case
doctest Sitemapper.SitemapGenerator
alias Sitemapper.{File, SitemapGenerator, URL}
test "add_url and finalize with a simple URL" do
url = %URL{loc: "http://example.com"}
%File{count: count, length: length, body: body} =
SitemapGenerator.new()
|> SitemapGenerator.add_url(url)
|> SitemapGenerator.finalize()
assert count == 1
assert length == 155
assert IO.chardata_to_string(body) ==
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n<url>\n <loc>http://example.com</loc>\n</url>\n</urlset>\n"
assert length == IO.iodata_length(body)
end
test "add_url with more than 50,000 URLs" do
result =
0..50_000
|> Enum.map(fn i ->
%URL{loc: "http://example.com/#{i}"}
end)
|> Enum.reduce(SitemapGenerator.new(), fn url, acc ->
SitemapGenerator.add_url(acc, url)
end)
assert result == {:error, :over_count}
end
test "add_url with more than 50MB" do
{error, %File{count: count, length: length, body: body}} =
0..50_000
|> Enum.map(fn i ->
block = String.duplicate("a", 1024)
%URL{loc: "http://example.com/#{block}/#{i}"}
end)
|> Enum.reduce_while(SitemapGenerator.new(), fn url, acc ->
case SitemapGenerator.add_url(acc, url) do
{:error, _} = err ->
acc = SitemapGenerator.finalize(acc)
{:halt, {err, acc}}
other ->
{:cont, other}
end
end)
assert error == {:error, :over_length}
assert count == 48735
assert length == 52_427_860
assert length == IO.iodata_length(body)
end
end
| 28.901639 | 182 | 0.598412 |
03e7af5fad899aa9c8906d949390f6359cdc8235 | 5,160 | ex | Elixir | lib/mix/tasks/hex.repo.ex | sudix/hex | f739a57d8829ea0b0f7759c164dc9149c3340e49 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/hex.repo.ex | sudix/hex | f739a57d8829ea0b0f7759c164dc9149c3340e49 | [
"Apache-2.0"
] | 1 | 2021-06-25T15:19:59.000Z | 2021-06-25T15:19:59.000Z | lib/mix/tasks/hex.repo.ex | sudix/hex | f739a57d8829ea0b0f7759c164dc9149c3340e49 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Hex.Repo do
use Mix.Task
@shortdoc "Manages Hex repositories"
@moduledoc """
Manages the list of available Hex repositories.
The repository is where packages and the registry of packages is stored.
You can fetch packages from multiple different repositories and packages
can depend on packages from other repositories. To use a package from another
repository than the global default `hexpm` add `repo: "my_repo"` to the
dependency declaration in `mix.exs`:
{:plug, "~> 1.0", repo: "my_repo"}
By default all dependencies of plug will also be fetched from `my_repo`
unless plug has declared otherwise in its dependency definition.
To use packages from `my_repo` you need to add it to your configuration
first. You do that by calling `mix hex.repo add my_repo https://myrepo.example.com`.
The default repo is called `hexpm` and points to https://repo.hex.pm. This
can be overridden by using `mix hex.repo set ...`.
A repository configured from an organization will have `hexpm:` prefixed to
its name. To depend on packages from an organization add `repo: "hexpm:my_organization"`
to the dependency declaration or simply `organization: "my_organization"`.
To configure organizations, see the `hex.organization` task.
## Add a repo
mix hex.repo add NAME URL
### Command line options
* `--public-key PATH` - Path to public key used to verify the registry (optional).
* `--auth-key KEY` - Key used to authenticate HTTP requests to repository (optional).
## Set config for repo
mix hex.repo set NAME --url URL
mix hex.repo set NAME --public-key PATH
mix hex.repo set NAME --auth-key KEY
## Remove repo
mix hex.repo remove NAME
## Show repo config
mix hex.repo show NAME
## List all repos
mix hex.repo list
"""
@switches [url: :string, public_key: :string, auth_key: :string]
def run(args) do
Hex.start()
{opts, args} = Hex.OptionParser.parse!(args, strict: @switches)
case args do
["add", name, url] ->
add(name, url, opts)
["set", name] ->
set(name, opts)
["remove", name] ->
remove(name)
["show", name] ->
show(name)
["list"] ->
list()
_ ->
invalid_args()
end
end
defp invalid_args() do
Mix.raise("""
Invalid arguments, expected one of:
mix hex.repo add NAME URL
mix hex.repo set NAME
mix hex.repo remove NAME
mix hex.repo show NAME
mix hex.repo list
""")
end
defp add(name, url, opts) do
public_key = read_public_key(opts[:public_key])
repo =
%{
url: url,
public_key: nil,
auth_key: nil
}
|> Map.merge(Enum.into(opts, %{}))
|> Map.put(:public_key, public_key)
Hex.State.fetch!(:repos)
|> Map.put(name, repo)
|> Hex.Config.update_repos()
end
defp set(name, opts) do
opts =
if public_key = opts[:public_key] do
Keyword.put(opts, :public_key, read_public_key(public_key))
else
opts
end
Hex.State.fetch!(:repos)
|> Map.update!(name, &Map.merge(&1, Enum.into(opts, %{})))
|> Hex.Config.update_repos()
end
defp remove(name) do
Hex.State.fetch!(:repos)
|> Map.delete(name)
|> Hex.Config.update_repos()
end
defp list() do
header = ["Name", "URL", "Public key", "Auth key"]
values =
Enum.map(Hex.State.fetch!(:repos), fn {name, config} ->
[
name,
config[:url],
show_public_key(config[:public_key]),
config[:auth_key]
]
end)
Mix.Tasks.Hex.print_table(header, values)
end
defp read_public_key(nil) do
nil
end
defp read_public_key(path) do
key =
path
|> Path.expand()
|> File.read!()
decode_public_key(key)
key
end
defp decode_public_key(key) do
[pem_entry] = :public_key.pem_decode(key)
:public_key.pem_entry_decode(pem_entry)
rescue
_ ->
Mix.raise("""
Could not decode public key. The public key contents are shown below.
#{key}
Public keys must be valid and be in the PEM format.
""")
end
defp show_public_key(nil), do: nil
defp show_public_key(public_key) do
[pem_entry] = :public_key.pem_decode(public_key)
public_key = :public_key.pem_entry_decode(pem_entry)
ssh_hostkey_fingerprint(public_key)
end
# Adapted from https://github.com/erlang/otp/blob/3eddb0f762de248d3230b38bc9d478bfbc8e7331/lib/public_key/src/public_key.erl#L824
defp ssh_hostkey_fingerprint(key) do
"SHA256:#{sshfp_string(key)}"
end
defp sshfp_string(key) do
:crypto.hash(:sha256, :public_key.ssh_encode(key, :ssh2_pubkey))
|> Base.encode64(padding: false)
end
defp show(name) do
case Map.fetch(Hex.State.fetch!(:repos), name) do
{:ok, repo} ->
header = ["URL", "Public key", "Auth key"]
rows = [[repo.url, show_public_key(repo.public_key), repo.auth_key]]
Mix.Tasks.Hex.print_table(header, rows)
:error ->
Mix.raise("Config does not contain repo #{name}")
end
end
end
| 24.688995 | 131 | 0.639729 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.