hexsha
stringlengths 40
40
| size
int64 2
991k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
208
| max_stars_repo_name
stringlengths 6
106
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
33.5k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
208
| max_issues_repo_name
stringlengths 6
106
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
16.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
208
| max_forks_repo_name
stringlengths 6
106
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
6.91k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 2
991k
| avg_line_length
float64 1
36k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
79e4922bd7158df424657ceae0a269d18cf22e67 | 2,225 | exs | Elixir | mix.exs | ashkan18/readtome | 09cdfa3813f49db816e8b477416672a87bd332ac | [
"MIT"
] | 1 | 2021-09-05T20:54:57.000Z | 2021-09-05T20:54:57.000Z | mix.exs | ashkan18/readtome | 09cdfa3813f49db816e8b477416672a87bd332ac | [
"MIT"
] | 17 | 2019-07-06T17:31:56.000Z | 2021-06-22T15:31:06.000Z | mix.exs | ashkan18/readtome | 09cdfa3813f49db816e8b477416672a87bd332ac | [
"MIT"
] | 1 | 2021-03-15T20:50:27.000Z | 2021-03-15T20:50:27.000Z | defmodule Readtome.Mixfile do
use Mix.Project
def project do
[
app: :readtome,
version: "0.0.1",
elixir: "~> 1.4",
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: {Readtome.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
[
{:absinthe_plug, "~> 1.5.2"},
{:absinthe_relay, "~> 1.5.0"},
{:arc, ">= 0.11.0"},
{:bcrypt_elixir, "~> 0.12"},
{:comeonin, "~> 4.0"},
{:cowboy, "~> 2.7"},
{:dataloader, "~> 1.0.0"},
{:ecto_sql, "~> 3.0"},
{:ex_aws_s3, "~> 2.0"},
{:ex_aws, "~> 2.1.0"},
{:furlex, git: "https://github.com/ashkan18/furlex.git", branch: "master"},
{:geo_postgis, "~> 3.1"},
{:gettext, "~> 0.11"},
{:guardian, "~> 1.0"},
{:hackney, "~> 1.6"},
{:httpoison, ">= 0.0.0"},
{:jason, "~> 1.1"},
{:phoenix_ecto, "~> 4.0"},
{:phoenix_html, "~> 2.14"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:phoenix_pubsub, "~> 2.0"},
{:phoenix, "~> 1.5.9"},
{:plug_cowboy, "~> 2.4.1"},
{:poison, ">= 3.1.0"},
{:postgrex, ">= 0.0.0"},
{:sweet_xml, "~> 0.6"},
{:tesla, "~> 1.3.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.8125 | 81 | 0.531685 |
79e4b1e1210743ec01c44c6d7faff47d104d40a6 | 2,894 | ex | Elixir | deps/mojito/lib/mojito/utils.ex | PrecisionNutrition/frogger | 96374fe0ac0ea616205f6678fe088802572e922e | [
"MIT"
] | null | null | null | deps/mojito/lib/mojito/utils.ex | PrecisionNutrition/frogger | 96374fe0ac0ea616205f6678fe088802572e922e | [
"MIT"
] | null | null | null | deps/mojito/lib/mojito/utils.ex | PrecisionNutrition/frogger | 96374fe0ac0ea616205f6678fe088802572e922e | [
"MIT"
] | null | null | null | defmodule Mojito.Utils do
@moduledoc false
alias Mojito.Error
@doc ~S"""
Ensures that the return value errors are of the form
`{:error, %Mojito.Error{}}`. Values `:ok` and `{:ok, val}` are
considered successful; other values are treated as errors.
"""
@spec wrap_return_value(any) :: :ok | {:ok, any} | {:error, Mojito.error()}
def wrap_return_value(rv) do
case rv do
:ok -> rv
{:ok, _} -> rv
{:error, %Error{}} -> rv
{:error, {:error, e}} -> {:error, %Error{reason: e}}
{:error, e} -> {:error, %Error{reason: e}}
{:error, _mint_conn, error} -> {:error, %Error{reason: error}}
other -> {:error, %Error{reason: :unknown, message: other}}
end
end
@doc ~S"""
Returns the protocol, hostname, and port (express or implied) from a
web URL.
iex> Mojito.Utils.decompose_url("http://example.com:8888/test")
{:ok, "http", "example.com", 8888}
iex> Mojito.Utils.decompose_url("https://user:[email protected]")
{:ok, "https", "example.com", 443}
"""
@spec decompose_url(String.t()) ::
{:ok, String.t(), String.t(), non_neg_integer} | {:error, any}
def decompose_url(url) do
try do
uri = URI.parse(url)
cond do
!uri.scheme || !uri.host || !uri.port ->
{:error, %Error{message: "invalid URL: #{url}"}}
:else ->
{:ok, uri.scheme, uri.host, uri.port}
end
rescue
e -> {:error, %Error{message: "invalid URL", reason: e}}
end
end
@doc ~S"""
Returns a relative URL including query and fragment parts, and any
necessary auth headers (i.e., for HTTP Basic auth).
"""
@spec get_relative_url_and_auth_headers(String.t()) ::
{:ok, String.t(), Mojito.headers()} | {:error, any}
def get_relative_url_and_auth_headers(url) do
try do
uri = URI.parse(url)
headers =
case uri.userinfo do
nil -> []
userinfo -> [{"authorization", "Basic #{Base.encode64(userinfo)}"}]
end
joined_url =
[
if(uri.path, do: "#{uri.path}", else: ""),
if(uri.query, do: "?#{uri.query}", else: ""),
if(uri.fragment, do: "##{uri.fragment}", else: ""),
]
|> Enum.join("")
relative_url =
if String.starts_with?(joined_url, "/") do
joined_url
else
"/" <> joined_url
end
{:ok, relative_url, headers}
rescue
e -> {:error, %Error{message: "invalid URL", reason: e}}
end
end
@doc ~S"""
Returns the correct Erlang TCP transport module for the given protocol.
"""
@spec protocol_to_transport(String.t()) :: {:ok, atom} | {:error, any}
def protocol_to_transport("https"), do: {:ok, :ssl}
def protocol_to_transport("http"), do: {:ok, :gen_tcp}
def protocol_to_transport(proto),
do: {:error, "unknown protocol #{inspect(proto)}"}
end
| 28.94 | 77 | 0.571873 |
79e4b26bea1b3ebd1f9b2a6cbe3df211fb4e0d29 | 324 | ex | Elixir | lib/kvstore.ex | rustamtolipov/kvstore | 1e7aba085fd0888975ef407377489d253d81bf2a | [
"MIT"
] | null | null | null | lib/kvstore.ex | rustamtolipov/kvstore | 1e7aba085fd0888975ef407377489d253d81bf2a | [
"MIT"
] | null | null | null | lib/kvstore.ex | rustamtolipov/kvstore | 1e7aba085fd0888975ef407377489d253d81bf2a | [
"MIT"
] | null | null | null | defmodule KVstore do
use Application
def start(_type, _args) do
import Supervisor.Spec
children = [
Plug.Adapters.Cowboy.child_spec(:http, KVstore.Router, [], [port: 4001]),
worker(KVstore.Storage, [])
]
opts = [strategy: :one_for_one]
Supervisor.start_link(children, opts)
end
end
| 19.058824 | 79 | 0.660494 |
79e4c290eef3af1240e27a275b81ff69c3323f7e | 521 | exs | Elixir | backend/priv/repo/migrations/20191102093740_create_users.exs | danesjenovdan/kjer.si | 185410ede2d42892e4d91c000099283254c5dc7a | [
"Unlicense"
] | 2 | 2019-11-02T21:28:34.000Z | 2019-11-28T18:01:08.000Z | backend/priv/repo/migrations/20191102093740_create_users.exs | danesjenovdan/kjer.si | 185410ede2d42892e4d91c000099283254c5dc7a | [
"Unlicense"
] | 17 | 2019-11-29T16:23:38.000Z | 2022-02-14T05:11:41.000Z | backend/priv/repo/migrations/20191102093740_create_users.exs | danesjenovdan/kjer.si | 185410ede2d42892e4d91c000099283254c5dc7a | [
"Unlicense"
] | null | null | null | defmodule KjerSi.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
execute "CREATE EXTENSION IF NOT EXISTS postgis"
create table(:users, primary_key: false) do
add :id, :binary_id, primary_key: true
add :nickname, :string, null: false
add :uid, :string, null: false
add :is_active, :boolean
add :is_admin, :boolean
timestamps(type: :utc_datetime_usec)
end
create unique_index(:users, [:nickname])
create unique_index(:users, [:uid])
end
end
| 24.809524 | 52 | 0.677543 |
79e50eaea6300398bc2852e8f674f12c01cd29f0 | 2,010 | ex | Elixir | lib/concentrate/struct_helpers.ex | paulswartz/concentrate | a69aa51c16071f2669932005be810da198f622c8 | [
"MIT"
] | 19 | 2018-01-22T18:39:20.000Z | 2022-02-22T16:15:30.000Z | lib/concentrate/struct_helpers.ex | mbta/concentrate | bae6e05713ed079b7da53867a01dd007861fb656 | [
"MIT"
] | 216 | 2018-01-22T14:22:39.000Z | 2022-03-31T10:30:31.000Z | lib/concentrate/struct_helpers.ex | paulswartz/concentrate | a69aa51c16071f2669932005be810da198f622c8 | [
"MIT"
] | 5 | 2018-01-22T14:18:15.000Z | 2021-04-26T18:34:19.000Z | defmodule Concentrate.StructHelpers do
@moduledoc false
@doc """
Builds accessors for each struct field.
## Example
defmodule Test do
defstruct_accessors([:one, :two])
end
iex> Test.one(Test.new(one: 1))
1
"""
defmacro defstruct_accessors(fields) do
[
define_struct(fields),
define_new(),
define_update()
] ++
for field <- fields do
[
define_accessor(field),
define_field_update(field)
]
end
end
@doc false
def define_struct(fields) do
quote do
defstruct unquote(fields)
@opaque t :: %__MODULE__{}
end
end
@doc false
def define_new do
quote do
@compile [inline: [new: 1]]
@spec new(Keyword.t()) :: t
def new(opts) when is_list(opts) do
struct!(__MODULE__, opts)
end
defoverridable new: 1
end
end
@doc false
def define_update do
quote do
@compile [inline: [update: 2]]
@spec update(%__MODULE__{} | t, Enumerable.t()) :: t
def update(%__MODULE__{} = existing, %{} = opts) do
Map.merge(existing, opts)
end
def update(%__MODULE__{} = existing, opts) do
update(existing, Map.new(opts))
end
end
end
@doc false
def define_field_update({field, _default}) do
define_field_update(field)
end
def define_field_update(field) do
name = :"update_#{field}"
quote do
@compile [inline: [{unquote(name), 2}]]
@spec unquote(name)(%__MODULE__{} | t, any) :: t
def unquote(name)(%__MODULE__{} = struct, new_value) do
%{struct | unquote(field) => new_value}
end
end
end
@doc false
def define_accessor({field, _default}) do
define_accessor(field)
end
def define_accessor(field) do
quote do
@compile [inline: [{unquote(field), 1}]]
@spec unquote(field)(%__MODULE__{} | t) :: any
def unquote(field)(%__MODULE__{unquote(field) => value}), do: value
end
end
end
| 20.9375 | 73 | 0.594527 |
79e51ca746a26532e42f3f93d009d2cf6ccd150c | 6,002 | ex | Elixir | apps/core/lib/core/persons/v2/validator.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/persons/v2/validator.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/persons/v2/validator.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 6 | 2018-05-11T13:59:32.000Z | 2022-01-19T20:15:22.000Z | defmodule Core.Persons.V2.Validator do
@moduledoc "Additional validation of Person request structure that cannot be covered by JSON Schema"
alias Core.Persons.V1.Validator, as: V1Validator
alias Core.ValidationError
alias Core.Validators.Error
alias Core.Validators.JsonObjects
@expiration_date_document_types ~w(
NATIONAL_ID
COMPLEMENTARY_PROTECTION_CERTIFICATE
PERMANENT_RESIDENCE_PERMIT
REFUGEE_CERTIFICATE
TEMPORARY_CERTIFICATE
TEMPORARY_PASSPORT
)
def validate(person) do
with :ok <- validate_tax_id(person),
:ok <- validate_unzr(person),
:ok <- validate_national_id(person),
:ok <- validate_birth_certificate_number(person),
:ok <- JsonObjects.array_unique_by_key(person, ["documents"], "type"),
:ok <- validate_person_phones(person),
:ok <- JsonObjects.array_unique_by_key(person, ["emergency_contact", "phones"], "type"),
:ok <- validate_auth_method(person),
:ok <- validate_confidant_persons(person),
:ok <- validate_person_passports(person),
:ok <- validate_document_dates(person) do
:ok
else
%ValidationError{path: path} = error ->
Error.dump(%{error | path: JsonObjects.combine_path("person", path)})
[%ValidationError{} | _] = errors ->
errors
|> Enum.map(fn %{path: path} = error -> %{error | path: JsonObjects.combine_path("person", path)} end)
|> Error.dump()
end
end
def validate_tax_id(%{"no_tax_id" => false} = person) do
tax_id = Map.get(person, "tax_id")
birth_date = Map.get(person, "birth_date")
age = Timex.diff(Timex.now(), Date.from_iso8601!(birth_date), :years)
if not is_nil(tax_id) or age < 14 do
:ok
else
%ValidationError{
description: "Only persons who refused the tax_id could be without tax_id",
params: ["tax_id"],
path: "$.person.tax_id"
}
end
end
def validate_tax_id(%{"no_tax_id" => true} = person) do
if is_nil(Map.get(person, "tax_id")) do
:ok
else
%ValidationError{
description: "Persons who refused the tax_id should be without tax_id",
params: ["no_tax_id"],
path: "$.person.tax_id"
}
end
end
def validate_unzr(%{"birth_date" => _, "unzr" => nil}), do: :ok
def validate_unzr(%{"birth_date" => birth_date, "unzr" => unzr}) do
bdate = String.replace(birth_date, "-", "")
if Regex.match?(~r/^(#{bdate}-\d{5})$/ui, unzr) do
:ok
else
%ValidationError{
description: "Birthdate or unzr is not correct",
params: ["unzr"],
path: "$.person.unzr"
}
end
end
def validate_unzr(_), do: :ok
def validate_national_id(%{} = person) do
national_id =
person
|> Map.get("documents", [])
|> Enum.find(fn
%{"type" => "NATIONAL_ID"} = national_id ->
national_id
_ ->
nil
end)
unzr? = Map.has_key?(person, "unzr")
if !national_id or unzr? do
:ok
else
%ValidationError{
description: "unzr is mandatory for document type NATIONAL_ID",
params: ["unzr"],
path: "$.person"
}
end
end
defdelegate(validate_birth_date(birth_date, path), to: V1Validator)
defdelegate validate_authentication_method_phone_number(authentication_methods), to: V1Validator
defdelegate validate_birth_certificate_number(person), to: V1Validator
defdelegate validate_person_phones(person), to: V1Validator
defdelegate validate_auth_method(person), to: V1Validator
defdelegate validate_confidant_persons(person), to: V1Validator
defdelegate validate_person_passports(person), to: V1Validator
defp validate_document_dates(%{"birth_date" => birth_date} = person) do
birth_date = Date.from_iso8601!(birth_date)
person
|> Map.get("documents", [])
|> Enum.with_index()
|> Enum.reduce_while(:ok, fn {document, index}, acc ->
issued_at = convert_date(document["issued_at"])
expiration_date = convert_date(document["expiration_date"])
with :ok <- validate_issued_at(issued_at, birth_date, index),
:ok <- validate_expiration_date(expiration_date, document["type"], index) do
{:cont, acc}
else
error ->
{:halt, error}
end
end)
end
defp validate_issued_at(nil, _, _), do: :ok
defp validate_issued_at(issued_at, birth_date, index) do
with {_, true} <- {:today, Date.compare(issued_at, Date.utc_today()) != :gt},
{_, true} <- {:birth_date, Date.compare(issued_at, birth_date) != :lt} do
:ok
else
{:today, _} ->
%ValidationError{
description: "Document issued date should be in the past",
params: [],
path: "$.person.documents.[#{index}].issued_at"
}
{:birth_date, _} ->
%ValidationError{
description: "Document issued date should greater than person.birth_date",
params: [],
path: "$.person.documents.[#{index}].issued_at"
}
end
end
defp validate_expiration_date(nil, document_type, index) when document_type in @expiration_date_document_types do
%ValidationError{
description: "expiration_date is mandatory for document_type #{document_type}",
params: [],
path: "$.person.documents.[#{index}].expiration_date"
}
end
defp validate_expiration_date(nil, _, _), do: :ok
defp validate_expiration_date(expiration_date, _, index) do
if Date.compare(expiration_date, Date.utc_today()) != :lt do
:ok
else
%ValidationError{
description: "Document expiration_date should be in the future",
params: [],
path: "$.person.documents.[#{index}].expiration_date"
}
end
end
defp convert_date(nil), do: nil
defp convert_date(value) when is_binary(value) do
with {:ok, date} <- Date.from_iso8601(value) do
date
else
_ -> nil
end
end
end
| 29.712871 | 115 | 0.637621 |
79e531d5911e17d7f3c03b515f4ad79fb0238d2e | 553 | ex | Elixir | lib/pixel_font/table_source/post/aglfn.ex | Dalgona/pixel_font | 6a65bf85e5228296eb29fddbfdd690565767ff76 | [
"MIT"
] | 17 | 2020-09-14T15:25:38.000Z | 2022-03-05T17:14:24.000Z | lib/pixel_font/table_source/post/aglfn.ex | Dalgona/pixel_font | 6a65bf85e5228296eb29fddbfdd690565767ff76 | [
"MIT"
] | 1 | 2021-08-19T05:05:37.000Z | 2021-08-19T05:05:37.000Z | lib/pixel_font/table_source/post/aglfn.ex | Dalgona/pixel_font | 6a65bf85e5228296eb29fddbfdd690565767ff76 | [
"MIT"
] | null | null | null | defmodule PixelFont.TableSource.Post.AGLFN do
data =
:pixel_font
|> :code.priv_dir()
|> Path.join("aglfn.txt")
|> File.open!([:read, :unicode])
|> IO.stream(:line)
|> Stream.reject(&String.starts_with?(&1, "#"))
|> Stream.map(&String.trim/1)
|> Stream.map(&String.split(&1, ";", trim: true))
|> Enum.map(fn [uv, name, _uni_name] ->
{uv |> Integer.parse(16) |> elem(0), name}
end)
|> Map.new()
@spec get_map() :: %{optional(integer()) => binary()}
def get_map, do: unquote(Macro.escape(data))
end
| 29.105263 | 55 | 0.576854 |
79e53e21a63be99248403dc08c17c9e4011aedb9 | 893 | exs | Elixir | test/ratio/decimal_conversion_test.exs | Qqwy/elixir-rational | 224ca1a5648ac69d2fd23cb05ccfa4b1942c1a86 | [
"MIT"
] | 31 | 2016-03-31T09:20:12.000Z | 2021-12-30T12:44:54.000Z | test/ratio/decimal_conversion_test.exs | Qqwy/elixir-rational | 224ca1a5648ac69d2fd23cb05ccfa4b1942c1a86 | [
"MIT"
] | 78 | 2016-11-23T19:25:21.000Z | 2022-03-25T10:18:00.000Z | test/ratio/decimal_conversion_test.exs | Qqwy/elixir-rational | 224ca1a5648ac69d2fd23cb05ccfa4b1942c1a86 | [
"MIT"
] | 13 | 2016-04-21T23:39:53.000Z | 2021-12-29T15:03:50.000Z | defmodule Ratio.DecimalConversionTest do
use ExUnit.Case, async: true
import Ratio, only: [<|>: 2]
@test_cases [
{Decimal.new("-1230"), Ratio.new(-1230)},
{Decimal.new("-123"), Ratio.new(-123)},
{Decimal.new("-12.3"), -123 <|> 10},
{Decimal.new("-1.23"), -123 <|> 100},
{Decimal.new("-0.123"), -123 <|> 1000},
{Decimal.new("-0.0123"), -123 <|> 10000},
{Decimal.new("1230"), Ratio.new(1230)},
{Decimal.new("123"), Ratio.new(123)},
{Decimal.new("12.3"), 123 <|> 10},
{Decimal.new("1.23"), 123 <|> 100},
{Decimal.new("0.123"), 123 <|> 1000},
{Decimal.new("0.0123"), 123 <|> 10000}
]
for {input, output} <- @test_cases do
test "Proper decimal-> ratio conversion for #{input}" do
assert Ratio.DecimalConversion.decimal_to_rational(unquote(Macro.escape(input))) ==
unquote(Macro.escape(output))
end
end
end
| 31.892857 | 89 | 0.580067 |
79e550be1714a0a0f289daea5124604579d9f3b2 | 155 | exs | Elixir | kousa/priv/repo/migrations/20210424191849_banner_url.exs | LeonardSSH/dogehouse | 584055ad407bc37fa35cdf36ebb271622e29d436 | [
"MIT"
] | 9 | 2021-03-17T03:56:18.000Z | 2021-09-24T22:45:14.000Z | kousa/priv/repo/migrations/20210424191849_banner_url.exs | ActuallyTomas/dogehouse | 8c3d2cd1d7e99e173f0658759467a391c4a90c4e | [
"MIT"
] | 12 | 2021-07-06T12:51:13.000Z | 2022-03-16T12:38:18.000Z | kousa/priv/repo/migrations/20210424191849_banner_url.exs | ActuallyTomas/dogehouse | 8c3d2cd1d7e99e173f0658759467a391c4a90c4e | [
"MIT"
] | 4 | 2021-07-15T20:33:50.000Z | 2022-03-27T12:46:47.000Z | defmodule Beef.Repo.Migrations.BannerUrl do
use Ecto.Migration
def change do
alter table(:users) do
add :bannerUrl, :text
end
end
end
| 15.5 | 43 | 0.690323 |
79e552f74d6508581c891a14a42ff7681226a8b3 | 20,544 | ex | Elixir | clients/compute/lib/google_api/compute/v1/api/addresses.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/addresses.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/addresses.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"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.Api.Addresses do
@moduledoc """
API calls for all endpoints tagged `Addresses`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Retrieves an aggregated list of addresses.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`.
For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`.
You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ```
* `:includeAllScopes` (*type:* `boolean()`) - Indicates whether every visible scope for each scope type (zone, region, global) should be included in the response. For new resource types added after this field, the flag has no effect as new resource types will always include every visible scope for each scope type in response. For resource types which predate this field, if this flag is omitted or false, only scopes of the scope types where the resource type is expected to be found will be included.
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by `name` or `creationTimestamp desc` is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.AddressAggregatedList{}}` on success
* `{:error, info}` on failure
"""
@spec compute_addresses_aggregated_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.AddressAggregatedList.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def compute_addresses_aggregated_list(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:includeAllScopes => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/aggregated/addresses", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.AddressAggregatedList{}])
end
@doc """
Deletes the specified address resource.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `region` (*type:* `String.t`) - Name of the region for this request.
* `address` (*type:* `String.t`) - Name of the address resource to delete.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_addresses_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def compute_addresses_delete(
connection,
project,
region,
address,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/{project}/regions/{region}/addresses/{address}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1),
"address" => URI.encode(address, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Returns the specified address resource.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `region` (*type:* `String.t`) - Name of the region for this request.
* `address` (*type:* `String.t`) - Name of the address resource to return.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Address{}}` on success
* `{:error, info}` on failure
"""
@spec compute_addresses_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Address.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def compute_addresses_get(
connection,
project,
region,
address,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/regions/{region}/addresses/{address}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1),
"address" => URI.encode(address, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Address{}])
end
@doc """
Creates an address resource in the specified project by using the data included in the request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `region` (*type:* `String.t`) - Name of the region for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.Compute.V1.Model.Address.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_addresses_insert(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def compute_addresses_insert(connection, project, region, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/regions/{region}/addresses", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Retrieves a list of addresses contained within the specified region.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `region` (*type:* `String.t`) - Name of the region for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`.
For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`.
You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ```
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by `name` or `creationTimestamp desc` is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.AddressList{}}` on success
* `{:error, info}` on failure
"""
@spec compute_addresses_list(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.AddressList.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def compute_addresses_list(connection, project, region, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/regions/{region}/addresses", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.AddressList{}])
end
end
| 55.674797 | 511 | 0.660436 |
79e55ada84862949265a86308ddea7cf7832fa12 | 1,736 | ex | Elixir | clients/tag_manager/lib/google_api/tag_manager/v2/model/revert_folder_response.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/tag_manager/lib/google_api/tag_manager/v2/model/revert_folder_response.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/tag_manager/lib/google_api/tag_manager/v2/model/revert_folder_response.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.TagManager.V2.Model.RevertFolderResponse do
@moduledoc """
The result of reverting folder changes in a workspace.
## Attributes
- folder (Folder): Folder as it appears in the latest container version since the last workspace synchronization operation. If no folder is present, that means the folder was deleted in the latest container version. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:folder => GoogleApi.TagManager.V2.Model.Folder.t()
}
field(:folder, as: GoogleApi.TagManager.V2.Model.Folder)
end
defimpl Poison.Decoder, for: GoogleApi.TagManager.V2.Model.RevertFolderResponse do
def decode(value, options) do
GoogleApi.TagManager.V2.Model.RevertFolderResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.TagManager.V2.Model.RevertFolderResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.166667 | 238 | 0.759793 |
79e567b4bbc648d15ce9399bde3948c274973da8 | 30,275 | ex | Elixir | lib/elixir/lib/kernel/typespec.ex | ggVGc/elixir | 1ca25436be2c46b688af4b50b7b3b19b3170c250 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel/typespec.ex | ggVGc/elixir | 1ca25436be2c46b688af4b50b7b3b19b3170c250 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel/typespec.ex | ggVGc/elixir | 1ca25436be2c46b688af4b50b7b3b19b3170c250 | [
"Apache-2.0"
] | null | null | null | defmodule Kernel.Typespec do
# TODO: Remove deprecated code on 2.0 and move this module to Module.Typespec.
@moduledoc false
## Deprecated API moved to Code.Typespec
@doc false
@deprecated "Use Code.Typespec.spec_to_quoted/2 instead"
def spec_to_ast(name, spec) do
Code.Typespec.spec_to_quoted(name, spec)
end
@doc false
@deprecated "Use Code.Typespec.type_to_quoted/1 instead"
def type_to_ast(type) do
Code.Typespec.type_to_quoted(type)
end
@doc false
@deprecated "Use Code.fetch_docs/1 instead"
def beam_typedocs(module) when is_atom(module) or is_binary(module) do
case Code.fetch_docs(module) do
{:docs_v1, _, _, _, _, _, docs} ->
for {{:type, name, arity}, _, _, doc, _} <- docs do
case doc do
:none -> {{name, arity}, nil}
:hidden -> {{name, arity}, false}
%{"en" => doc_string} -> {{name, arity}, doc_string}
end
end
{:error, _} ->
nil
end
end
@doc false
@deprecated "Use Code.Typespec.fetch_types/1 instead"
def beam_types(module) when is_atom(module) or is_binary(module) do
case Code.Typespec.fetch_types(module) do
{:ok, types} -> types
:error -> nil
end
end
@doc false
@deprecated "Use Code.Typespec.fetch_specs/1 instead"
def beam_specs(module) when is_atom(module) or is_binary(module) do
case Code.Typespec.fetch_specs(module) do
{:ok, specs} -> specs
:error -> nil
end
end
@doc false
@deprecated "Use Code.Typespec.fetch_callbacks/1 instead"
def beam_callbacks(module) when is_atom(module) or is_binary(module) do
case Code.Typespec.fetch_callbacks(module) do
{:ok, callbacks} -> callbacks
:error -> nil
end
end
## Hooks for Module functions
def defines_type?(module, {name, arity} = signature)
when is_atom(module) and is_atom(name) and arity in 0..255 do
{_set, bag} = :elixir_module.data_tables(module)
finder = fn {_kind, expr, _caller} ->
type_to_signature(expr) == signature
end
:lists.any(finder, get_typespec(bag, :type))
end
def spec_to_callback(module, {name, arity} = signature)
when is_atom(module) and is_atom(name) and arity in 0..255 do
{_set, bag} = :elixir_module.data_tables(module)
filter = fn {expr, _} = object ->
if spec_to_signature(expr) == signature do
:ets.delete_object(bag, {:spec, object})
store_typespec(bag, :callback, object)
true
else
false
end
end
:lists.filter(filter, get_typespec(bag, :spec)) != []
end
## Typespec definition and storage
@doc """
Defines a typespec.
Invoked by `Kernel.@/1` expansion.
"""
def deftypespec(:spec, expr, _line, _file, module, pos) do
{_set, bag} = :elixir_module.data_tables(module)
store_typespec(bag, :spec, {expr, pos})
end
def deftypespec(kind, expr, line, _file, module, pos)
when kind in [:callback, :macrocallback] do
{set, bag} = :elixir_module.data_tables(module)
case spec_to_signature(expr) do
{name, arity} ->
{line, doc} = get_doc_info(set, :doc, line)
store_doc(set, kind, name, arity, line, :doc, doc, %{})
:error ->
:error
end
store_typespec(bag, kind, {expr, pos})
end
def deftypespec(kind, expr, line, file, module, pos)
when kind in [:type, :typep, :opaque] do
{set, bag} = :elixir_module.data_tables(module)
case type_to_signature(expr) do
{name, arity} when kind == :typep ->
{line, doc} = get_doc_info(set, :typedoc, line)
if doc do
warning =
"type #{name}/#{arity} is private, @typedoc's are always discarded for private types"
:elixir_errors.warn(line, file, warning)
end
{name, arity} ->
{line, doc} = get_doc_info(set, :typedoc, line)
spec_meta = if kind == :opaque, do: %{opaque: true}, else: %{}
store_doc(set, :type, name, arity, line, :typedoc, doc, spec_meta)
:error ->
:error
end
store_typespec(bag, :type, {kind, expr, pos})
end
defp get_typespec(bag, key) do
:ets.lookup_element(bag, key, 2)
catch
:error, :badarg -> []
end
defp store_typespec(bag, key, value) do
:ets.insert(bag, {key, value})
:ok
end
defp store_doc(set, kind, name, arity, line, doc_kind, doc, spec_meta) do
doc_meta = get_doc_meta(spec_meta, doc_kind, set)
:ets.insert(set, {{kind, name, arity}, line, doc, doc_meta})
end
defp get_doc_info(set, attr, line) do
case :ets.take(set, attr) do
[{^attr, {line, doc}, _}] -> {line, doc}
[] -> {line, nil}
end
end
defp get_doc_meta(spec_meta, doc_kind, set) do
case :ets.take(set, {doc_kind, :meta}) do
[{{^doc_kind, :meta}, metadata, _}] -> Map.merge(metadata, spec_meta)
[] -> spec_meta
end
end
defp spec_to_signature({:when, _, [spec, _]}), do: type_to_signature(spec)
defp spec_to_signature(other), do: type_to_signature(other)
defp type_to_signature({:::, _, [{name, _, context}, _]})
when is_atom(name) and name != ::: and is_atom(context),
do: {name, 0}
defp type_to_signature({:::, _, [{name, _, args}, _]}) when is_atom(name) and name != :::,
do: {name, length(args)}
defp type_to_signature(_), do: :error
## Translation from Elixir AST to typespec AST
@doc false
def translate_typespecs_for_module(_set, bag) do
type_typespecs = take_typespec(bag, :type)
defined_type_pairs = collect_defined_type_pairs(type_typespecs)
state = %{
defined_type_pairs: defined_type_pairs,
used_type_pairs: [],
local_vars: %{},
undefined_type_error_enabled?: true
}
{types, state} = Enum.map_reduce(type_typespecs, state, &translate_type/2)
{specs, state} = Enum.map_reduce(take_typespec(bag, :spec), state, &translate_spec/2)
{callbacks, state} = Enum.map_reduce(take_typespec(bag, :callback), state, &translate_spec/2)
{macrocallbacks, state} =
Enum.map_reduce(take_typespec(bag, :macrocallback), state, &translate_spec/2)
optional_callbacks = List.flatten(get_typespec(bag, {:accumulate, :optional_callbacks}))
used_types = filter_used_types(types, state)
{used_types, specs, callbacks, macrocallbacks, optional_callbacks}
end
defp take_typespec(bag, key) do
:ets.take(bag, key)
end
defp collect_defined_type_pairs(type_typespecs) do
Enum.reduce(type_typespecs, %{}, fn {_, {_, expr, pos}}, type_pairs ->
%{file: file, line: line} = env = :elixir_locals.get_cached_env(pos)
case type_to_signature(expr) do
{name, arity} = type_pair ->
if builtin_type?(name, arity) do
message = "type #{name}/#{arity} is a builtin type and it cannot be redefined"
compile_error(env, message)
end
if Map.has_key?(type_pairs, type_pair) do
compile_error(env, "type #{name}/#{arity} is already defined")
end
Map.put(type_pairs, type_pair, {file, line})
:error ->
compile_error(env, "invalid type specification: #{Macro.to_string(expr)}")
end
end)
end
defp filter_used_types(types, state) do
Enum.filter(types, fn {_kind, {name, arity} = type_pair, _line, _type, export} ->
if type_pair not in state.used_type_pairs and not export do
%{^type_pair => {file, line}} = state.defined_type_pairs
:elixir_errors.warn(line, file, "type #{name}/#{arity} is unused")
false
else
true
end
end)
end
defp translate_type({_, {kind, {:::, _, [{name, _, args}, definition]}, pos}}, state) do
caller = :elixir_locals.get_cached_env(pos)
state = clean_local_state(state)
args =
if is_atom(args) do
[]
else
for(arg <- args, do: variable(arg))
end
vars = for {:var, _, var} <- args, do: var
state = Enum.reduce(vars, state, &update_local_vars(&2, &1))
{spec, state} = typespec(definition, vars, caller, state)
vars = for {:var, _, _} = var <- args, do: var
type = {name, spec, vars}
arity = length(args)
ensure_no_unused_local_vars!(caller, state.local_vars)
{kind, export} =
case kind do
:type -> {:type, true}
:typep -> {:type, false}
:opaque -> {:opaque, true}
end
invalid_args = Enum.reject(args, &valid_variable_ast?/1)
unless invalid_args == [] do
invalid_args = invalid_args |> Enum.map(&Macro.to_string/1) |> Enum.join(", ")
message =
"@type definitions expect all arguments to be variables. The type " <>
"#{name}/#{arity} has an invalid argument(s): #{invalid_args}"
compile_error(caller, message)
end
if underspecified?(kind, arity, spec) do
message = "@#{kind} type #{name}/#{arity} is underspecified and therefore meaningless"
:elixir_errors.warn(caller.line, caller.file, message)
end
{{kind, {name, arity}, caller.line, type, export}, state}
end
defp valid_variable_ast?({variable_name, _, context})
when is_atom(variable_name) and is_atom(context),
do: true
defp valid_variable_ast?(_), do: false
defp underspecified?(:opaque, 0, {:type, _, type, []}) when type in [:any, :term], do: true
defp underspecified?(_kind, _arity, _spec), do: false
defp translate_spec({kind, {{:when, _meta, [spec, guard]}, pos}}, state) do
caller = :elixir_locals.get_cached_env(pos)
translate_spec(kind, spec, guard, caller, state)
end
defp translate_spec({kind, {spec, pos}}, state) do
caller = :elixir_locals.get_cached_env(pos)
translate_spec(kind, spec, [], caller, state)
end
defp translate_spec(kind, {:::, meta, [{name, _, args}, return]}, guard, caller, state)
when is_atom(name) and name != ::: do
translate_spec(kind, meta, name, args, return, guard, caller, state)
end
defp translate_spec(_kind, {name, _meta, _args} = spec, _guard, caller, _state)
when is_atom(name) and name != ::: do
spec = Macro.to_string(spec)
compile_error(caller, "type specification missing return type: #{spec}")
end
defp translate_spec(_kind, spec, _guard, caller, _state) do
spec = Macro.to_string(spec)
compile_error(caller, "invalid type specification: #{spec}")
end
defp translate_spec(kind, meta, name, args, return, guard, caller, state) when is_atom(args),
do: translate_spec(kind, meta, name, [], return, guard, caller, state)
defp translate_spec(kind, meta, name, args, return, guard, caller, state) do
ensure_no_defaults!(args)
state = clean_local_state(state)
unless Keyword.keyword?(guard) do
error = "expected keywords as guard in type specification, got: #{Macro.to_string(guard)}"
compile_error(caller, error)
end
line = line(meta)
vars = Keyword.keys(guard)
{fun_args, state} = fn_args(meta, args, return, vars, caller, state)
spec = {:type, line, :fun, fun_args}
{spec, state} =
case guard_to_constraints(guard, vars, meta, caller, state) do
{[], state} -> {spec, state}
{constraints, state} -> {{:type, line, :bounded_fun, [spec, constraints]}, state}
end
ensure_no_unused_local_vars!(caller, state.local_vars)
arity = length(args)
{{kind, {name, arity}, caller.line, spec}, state}
end
# TODO: Remove char_list type by 2.0
defp builtin_type?(:char_list, 0), do: true
defp builtin_type?(:charlist, 0), do: true
defp builtin_type?(:as_boolean, 1), do: true
defp builtin_type?(:struct, 0), do: true
defp builtin_type?(:nonempty_charlist, 0), do: true
defp builtin_type?(:keyword, 0), do: true
defp builtin_type?(:keyword, 1), do: true
defp builtin_type?(name, arity), do: :erl_internal.is_type(name, arity)
defp ensure_no_defaults!(args) do
Enum.each(args, fn
{:::, _, [left, right]} ->
ensure_not_default(left)
ensure_not_default(right)
left
other ->
ensure_not_default(other)
other
end)
end
defp ensure_not_default({:\\, _, [_, _]}) do
raise ArgumentError, "default arguments \\\\ not supported in typespecs"
end
defp ensure_not_default(_), do: :ok
defp guard_to_constraints(guard, vars, meta, caller, state) do
line = line(meta)
Enum.flat_map_reduce(guard, state, fn
{_name, {:var, _, context}}, state when is_atom(context) ->
{[], state}
{name, type}, state ->
{spec, state} = typespec(type, vars, caller, state)
constraint = [{:atom, line, :is_subtype}, [{:var, line, name}, spec]]
state = update_local_vars(state, name)
{[{:type, line, :constraint, constraint}], state}
end)
end
## To typespec conversion
defp line(meta) do
Keyword.get(meta, :line, 0)
end
# Handle unions
defp typespec({:|, meta, [_, _]} = exprs, vars, caller, state) do
exprs = collect_union(exprs)
{union, state} = Enum.map_reduce(exprs, state, &typespec(&1, vars, caller, &2))
{{:type, line(meta), :union, union}, state}
end
# Handle binaries
defp typespec({:<<>>, meta, []}, _, _, state) do
line = line(meta)
{{:type, line, :binary, [{:integer, line, 0}, {:integer, line, 0}]}, state}
end
defp typespec(
{:<<>>, meta, [{:::, unit_meta, [{:_, _, ctx1}, {:*, _, [{:_, _, ctx2}, unit]}]}]},
_,
_,
state
)
when is_atom(ctx1) and is_atom(ctx2) and is_integer(unit) do
line = line(meta)
{{:type, line, :binary, [{:integer, line, 0}, {:integer, line(unit_meta), unit}]}, state}
end
defp typespec({:<<>>, meta, [{:::, size_meta, [{:_, _, ctx}, size]}]}, _, _, state)
when is_atom(ctx) and is_integer(size) do
line = line(meta)
{{:type, line, :binary, [{:integer, line(size_meta), size}, {:integer, line, 0}]}, state}
end
defp typespec(
{
:<<>>,
meta,
[
{:::, size_meta, [{:_, _, ctx1}, size]},
{:::, unit_meta, [{:_, _, ctx2}, {:*, _, [{:_, _, ctx3}, unit]}]}
]
},
_,
_,
state
)
when is_atom(ctx1) and is_atom(ctx2) and is_atom(ctx3) and is_integer(size) and
is_integer(unit) do
args = [{:integer, line(size_meta), size}, {:integer, line(unit_meta), unit}]
{{:type, line(meta), :binary, args}, state}
end
## Handle maps and structs
defp typespec({:map, meta, args}, _vars, _caller, state) when args == [] or is_atom(args) do
{{:type, line(meta), :map, :any}, state}
end
defp typespec({:%{}, meta, fields} = map, vars, caller, state) do
{fields, state} =
Enum.map_reduce(fields, state, fn
{k, v}, state when is_atom(k) ->
{arg1, state} = typespec(k, vars, caller, state)
{arg2, state} = typespec(v, vars, caller, state)
{{:type, line(meta), :map_field_exact, [arg1, arg2]}, state}
{{:required, meta2, [k]}, v}, state ->
{arg1, state} = typespec(k, vars, caller, state)
{arg2, state} = typespec(v, vars, caller, state)
{{:type, line(meta2), :map_field_exact, [arg1, arg2]}, state}
{{:optional, meta2, [k]}, v}, state ->
{arg1, state} = typespec(k, vars, caller, state)
{arg2, state} = typespec(v, vars, caller, state)
{{:type, line(meta2), :map_field_assoc, [arg1, arg2]}, state}
{k, v}, state ->
# TODO: Warn on Elixir v1.8 (since v1.6 is the first version to drop support for 18 and
# older)
# warning =
# "invalid map specification. %{foo => bar} is deprecated in favor of " <>
# "%{required(foo) => bar} and %{optional(foo) => bar}."
# :elixir_errors.warn(caller.line, caller.file, warning)
{arg1, state} = typespec(k, vars, caller, state)
{arg2, state} = typespec(v, vars, caller, state)
{{:type, line(meta), :map_field_assoc, [arg1, arg2]}, state}
{:|, _, [_, _]}, _state ->
error =
"invalid map specification. When using the | operator in the map key, " <>
"make sure to wrap the key type in parentheses: #{Macro.to_string(map)}"
compile_error(caller, error)
_, _state ->
compile_error(caller, "invalid map specification: #{Macro.to_string(map)}")
end)
{{:type, line(meta), :map, fields}, state}
end
defp typespec({:%, _, [name, {:%{}, meta, fields}]}, vars, caller, state) do
# We cannot set a function name to avoid tracking
# as a compile time dependency, because for structs it actually is one.
module = Macro.expand(name, caller)
struct =
if module == caller.module do
Module.get_attribute(module, :struct) ||
compile_error(caller, "struct is not defined for #{Macro.to_string(name)}")
else
module.__struct__
end
struct = struct |> Map.from_struct() |> Map.to_list()
unless Keyword.keyword?(fields) do
compile_error(caller, "expected key-value pairs in struct #{Macro.to_string(name)}")
end
types =
Enum.map(struct, fn {field, _} ->
{field, Keyword.get(fields, field, quote(do: term()))}
end)
Enum.each(fields, fn {field, _} ->
unless Keyword.has_key?(struct, field) do
compile_error(caller, "undefined field #{field} on struct #{Macro.to_string(name)}")
end
end)
typespec({:%{}, meta, [__struct__: module] ++ types}, vars, caller, state)
end
# Handle records
defp typespec({:record, meta, [atom]}, vars, caller, state) do
typespec({:record, meta, [atom, []]}, vars, caller, state)
end
defp typespec({:record, meta, [tag, field_specs]}, vars, caller, state) do
# We cannot set a function name to avoid tracking
# as a compile time dependency because for records it actually is one.
case Macro.expand({tag, [], [{:{}, [], []}]}, caller) do
{_, _, [name, fields | _]} when is_list(fields) ->
types =
Enum.map(fields, fn {field, _} ->
Keyword.get(field_specs, field, quote(do: term()))
end)
Enum.each(field_specs, fn {field, _} ->
unless Keyword.has_key?(fields, field) do
compile_error(caller, "undefined field #{field} on record #{inspect(tag)}")
end
end)
typespec({:{}, meta, [name | types]}, vars, caller, state)
_ ->
compile_error(caller, "unknown record #{inspect(tag)}")
end
end
# Handle ranges
defp typespec({:.., meta, args}, vars, caller, state) do
{args, state} = Enum.map_reduce(args, state, &typespec(&1, vars, caller, &2))
{{:type, line(meta), :range, args}, state}
end
# Handle special forms
defp typespec({:__MODULE__, _, atom}, vars, caller, state) when is_atom(atom) do
typespec(caller.module, vars, caller, state)
end
defp typespec({:__aliases__, _, _} = alias, vars, caller, state) do
# We set a function name to avoid tracking
# aliases in typespecs as compile time dependencies.
atom = Macro.expand(alias, %{caller | function: {:typespec, 0}})
typespec(atom, vars, caller, state)
end
# Handle funs
defp typespec([{:->, meta, [arguments, return]}], vars, caller, state)
when is_list(arguments) do
{args, state} = fn_args(meta, arguments, return, vars, caller, state)
{{:type, line(meta), :fun, args}, state}
end
# Handle type operator
defp typespec(
{:::, meta, [{var_name, var_meta, context}, expr]} = ann_type,
vars,
caller,
state
)
when is_atom(var_name) and is_atom(context) do
case typespec(expr, vars, caller, state) do
{{:ann_type, _, _}, _state} ->
message =
"invalid type annotation. Type annotations cannot be nested: " <>
"#{Macro.to_string(ann_type)}"
# TODO: make this an error in elixir 2.0 and remove the code below
:elixir_errors.warn(caller.line, caller.file, message)
# This may be generating an invalid typespec but we need to generate it
# to avoid breaking existing code that was valid but only broke dialyzer
{right, state} = typespec(expr, vars, caller, state)
{{:ann_type, line(meta), [{:var, line(var_meta), var_name}, right]}, state}
{right, state} ->
{{:ann_type, line(meta), [{:var, line(var_meta), var_name}, right]}, state}
end
end
defp typespec({:::, meta, [left, right]} = expr, vars, caller, state) do
message =
"invalid type annotation. When using the | operator to represent the union of types, " <>
"make sure to wrap type annotations in parentheses: #{Macro.to_string(expr)}"
# TODO: make this an error in Elixir 2.0, and remove the code below and the
# :undefined_type_error_enabled? key from the state
:elixir_errors.warn(caller.line, caller.file, message)
# This may be generating an invalid typespec but we need to generate it
# to avoid breaking existing code that was valid but only broke dialyzer
state = %{state | undefined_type_error_enabled?: false}
{left, state} = typespec(left, vars, caller, state)
state = %{state | undefined_type_error_enabled?: true}
{right, state} = typespec(right, vars, caller, state)
{{:ann_type, line(meta), [left, right]}, state}
end
# Handle unary ops
defp typespec({op, meta, [integer]}, _, _, state) when op in [:+, :-] and is_integer(integer) do
line = line(meta)
{{:op, line, op, {:integer, line, integer}}, state}
end
# Handle remote calls in the form of @module_attribute.type.
# These are not handled by the general remote type clause as calling
# Macro.expand/2 on the remote does not expand module attributes (but expands
# things like __MODULE__).
defp typespec(
{{:., meta, [{:@, _, [{attr, _, _}]}, name]}, _, args} = orig,
vars,
caller,
state
) do
remote = Module.get_attribute(caller.module, attr)
unless is_atom(remote) and remote != nil do
message =
"invalid remote in typespec: #{Macro.to_string(orig)} (@#{attr} is #{inspect(remote)})"
compile_error(caller, message)
end
{remote_spec, state} = typespec(remote, vars, caller, state)
{name_spec, state} = typespec(name, vars, caller, state)
type = {remote_spec, meta, name_spec, args}
remote_type(type, vars, caller, state)
end
# Handle remote calls
defp typespec({{:., meta, [remote, name]}, _, args} = orig, vars, caller, state) do
# We set a function name to avoid tracking
# aliases in typespecs as compile time dependencies.
remote = Macro.expand(remote, %{caller | function: {:typespec, 0}})
unless is_atom(remote) do
compile_error(caller, "invalid remote in typespec: #{Macro.to_string(orig)}")
end
{remote_spec, state} = typespec(remote, vars, caller, state)
{name_spec, state} = typespec(name, vars, caller, state)
type = {remote_spec, meta, name_spec, args}
remote_type(type, vars, caller, state)
end
# Handle tuples
defp typespec({:tuple, meta, []}, _vars, _caller, state) do
{{:type, line(meta), :tuple, :any}, state}
end
defp typespec({:{}, meta, t}, vars, caller, state) when is_list(t) do
{args, state} = Enum.map_reduce(t, state, &typespec(&1, vars, caller, &2))
{{:type, line(meta), :tuple, args}, state}
end
defp typespec({left, right}, vars, caller, state) do
typespec({:{}, [], [left, right]}, vars, caller, state)
end
# Handle blocks
defp typespec({:__block__, _meta, [arg]}, vars, caller, state) do
typespec(arg, vars, caller, state)
end
# Handle variables or local calls
defp typespec({name, meta, atom}, vars, caller, state) when is_atom(atom) do
if name in vars do
state = update_local_vars(state, name)
{{:var, line(meta), name}, state}
else
typespec({name, meta, []}, vars, caller, state)
end
end
# Handle local calls
defp typespec({:string, meta, arguments}, vars, caller, state) do
warning =
"string() type use is discouraged. " <>
"For character lists, use charlist() type, for strings, String.t()\n" <>
Exception.format_stacktrace(Macro.Env.stacktrace(caller))
:elixir_errors.warn(caller.line, caller.file, warning)
{arguments, state} = Enum.map_reduce(arguments, state, &typespec(&1, vars, caller, &2))
{{:type, line(meta), :string, arguments}, state}
end
defp typespec({:nonempty_string, meta, arguments}, vars, caller, state) do
warning =
"nonempty_string() type use is discouraged. " <>
"For non-empty character lists, use nonempty_charlist() type, for strings, String.t()\n" <>
Exception.format_stacktrace(Macro.Env.stacktrace(caller))
:elixir_errors.warn(caller.line, caller.file, warning)
{arguments, state} = Enum.map_reduce(arguments, state, &typespec(&1, vars, caller, &2))
{{:type, line(meta), :nonempty_string, arguments}, state}
end
# TODO: Remove char_list type by 2.0
defp typespec({type, _meta, []}, vars, caller, state) when type in [:charlist, :char_list] do
if type == :char_list do
warning = "the char_list() type is deprecated, use charlist()"
:elixir_errors.warn(caller.line, caller.file, warning)
end
typespec(quote(do: :elixir.charlist()), vars, caller, state)
end
defp typespec({:nonempty_charlist, _meta, []}, vars, caller, state) do
typespec(quote(do: :elixir.nonempty_charlist()), vars, caller, state)
end
defp typespec({:struct, _meta, []}, vars, caller, state) do
typespec(quote(do: :elixir.struct()), vars, caller, state)
end
defp typespec({:as_boolean, _meta, [arg]}, vars, caller, state) do
typespec(quote(do: :elixir.as_boolean(unquote(arg))), vars, caller, state)
end
defp typespec({:keyword, _meta, args}, vars, caller, state) when length(args) <= 1 do
typespec(quote(do: :elixir.keyword(unquote_splicing(args))), vars, caller, state)
end
defp typespec({:fun, meta, args}, vars, caller, state) do
{args, state} = Enum.map_reduce(args, state, &typespec(&1, vars, caller, &2))
{{:type, line(meta), :fun, args}, state}
end
defp typespec({name, meta, arguments}, vars, caller, state) do
{arguments, state} = Enum.map_reduce(arguments, state, &typespec(&1, vars, caller, &2))
arity = length(arguments)
case :erl_internal.is_type(name, arity) do
true ->
{{:type, line(meta), name, arguments}, state}
false ->
if state.undefined_type_error_enabled? and
not Map.has_key?(state.defined_type_pairs, {name, arity}) do
compile_error(caller, "type #{name}/#{arity} undefined")
end
state =
if {name, arity} in state.used_type_pairs do
state
else
%{state | used_type_pairs: [{name, arity} | state.used_type_pairs]}
end
{{:user_type, line(meta), name, arguments}, state}
end
end
# Handle literals
defp typespec(atom, _, _, state) when is_atom(atom) do
{{:atom, 0, atom}, state}
end
defp typespec(integer, _, _, state) when is_integer(integer) do
{{:integer, 0, integer}, state}
end
defp typespec([], vars, caller, state) do
typespec({nil, [], []}, vars, caller, state)
end
defp typespec([{:..., _, atom}], vars, caller, state) when is_atom(atom) do
typespec({:nonempty_list, [], []}, vars, caller, state)
end
defp typespec([spec, {:..., _, atom}], vars, caller, state) when is_atom(atom) do
typespec({:nonempty_list, [], [spec]}, vars, caller, state)
end
defp typespec([spec], vars, caller, state) do
typespec({:list, [], [spec]}, vars, caller, state)
end
defp typespec(list, vars, caller, state) when is_list(list) do
[head | tail] = Enum.reverse(list)
union =
Enum.reduce(tail, validate_kw(head, list, caller), fn elem, acc ->
{:|, [], [validate_kw(elem, list, caller), acc]}
end)
typespec({:list, [], [union]}, vars, caller, state)
end
defp typespec(other, _vars, caller, _state) do
compile_error(caller, "unexpected expression in typespec: #{Macro.to_string(other)}")
end
## Helpers
defp compile_error(caller, desc) do
raise CompileError, file: caller.file, line: caller.line, description: desc
end
defp remote_type({remote, meta, name, arguments}, vars, caller, state) do
{arguments, state} = Enum.map_reduce(arguments, state, &typespec(&1, vars, caller, &2))
{{:remote_type, line(meta), [remote, name, arguments]}, state}
end
defp collect_union({:|, _, [a, b]}), do: [a | collect_union(b)]
defp collect_union(v), do: [v]
defp validate_kw({key, _} = t, _, _caller) when is_atom(key), do: t
defp validate_kw(_, original, caller) do
compile_error(caller, "unexpected list in typespec: #{Macro.to_string(original)}")
end
defp fn_args(meta, args, return, vars, caller, state) do
{fun_args, state} = fn_args(meta, args, vars, caller, state)
{spec, state} = typespec(return, vars, caller, state)
case [fun_args, spec] do
[{:type, _, :any}, {:type, _, :any, []}] -> {[], state}
x -> {x, state}
end
end
defp fn_args(meta, [{:..., _, _}], _vars, _caller, state) do
{{:type, line(meta), :any}, state}
end
defp fn_args(meta, args, vars, caller, state) do
{args, state} = Enum.map_reduce(args, state, &typespec(&1, vars, caller, &2))
{{:type, line(meta), :product, args}, state}
end
defp variable({name, meta, args}) when is_atom(name) and is_atom(args) do
{:var, line(meta), name}
end
defp variable(expr), do: expr
defp clean_local_state(state) do
%{state | local_vars: %{}}
end
defp update_local_vars(%{local_vars: local_vars} = state, var_name) do
case Map.fetch(local_vars, var_name) do
{:ok, :used_once} -> %{state | local_vars: Map.put(local_vars, var_name, :used_multiple)}
{:ok, :used_multiple} -> state
:error -> %{state | local_vars: Map.put(local_vars, var_name, :used_once)}
end
end
defp ensure_no_unused_local_vars!(caller, local_vars) do
for {name, :used_once} <- local_vars do
compile_error(caller, "type variable #{name} is unused")
end
end
end
| 33.379272 | 99 | 0.623881 |
79e5fcc5d81f27a747b959021d228abe5a530e00 | 3,188 | exs | Elixir | apps/ewallet_db/test/ewallet_db/types/wallet_address_test.exs | vanmil/ewallet | 6c1aca95a83e0a9d93007670a40d8c45764a8122 | [
"Apache-2.0"
] | null | null | null | apps/ewallet_db/test/ewallet_db/types/wallet_address_test.exs | vanmil/ewallet | 6c1aca95a83e0a9d93007670a40d8c45764a8122 | [
"Apache-2.0"
] | null | null | null | apps/ewallet_db/test/ewallet_db/types/wallet_address_test.exs | vanmil/ewallet | 6c1aca95a83e0a9d93007670a40d8c45764a8122 | [
"Apache-2.0"
] | null | null | null | defmodule EWalletDB.Types.WalletAddressTest do
use EWalletDB.SchemaCase
alias EWalletDB.Types.WalletAddress
alias EWalletDB.Wallet
describe "cast/1" do
test "casts input to lower case" do
assert WalletAddress.cast("ABCD-123456789012") == {:ok, "abcd123456789012"}
end
test "strips all non-alphanumerics" do
assert WalletAddress.cast("abcd%1234/5678_9012") == {:ok, "abcd123456789012"}
end
test "accepts inputs with all integers" do
assert WalletAddress.cast("1234123456789012") == {:ok, "1234123456789012"}
end
test "returns error if any of the 12 latter characters consist of non-integers" do
assert WalletAddress.cast("abcd-1234-5678-901X") == :error
assert WalletAddress.cast("abcd-1234-5XX8-9012") == :error
end
test "returns error if the input has invalid length" do
assert WalletAddress.cast("abcd1234") == :error
assert WalletAddress.cast("abcd1234567890123") == :error
end
end
describe "load/1" do
# The wallet address is stored as string in the database,
# so no transformation needed.
test "returns the same string" do
assert WalletAddress.load("abcd123456789012") == {:ok, "abcd123456789012"}
end
end
describe "dump/1" do
# The wallet address should have already been casted via `cast/1`
# to a uniformed format. So no transformation needed.
test "returns the same string" do
assert WalletAddress.dump("abcd123456789012") == {:ok, "abcd123456789012"}
end
end
describe "wallet_address/2" do
test "populates the schema with a valid wallet address" do
{:ok, wallet} =
:wallet
|> params_for(address: nil)
|> Wallet.insert()
assert String.match?(wallet.address, ~r/^[a-z]{4}[0-9]{12}$/)
end
test "uses the given wallet address if provided" do
{:ok, wallet} =
:wallet
|> params_for(address: "test-1234-5678-9012")
|> Wallet.insert()
assert wallet.address == "test123456789012"
end
end
describe "generate/1" do
test "returns {:ok, address}" do
{:ok, address} = WalletAddress.generate()
assert String.match?(address, ~r/^[a-z]{4}[0-9]{12}$/)
end
test "returns {:ok, address} when prefix is provided" do
{:ok, address} = WalletAddress.generate("abcd")
assert String.match?(address, ~r/^abcd[0-9]{12}$/)
end
test "returns {:ok, address} when prefix less than 4 characters are provided" do
{:ok, address} = WalletAddress.generate("ab")
assert String.match?(address, ~r/^ab[0-9]{2}[0-9]{12}$/)
end
test "returns {:ok, address} when the prefix contains numbers" do
{:ok, address} = WalletAddress.generate("9999")
assert String.match?(address, ~r/^9999[0-9]{12}$/)
end
test "returns :error if prefix contains invalid character" do
assert WalletAddress.generate("abc%") == :error
assert WalletAddress.generate("____") == :error
end
end
describe "autogenerate/1" do
test "returns a wallet address ID" do
address = WalletAddress.autogenerate("abcd")
assert String.match?(address, ~r/^abcd[0-9]{12}$/)
end
end
end
| 31.88 | 86 | 0.654956 |
79e65c1b88ad988aacd63c1ab9b5101e7c9f613d | 394 | exs | Elixir | priv/repo/migrations/20181004203212_create_messages.exs | woeye/twaddler | e06a22a94520055bc33aaaacfe51989ba8ab665f | [
"Apache-2.0"
] | 1 | 2018-10-08T13:57:08.000Z | 2018-10-08T13:57:08.000Z | priv/repo/migrations/20181004203212_create_messages.exs | woeye/twaddler | e06a22a94520055bc33aaaacfe51989ba8ab665f | [
"Apache-2.0"
] | null | null | null | priv/repo/migrations/20181004203212_create_messages.exs | woeye/twaddler | e06a22a94520055bc33aaaacfe51989ba8ab665f | [
"Apache-2.0"
] | 1 | 2018-10-08T13:55:44.000Z | 2018-10-08T13:55:44.000Z | defmodule Twaddler.Repo.Migrations.CreateMessages do
use Ecto.Migration
def change do
create table(:messages) do
add :uuid, :string
add :text, :text
add :user_id, references(:users)
add :conversation_id, references(:conversations)
timestamps()
end
create index(:messages, [:conversation_id])
create unique_index(:messages, [:uuid])
end
end
| 23.176471 | 54 | 0.680203 |
79e65e1bd4002def5bf2fee392dbbcfd8a3696ec | 884 | ex | Elixir | server/lib/fakers_api/people/person.ex | bart-kosmala/fakers | aff49689c2507a5f8e6e81441bd922ec8887bbc9 | [
"MIT"
] | 5 | 2020-11-15T17:46:40.000Z | 2021-06-15T16:10:57.000Z | server/lib/fakers_api/people/person.ex | bart-kosmala/fakers | aff49689c2507a5f8e6e81441bd922ec8887bbc9 | [
"MIT"
] | 5 | 2020-12-04T13:38:10.000Z | 2020-12-18T11:15:50.000Z | server/lib/fakers_api/people/person.ex | bart-kosmala/fakers | aff49689c2507a5f8e6e81441bd922ec8887bbc9 | [
"MIT"
] | 2 | 2020-12-18T11:16:18.000Z | 2021-01-19T22:03:35.000Z | defmodule FakersApi.People.Person do
use Ecto.Schema
import Ecto.Changeset
alias FakersApi.People.{PersonAddress, PersonContact, DeceasedPerson}
schema "person" do
field :birth_date, :date
field :first_name, :string
field :last_name, :string
field :pesel, :string
field :second_name, :string
field :sex, :string
has_many :person_addresses, PersonAddress
has_many :addresses, through: [:person_addresses, :address]
has_many :person_contacts, PersonContact
has_many :contacts, through: [:person_contacts, :contact]
has_one :deceased_person, DeceasedPerson
end
@doc false
def changeset(person, attrs) do
person
|> cast(attrs, [:pesel, :first_name, :second_name, :last_name, :sex, :birth_date])
|> validate_required([:pesel, :first_name, :last_name, :sex, :birth_date])
|> unique_constraint(:pesel)
end
end
| 28.516129 | 86 | 0.714932 |
79e668ca4bb8e5c86dd2aecea5b4ec2040a39308 | 378 | ex | Elixir | lib/titeenipeli/auth/guardian.ex | Cadiac/titeenit-backend | 51db7a1f93dc78a769bb309b94b1b893cefdcdc9 | [
"MIT"
] | null | null | null | lib/titeenipeli/auth/guardian.ex | Cadiac/titeenit-backend | 51db7a1f93dc78a769bb309b94b1b893cefdcdc9 | [
"MIT"
] | null | null | null | lib/titeenipeli/auth/guardian.ex | Cadiac/titeenit-backend | 51db7a1f93dc78a769bb309b94b1b893cefdcdc9 | [
"MIT"
] | null | null | null | defmodule Titeenipeli.Auth.Guardian do
use Guardian, otp_app: :titeenipeli
alias Titeenipeli.Core
def subject_for_token(user, _claims) do
{:ok, user.id}
end
def resource_from_claims(claims) do
user_id = claims["sub"]
user = Core.get_user!(user_id)
{:ok, %{id: user_id, username: user.username || user.first_name, guild_id: user.guild_id}}
end
end
| 23.625 | 94 | 0.708995 |
79e669e4b60e144aeaeceb09b3f7aa57a4c7fb76 | 642 | ex | Elixir | lib/uro/accounts/user_privilege_ruleset.ex | V-Sekai/uro | 0b23da65d5c7e459efcd6b2c3d9bdf91c533b737 | [
"MIT"
] | 1 | 2022-01-11T04:05:39.000Z | 2022-01-11T04:05:39.000Z | lib/uro/accounts/user_privilege_ruleset.ex | V-Sekai/uro | 0b23da65d5c7e459efcd6b2c3d9bdf91c533b737 | [
"MIT"
] | 35 | 2021-02-10T08:18:57.000Z | 2021-05-06T17:19:50.000Z | lib/uro/accounts/user_privilege_ruleset.ex | V-Sekai/uro | 0b23da65d5c7e459efcd6b2c3d9bdf91c533b737 | [
"MIT"
] | null | null | null | defmodule Uro.Accounts.UserPrivilegeRuleset do
use Ecto.Schema
import Ecto.Changeset
schema "user_privilege_rulesets" do
belongs_to :user, Uro.Accounts.User, foreign_key: :user_id, type: :binary_id
field :is_admin, :boolean, default: false
field :can_upload_avatars, :boolean, default: false
field :can_upload_maps, :boolean, default: false
field :can_upload_props, :boolean, default: false
timestamps()
end
def admin_changeset(user_privilege_ruleset_or_changeset, attrs) do
user_privilege_ruleset_or_changeset
|> cast(attrs, [:can_upload_avatars, :can_upload_maps, :can_upload_props])
end
end
| 30.571429 | 80 | 0.76324 |
79e6b2311b656419019e963aeff0c2fd193b49fb | 4,643 | ex | Elixir | apps/snitch_core/lib/core/data/model/images.ex | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | 1 | 2021-04-08T22:29:19.000Z | 2021-04-08T22:29:19.000Z | apps/snitch_core/lib/core/data/model/images.ex | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | null | null | null | apps/snitch_core/lib/core/data/model/images.ex | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | null | null | null | defmodule Snitch.Data.Model.Image do
@moduledoc """
Helper functions to handle image uploads.
"""
use Snitch.Data.Model
alias Snitch.Data.Schema.Image
alias Snitch.Data.Schema.GeneralConfiguration, as: GC
alias Snitch.Tools.Helper.ImageUploader
alias Ecto.Multi
@cwd File.cwd!()
def create(module, %{"image" => image} = params, association) do
multi =
Multi.new()
|> Multi.run(:struct, fn _, _ ->
QH.create(module, params, Repo)
end)
|> Multi.run(:image, fn _, %{struct: struct} ->
params = %{"image" => Map.put(image, :url, image_url(image.filename, struct))}
QH.create(Image, params, Repo)
end)
|> Multi.run(:association, fn _, %{image: image, struct: struct} ->
params = Map.put(%{}, association, %{image_id: image.id})
QH.update(module, params, struct, Repo)
end)
|> upload_image_multi(image)
|> persist()
end
@spec update(Image.t(), map) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}
def update(image, params) do
QH.update(Image, image, params, Repo)
end
def update(module, struct, %{"image" => image} = params, association) do
old_image = struct.image
Multi.new()
|> Multi.run(:image, fn _, _ ->
params = %{"image" => Map.put(image, :url, image_url(image.filename, struct))}
QH.create(Image, params, Repo)
end)
|> Multi.run(:struct, fn _, %{image: image} ->
params = Map.put(params, association, %{image_id: image.id})
QH.update(module, params, struct, Repo)
end)
|> delete_image_multi(old_image, struct)
|> upload_image_multi(image)
|> persist()
end
def delete(struct, image, changeset) do
Multi.new()
|> Multi.run(:delete_struct, fn _, _ ->
Repo.delete(changeset)
end)
|> delete_image_multi(image, struct)
|> persist()
end
def delete_image_multi(multi, nil, struct) do
multi
end
def delete_image_multi(multi, image, struct) do
multi
|> Multi.run(:remove_from_upload, fn _, _ ->
struct = %{struct | tenant: Repo.get_prefix()}
case delete_image(image.name, struct) do
:ok ->
{:ok, "success"}
_ ->
{:error, "not_found"}
end
end)
|> Multi.run(:delete_image, fn _, _ ->
QH.delete(Image, image.id, Repo)
end)
end
def store(image, struct) do
struct = %{struct | tenant: Repo.get_prefix()}
ImageUploader.store({image, struct})
end
def delete_image(image, struct) do
struct = %{struct | tenant: Repo.get_prefix()}
ImageUploader.delete({image, struct})
end
def upload_image_multi(multi, %{filename: name, path: path, type: type} = image) do
Multi.run(multi, :image_upload, fn _, %{struct: struct} ->
image = %Plug.Upload{filename: name, path: path, content_type: type}
struct = %{struct | tenant: Repo.get_prefix()}
case ImageUploader.store({image, struct}) do
{:ok, _} ->
{:ok, struct}
_ ->
{:error, "upload error"}
end
end)
end
def persist(multi) do
case Repo.transaction(multi) do
{:ok, %{struct: struct} = multi_result} ->
{:ok, struct}
{:ok, _} ->
{:ok, "success"}
{:error, _, failed_value, _} ->
{:error, failed_value}
end
end
def check_arc_config do
Application.get_env(:arc, :storage) == Arc.Storage.Local
end
def image_url(name, struct, version \\ :thumb) do
base_url = System.get_env("BACKEND_URL")
case Mix.env() do
:dev ->
base_url <> get_image(name, struct, version)
_ ->
get_image(name, struct, version)
end
end
@doc """
Returns the url of the location where image is stored.
Takes as input `name` of the `image` and the corresponding
struct.
"""
defp get_image(name, struct, version) do
struct = %{struct | tenant: Repo.get_prefix()}
image_url = ImageUploader.url({name, struct}, version)
case check_arc_config do
true ->
handle_image_url(image_url)
false ->
image_url
end
end
defp handle_image_url(image_url) do
base_path = String.replace(@cwd, "snitch_core", "admin_app")
case image_url do
nil ->
""
url ->
Path.join(["/"], Path.relative_to(url, base_path))
end
end
def handle_image_value(%Plug.Upload{} = file) do
extension = Path.extname(file.filename)
name = Nanoid.generate() <> extension
%{}
|> Map.put(:filename, name)
|> Map.put(:path, file.path)
|> Map.put(:type, file.content_type)
end
def handle_image_value(_), do: nil
end
| 25.510989 | 87 | 0.604997 |
79e6f1be7a749d4e096a9482ec33fdcac1b76f33 | 667 | exs | Elixir | elixir/samples/phoenix-chat-sample/mix.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | 2 | 2015-12-09T02:16:51.000Z | 2021-07-26T22:53:43.000Z | elixir/samples/phoenix-chat-sample/mix.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | null | null | null | elixir/samples/phoenix-chat-sample/mix.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | 1 | 2016-05-08T18:40:31.000Z | 2016-05-08T18:40:31.000Z | defmodule PhoenixChatSample.Mixfile do
use Mix.Project
def project do
[app: :phoenix_chat_sample,
version: "0.0.1",
elixir: "~> 1.0",
elixirc_paths: ["lib", "web"],
compilers: [:phoenix] ++ Mix.compilers,
deps: deps]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[mod: {PhoenixChatSample, []},
applications: [:phoenix, :cowboy, :logger]]
end
# Specifies your project dependencies
#
# Type `mix help deps` for examples and options
defp deps do
[{:phoenix, github: "phoenixframework/phoenix"},
{:cowboy, "~> 1.0"}]
end
end
| 23 | 52 | 0.641679 |
79e74890121e34c05791d54bba1206ef9a0d2554 | 913 | ex | Elixir | lib/job.ex | ConduitMobileRND/tiktak | 6676976749c950ad71dc9caa1333e53aa15d0f7b | [
"MIT"
] | 24 | 2018-12-31T09:44:20.000Z | 2022-02-02T03:03:00.000Z | lib/job.ex | ConduitMobileRND/tiktak | 6676976749c950ad71dc9caa1333e53aa15d0f7b | [
"MIT"
] | null | null | null | lib/job.ex | ConduitMobileRND/tiktak | 6676976749c950ad71dc9caa1333e53aa15d0f7b | [
"MIT"
] | 2 | 2019-01-23T00:54:45.000Z | 2019-05-28T10:14:44.000Z | defmodule TikTak.Job do
use Ecto.Schema
require Ecto.Query
alias Ecto.{Query, Changeset}
alias TikTak.{Schedule, Job}
schema "jobs" do
belongs_to :schedule, Schedule, type: :string
field :next_run, :integer
field :callback_url, :string
field :priority, :integer, default: 5
end
def get(job_ids) do
Query.from(j in Job, where: j.id in ^job_ids)
end
def get_by_schedule(schedule_id) do
Query.from(j in Job, where: j.schedule_id == ^schedule_id)
end
def get_mature(limit) do
current_time = DateTime.utc_now
|> DateTime.to_unix
Query.from(j in Job, where: j.next_run < ^current_time, order_by: [j.priority, j.next_run], limit: ^limit)
end
def create(job) do
%Job{}
|> Changeset.cast(job, [:schedule_id, :next_run, :callback_url, :priority])
|> Changeset.validate_required([:schedule_id, :next_run, :callback_url])
end
end | 27.666667 | 110 | 0.67908 |
79e760bdb6420d738ad607b22f75b9d77c98bde3 | 9,163 | ex | Elixir | clients/content/lib/google_api/content/v2/api/accountstatuses.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/api/accountstatuses.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/api/accountstatuses.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Content.V2.Api.Accountstatuses do
@moduledoc """
API calls for all endpoints tagged `Accountstatuses`.
"""
alias GoogleApi.Content.V2.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Retrieves multiple Merchant Center account statuses in a single request.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.AccountstatusesCustomBatchRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.AccountstatusesCustomBatchResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_accountstatuses_custombatch(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.AccountstatusesCustomBatchResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def content_accountstatuses_custombatch(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/accountstatuses/batch", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.AccountstatusesCustomBatchResponse{}]
)
end
@doc """
Retrieves the status of a Merchant Center account. No itemLevelIssues are returned for multi-client accounts.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and accountId must be the ID of a sub-account of this account.
* `account_id` (*type:* `String.t`) - The ID of the account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:destinations` (*type:* `list(String.t)`) - If set, only issues for the specified destinations are returned, otherwise only issues for the Shopping destination.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.AccountStatus{}}` on success
* `{:error, info}` on failure
"""
@spec content_accountstatuses_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.AccountStatus.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def content_accountstatuses_get(
connection,
merchant_id,
account_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:destinations => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{merchantId}/accountstatuses/{accountId}", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"accountId" => URI.encode(account_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.AccountStatus{}])
end
@doc """
Lists the statuses of the sub-accounts in your Merchant Center account.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the managing account. This must be a multi-client account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:destinations` (*type:* `list(String.t)`) - If set, only issues for the specified destinations are returned, otherwise only issues for the Shopping destination.
* `:maxResults` (*type:* `integer()`) - The maximum number of account statuses to return in the response, used for paging.
* `:pageToken` (*type:* `String.t`) - The token returned by the previous request.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.AccountstatusesListResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_accountstatuses_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.AccountstatusesListResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def content_accountstatuses_list(connection, merchant_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:destinations => :query,
:maxResults => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{merchantId}/accountstatuses", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.AccountstatusesListResponse{}]
)
end
end
| 44.480583 | 234 | 0.646077 |
79e767650b36e0845cea7dfd5de1980c0f47105a | 502 | exs | Elixir | euler/elixir/0003-largest-prime-factor.exs | kerkeslager/sandbox | 45ec9c36ab7241cee93e615b3c901b5b80aa7aff | [
"MIT"
] | null | null | null | euler/elixir/0003-largest-prime-factor.exs | kerkeslager/sandbox | 45ec9c36ab7241cee93e615b3c901b5b80aa7aff | [
"MIT"
] | null | null | null | euler/elixir/0003-largest-prime-factor.exs | kerkeslager/sandbox | 45ec9c36ab7241cee93e615b3c901b5b80aa7aff | [
"MIT"
] | null | null | null | defmodule LargestPrimeFactor do
def largest_prime_factor(start, n) do
if start >= (n / 2) do
n
else
if rem(n, start) == 0 do
largest_prime_factor(start, div(n, start))
else
largest_prime_factor(start + 2, n)
end
end
end
def largest_prime_factor(n) do
n_next = if rem(n, 2) == 0 do
div(n, 2)
else
n
end
largest_prime_factor(3, n_next)
end
end
IO.puts(LargestPrimeFactor.largest_prime_factor(600851475143))
| 19.307692 | 62 | 0.613546 |
79e7c4bf82de200faecba3ecef19abf3e04a9b66 | 939 | ex | Elixir | lib/broadway/caller_acknowledger.ex | nathanl/broadway | 261660c4bb810b16942b623f99b367ea81490852 | [
"Apache-2.0"
] | 1,004 | 2020-01-20T15:19:59.000Z | 2022-03-30T07:19:34.000Z | lib/broadway/caller_acknowledger.ex | nathanl/broadway | 261660c4bb810b16942b623f99b367ea81490852 | [
"Apache-2.0"
] | 130 | 2020-01-26T10:09:30.000Z | 2022-03-21T13:20:11.000Z | lib/broadway/caller_acknowledger.ex | nathanl/broadway | 261660c4bb810b16942b623f99b367ea81490852 | [
"Apache-2.0"
] | 90 | 2020-01-24T17:01:33.000Z | 2022-02-16T04:42:59.000Z | defmodule Broadway.CallerAcknowledger do
@moduledoc """
A simple acknowledger that sends a message back to a caller.
It must be stored as:
acknowledger: {Broadway.CallerAcknowledger, {pid, ref}, term}
The second element is a tuple with the pid to receive the messages
and a unique identifier (usually a reference). The third element,
which is per message, is ignored.
It sends a message in the format:
{:ack, ref, successful_messages, failed_messages}
If `Broadway.Message.configure_ack/2` is called on a message that
uses this acknowledger, then the following message is sent:
{:configure, ref, options}
"""
@behaviour Broadway.Acknowledger
@impl true
def ack({pid, ref}, successful, failed) do
send(pid, {:ack, ref, successful, failed})
end
@impl true
def configure({pid, ref}, ack_data, options) do
send(pid, {:configure, ref, options})
{:ok, ack_data}
end
end
| 25.378378 | 68 | 0.705005 |
79e7d21a483d8ef71f2b30b73e8924b144d44957 | 412 | ex | Elixir | apps/sue/lib/sue/models/response.ex | inculi/Sue | 42e249aec1d9c467db63526966d9690d5c58f346 | [
"MIT"
] | 9 | 2018-03-23T11:18:21.000Z | 2021-08-06T18:38:37.000Z | lib/sue/models/response.ex | alwayswimmin/Sue | 33dfd860e7d5b6dce11e2dc202924efad6a9474c | [
"MIT"
] | 21 | 2017-12-01T05:57:10.000Z | 2021-06-06T18:53:25.000Z | lib/sue/models/response.ex | alwayswimmin/Sue | 33dfd860e7d5b6dce11e2dc202924efad6a9474c | [
"MIT"
] | 6 | 2018-03-23T11:24:21.000Z | 2021-08-06T18:40:28.000Z | defmodule Sue.Models.Response do
alias __MODULE__
@type t() :: %__MODULE__{}
defstruct [
:body,
attachments: []
]
defimpl String.Chars, for: Response do
def to_string(%Response{body: body, attachments: [%Sue.Models.Attachment{} | _]}) do
"#Response<body:'#{body}',:has_media>"
end
def to_string(%Response{body: body}) do
"#Response<body:'#{body}'>"
end
end
end
| 20.6 | 88 | 0.623786 |
79e7e5d365cd44109856d57bd1630e581176141e | 1,669 | ex | Elixir | clients/bigtable_admin/lib/google_api/bigtable_admin/v2/model/get_iam_policy_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/bigtable_admin/lib/google_api/bigtable_admin/v2/model/get_iam_policy_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/bigtable_admin/lib/google_api/bigtable_admin/v2/model/get_iam_policy_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.BigtableAdmin.V2.Model.GetIamPolicyRequest do
@moduledoc """
Request message for `GetIamPolicy` method.
## Attributes
* `options` (*type:* `GoogleApi.BigtableAdmin.V2.Model.GetPolicyOptions.t`, *default:* `nil`) - OPTIONAL: A `GetPolicyOptions` object for specifying options to
`GetIamPolicy`. This field is only used by Cloud IAM.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:options => GoogleApi.BigtableAdmin.V2.Model.GetPolicyOptions.t()
}
field(:options, as: GoogleApi.BigtableAdmin.V2.Model.GetPolicyOptions)
end
defimpl Poison.Decoder, for: GoogleApi.BigtableAdmin.V2.Model.GetIamPolicyRequest do
def decode(value, options) do
GoogleApi.BigtableAdmin.V2.Model.GetIamPolicyRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigtableAdmin.V2.Model.GetIamPolicyRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.770833 | 163 | 0.753745 |
79e7f07d17840d53ec7bfc96a0645d8372ba0bb1 | 1,313 | ex | Elixir | lib/sudachi.ex | shoz-f/sudachi_ex | c873626fbc2c1f999b814a65c4873f4db3963065 | [
"Apache-2.0"
] | null | null | null | lib/sudachi.ex | shoz-f/sudachi_ex | c873626fbc2c1f999b814a65c4873f4db3963065 | [
"Apache-2.0"
] | null | null | null | lib/sudachi.ex | shoz-f/sudachi_ex | c873626fbc2c1f999b814a65c4873f4db3963065 | [
"Apache-2.0"
] | null | null | null | defmodule Sudachi do
@moduledoc """
sudachi_ex is the Elixir binding of Sudachi, the Japanese morphological analyzer.
## Installation
the sudachi_ex is installed by adding `sudachi` to your list of dependencies in `mix.exs`:
```elixir
def deps do
[
{:sudachi, "~> 0.1.0"}
]
end
```
You need to featch a sudachi dictionary:
```shell
mix sudachi.fetch_dic
```
"""
alias Sudachi.NIF
@doc """
Analize the text and return the list of morphemes.
## Parameters
* text - input text.
* opts - analysis options
- :all - Include extended analysis.
- :debug - with debug outputs.
## Examples
```Elixir
iex> res = Sudachi.analize("打込む かつ丼 附属 vintage")
[
["打込む", "動詞", "一般", "*", "*", "五段-マ行", "終止形-一般", "打ち込む"],
[" ", "空白", "*", "*", "*", "*", "*", " "],
["かつ丼", "名詞", "普通名詞", "一般", "*", "*", "*", "カツ丼"],
[" ", "空白", "*", "*", "*", "*", "*", " "],
["附属", "名詞", "普通名詞", "サ変可能", "*", "*", "*", "付属"],
[" ", "空白", "*", "*", "*", "*", "*", " "],
["vintage", "名詞", "普通名詞", "一般", "*", "*", "*", "ビンテージ"]
]
```
"""
def analize(text, opts \\ []) do
put_all = (:all in opts)
enable_debug = (:debug in opts)
NIF.analize(text, put_all, enable_debug)
end
end
| 23.035088 | 92 | 0.482102 |
79e80fce32694cbc32898453556dd9317797c322 | 11,538 | ex | Elixir | lib/codes/codes_v17.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_v17.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_v17.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_V17 do
alias IcdCode.ICDCode
def _V170XXA do
%ICDCode{full_code: "V170XXA",
category_code: "V17",
short_code: "0XXA",
full_name: "Pedal cycle driver injured in collision with fixed or stationary object in nontraffic accident, initial encounter",
short_name: "Pedal cycle driver injured in collision with fixed or stationary object in nontraffic accident, initial encounter",
category_name: "Pedal cycle driver injured in collision with fixed or stationary object in nontraffic accident, initial encounter"
}
end
def _V170XXD do
%ICDCode{full_code: "V170XXD",
category_code: "V17",
short_code: "0XXD",
full_name: "Pedal cycle driver injured in collision with fixed or stationary object in nontraffic accident, subsequent encounter",
short_name: "Pedal cycle driver injured in collision with fixed or stationary object in nontraffic accident, subsequent encounter",
category_name: "Pedal cycle driver injured in collision with fixed or stationary object in nontraffic accident, subsequent encounter"
}
end
def _V170XXS do
%ICDCode{full_code: "V170XXS",
category_code: "V17",
short_code: "0XXS",
full_name: "Pedal cycle driver injured in collision with fixed or stationary object in nontraffic accident, sequela",
short_name: "Pedal cycle driver injured in collision with fixed or stationary object in nontraffic accident, sequela",
category_name: "Pedal cycle driver injured in collision with fixed or stationary object in nontraffic accident, sequela"
}
end
def _V171XXA do
%ICDCode{full_code: "V171XXA",
category_code: "V17",
short_code: "1XXA",
full_name: "Pedal cycle passenger injured in collision with fixed or stationary object in nontraffic accident, initial encounter",
short_name: "Pedal cycle passenger injured in collision with fixed or stationary object in nontraffic accident, initial encounter",
category_name: "Pedal cycle passenger injured in collision with fixed or stationary object in nontraffic accident, initial encounter"
}
end
def _V171XXD do
%ICDCode{full_code: "V171XXD",
category_code: "V17",
short_code: "1XXD",
full_name: "Pedal cycle passenger injured in collision with fixed or stationary object in nontraffic accident, subsequent encounter",
short_name: "Pedal cycle passenger injured in collision with fixed or stationary object in nontraffic accident, subsequent encounter",
category_name: "Pedal cycle passenger injured in collision with fixed or stationary object in nontraffic accident, subsequent encounter"
}
end
def _V171XXS do
%ICDCode{full_code: "V171XXS",
category_code: "V17",
short_code: "1XXS",
full_name: "Pedal cycle passenger injured in collision with fixed or stationary object in nontraffic accident, sequela",
short_name: "Pedal cycle passenger injured in collision with fixed or stationary object in nontraffic accident, sequela",
category_name: "Pedal cycle passenger injured in collision with fixed or stationary object in nontraffic accident, sequela"
}
end
def _V172XXA do
%ICDCode{full_code: "V172XXA",
category_code: "V17",
short_code: "2XXA",
full_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in nontraffic accident, initial encounter",
short_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in nontraffic accident, initial encounter",
category_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in nontraffic accident, initial encounter"
}
end
def _V172XXD do
%ICDCode{full_code: "V172XXD",
category_code: "V17",
short_code: "2XXD",
full_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in nontraffic accident, subsequent encounter",
short_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in nontraffic accident, subsequent encounter",
category_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in nontraffic accident, subsequent encounter"
}
end
def _V172XXS do
%ICDCode{full_code: "V172XXS",
category_code: "V17",
short_code: "2XXS",
full_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in nontraffic accident, sequela",
short_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in nontraffic accident, sequela",
category_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in nontraffic accident, sequela"
}
end
def _V173XXA do
%ICDCode{full_code: "V173XXA",
category_code: "V17",
short_code: "3XXA",
full_name: "Person boarding or alighting a pedal cycle injured in collision with fixed or stationary object, initial encounter",
short_name: "Person boarding or alighting a pedal cycle injured in collision with fixed or stationary object, initial encounter",
category_name: "Person boarding or alighting a pedal cycle injured in collision with fixed or stationary object, initial encounter"
}
end
def _V173XXD do
%ICDCode{full_code: "V173XXD",
category_code: "V17",
short_code: "3XXD",
full_name: "Person boarding or alighting a pedal cycle injured in collision with fixed or stationary object, subsequent encounter",
short_name: "Person boarding or alighting a pedal cycle injured in collision with fixed or stationary object, subsequent encounter",
category_name: "Person boarding or alighting a pedal cycle injured in collision with fixed or stationary object, subsequent encounter"
}
end
def _V173XXS do
%ICDCode{full_code: "V173XXS",
category_code: "V17",
short_code: "3XXS",
full_name: "Person boarding or alighting a pedal cycle injured in collision with fixed or stationary object, sequela",
short_name: "Person boarding or alighting a pedal cycle injured in collision with fixed or stationary object, sequela",
category_name: "Person boarding or alighting a pedal cycle injured in collision with fixed or stationary object, sequela"
}
end
def _V174XXA do
%ICDCode{full_code: "V174XXA",
category_code: "V17",
short_code: "4XXA",
full_name: "Pedal cycle driver injured in collision with fixed or stationary object in traffic accident, initial encounter",
short_name: "Pedal cycle driver injured in collision with fixed or stationary object in traffic accident, initial encounter",
category_name: "Pedal cycle driver injured in collision with fixed or stationary object in traffic accident, initial encounter"
}
end
def _V174XXD do
%ICDCode{full_code: "V174XXD",
category_code: "V17",
short_code: "4XXD",
full_name: "Pedal cycle driver injured in collision with fixed or stationary object in traffic accident, subsequent encounter",
short_name: "Pedal cycle driver injured in collision with fixed or stationary object in traffic accident, subsequent encounter",
category_name: "Pedal cycle driver injured in collision with fixed or stationary object in traffic accident, subsequent encounter"
}
end
def _V174XXS do
%ICDCode{full_code: "V174XXS",
category_code: "V17",
short_code: "4XXS",
full_name: "Pedal cycle driver injured in collision with fixed or stationary object in traffic accident, sequela",
short_name: "Pedal cycle driver injured in collision with fixed or stationary object in traffic accident, sequela",
category_name: "Pedal cycle driver injured in collision with fixed or stationary object in traffic accident, sequela"
}
end
def _V175XXA do
%ICDCode{full_code: "V175XXA",
category_code: "V17",
short_code: "5XXA",
full_name: "Pedal cycle passenger injured in collision with fixed or stationary object in traffic accident, initial encounter",
short_name: "Pedal cycle passenger injured in collision with fixed or stationary object in traffic accident, initial encounter",
category_name: "Pedal cycle passenger injured in collision with fixed or stationary object in traffic accident, initial encounter"
}
end
def _V175XXD do
%ICDCode{full_code: "V175XXD",
category_code: "V17",
short_code: "5XXD",
full_name: "Pedal cycle passenger injured in collision with fixed or stationary object in traffic accident, subsequent encounter",
short_name: "Pedal cycle passenger injured in collision with fixed or stationary object in traffic accident, subsequent encounter",
category_name: "Pedal cycle passenger injured in collision with fixed or stationary object in traffic accident, subsequent encounter"
}
end
def _V175XXS do
%ICDCode{full_code: "V175XXS",
category_code: "V17",
short_code: "5XXS",
full_name: "Pedal cycle passenger injured in collision with fixed or stationary object in traffic accident, sequela",
short_name: "Pedal cycle passenger injured in collision with fixed or stationary object in traffic accident, sequela",
category_name: "Pedal cycle passenger injured in collision with fixed or stationary object in traffic accident, sequela"
}
end
def _V179XXA do
%ICDCode{full_code: "V179XXA",
category_code: "V17",
short_code: "9XXA",
full_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in traffic accident, initial encounter",
short_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in traffic accident, initial encounter",
category_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in traffic accident, initial encounter"
}
end
def _V179XXD do
%ICDCode{full_code: "V179XXD",
category_code: "V17",
short_code: "9XXD",
full_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in traffic accident, subsequent encounter",
short_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in traffic accident, subsequent encounter",
category_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in traffic accident, subsequent encounter"
}
end
def _V179XXS do
%ICDCode{full_code: "V179XXS",
category_code: "V17",
short_code: "9XXS",
full_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in traffic accident, sequela",
short_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in traffic accident, sequela",
category_name: "Unspecified pedal cyclist injured in collision with fixed or stationary object in traffic accident, sequela"
}
end
end
| 58.867347 | 150 | 0.715982 |
79e86a3aa02b63c153f691b0882066525ffe2a8d | 5,584 | exs | Elixir | test/lib/plaid/item_test.exs | GetAmbush/plaid-elixir | 16f1c650051f3c2d3c551692868f466b244a0c15 | [
"MIT"
] | null | null | null | test/lib/plaid/item_test.exs | GetAmbush/plaid-elixir | 16f1c650051f3c2d3c551692868f466b244a0c15 | [
"MIT"
] | null | null | null | test/lib/plaid/item_test.exs | GetAmbush/plaid-elixir | 16f1c650051f3c2d3c551692868f466b244a0c15 | [
"MIT"
] | 1 | 2019-10-08T12:56:22.000Z | 2019-10-08T12:56:22.000Z | defmodule Plaid.ItemTest do
use ExUnit.Case
import Plaid.Factory
setup do
bypass = Bypass.open()
Application.put_env(:plaid, :root_uri, "http://localhost:#{bypass.port}/")
{:ok, bypass: bypass}
end
describe "item" do
test "get/1 requests POST and returns Plaid.Item", %{bypass: bypass} do
body = http_response_body(:item)
Bypass.expect(bypass, fn conn ->
assert "POST" == conn.method
assert "item/get" == Enum.join(conn.path_info, "/")
Plug.Conn.resp(conn, 200, Poison.encode!(body))
end)
assert {:ok, resp} = Plaid.Item.get(%{access_token: "my-token"})
assert Plaid.Item == resp.__struct__
assert {:ok, _} = Jason.encode(resp)
end
test "exchange_public_token/1 requests POST and returns map", %{bypass: bypass} do
body = http_response_body(:exchange_public_token)
Bypass.expect(bypass, fn conn ->
assert "POST" == conn.method
assert "item/public_token/exchange" == Enum.join(conn.path_info, "/")
Plug.Conn.resp(conn, 200, Poison.encode!(body))
end)
assert {:ok, resp} = Plaid.Item.exchange_public_token(%{public_token: "public-token"})
assert resp.access_token == body["access_token"]
assert resp.item_id == body["item_id"]
assert resp.request_id == body["request_id"]
end
test "create_public_token/1 request POST and returns map", %{bypass: bypass} do
body = http_response_body(:create_public_token)
Bypass.expect(bypass, fn conn ->
assert "POST" == conn.method
assert "item/public_token/create" == Enum.join(conn.path_info, "/")
Plug.Conn.resp(conn, 200, Poison.encode!(body))
end)
assert {:ok, resp} = Plaid.Item.create_public_token(%{access_token: "my-token"})
assert resp.public_token == body["public_token"]
assert resp.expiration == body["expiration"]
assert resp.request_id == body["request_id"]
end
test "update_webhook/1 requests POST and returns Plaid.Item", %{bypass: bypass} do
body = http_response_body(:webhook)
Bypass.expect(bypass, fn conn ->
{:ok, req_body, _conn} = Plug.Conn.read_body(conn)
assert "POST" == conn.method
assert "item/webhook/update" == Enum.join(conn.path_info, "/")
assert String.starts_with?(req_body, "{\"webhook\":\"https://plaid.com/updated/hook\"")
Plug.Conn.resp(conn, 200, Poison.encode!(body))
end)
params = %{access_token: "my-token", webhook: "https://plaid.com/updated/hook"}
assert {:ok, resp} = Plaid.Item.update_webhook(params)
assert Plaid.Item == resp.__struct__
assert {:ok, _} = Jason.encode(resp)
end
test "rotate_access_token/1 requests POST and returns success", %{bypass: bypass} do
body = http_response_body(:rotate_access_token)
Bypass.expect(bypass, fn conn ->
{:ok, req_body, _conn} = Plug.Conn.read_body(conn)
assert "POST" == conn.method
assert "item/access_token/invalidate" == Enum.join(conn.path_info, "/")
assert String.ends_with?(req_body, "\"access_token\":\"my-token\"}")
Plug.Conn.resp(conn, 200, Poison.encode!(body))
end)
assert {:ok, resp} = Plaid.Item.rotate_access_token(%{access_token: "my-token"})
assert resp.new_access_token == body["new_access_token"]
end
test "update_version_access_token/1 requests POST and returns success", %{bypass: bypass} do
body = http_response_body(:update_version_access_token)
Bypass.expect(bypass, fn conn ->
{:ok, req_body, _conn} = Plug.Conn.read_body(conn)
assert "POST" == conn.method
assert "item/access_token/update_version" == Enum.join(conn.path_info, "/")
assert String.ends_with?(req_body, "\"access_token_v1\":\"my-token\"}")
Plug.Conn.resp(conn, 200, Poison.encode!(body))
end)
assert {:ok, resp} = Plaid.Item.update_version_access_token(%{access_token_v1: "my-token"})
assert resp.access_token == body["access_token"]
end
test "delete/1 requests POST and returns success", %{bypass: bypass} do
body = http_response_body(:delete)
Bypass.expect(bypass, fn conn ->
assert "POST" == conn.method
assert "item/delete" == Enum.join(conn.path_info, "/")
Plug.Conn.resp(conn, 200, Poison.encode!(body))
end)
assert {:ok, resp} = Plaid.Item.delete(%{access_token: "my-token"})
assert resp.deleted == body["deleted"]
end
test "create_dwolla_token/1 request POST and returns token", %{bypass: bypass} do
body = http_response_body(:processor_token)
Bypass.expect(bypass, fn conn ->
assert "POST" == conn.method
assert "processor/dwolla/processor_token/create" == Enum.join(conn.path_info, "/")
Plug.Conn.resp(conn, 200, Poison.encode!(body))
end)
assert {:ok, resp} =
Plaid.Item.create_dwolla_token(%{access_token: "token", account_id: "id"})
assert resp.processor_token
end
test "create_stripe_token/1 request POST and returns token", %{bypass: bypass} do
body = http_response_body(:processor_token)
Bypass.expect(bypass, fn conn ->
assert "POST" == conn.method
assert "processor/stripe/bank_account_token/create" == Enum.join(conn.path_info, "/")
Plug.Conn.resp(conn, 200, Poison.encode!(body))
end)
assert {:ok, resp} =
Plaid.Item.create_stripe_token(%{access_token: "token", account_id: "id"})
assert resp.processor_token
end
end
end
| 37.72973 | 97 | 0.645953 |
79e89d0eab4a368e7e6510f7560398667dce1efc | 876 | ex | Elixir | deps/absinthe/lib/absinthe/type/non_null.ex | JoakimEskils/elixir-absinthe | d81e24ec7c7b1164e6d152101dd50422f192d7e9 | [
"MIT"
] | 3 | 2017-06-22T16:33:58.000Z | 2021-07-07T15:21:09.000Z | lib/absinthe/type/non_null.ex | bruce/absinthe | 19b63d3aaa9fb75aad01ffd5e91d89e0b30d7f91 | [
"MIT"
] | null | null | null | lib/absinthe/type/non_null.ex | bruce/absinthe | 19b63d3aaa9fb75aad01ffd5e91d89e0b30d7f91 | [
"MIT"
] | null | null | null | defmodule Absinthe.Type.NonNull do
@moduledoc """
A type that wraps an underlying type, acting identically to that type but
adding a non-null constraint.
By default, all types in GraphQL are nullable. To declare a type that
disallows null, wrap it in a `Absinthe.Type.NonNull` struct.
## Examples
Given a type, `:item`, to declare it as non-null, you could do the following:
```
type: %Absinthe.Type.NonNull{of_type: :item}
```
But normally this would be done using `Absinthe.Schema.Notation.non_null/1`.
```
type: non_null(:item)
```
"""
use Absinthe.Introspection.Kind
use Absinthe.Type.Fetch
@typedoc """
A defined non-null type.
## Options
* `:of_type` -- the underlying type to wrap
"""
defstruct of_type: nil
@type t :: %__MODULE__{of_type: Absinthe.Type.nullable_t}
@type t(x) :: %__MODULE__{of_type: x}
end
| 22.461538 | 79 | 0.687215 |
79e8a53ff6d0eb302287396adba4863e8f26ca84 | 4,714 | exs | Elixir | lib/elixir/test/elixir/task_test.exs | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | 1 | 2015-02-23T00:01:48.000Z | 2015-02-23T00:01:48.000Z | lib/elixir/test/elixir/task_test.exs | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/task_test.exs | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | null | null | null | Code.require_file "test_helper.exs", __DIR__
defmodule TaskTest do
use ExUnit.Case
setup do
Logger.remove_backend(:console)
on_exit fn -> Logger.add_backend(:console, flush: true) end
:ok
end
def wait_and_send(caller, atom) do
send caller, :ready
receive do: (true -> true)
send caller, atom
end
test "async/1" do
parent = self()
fun = fn -> wait_and_send(parent, :done) end
task = Task.async(fun)
# Assert the struct
assert task.__struct__ == Task
assert is_pid task.pid
assert is_reference task.ref
# Assert the link
{:links, links} = Process.info(self, :links)
assert task.pid in links
receive do: (:ready -> :ok)
# Assert the initial call
{:name, fun_name} = :erlang.fun_info(fun, :name)
assert {__MODULE__, fun_name, 0} === :proc_lib.translate_initial_call(task.pid)
# Run the task
send task.pid, true
# Assert response and monitoring messages
ref = task.ref
assert_receive {^ref, :done}
assert_receive {:DOWN, ^ref, _, _, :normal}
end
test "async/3" do
task = Task.async(__MODULE__, :wait_and_send, [self(), :done])
assert task.__struct__ == Task
{:links, links} = Process.info(self, :links)
assert task.pid in links
receive do: (:ready -> :ok)
assert {__MODULE__, :wait_and_send, 2} === :proc_lib.translate_initial_call(task.pid)
send(task.pid, true)
assert Task.await(task) === :done
assert_receive :done
end
test "start/1" do
parent = self()
fun = fn -> wait_and_send(parent, :done) end
{:ok, pid} = Task.start(fun)
{:links, links} = Process.info(self, :links)
refute pid in links
receive do: (:ready -> :ok)
{:name, fun_name} = :erlang.fun_info(fun, :name)
assert {__MODULE__, fun_name, 0} === :proc_lib.translate_initial_call(pid)
send pid, true
assert_receive :done
end
test "start/3" do
{:ok, pid} = Task.start(__MODULE__, :wait_and_send, [self(), :done])
{:links, links} = Process.info(self, :links)
refute pid in links
receive do: (:ready -> :ok)
assert {__MODULE__, :wait_and_send, 2} === :proc_lib.translate_initial_call(pid)
send pid, true
assert_receive :done
end
test "start_link/1" do
parent = self()
fun = fn -> wait_and_send(parent, :done) end
{:ok, pid} = Task.start_link(fun)
{:links, links} = Process.info(self, :links)
assert pid in links
receive do: (:ready -> :ok)
{:name, fun_name} = :erlang.fun_info(fun, :name)
assert {__MODULE__, fun_name, 0} === :proc_lib.translate_initial_call(pid)
send pid, true
assert_receive :done
end
test "start_link/3" do
{:ok, pid} = Task.start_link(__MODULE__, :wait_and_send, [self(), :done])
{:links, links} = Process.info(self, :links)
assert pid in links
receive do: (:ready -> :ok)
assert {__MODULE__, :wait_and_send, 2} === :proc_lib.translate_initial_call(pid)
send pid, true
assert_receive :done
end
test "await/1 exits on timeout" do
task = %Task{ref: make_ref()}
assert catch_exit(Task.await(task, 0)) == {:timeout, {Task, :await, [task, 0]}}
end
test "await/1 exits on normal exit" do
task = Task.async(fn -> exit :normal end)
assert catch_exit(Task.await(task)) == {:normal, {Task, :await, [task, 5000]}}
end
test "await/1 exits on task throw" do
Process.flag(:trap_exit, true)
task = Task.async(fn -> throw :unknown end)
assert {{{:nocatch, :unknown}, _}, {Task, :await, [^task, 5000]}} =
catch_exit(Task.await(task))
end
test "await/1 exits on task error" do
Process.flag(:trap_exit, true)
task = Task.async(fn -> raise "oops" end)
assert {{%RuntimeError{}, _}, {Task, :await, [^task, 5000]}} =
catch_exit(Task.await(task))
end
test "await/1 exits on task exit" do
Process.flag(:trap_exit, true)
task = Task.async(fn -> exit :unknown end)
assert {:unknown, {Task, :await, [^task, 5000]}} =
catch_exit(Task.await(task))
end
test "await/1 exits on :noconnection" do
ref = make_ref()
task = %Task{ref: ref, pid: self()}
send self(), {:DOWN, ref, self(), self(), :noconnection}
assert catch_exit(Task.await(task)) |> elem(0) == {:nodedown, :nonode@nohost}
end
test "find/2" do
task = %Task{ref: make_ref}
assert Task.find([task], {make_ref, :ok}) == nil
assert Task.find([task], {task.ref, :ok}) == {:ok, task}
assert Task.find([task], {:DOWN, make_ref, :process, self, :kill}) == nil
msg = {:DOWN, task.ref, :process, self, :kill}
assert catch_exit(Task.find([task], msg)) ==
{:kill, {Task, :find, [[task], msg]}}
end
end
| 26.784091 | 89 | 0.624735 |
79e8c15d387b907f7ce595f238d313f7ec72d8dc | 343 | ex | Elixir | apps/plant_monitor_web/lib/plant_monitor_web/views/api/user_view.ex | bartoszgorka/PlantMonitor | 23e18cd76c51bd8eee021ee98668926de885047b | [
"MIT"
] | 2 | 2019-01-25T21:21:56.000Z | 2021-02-24T08:18:51.000Z | apps/plant_monitor_web/lib/plant_monitor_web/views/api/user_view.ex | bartoszgorka/PlantMonitor | 23e18cd76c51bd8eee021ee98668926de885047b | [
"MIT"
] | null | null | null | apps/plant_monitor_web/lib/plant_monitor_web/views/api/user_view.ex | bartoszgorka/PlantMonitor | 23e18cd76c51bd8eee021ee98668926de885047b | [
"MIT"
] | null | null | null | defmodule PlantMonitorWeb.API.UserView do
@moduledoc """
User view render.
"""
use PlantMonitorWeb, :view
alias PlantMonitorWeb.Structs.ConfirmResponse
def render("correct_register.json", _assigns) do
%ConfirmResponse{
message: "Correct registed in PlantMonitor API. Now you can login and use our API."
}
end
end
| 22.866667 | 89 | 0.725948 |
79e8cebfd4a2f5b969e4bfcb823a20fbaba2dba1 | 1,150 | exs | Elixir | config/config.exs | everilae/httpoison_retry | aa11029bf7a7f0169d76ed8749ad7a8203ccaf7b | [
"MIT"
] | 14 | 2018-03-27T17:09:33.000Z | 2021-12-05T22:53:10.000Z | config/config.exs | everilae/httpoison_retry | aa11029bf7a7f0169d76ed8749ad7a8203ccaf7b | [
"MIT"
] | 4 | 2018-04-20T20:47:26.000Z | 2020-03-23T19:33:11.000Z | config/config.exs | mpihlak/httpoison_retry | 4ac3cc3fd90f90b5482fac56314c90d837bbb429 | [
"MIT"
] | 9 | 2018-03-29T10:14:26.000Z | 2021-05-31T06:01:05.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
config :httpoison_retry,
wait: 1 # Set the wait time to be 1 millisecond to increase test time
#
# and access this configuration in your application as:
#
# Application.get_env(:httpoison_retry, :key)
#
# You can also configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 38.333333 | 73 | 0.75913 |
79e8edb5fa131103ffcd27d656631d1014004b54 | 1,455 | ex | Elixir | clients/service_usage/lib/google_api/service_usage/v1/model/update_admin_quota_policy_metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/service_usage/lib/google_api/service_usage/v1/model/update_admin_quota_policy_metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/service_usage/lib/google_api/service_usage/v1/model/update_admin_quota_policy_metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ServiceUsage.V1.Model.UpdateAdminQuotaPolicyMetadata do
@moduledoc """
Metadata message that provides information such as progress, partial failures, and similar information on each GetOperation call of LRO returned by UpdateAdminQuotaPolicy.
## Attributes
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{}
end
defimpl Poison.Decoder, for: GoogleApi.ServiceUsage.V1.Model.UpdateAdminQuotaPolicyMetadata do
def decode(value, options) do
GoogleApi.ServiceUsage.V1.Model.UpdateAdminQuotaPolicyMetadata.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceUsage.V1.Model.UpdateAdminQuotaPolicyMetadata do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.642857 | 173 | 0.781443 |
79e8f110d3ba23c6fe8e5efa9496ee18b0454b3a | 277 | ex | Elixir | coherence_demo_no_confirm/lib/coherence_demo/repo.ex | hotpyn/coherence-setup | fc10bb15d993ae0dd13a19fd178bdfb4ee13d6b6 | [
"MIT"
] | null | null | null | coherence_demo_no_confirm/lib/coherence_demo/repo.ex | hotpyn/coherence-setup | fc10bb15d993ae0dd13a19fd178bdfb4ee13d6b6 | [
"MIT"
] | null | null | null | coherence_demo_no_confirm/lib/coherence_demo/repo.ex | hotpyn/coherence-setup | fc10bb15d993ae0dd13a19fd178bdfb4ee13d6b6 | [
"MIT"
] | null | null | null | defmodule CoherenceDemo.Repo do
use Ecto.Repo, otp_app: :coherence_demo
@doc """
Dynamically loads the repository url from the
DATABASE_URL environment variable.
"""
def init(_, opts) do
{:ok, Keyword.put(opts, :url, System.get_env("DATABASE_URL"))}
end
end
| 23.083333 | 66 | 0.711191 |
79e8f403cc0024cdb5d5893974752e253124e572 | 347 | exs | Elixir | microservice/priv/repo/seeds.exs | eduardobarbiero/microservice-contacts | 330d1855c8b9296e030bfe62cabc3a1c20cef500 | [
"MIT"
] | null | null | null | microservice/priv/repo/seeds.exs | eduardobarbiero/microservice-contacts | 330d1855c8b9296e030bfe62cabc3a1c20cef500 | [
"MIT"
] | null | null | null | microservice/priv/repo/seeds.exs | eduardobarbiero/microservice-contacts | 330d1855c8b9296e030bfe62cabc3a1c20cef500 | [
"MIT"
] | null | null | null | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Microservice.Repo.insert!(%SomeModel{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 28.916667 | 61 | 0.706052 |
79e9219e849037f08bc1ea1a6e1ca7da4a0248c4 | 450 | exs | Elixir | api/test/muhnee_web/views/error_view_test.exs | bkbooth/muhnee | b0a1f33f3509a8b1ca90db77001ccfd26b8b3c67 | [
"MIT"
] | null | null | null | api/test/muhnee_web/views/error_view_test.exs | bkbooth/muhnee | b0a1f33f3509a8b1ca90db77001ccfd26b8b3c67 | [
"MIT"
] | null | null | null | api/test/muhnee_web/views/error_view_test.exs | bkbooth/muhnee | b0a1f33f3509a8b1ca90db77001ccfd26b8b3c67 | [
"MIT"
] | null | null | null | defmodule MuhneeWeb.ErrorViewTest do
use MuhneeWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.json" do
assert render(MuhneeWeb.ErrorView, "404.json", []) == %{errors: %{detail: "Not Found"}}
end
test "renders 500.json" do
assert render(MuhneeWeb.ErrorView, "500.json", []) ==
%{errors: %{detail: "Internal Server Error"}}
end
end
| 28.125 | 91 | 0.68 |
79e92ad976ed729f973586eb75977f882af3bee1 | 30,027 | ex | Elixir | lib/elixir/lib/system.ex | cdfuller/elixir | 3bd3f88d57d7fff6cab7b171294b89fb08eedfe7 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/system.ex | cdfuller/elixir | 3bd3f88d57d7fff6cab7b171294b89fb08eedfe7 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/system.ex | cdfuller/elixir | 3bd3f88d57d7fff6cab7b171294b89fb08eedfe7 | [
"Apache-2.0"
] | null | null | null | defmodule System do
@moduledoc """
The `System` module provides functions that interact directly
with the VM or the host system.
## Time
The `System` module also provides functions that work with time,
returning different times kept by the system with support for
different time units.
One of the complexities in relying on system times is that they
may be adjusted. For example, when you enter and leave daylight
saving time, the system clock will be adjusted, often adding
or removing one hour. We call such changes "time warps". In
order to understand how such changes may be harmful, imagine
the following code:
## DO NOT DO THIS
prev = System.os_time()
# ... execute some code ...
next = System.os_time()
diff = next - prev
If, while the code is executing, the system clock changes,
some code that executed in 1 second may be reported as taking
over 1 hour! To address such concerns, the VM provides a
monotonic time via `System.monotonic_time/0` which never
decreases and does not leap:
## DO THIS
prev = System.monotonic_time()
# ... execute some code ...
next = System.monotonic_time()
diff = next - prev
Generally speaking, the VM provides three time measurements:
* `os_time/0` - the time reported by the operating system (OS). This time may be
adjusted forwards or backwards in time with no limitation;
* `system_time/0` - the VM view of the `os_time/0`. The system time and operating
system time may not match in case of time warps although the VM works towards
aligning them. This time is not monotonic (i.e., it may decrease)
as its behaviour is configured [by the VM time warp
mode](http://www.erlang.org/doc/apps/erts/time_correction.html#Time_Warp_Modes);
* `monotonic_time/0` - a monotonically increasing time provided
by the Erlang VM.
The time functions in this module work in the `:native` unit
(unless specified otherwise), which is operating system dependent. Most of
the time, all calculations are done in the `:native` unit, to
avoid loss of precision, with `convert_time_unit/3` being
invoked at the end to convert to a specific time unit like
`:millisecond` or `:microsecond`. See the `t:time_unit/0` type for
more information.
For a more complete rundown on the VM support for different
times, see the [chapter on time and time
correction](http://www.erlang.org/doc/apps/erts/time_correction.html)
in the Erlang docs.
"""
@typedoc """
The time unit to be passed to functions like `monotonic_time/1` and others.
The `:second`, `:millisecond`, `:microsecond` and `:nanosecond` time
units controls the return value of the functions that accept a time unit.
A time unit can also be a strictly positive integer. In this case, it
represents the "parts per second": the time will be returned in `1 /
parts_per_second` seconds. For example, using the `:millisecond` time unit
is equivalent to using `1000` as the time unit (as the time will be returned
in 1/1000 seconds - milliseconds).
"""
@type time_unit ::
:second
| :millisecond
| :microsecond
| :nanosecond
| pos_integer
@base_dir :filename.join(__DIR__, "../../..")
@version_file :filename.join(@base_dir, "VERSION")
defp strip(iodata) do
:re.replace(iodata, "^[\s\r\n\t]+|[\s\r\n\t]+$", "", [:global, return: :binary])
end
defp read_stripped(path) do
case :file.read_file(path) do
{:ok, binary} ->
strip(binary)
_ ->
""
end
end
# Read and strip the version from the VERSION file.
defmacrop get_version do
case read_stripped(@version_file) do
"" -> raise "could not read the version number from VERSION"
data -> data
end
end
# Returns OTP version that Elixir was compiled with.
defmacrop get_otp_release do
:erlang.list_to_binary(:erlang.system_info(:otp_release))
end
# Tries to run "git rev-parse --short HEAD". In the case of success returns
# the short revision hash. If that fails, returns an empty string.
defmacrop get_revision do
null =
case :os.type() do
{:win32, _} -> 'NUL'
_ -> '/dev/null'
end
'git rev-parse --short HEAD 2> '
|> Kernel.++(null)
|> :os.cmd()
|> strip
end
defp revision, do: get_revision()
# Get the date at compilation time.
# Follows https://reproducible-builds.org/specs/source-date-epoch/
defmacrop get_date do
unix_epoch =
if source_date_epoch = :os.getenv('SOURCE_DATE_EPOCH') do
try do
List.to_integer(source_date_epoch)
rescue
_ -> nil
end
end
unix_epoch = unix_epoch || :os.system_time(:second)
{{year, month, day}, {hour, minute, second}} =
:calendar.gregorian_seconds_to_datetime(unix_epoch + 62_167_219_200)
"~4..0b-~2..0b-~2..0bT~2..0b:~2..0b:~2..0bZ"
|> :io_lib.format([year, month, day, hour, minute, second])
|> :erlang.iolist_to_binary()
end
@doc """
Returns the endianness.
"""
@spec endianness() :: :little | :big
def endianness do
:erlang.system_info(:endian)
end
@doc """
Returns the endianness the system was compiled with.
"""
@endianness :erlang.system_info(:endian)
@spec compiled_endianness() :: :little | :big
def compiled_endianness do
@endianness
end
@doc """
Elixir version information.
Returns Elixir's version as binary.
"""
@spec version() :: String.t()
def version, do: get_version()
@doc """
Elixir build information.
Returns a map with the Elixir version, short Git revision hash and compilation date.
Every value in the map is a string, and these are:
* `:build` - the Elixir version, short Git revision hash and
Erlang/OTP release it was compiled with
* `:date` - a string representation of the ISO8601 date and time it was built
* `:opt_release` - OTP release it was compiled with
* `:revision` - short Git revision hash
* `:version` - the Elixir version
One should not rely on the specific formats returned by each of those fields.
Instead one should use specialized functions, such as `version/0` to retrieve
the Elixir version and `otp_release/0` to retrieve the Erlang/OTP release.
## Examples
iex> System.build_info()
%{
build: "1.9.0-dev (772a00a0c) (compiled with Erlang/OTP 21)",
date: "2018-12-24T01:09:21Z",
otp_release: "21",
revision: "772a00a0c",
version: "1.9.0-dev"
}
"""
@spec build_info() :: %{required(atom) => String.t()}
def build_info do
%{
build: build(),
date: get_date(),
revision: revision(),
version: version(),
otp_release: get_otp_release()
}
end
# Returns a string of the build info
defp build do
{:ok, v} = Version.parse(version())
revision_string = if v.pre != [] and revision() != "", do: " (#{revision()})", else: ""
otp_version_string = " (compiled with Erlang/OTP #{get_otp_release()})"
version() <> revision_string <> otp_version_string
end
@doc """
Lists command line arguments.
Returns the list of command line arguments passed to the program.
"""
@spec argv() :: [String.t()]
def argv do
:elixir_config.get(:argv)
end
@doc """
Modifies command line arguments.
Changes the list of command line arguments. Use it with caution,
as it destroys any previous argv information.
"""
@spec argv([String.t()]) :: :ok
def argv(args) do
:elixir_config.put(:argv, args)
end
@doc """
Current working directory.
Returns the current working directory or `nil` if one
is not available.
"""
@deprecated "Use File.cwd/0 instead"
@spec cwd() :: String.t() | nil
def cwd do
case File.cwd() do
{:ok, cwd} -> cwd
_ -> nil
end
end
@doc """
Current working directory, exception on error.
Returns the current working directory or raises `RuntimeError`.
"""
@deprecated "Use File.cwd!/0 instead"
@spec cwd!() :: String.t()
def cwd! do
case File.cwd() do
{:ok, cwd} ->
cwd
_ ->
raise "could not get a current working directory, the current location is not accessible"
end
end
@doc """
User home directory.
Returns the user home directory (platform independent).
"""
@spec user_home() :: String.t() | nil
def user_home do
:elixir_config.get(:home)
end
@doc """
User home directory, exception on error.
Same as `user_home/0` but raises `RuntimeError`
instead of returning `nil` if no user home is set.
"""
@spec user_home!() :: String.t()
def user_home! do
user_home() || raise "could not find the user home, please set the HOME environment variable"
end
@doc ~S"""
Writable temporary directory.
Returns a writable temporary directory.
Searches for directories in the following order:
1. the directory named by the TMPDIR environment variable
2. the directory named by the TEMP environment variable
3. the directory named by the TMP environment variable
4. `C:\TMP` on Windows or `/tmp` on Unix
5. as a last resort, the current working directory
Returns `nil` if none of the above are writable.
"""
@spec tmp_dir() :: String.t() | nil
def tmp_dir do
write_env_tmp_dir('TMPDIR') || write_env_tmp_dir('TEMP') || write_env_tmp_dir('TMP') ||
write_tmp_dir('/tmp') || write_cwd_tmp_dir()
end
defp write_cwd_tmp_dir do
case File.cwd() do
{:ok, cwd} -> write_tmp_dir(cwd)
_ -> nil
end
end
@doc """
Writable temporary directory, exception on error.
Same as `tmp_dir/0` but raises `RuntimeError`
instead of returning `nil` if no temp dir is set.
"""
@spec tmp_dir!() :: String.t()
def tmp_dir! do
tmp_dir() ||
raise "could not get a writable temporary directory, please set the TMPDIR environment variable"
end
defp write_env_tmp_dir(env) do
case :os.getenv(env) do
false -> nil
tmp -> write_tmp_dir(tmp)
end
end
defp write_tmp_dir(dir) do
case File.stat(dir) do
{:ok, stat} ->
case {stat.type, stat.access} do
{:directory, access} when access in [:read_write, :write] ->
IO.chardata_to_string(dir)
_ ->
nil
end
{:error, _} ->
nil
end
end
@doc """
Registers a program exit handler function.
Registers a function that will be invoked at the end of program execution.
Useful for invoking a hook in "script" mode.
The handler always executes in a different process from the one it was
registered in. As a consequence, any resources managed by the calling process
(ETS tables, open files, etc.) won't be available by the time the handler
function is invoked.
The function must receive the exit status code as an argument.
"""
@spec at_exit((non_neg_integer -> any)) :: :ok
def at_exit(fun) when is_function(fun, 1) do
:elixir_config.update(:at_exit, &[fun | &1])
:ok
end
@doc """
Locates an executable on the system.
This function looks up an executable program given
its name using the environment variable PATH on Unix
and Windows. It also considers the proper executable
extension for each operating system, so for Windows it will try to
lookup files with `.com`, `.cmd` or similar extensions.
"""
@spec find_executable(binary) :: binary | nil
def find_executable(program) when is_binary(program) do
assert_no_null_byte!(program, "System.find_executable/1")
case :os.find_executable(String.to_charlist(program)) do
false -> nil
other -> List.to_string(other)
end
end
@doc """
Returns all system environment variables.
The returned value is a map containing name-value pairs.
Variable names and their values are strings.
"""
@spec get_env() :: %{optional(String.t()) => String.t()}
def get_env do
Enum.into(:os.getenv(), %{}, fn var ->
var = IO.chardata_to_string(var)
[k, v] = String.split(var, "=", parts: 2)
{k, v}
end)
end
@doc """
Returns the value of the given environment variable.
The returned value of the environment variable
`varname` is a string, or `nil` if the environment
variable is undefined.
"""
@spec get_env(String.t()) :: String.t() | nil
def get_env(varname) when is_binary(varname) do
case :os.getenv(String.to_charlist(varname)) do
false -> nil
other -> List.to_string(other)
end
end
@doc """
Erlang VM process identifier.
Returns the process identifier of the current Erlang emulator
in the format most commonly used by the operating system environment.
For more information, see `:os.getpid/0`.
"""
@spec get_pid() :: binary
def get_pid, do: IO.iodata_to_binary(:os.getpid())
@doc """
Sets an environment variable value.
Sets a new `value` for the environment variable `varname`.
"""
@spec put_env(binary, binary) :: :ok
def put_env(varname, value) when is_binary(varname) and is_binary(value) do
case :binary.match(varname, "=") do
{_, _} ->
raise ArgumentError,
"cannot execute System.put_env/2 for key with \"=\", got: #{inspect(varname)}"
:nomatch ->
:os.putenv(String.to_charlist(varname), String.to_charlist(value))
:ok
end
end
@doc """
Sets multiple environment variables.
Sets a new value for each environment variable corresponding
to each `{key, value}` pair in `enum`.
"""
@spec put_env(Enumerable.t()) :: :ok
def put_env(enum) do
Enum.each(enum, fn {key, val} -> put_env(key, val) end)
end
@doc """
Deletes an environment variable.
Removes the variable `varname` from the environment.
"""
@spec delete_env(String.t()) :: :ok
def delete_env(varname) do
:os.unsetenv(String.to_charlist(varname))
:ok
end
@doc """
Deprecated mechanism to retrieve the last exception stacktrace.
Accessing the stacktrace outside of a rescue/catch is deprecated.
If you want to support only Elixir v1.7+, you must access
`__STACKTRACE__/0` inside a rescue/catch. If you want to support
earlier Elixir versions, move `System.stacktrace/0` inside a rescue/catch.
Note that the Erlang VM (and therefore this function) does not
return the current stacktrace but rather the stacktrace of the
latest exception. To retrieve the stacktrace of the current process,
use `Process.info(self(), :current_stacktrace)` instead.
"""
# TODO: Fully deprecate it on Elixir v1.11 via @deprecated
# It is currently partially deprecated in elixir_dispatch.erl
def stacktrace do
apply(:erlang, :get_stacktrace, [])
end
@doc """
Immediately halts the Erlang runtime system.
Terminates the Erlang runtime system without properly shutting down
applications and ports. Please see `stop/1` for a careful shutdown of the
system.
`status` must be a non-negative integer, the atom `:abort` or a binary.
* If an integer, the runtime system exits with the integer value which
is returned to the operating system.
* If `:abort`, the runtime system aborts producing a core dump, if that is
enabled in the operating system.
* If a string, an Erlang crash dump is produced with status as slogan,
and then the runtime system exits with status code 1.
Note that on many platforms, only the status codes 0-255 are supported
by the operating system.
For more information, see `:erlang.halt/1`.
## Examples
System.halt(0)
System.halt(1)
System.halt(:abort)
"""
@spec halt(non_neg_integer | binary | :abort) :: no_return
def halt(status \\ 0)
def halt(status) when is_integer(status) or status == :abort do
:erlang.halt(status)
end
def halt(status) when is_binary(status) do
:erlang.halt(String.to_charlist(status))
end
@doc """
Returns the operating system PID for the current Erlang runtime system instance.
Returns a string containing the (usually) numerical identifier for a process.
On UNIX, this is typically the return value of the `getpid()` system call.
On Windows, the process ID as returned by the `GetCurrentProcessId()` system
call is used.
## Examples
System.pid()
"""
@doc since: "1.9.0"
def pid do
List.to_string(:os.getpid())
end
@doc """
Restarts all applications in the Erlang runtime system.
All applications are taken down smoothly, all code is unloaded, and all ports
are closed before the system starts all applications once again.
## Examples
System.restart()
"""
@doc since: "1.9.0"
defdelegate restart(), to: :init
@doc """
Carefully stops the Erlang runtime system.
All applications are taken down smoothly, all code is unloaded, and all ports
are closed before the system terminates by calling `halt/1`.
`status` must be a non-negative integer value which is returned by the
runtime system to the operating system.
Note that on many platforms, only the status codes 0-255 are supported
by the operating system.
## Examples
System.stop(0)
System.stop(1)
"""
@doc since: "1.5.0"
@spec stop(non_neg_integer | binary) :: no_return
def stop(status \\ 0)
def stop(status) when is_integer(status) do
:init.stop(status)
end
def stop(status) when is_binary(status) do
:init.stop(String.to_charlist(status))
end
@doc ~S"""
Executes the given `command` with `args`.
`command` is expected to be an executable available in PATH
unless an absolute path is given.
`args` must be a list of binaries which the executable will receive
as its arguments as is. This means that:
* environment variables will not be interpolated
* wildcard expansion will not happen (unless `Path.wildcard/2` is used
explicitly)
* arguments do not need to be escaped or quoted for shell safety
This function returns a tuple containing the collected result
and the command exit status.
Internally, this function uses a `Port` for interacting with the
outside world. However, if you plan to run a long-running program,
ports guarantee stdin/stdout devices will be closed but it does not
automatically terminate the program. The documentation for the
`Port` module describes this problem and possible solutions under
the "Zombie processes" section.
## Examples
iex> System.cmd("echo", ["hello"])
{"hello\n", 0}
iex> System.cmd("echo", ["hello"], env: [{"MIX_ENV", "test"}])
{"hello\n", 0}
iex> System.cmd("echo", ["hello"], into: IO.stream(:stdio, :line))
hello
{%IO.Stream{}, 0}
## Options
* `:into` - injects the result into the given collectable, defaults to `""`
* `:cd` - the directory to run the command in
* `:env` - an enumerable of tuples containing environment key-value as binary
* `:arg0` - sets the command arg0
* `:stderr_to_stdout` - redirects stderr to stdout when `true`
* `:parallelism` - when `true`, the VM will schedule port tasks to improve
parallelism in the system. If set to `false`, the VM will try to perform
commands immediately, improving latency at the expense of parallelism.
The default can be set on system startup by passing the "+spp" argument
to `--erl`.
## Error reasons
If invalid arguments are given, `ArgumentError` is raised by
`System.cmd/3`. `System.cmd/3` also expects a strict set of
options and will raise if unknown or invalid options are given.
Furthermore, `System.cmd/3` may fail with one of the POSIX reasons
detailed below:
* `:system_limit` - all available ports in the Erlang emulator are in use
* `:enomem` - there was not enough memory to create the port
* `:eagain` - there are no more available operating system processes
* `:enametoolong` - the external command given was too long
* `:emfile` - there are no more available file descriptors
(for the operating system process that the Erlang emulator runs in)
* `:enfile` - the file table is full (for the entire operating system)
* `:eacces` - the command does not point to an executable file
* `:enoent` - the command does not point to an existing file
## Shell commands
If you desire to execute a trusted command inside a shell, with pipes,
redirecting and so on, please check `:os.cmd/1`.
"""
@spec cmd(binary, [binary], keyword) :: {Collectable.t(), exit_status :: non_neg_integer}
def cmd(command, args, opts \\ []) when is_binary(command) and is_list(args) do
assert_no_null_byte!(command, "System.cmd/3")
unless Enum.all?(args, &is_binary/1) do
raise ArgumentError, "all arguments for System.cmd/3 must be binaries"
end
cmd = String.to_charlist(command)
cmd =
if Path.type(cmd) == :absolute do
cmd
else
:os.find_executable(cmd) || :erlang.error(:enoent, [command, args, opts])
end
{into, opts} = cmd_opts(opts, [:use_stdio, :exit_status, :binary, :hide, args: args], "")
{initial, fun} = Collectable.into(into)
try do
do_cmd(Port.open({:spawn_executable, cmd}, opts), initial, fun)
catch
kind, reason ->
fun.(initial, :halt)
:erlang.raise(kind, reason, __STACKTRACE__)
else
{acc, status} -> {fun.(acc, :done), status}
end
end
defp do_cmd(port, acc, fun) do
receive do
{^port, {:data, data}} ->
do_cmd(port, fun.(acc, {:cont, data}), fun)
{^port, {:exit_status, status}} ->
{acc, status}
end
end
defp cmd_opts([{:into, any} | t], opts, _into), do: cmd_opts(t, opts, any)
defp cmd_opts([{:cd, bin} | t], opts, into) when is_binary(bin),
do: cmd_opts(t, [{:cd, bin} | opts], into)
defp cmd_opts([{:arg0, bin} | t], opts, into) when is_binary(bin),
do: cmd_opts(t, [{:arg0, bin} | opts], into)
defp cmd_opts([{:stderr_to_stdout, true} | t], opts, into),
do: cmd_opts(t, [:stderr_to_stdout | opts], into)
defp cmd_opts([{:stderr_to_stdout, false} | t], opts, into), do: cmd_opts(t, opts, into)
defp cmd_opts([{:parallelism, bool} | t], opts, into) when is_boolean(bool),
do: cmd_opts(t, [{:parallelism, bool} | opts], into)
defp cmd_opts([{:env, enum} | t], opts, into),
do: cmd_opts(t, [{:env, validate_env(enum)} | opts], into)
defp cmd_opts([{key, val} | _], _opts, _into),
do: raise(ArgumentError, "invalid option #{inspect(key)} with value #{inspect(val)}")
defp cmd_opts([], opts, into), do: {into, opts}
defp validate_env(enum) do
Enum.map(enum, fn
{k, nil} ->
{String.to_charlist(k), false}
{k, v} ->
{String.to_charlist(k), String.to_charlist(v)}
other ->
raise ArgumentError, "invalid environment key-value #{inspect(other)}"
end)
end
@doc """
Returns the current monotonic time in the `:native` time unit.
This time is monotonically increasing and starts in an unspecified
point in time.
Inlined by the compiler.
"""
@spec monotonic_time() :: integer
def monotonic_time do
:erlang.monotonic_time()
end
@doc """
Returns the current monotonic time in the given time unit.
This time is monotonically increasing and starts in an unspecified
point in time.
"""
@spec monotonic_time(time_unit) :: integer
def monotonic_time(unit) do
:erlang.monotonic_time(normalize_time_unit(unit))
end
@doc """
Returns the current system time in the `:native` time unit.
It is the VM view of the `os_time/0`. They may not match in
case of time warps although the VM works towards aligning
them. This time is not monotonic.
Inlined by the compiler.
"""
@spec system_time() :: integer
def system_time do
:erlang.system_time()
end
@doc """
Returns the current system time in the given time unit.
It is the VM view of the `os_time/0`. They may not match in
case of time warps although the VM works towards aligning
them. This time is not monotonic.
"""
@spec system_time(time_unit) :: integer
def system_time(unit) do
:erlang.system_time(normalize_time_unit(unit))
end
@doc """
Converts `time` from time unit `from_unit` to time unit `to_unit`.
The result is rounded via the floor function.
`convert_time_unit/3` accepts an additional time unit (other than the
ones in the `t:time_unit/0` type) called `:native`. `:native` is the time
unit used by the Erlang runtime system. It's determined when the runtime
starts and stays the same until the runtime is stopped. To determine what
the `:native` unit amounts to in a system, you can call this function to
convert 1 second to the `:native` time unit (i.e.,
`System.convert_time_unit(1, :second, :native)`).
"""
@spec convert_time_unit(integer, time_unit | :native, time_unit | :native) :: integer
def convert_time_unit(time, from_unit, to_unit) do
:erlang.convert_time_unit(time, normalize_time_unit(from_unit), normalize_time_unit(to_unit))
end
@doc """
Returns the current time offset between the Erlang VM monotonic
time and the Erlang VM system time.
The result is returned in the `:native` time unit.
See `time_offset/1` for more information.
Inlined by the compiler.
"""
@spec time_offset() :: integer
def time_offset do
:erlang.time_offset()
end
@doc """
Returns the current time offset between the Erlang VM monotonic
time and the Erlang VM system time.
The result is returned in the given time unit `unit`. The returned
offset, added to an Erlang monotonic time (e.g., obtained with
`monotonic_time/1`), gives the Erlang system time that corresponds
to that monotonic time.
"""
@spec time_offset(time_unit) :: integer
def time_offset(unit) do
:erlang.time_offset(normalize_time_unit(unit))
end
@doc """
Returns the current operating system (OS) time.
The result is returned in the `:native` time unit.
This time may be adjusted forwards or backwards in time
with no limitation and is not monotonic.
Inlined by the compiler.
"""
@spec os_time() :: integer
def os_time do
:os.system_time()
end
@doc """
Returns the current operating system (OS) time in the given time `unit`.
This time may be adjusted forwards or backwards in time
with no limitation and is not monotonic.
"""
@spec os_time(time_unit) :: integer
def os_time(unit) do
:os.system_time(normalize_time_unit(unit))
end
@doc """
Returns the Erlang/OTP release number.
"""
@spec otp_release :: String.t()
def otp_release do
:erlang.list_to_binary(:erlang.system_info(:otp_release))
end
@doc """
Returns the number of schedulers in the VM.
"""
@spec schedulers :: pos_integer
def schedulers do
:erlang.system_info(:schedulers)
end
@doc """
Returns the number of schedulers online in the VM.
"""
@spec schedulers_online :: pos_integer
def schedulers_online do
:erlang.system_info(:schedulers_online)
end
@doc """
Generates and returns an integer that is unique in the current runtime
instance.
"Unique" means that this function, called with the same list of `modifiers`,
will never return the same integer more than once on the current runtime
instance.
If `modifiers` is `[]`, then a unique integer (that can be positive or negative) is returned.
Other modifiers can be passed to change the properties of the returned integer:
* `:positive` - the returned integer is guaranteed to be positive.
* `:monotonic` - the returned integer is monotonically increasing. This
means that, on the same runtime instance (but even on different
processes), integers returned using the `:monotonic` modifier will always
be strictly less than integers returned by successive calls with the
`:monotonic` modifier.
All modifiers listed above can be combined; repeated modifiers in `modifiers`
will be ignored.
Inlined by the compiler.
"""
@spec unique_integer([:positive | :monotonic]) :: integer
def unique_integer(modifiers \\ []) do
:erlang.unique_integer(modifiers)
end
defp assert_no_null_byte!(binary, operation) do
case :binary.match(binary, "\0") do
{_, _} ->
raise ArgumentError,
"cannot execute #{operation} for program with null byte, got: #{inspect(binary)}"
:nomatch ->
binary
end
end
defp normalize_time_unit(:native), do: :native
defp normalize_time_unit(:second), do: :second
defp normalize_time_unit(:millisecond), do: :millisecond
defp normalize_time_unit(:microsecond), do: :microsecond
defp normalize_time_unit(:nanosecond), do: :nanosecond
defp normalize_time_unit(:seconds), do: warn(:seconds, :second)
defp normalize_time_unit(:milliseconds), do: warn(:milliseconds, :millisecond)
defp normalize_time_unit(:microseconds), do: warn(:microseconds, :microsecond)
defp normalize_time_unit(:nanoseconds), do: warn(:nanoseconds, :nanosecond)
defp normalize_time_unit(:milli_seconds), do: warn(:milli_seconds, :millisecond)
defp normalize_time_unit(:micro_seconds), do: warn(:micro_seconds, :microsecond)
defp normalize_time_unit(:nano_seconds), do: warn(:nano_seconds, :nanosecond)
defp normalize_time_unit(unit) when is_integer(unit) and unit > 0, do: unit
defp normalize_time_unit(other) do
raise ArgumentError,
"unsupported time unit. Expected :second, :millisecond, " <>
":microsecond, :nanosecond, or a positive integer, " <> "got #{inspect(other)}"
end
defp warn(unit, replacement_unit) do
{:current_stacktrace, stacktrace} = Process.info(self(), :current_stacktrace)
stacktrace = Enum.drop(stacktrace, 3)
:elixir_config.warn({System, unit}, stacktrace) &&
IO.warn(
"deprecated time unit: #{inspect(unit)}. A time unit should be " <>
":second, :millisecond, :microsecond, :nanosecond, or a positive integer",
stacktrace
)
replacement_unit
end
end
| 30.3917 | 102 | 0.678689 |
79e93edf812fa33ed9e67274be4792b47814eee6 | 2,242 | ex | Elixir | clients/content/lib/google_api/content/v2/model/order_report_disbursement.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/order_report_disbursement.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/order_report_disbursement.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Content.V2.Model.OrderReportDisbursement do
@moduledoc """
Order disbursement. All methods require the payment analyst role.
## Attributes
- disbursementAmount (Price): The disbursement amount. Defaults to: `null`.
- disbursementCreationDate (String.t): The disbursement date, in ISO 8601 format. Defaults to: `null`.
- disbursementDate (String.t): The date the disbursement was initiated, in ISO 8601 format. Defaults to: `null`.
- disbursementId (String.t): The ID of the disbursement. Defaults to: `null`.
- merchantId (String.t): The ID of the managing account. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:disbursementAmount => GoogleApi.Content.V2.Model.Price.t(),
:disbursementCreationDate => any(),
:disbursementDate => any(),
:disbursementId => any(),
:merchantId => any()
}
field(:disbursementAmount, as: GoogleApi.Content.V2.Model.Price)
field(:disbursementCreationDate)
field(:disbursementDate)
field(:disbursementId)
field(:merchantId)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrderReportDisbursement do
def decode(value, options) do
GoogleApi.Content.V2.Model.OrderReportDisbursement.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrderReportDisbursement do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.366667 | 114 | 0.736842 |
79e95fa22dcf7e114f8eb4d425870057780c4139 | 6,518 | ex | Elixir | lib/subscription.ex | Packlane/braintree-elixir | 018ed351c64cdac577bf4acb93f73c1adddf70da | [
"MIT"
] | null | null | null | lib/subscription.ex | Packlane/braintree-elixir | 018ed351c64cdac577bf4acb93f73c1adddf70da | [
"MIT"
] | null | null | null | lib/subscription.ex | Packlane/braintree-elixir | 018ed351c64cdac577bf4acb93f73c1adddf70da | [
"MIT"
] | null | null | null | defmodule Braintree.Subscription do
@moduledoc """
Manage customer subscriptions to recurring billing plans.
For additional reference see:
https://developers.braintreepayments.com/reference/request/subscription/create/ruby
"""
use Braintree.Construction
alias Braintree.{HTTP, Transaction, AddOn, Search}
alias Braintree.ErrorResponse, as: Error
@type t :: %__MODULE__{
id: String.t(),
plan_id: String.t(),
balance: String.t(),
billing_day_of_month: String.t(),
billing_period_end_date: String.t(),
billing_period_start_date: String.t(),
created_at: String.t(),
current_billing_cycle: String.t(),
days_past_due: String.t(),
descriptor: String.t(),
failure_count: String.t(),
first_billing_date: String.t(),
merchant_account_id: String.t(),
never_expires: String.t(),
next_bill_amount: String.t(),
next_billing_date: String.t(),
next_billing_period_amount: String.t(),
number_of_billing_cycles: String.t(),
paid_through_date: String.t(),
payment_method_token: String.t(),
price: String.t(),
status: String.t(),
trial_duration: String.t(),
trial_duration_unit: String.t(),
trial_period: String.t(),
updated_at: String.t(),
add_ons: [AddOn.t()],
discounts: [any],
transactions: [Transaction.t()],
status_history: [any]
}
defstruct id: nil,
plan_id: nil,
balance: nil,
billing_day_of_month: nil,
billing_period_end_date: nil,
billing_period_start_date: nil,
created_at: nil,
current_billing_cycle: nil,
days_past_due: nil,
descriptor: nil,
failure_count: nil,
first_billing_date: nil,
merchant_account_id: nil,
never_expires: nil,
next_bill_amount: nil,
next_billing_date: nil,
next_billing_period_amount: nil,
number_of_billing_cycles: nil,
paid_through_date: nil,
payment_method_token: nil,
price: nil,
status: nil,
trial_duration: nil,
trial_duration_unit: nil,
trial_period: nil,
updated_at: nil,
add_ons: [],
discounts: [],
transactions: [],
status_history: []
@doc """
Create a subscription, or return an error response with after failed
validation.
## Example
{:ok, sub} = Braintree.Subscription.create(%{
payment_method_token: card.token,
plan_id: "starter"
})
"""
@spec create(map, Keyword.t()) :: {:ok, t} | {:error, Error.t()}
def create(params \\ %{}, opts \\ []) do
with {:ok, payload} <- HTTP.post("subscriptions", %{subscription: params}, opts) do
{:ok, new(payload)}
end
end
@doc """
Find an existing subscription by `subscription_id`
## Example
{:ok, subscription} = Subscription.find("123")
"""
@spec find(String.t(), Keyword.t()) :: {:ok, t} | {:error, Error.t()}
def find(subscription_id, opts \\ []) do
with {:ok, payload} <- HTTP.get("subscriptions/#{subscription_id}", opts) do
{:ok, new(payload)}
end
end
@doc """
Cancel an existing subscription by `subscription_id`. A cancelled subscription
cannot be reactivated, you would need to create a new one.
## Example
{:ok, subscription} = Subscription.cancel("123")
"""
@spec cancel(String.t(), Keyword.t()) :: {:ok, t} | {:error, Error.t()}
def cancel(subscription_id, opts \\ []) do
with {:ok, payload} <- HTTP.put("subscriptions/#{subscription_id}/cancel", opts) do
{:ok, new(payload)}
end
end
@doc """
You can manually retry charging past due subscriptions.
By default, we will use the subscription balance when retrying the
transaction. If you would like to use a different amount you can optionally
specify the amount for the transaction.
A successful manual retry of a past due subscription will **always** reduce
the balance of that subscription to $0, regardless of the amount of the
retry.
## Example
{:ok, transaction} = Braintree.Subscription.retry_charge(sub_id)
{:ok, transaction} = Braintree.Subscription.retry_charge(sub_id, "24.00")
"""
@spec retry_charge(String.t()) :: {:ok, Transaction.t()}
@spec retry_charge(String.t(), String.t() | nil, Keyword.t()) ::
{:ok, Transaction.t()} | {:error, Error.t()}
def retry_charge(subscription_id, amount \\ nil, opts \\ []) do
Transaction.sale(%{amount: amount, subscription_id: subscription_id}, opts)
end
@doc """
To update a subscription, use its ID along with new attributes. The same
validations apply as when creating a subscription. Any attribute not passed will
remain unchanged.
## Example
{:ok, subscription} = Braintree.Subscription.update("subscription_id", %{
plan_id: "new_plan_id"
})
subscription.plan_id # "new_plan_id"
"""
@spec update(binary, map, Keyword.t()) :: {:ok, t} | {:error, Error.t()}
def update(id, params, opts \\ []) when is_binary(id) and is_map(params) do
with {:ok, payload} <- HTTP.put("subscriptions/" <> id, %{subscription: params}, opts) do
{:ok, new(payload)}
end
end
@doc """
To search for subscriptions, pass a map of search parameters.
## Example:
{:ok, subscriptions} = Braintree.Subscription.search(%{plan_id: %{is: "starter"}})
"""
@spec search(map, Keyword.t()) :: {:ok, t} | {:error, Error.t()}
def search(params, opts \\ []) when is_map(params) do
Search.perform(params, "subscriptions", &new/1, opts)
end
@doc """
Convert a map into a Subscription struct. Add_ons and transactions
are converted to a list of structs as well.
## Example
subscripton = Braintree.Subscription.new(%{"plan_id" => "business",
"status" => "Active"})
"""
def new(%{"subscription" => map}) do
new(map)
end
def new(map) when is_map(map) do
subscription = super(map)
add_ons = AddOn.new(subscription.add_ons)
transactions = Transaction.new(subscription.transactions)
%{subscription | add_ons: add_ons, transactions: transactions}
end
def new(list) when is_list(list) do
Enum.map(list, &new/1)
end
end
| 31.795122 | 93 | 0.613071 |
79e96dee677827b8040b952cea44ef79e891a6be | 846 | exs | Elixir | mix.exs | redvers/cbclientapi | 2a2e1987f71e664cbeb2fcc6309db7b982ba3123 | [
"RSA-MD"
] | 1 | 2015-06-22T19:56:20.000Z | 2015-06-22T19:56:20.000Z | mix.exs | redvers/cbclientapi | 2a2e1987f71e664cbeb2fcc6309db7b982ba3123 | [
"RSA-MD"
] | null | null | null | mix.exs | redvers/cbclientapi | 2a2e1987f71e664cbeb2fcc6309db7b982ba3123 | [
"RSA-MD"
] | null | null | null | defmodule Cbclientapi.Mixfile do
use Mix.Project
def project do
[app: :cbclientapi,
version: "0.0.1",
elixir: "~> 1.0",
deps: deps]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[applications: [:logger, :idna, :hackney, :exjsx]]
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
[
{:hackney, "~> 1.0"},
{:exjsx, "~> 3.1"},
{:httparrot, "~> 0.3.4", only: :test},
{:meck, "~> 0.8.2", only: :test},
{:earmark, "~> 0.1", only: :docs},
{:ex_doc, "~> 0.7", only: :docs},
]
end
end
| 22.263158 | 77 | 0.549645 |
79e984ba04fbc2ec0c4951439bb748d67a55525c | 1,492 | ex | Elixir | lib/live_view_demo_web/views/error_helpers.ex | manojsamanta/codebreaker-prototype | 14d521db45784dee692de9e7252dd6a54bb793bb | [
"MIT"
] | null | null | null | lib/live_view_demo_web/views/error_helpers.ex | manojsamanta/codebreaker-prototype | 14d521db45784dee692de9e7252dd6a54bb793bb | [
"MIT"
] | null | null | null | lib/live_view_demo_web/views/error_helpers.ex | manojsamanta/codebreaker-prototype | 14d521db45784dee692de9e7252dd6a54bb793bb | [
"MIT"
] | null | null | null | defmodule LiveViewDemoWeb.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
content_tag(:span, translate_error(error), class: "help-block")
end)
end
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# When using gettext, we typically pass the strings we want
# to translate as a static argument:
#
# # Translate "is invalid" in the "errors" domain
# dgettext("errors", "is invalid")
#
# # Translate the number of files with plural rules
# dngettext("errors", "1 file", "%{count} files", count)
#
# Because the error messages we show in our forms and APIs
# are defined inside Ecto, we need to translate them dynamically.
# This requires us to call the Gettext module passing our gettext
# backend as first argument.
#
# Note we use the "errors" domain, which means translations
# should be written to the errors.po file. The :count option is
# set by Ecto and indicates we should also apply plural rules.
if count = opts[:count] do
Gettext.dngettext(LiveViewDemoWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(LiveViewDemoWeb.Gettext, "errors", msg, opts)
end
end
end
| 33.155556 | 81 | 0.673592 |
79e989bfdadc00a1b2c1b3fc1c27250e138eb247 | 523 | ex | Elixir | lib/stripe_mock_web/views/refund_view.ex | whitepaperclip/stripe_mock | a8ba9101a04216f26d0650eb38448173d8e090a1 | [
"MIT"
] | 4 | 2019-06-04T20:35:21.000Z | 2021-09-02T04:04:21.000Z | lib/stripe_mock_web/views/refund_view.ex | whitepaperclip/stripe_mock | a8ba9101a04216f26d0650eb38448173d8e090a1 | [
"MIT"
] | 2 | 2020-02-04T17:38:12.000Z | 2021-04-29T06:59:06.000Z | lib/stripe_mock_web/views/refund_view.ex | whitepaperclip/stripe_mock | a8ba9101a04216f26d0650eb38448173d8e090a1 | [
"MIT"
] | null | null | null | defmodule StripeMockWeb.RefundView do
use StripeMockWeb, :view
alias StripeMockWeb.RefundView
def render("index.json", %{conn: conn, page: page}) do
render_page(conn, page, RefundView, "refund.json")
end
def render("show.json", %{refund: refund}) do
render_one(refund, RefundView, "refund.json")
end
def render("refund.json", %{refund: refund}) do
refund
|> as_map("refund")
|> Map.take(~w(id object created amount metadata reason)a)
|> Map.put(:charge, refund.charge_id)
end
end
| 26.15 | 62 | 0.684512 |
79e9d2bce44e73582fb999ef557d05b37de92c19 | 2,321 | ex | Elixir | lib/mix/lib/mix/generator.ex | guilleiguaran/elixir | 952052869ff7af0e293d2a7160b1aebc68fc46be | [
"Apache-2.0"
] | 1 | 2015-11-12T19:23:45.000Z | 2015-11-12T19:23:45.000Z | lib/mix/lib/mix/generator.ex | guilleiguaran/elixir | 952052869ff7af0e293d2a7160b1aebc68fc46be | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/generator.ex | guilleiguaran/elixir | 952052869ff7af0e293d2a7160b1aebc68fc46be | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Generator do
@moduledoc """
Conveniences for working with paths and generating content.
All of those functions are verbose, in the sense they log
the action to be performed via `Mix.shell`.
"""
@doc """
Creates a file with the given contents.
If the file already exists, asks for user confirmation.
"""
def create_file(path, contents) when is_binary(path) do
Mix.shell.info "%{green}* creating%{reset} #{Path.relative_to_cwd path}"
if overwriting?(path) do
File.mkdir_p!(Path.dirname(path))
File.write!(path, contents)
end
end
@doc """
Creates a directory if one does not exist yet.
"""
def create_directory(path) when is_binary(path) do
Mix.shell.info "%{green}* creating%{reset} #{Path.relative_to_cwd path}"
File.mkdir_p! path
end
defp overwriting?(path) do
if File.exists?(path) do
full = Path.expand(path)
Mix.shell.yes?(Path.relative_to_cwd(full) <> " already exists, overwrite?")
else
true
end
end
@doc """
Reads the content from a file relative to the current
file and not relative to the cwd. Useful when used with
embed macros:
embed_template :lib, from_file("../templates/lib.eex")
"""
defmacro from_file(path) do
quote do
File.read! Path.expand(unquote(path), __ENV__.file)
end
end
@doc """
Embed a template given by `contents` into the current module.
It will define a private function with the `name` followed by
`_template` that expects assigns as arguments.
This function must be invoked passing a keyword list.
Each key in the keyword list can be accessed in the
template using the `@` macro.
For more information, check `EEx.SmartEngine`.
"""
defmacro embed_template(name, contents) do
quote do
require EEx
EEx.function_from_string :defp, :"#{unquote(name)}_template", "<% _ = assigns %>" <> unquote(contents), [:assigns]
end
end
@doc """
Embeds a text given by `contents` into the current module.
It will define a private function with the `name` followed by
`_text` that expects no argument.
"""
defmacro embed_text(name, contents) do
quote bind_quoted: [name: name, contents: Macro.escape(contents)] do
defp unquote(:"#{name}_text")(), do: unquote(contents)
end
end
end
| 27.630952 | 120 | 0.682464 |
79e9dba3e56f1b9dcfbc96f54da367357f4cf59a | 581 | ex | Elixir | lib/codewar_web/views/admin/challenge_view.ex | hanam1ni/codewar-web | 0d7c46ac32d85b1d76c604226e0f3d6f2b76b0ad | [
"MIT"
] | 2 | 2021-06-29T02:22:28.000Z | 2022-02-15T06:32:15.000Z | lib/codewar_web/views/admin/challenge_view.ex | hanam1ni/codewar-web | 0d7c46ac32d85b1d76c604226e0f3d6f2b76b0ad | [
"MIT"
] | 14 | 2021-05-06T04:27:19.000Z | 2021-08-24T11:15:33.000Z | lib/codewar_web/views/admin/challenge_view.ex | hanam1ni/codewar-web | 0d7c46ac32d85b1d76c604226e0f3d6f2b76b0ad | [
"MIT"
] | 1 | 2021-08-20T07:50:19.000Z | 2021-08-20T07:50:19.000Z | defmodule CodewarWeb.Admin.ChallengeView do
use CodewarWeb, :view
def to_markdown(nil), do: content_tag(:p, gettext("No content"))
def to_markdown(content), do: Earmark.as_html!(content)
def to_validity_status(answer) when answer.is_rejected,
do: content_tag(:span, gettext("Rejected"), class: "badge badge--danger")
def to_validity_status(answer) when answer.is_valid,
do: content_tag(:span, gettext("Valid"), class: "badge badge--success")
def to_validity_status(_answer),
do: content_tag(:span, gettext("Invalid"), class: "badge badge--warning")
end
| 36.3125 | 77 | 0.736661 |
79e9df8c7c6611e61d4a85be0ea9647d1f84411d | 4,195 | ex | Elixir | clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/pivot.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/pivot.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/pivot.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.AnalyticsReporting.V4.Model.Pivot do
@moduledoc """
The Pivot describes the pivot section in the request. The Pivot helps rearrange the information in the table for certain reports by pivoting your data on a second dimension.
## Attributes
* `dimensionFilterClauses` (*type:* `list(GoogleApi.AnalyticsReporting.V4.Model.DimensionFilterClause.t)`, *default:* `nil`) - DimensionFilterClauses are logically combined with an `AND` operator: only data that is included by all these DimensionFilterClauses contributes to the values in this pivot region. Dimension filters can be used to restrict the columns shown in the pivot region. For example if you have `ga:browser` as the requested dimension in the pivot region, and you specify key filters to restrict `ga:browser` to only "IE" or "Firefox", then only those two browsers would show up as columns.
* `dimensions` (*type:* `list(GoogleApi.AnalyticsReporting.V4.Model.Dimension.t)`, *default:* `nil`) - A list of dimensions to show as pivot columns. A Pivot can have a maximum of 4 dimensions. Pivot dimensions are part of the restriction on the total number of dimensions allowed in the request.
* `maxGroupCount` (*type:* `integer()`, *default:* `nil`) - Specifies the maximum number of groups to return. The default value is 10, also the maximum value is 1,000.
* `metrics` (*type:* `list(GoogleApi.AnalyticsReporting.V4.Model.Metric.t)`, *default:* `nil`) - The pivot metrics. Pivot metrics are part of the restriction on total number of metrics allowed in the request.
* `startGroup` (*type:* `integer()`, *default:* `nil`) - If k metrics were requested, then the response will contain some data-dependent multiple of k columns in the report. E.g., if you pivoted on the dimension `ga:browser` then you'd get k columns for "Firefox", k columns for "IE", k columns for "Chrome", etc. The ordering of the groups of columns is determined by descending order of "total" for the first of the k values. Ties are broken by lexicographic ordering of the first pivot dimension, then lexicographic ordering of the second pivot dimension, and so on. E.g., if the totals for the first value for Firefox, IE, and Chrome were 8, 2, 8, respectively, the order of columns would be Chrome, Firefox, IE. The following let you choose which of the groups of k columns are included in the response.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:dimensionFilterClauses =>
list(GoogleApi.AnalyticsReporting.V4.Model.DimensionFilterClause.t()),
:dimensions => list(GoogleApi.AnalyticsReporting.V4.Model.Dimension.t()),
:maxGroupCount => integer(),
:metrics => list(GoogleApi.AnalyticsReporting.V4.Model.Metric.t()),
:startGroup => integer()
}
field(:dimensionFilterClauses,
as: GoogleApi.AnalyticsReporting.V4.Model.DimensionFilterClause,
type: :list
)
field(:dimensions, as: GoogleApi.AnalyticsReporting.V4.Model.Dimension, type: :list)
field(:maxGroupCount)
field(:metrics, as: GoogleApi.AnalyticsReporting.V4.Model.Metric, type: :list)
field(:startGroup)
end
defimpl Poison.Decoder, for: GoogleApi.AnalyticsReporting.V4.Model.Pivot do
def decode(value, options) do
GoogleApi.AnalyticsReporting.V4.Model.Pivot.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AnalyticsReporting.V4.Model.Pivot do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 65.546875 | 812 | 0.749225 |
79e9f7778d3ce78920e8497ef053d0f48f8821f4 | 1,293 | exs | Elixir | mix.exs | jeromedoyle/ravenx_chat | 36549431fd8721288ef941cfd754bfca252c6ba9 | [
"MIT"
] | null | null | null | mix.exs | jeromedoyle/ravenx_chat | 36549431fd8721288ef941cfd754bfca252c6ba9 | [
"MIT"
] | null | null | null | mix.exs | jeromedoyle/ravenx_chat | 36549431fd8721288ef941cfd754bfca252c6ba9 | [
"MIT"
] | null | null | null | defmodule RavenxChat.MixProject do
use Mix.Project
def project do
[
app: :ravenx_chat,
version: "0.1.0",
elixir: "~> 1.4",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
description: description(),
package: package(),
deps: deps(),
docs: docs()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:ravenx, "~> 1.1 or ~> 2.0"},
{:poison, "~> 2.0 or ~> 3.0"},
{:httpoison, "~> 0.12 or ~> 1.0"},
{:ex_doc, ">= 0.0.0", only: :dev}
]
end
defp docs do
[
main: "readme",
source_url: "https://github.com/jeromedoyle/ravenx_chat",
extras: ["README.md"]
]
end
defp description do
"""
Ravenx strategy to send notifications to Hangouts Chat.
"""
end
defp package do
# These are the default files included in the package
[
name: :ravenx_chat,
files: ["lib", "mix.exs", "README*", "LICENSE*"],
maintainers: ["Jerome Doyle"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/jeromedoyle/ravenx_chat"}
]
end
end
| 21.55 | 72 | 0.556845 |
79ea6ab7938ce68370b1be81e4beab933eb67bae | 8,141 | exs | Elixir | apps/ehealth/test/integration/v1/approving_declaration_request_test.exs | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 8 | 2019-06-14T11:34:49.000Z | 2021-08-05T19:14:24.000Z | apps/ehealth/test/integration/v1/approving_declaration_request_test.exs | edenlabllc/ehealth.api.public | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 1 | 2019-07-08T15:20:22.000Z | 2019-07-08T15:20:22.000Z | apps/ehealth/test/integration/v1/approving_declaration_request_test.exs | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 6 | 2018-05-11T13:59:32.000Z | 2022-01-19T20:15:22.000Z | defmodule EHealth.Integraiton.DeclarationRequestApproveTest do
@moduledoc false
use EHealth.Web.ConnCase, async: false
alias Core.Repo
alias Core.DeclarationRequests.DeclarationRequest
import Mox
setup :verify_on_exit!
describe "Approve declaration with auth type OTP or NA" do
test "happy path: declaration is successfully approved via OTP code", %{conn: conn} do
expect(OPSMock, :get_declarations_count, fn _, _ ->
{:ok, %{"data" => %{"count" => 1}}}
end)
party = insert(:prm, :party)
legal_entity = insert(:prm, :legal_entity)
%{id: employee_id} = insert(:prm, :employee, party: party, legal_entity_id: legal_entity.id)
%{id: id} =
insert(
:il,
:declaration_request,
authentication_method_current: %{
"type" => "OTP",
"number" => "+380972805261"
},
data: %{"employee" => %{"id" => employee_id}}
)
otp_verification_expect()
resp =
conn
|> put_req_header("x-consumer-id", "ce377dea-d8c4-4dd8-9328-de24b1ee3879")
|> put_req_header("x-consumer-metadata", Jason.encode!(%{client_id: ""}))
|> patch("/api/declaration_requests/#{id}/actions/approve", Jason.encode!(%{"verification_code" => "12345"}))
|> json_response(200)
assert id == resp["data"]["id"]
assert "APPROVED" = resp["data"]["status"]
declaration_request = Repo.get(DeclarationRequest, id)
assert "APPROVED" = declaration_request.status
assert "ce377dea-d8c4-4dd8-9328-de24b1ee3879" == declaration_request.updated_by
end
test "declaration is successfully approved without verification", %{conn: conn} do
expect(OPSMock, :get_declarations_count, fn _, _ ->
{:ok, %{"data" => %{"count" => 1}}}
end)
party = insert(:prm, :party)
legal_entity = insert(:prm, :legal_entity)
%{id: employee_id} = insert(:prm, :employee, party: party, legal_entity_id: legal_entity.id)
%{id: id} =
insert(
:il,
:declaration_request,
authentication_method_current: %{
"type" => "NA",
"number" => "+380972805261"
},
data: %{"employee" => %{"id" => employee_id}}
)
resp =
conn
|> put_req_header("x-consumer-id", "ce377dea-d8c4-4dd8-9328-de24b1ee3879")
|> put_req_header("x-consumer-metadata", Jason.encode!(%{client_id: ""}))
|> patch("/api/declaration_requests/#{id}/actions/approve")
|> json_response(200)
assert id == resp["data"]["id"]
assert "APPROVED" = resp["data"]["status"]
declaration_request = Repo.get(DeclarationRequest, id)
assert "APPROVED" = declaration_request.status
assert "ce377dea-d8c4-4dd8-9328-de24b1ee3879" == declaration_request.updated_by
end
test "declaration failed to approve: invalid OTP", %{conn: conn} do
%{id: id} =
insert(
:il,
:declaration_request,
authentication_method_current: %{
"type" => "OTP",
"number" => "+380972805261"
}
)
otp_verification_expect(2)
response =
conn
|> put_req_header("x-consumer-id", "ce377dea-d8c4-4dd8-9328-de24b1ee3879")
|> put_req_header("x-consumer-metadata", Jason.encode!(%{client_id: ""}))
|> patch("/api/declaration_requests/#{id}/actions/approve", Jason.encode!(%{"verification_code" => "invalid"}))
|> json_response(422)
assert %{"error" => %{"type" => "forbidden", "message" => _}} = response
response =
conn
|> put_req_header("x-consumer-id", "ce377dea-d8c4-4dd8-9328-de24b1ee3879")
|> put_req_header("x-consumer-metadata", Jason.encode!(%{client_id: ""}))
|> patch("/api/declaration_requests/#{id}/actions/approve", Jason.encode!(%{"verification_code" => "54321"}))
|> json_response(500)
assert %{"error" => %{"type" => "proxied error", "message" => _}} = response
end
end
describe "Offline verification" do
test "happy path: declaration is successfully approved via offline docs check", %{conn: conn} do
expect(OPSMock, :get_declarations_count, fn _, _ ->
{:ok, %{"data" => %{"count" => 1}}}
end)
expect(MediaStorageMock, :create_signed_url, 2, fn _, _, _, _, _ ->
{:ok, %{secret_url: "http://localhost/good_upload_1"}}
end)
expect(MediaStorageMock, :verify_uploaded_file, 2, fn _, _ ->
{:ok, %HTTPoison.Response{status_code: 200}}
end)
party = insert(:prm, :party)
legal_entity = insert(:prm, :legal_entity)
%{id: employee_id} = insert(:prm, :employee, party: party, legal_entity_id: legal_entity.id)
%{id: id} =
insert(
:il,
:declaration_request,
authentication_method_current: %{
"type" => "OFFLINE"
},
data: %{"employee" => %{"id" => employee_id}},
documents: [
%{"type" => "A", "verb" => "HEAD"},
%{"type" => "B", "verb" => "HEAD"}
]
)
resp =
conn
|> put_req_header("x-consumer-id", "ce377dea-d8c4-4dd8-9328-de24b1ee3879")
|> put_req_header("x-consumer-metadata", Jason.encode!(%{client_id: ""}))
|> patch("/api/declaration_requests/#{id}/actions/approve")
|> json_response(200)
assert "APPROVED" = resp["data"]["status"]
declaration_request = Repo.get(DeclarationRequest, id)
assert "APPROVED" = declaration_request.status
assert "ce377dea-d8c4-4dd8-9328-de24b1ee3879" == declaration_request.updated_by
end
test "offline documents was not uploaded. Declaration cannot be approved", %{conn: conn} do
expect(MediaStorageMock, :create_signed_url, 2, fn _, _, _, _, _ ->
{:ok, %{secret_url: "http://localhost/good_upload_1"}}
end)
expect(MediaStorageMock, :verify_uploaded_file, 2, fn _, _ ->
{:ok, %HTTPoison.Response{status_code: 404}}
end)
%{id: id} =
insert(
:il,
:declaration_request,
authentication_method_current: %{
"type" => "OFFLINE"
},
documents: [
%{"type" => "404", "verb" => "HEAD"},
%{"type" => "empty", "verb" => "HEAD"}
]
)
conn =
conn
|> put_req_header("x-consumer-id", "ce377dea-d8c4-4dd8-9328-de24b1ee3879")
|> put_req_header("x-consumer-metadata", Jason.encode!(%{client_id: ""}))
|> patch("/api/declaration_requests/#{id}/actions/approve")
resp = json_response(conn, 409)
assert "Documents 404, empty is not uploaded" == resp["error"]["message"]
end
test "Ael not responding. Declaration cannot be approved", %{conn: conn} do
expect(MediaStorageMock, :create_signed_url, fn _, _, _, _, _ ->
{:ok, %{secret_url: "http://localhost/good_upload_1"}}
end)
expect(MediaStorageMock, :verify_uploaded_file, fn _, _ ->
{:error, %HTTPoison.Error{id: nil, reason: :timeout}}
end)
%{id: id} =
insert(
:il,
:declaration_request,
authentication_method_current: %{
"type" => "OFFLINE"
},
documents: [
%{"type" => "empty", "verb" => "HEAD"},
%{"type" => "error", "verb" => "HEAD"},
%{"type" => "404", "verb" => "HEAD"}
]
)
conn
|> put_req_header("x-consumer-id", "ce377dea-d8c4-4dd8-9328-de24b1ee3879")
|> put_req_header("x-consumer-metadata", Jason.encode!(%{client_id: ""}))
|> patch("/api/declaration_requests/#{id}/actions/approve")
|> json_response(500)
end
end
defp otp_verification_expect(count \\ 1) do
expect(RPCWorkerMock, :run, count, fn "otp_verification_api", OtpVerification.Rpc, :complete, [_, code] ->
case code do
"12345" -> {:ok, %{status: "verified"}}
"54321" -> nil
_ -> {:error, {:forbidden, "Invalid verification code"}}
end
end)
end
end
| 33.920833 | 119 | 0.577079 |
79eaf35157a0ef66226ae96b8f037a0ec0918271 | 615 | exs | Elixir | test/farmware_runtime/pipe_worker_test.exs | bahanni/custom_rpi4 | ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5 | [
"MIT"
] | null | null | null | test/farmware_runtime/pipe_worker_test.exs | bahanni/custom_rpi4 | ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5 | [
"MIT"
] | null | null | null | test/farmware_runtime/pipe_worker_test.exs | bahanni/custom_rpi4 | ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5 | [
"MIT"
] | null | null | null | defmodule FarmbotOS.FarmwareRuntime.PipeWorkerTest do
use ExUnit.Case
use Mimic
import ExUnit.CaptureLog
alias FarmbotOS.FarmwareRuntime.PipeWorker
setup :verify_on_exit!
defmodule FakeState do
defstruct [:direction, :pipe_name, :pipe]
end
test "terminate/2" do
state = %FakeState{
direction: "direction",
pipe_name: "/tmp/farmbot_os_test_pipe",
pipe: nil
}
msg = "PipeWorker #{state.direction} #{state.pipe_name} exit"
File.touch(state.pipe_name)
terminate = fn -> PipeWorker.terminate(nil, state) end
assert capture_log(terminate) =~ msg
end
end
| 24.6 | 65 | 0.707317 |
79eafce9d70e211b837a043c79ca643b79e1c026 | 712 | ex | Elixir | lib/harald/hci/commands/controller_and_baseband/write_simple_pairing_mode.ex | RicardoTrindade/harald | 3f56003265c29af0780730eb538183b50e55df2f | [
"MIT"
] | 59 | 2019-02-16T00:09:58.000Z | 2020-03-29T23:37:36.000Z | lib/harald/hci/commands/controller_and_baseband/write_simple_pairing_mode.ex | RicardoTrindade/harald | 3f56003265c29af0780730eb538183b50e55df2f | [
"MIT"
] | 19 | 2019-02-15T22:41:43.000Z | 2020-02-15T19:20:57.000Z | lib/harald/hci/commands/controller_and_baseband/write_simple_pairing_mode.ex | RicardoTrindade/harald | 3f56003265c29af0780730eb538183b50e55df2f | [
"MIT"
] | 9 | 2020-05-07T00:02:36.000Z | 2021-09-17T18:17:46.000Z | defmodule Harald.HCI.Commands.ControllerAndBaseband.WriteSimplePairingMode do
@moduledoc """
Reference: version 5.2, Vol 4, Part E, 7.3.59.
"""
alias Harald.HCI.Commands.Command
@behaviour Command
@impl Command
def encode(%{simple_pairing_mode: true}), do: {:ok, <<1>>}
def encode(%{simple_pairing_mode: false}), do: {:ok, <<0>>}
@impl Command
def decode(<<1>>), do: {:ok, %{simple_pairing_mode: true}}
def decode(<<0>>), do: {:ok, %{simple_pairing_mode: false}}
@impl Command
def decode_return_parameters(<<status>>), do: {:ok, %{status: status}}
@impl Command
def encode_return_parameters(%{status: status}), do: {:ok, <<status>>}
@impl Command
def ocf(), do: 0x56
end
| 26.37037 | 77 | 0.66573 |
79eb0cdc2d3218c8219725d30978267dd7a7f2e0 | 523 | exs | Elixir | mix.exs | asciibeats/elixir_ranch | 5331c101e43b1fb75aa8d53849cad95358ead3b4 | [
"MIT"
] | 30 | 2022-01-23T13:04:02.000Z | 2022-01-30T04:05:45.000Z | mix.exs | asciibeats/elixir_ranch | 5331c101e43b1fb75aa8d53849cad95358ead3b4 | [
"MIT"
] | null | null | null | mix.exs | asciibeats/elixir_ranch | 5331c101e43b1fb75aa8d53849cad95358ead3b4 | [
"MIT"
] | 2 | 2022-01-28T13:51:21.000Z | 2022-01-29T04:09:50.000Z | defmodule ElixirRanch.MixProject do
use Mix.Project
def project do
[
app: :elixir_ranch,
version: "0.1.0",
elixir: "~> 1.13",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
mod: {ElixirRanch.Application, []},
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:ranch, "~> 2.1.0"}
]
end
end
| 18.034483 | 59 | 0.575526 |
79eb2575c73494005a25eb737476bbf29741cc53 | 1,129 | ex | Elixir | test/process_managers/support/multi/todo_list.ex | mquickform/commanded | 260b1ec28c2fb3c1fcbb61b8c4abacabd7dc7ed2 | [
"MIT"
] | null | null | null | test/process_managers/support/multi/todo_list.ex | mquickform/commanded | 260b1ec28c2fb3c1fcbb61b8c4abacabd7dc7ed2 | [
"MIT"
] | 1 | 2018-12-05T18:17:08.000Z | 2018-12-05T18:17:08.000Z | test/process_managers/support/multi/todo_list.ex | mquickform/commanded | 260b1ec28c2fb3c1fcbb61b8c4abacabd7dc7ed2 | [
"MIT"
] | 1 | 2018-12-05T18:15:03.000Z | 2018-12-05T18:15:03.000Z | defmodule Commanded.ProcessManagers.TodoList do
@moduledoc false
defstruct todo_uuids: []
defmodule Commands do
defmodule(CreateList, do: defstruct([:list_uuid, :todo_uuids]))
defmodule(MarkAllDone, do: defstruct([:list_uuid]))
end
defmodule Events do
defmodule(TodoListCreated, do: defstruct([:list_uuid, :todo_uuids]))
defmodule(ListAllDone, do: defstruct([:list_uuid, :todo_uuids]))
end
alias Commanded.ProcessManagers.TodoList
alias Commanded.ProcessManagers.TodoList.Commands.{CreateList, MarkAllDone}
alias Commanded.ProcessManagers.TodoList.Events.{TodoListCreated, ListAllDone}
def execute(%TodoList{}, %CreateList{list_uuid: list_uuid, todo_uuids: todo_uuids}) do
%TodoListCreated{list_uuid: list_uuid, todo_uuids: todo_uuids}
end
def execute(%TodoList{todo_uuids: todo_uuids}, %MarkAllDone{list_uuid: list_uuid}) do
%ListAllDone{list_uuid: list_uuid, todo_uuids: todo_uuids}
end
def apply(%TodoList{} = state, %TodoListCreated{todo_uuids: todo_uuids}),
do: %TodoList{state | todo_uuids: todo_uuids}
def apply(%TodoList{} = state, _event), do: state
end
| 34.212121 | 88 | 0.758193 |
79eb49dd0314a1da58a155e41f24ec031c0d3bf1 | 1,277 | ex | Elixir | apps/tai/lib/tai/advisors/groups/rich_config.ex | ccamateur/tai | 41c4b3e09dafc77987fa3f6b300c15461d981e16 | [
"MIT"
] | 276 | 2018-01-16T06:36:06.000Z | 2021-03-20T21:48:01.000Z | apps/tai/lib/tai/advisors/groups/rich_config.ex | ccamateur/tai | 41c4b3e09dafc77987fa3f6b300c15461d981e16 | [
"MIT"
] | 78 | 2020-10-12T06:21:43.000Z | 2022-03-28T09:02:00.000Z | apps/tai/lib/tai/advisors/groups/rich_config.ex | yurikoval/tai | 94254b45d22fa0307b01577ff7c629c7280c0295 | [
"MIT"
] | 43 | 2018-06-09T09:54:51.000Z | 2021-03-07T07:35:17.000Z | defmodule Tai.Advisors.Groups.RichConfig do
alias Tai.Advisors.Groups.RichConfigProvider
@type config :: map
@type provider :: module
@spec parse(config, provider) :: config
def parse(raw_config, provider \\ RichConfigProvider) do
raw_config |> Enum.reduce(%{}, &parse_item(&1, &2, provider))
end
defp parse_item({k, {{venue_id, product_symbol}, :product}}, acc, provider) do
product = provider.products |> find_product(venue_id, product_symbol)
acc |> Map.put(k, product)
end
defp parse_item({k, {{venue_id, product_symbol, credential_id}, :fee}}, acc, provider) do
fee = provider.fees |> find_fee(venue_id, product_symbol, credential_id)
acc |> Map.put(k, fee)
end
defp parse_item({k, {raw_val, :decimal}}, acc, _provider) do
decimal_val = Tai.Utils.Decimal.cast!(raw_val)
acc |> Map.put(k, decimal_val)
end
defp parse_item({k, v}, acc, _provider), do: acc |> Map.put(k, v)
defp find_product(products, venue_id, symbol) do
products |> Enum.find(fn p -> p.venue_id == venue_id && p.symbol == symbol end)
end
defp find_fee(fees, venue_id, symbol, credential_id) do
fees
|> Enum.find(fn f ->
f.venue_id == venue_id && f.symbol == symbol && f.credential_id == credential_id
end)
end
end
| 31.925 | 91 | 0.678935 |
79eb99260af0cf7d7078c9b0505a030ec2b694b3 | 3,841 | ex | Elixir | lib/signaturex.ex | Tiltify/signaturex | 7018eb22cb4c4ffe9d4f5785eb57d005bfb31d1f | [
"MIT"
] | null | null | null | lib/signaturex.ex | Tiltify/signaturex | 7018eb22cb4c4ffe9d4f5785eb57d005bfb31d1f | [
"MIT"
] | null | null | null | lib/signaturex.ex | Tiltify/signaturex | 7018eb22cb4c4ffe9d4f5785eb57d005bfb31d1f | [
"MIT"
] | null | null | null | defmodule Signaturex do
alias Signaturex.CryptoHelper
alias Signaturex.Time
defmodule AuthenticationError do
defexception message: "Error on authentication"
end
@doc """
Validate request
Raises an AuthenticationError if the request is invalid
"""
@spec validate!(binary, binary, binary | atom, binary, Map.t, integer) :: true
def validate!(key, secret, method, path, params, timestamp_grace \\ 600) do
validate_version!(params["auth_version"])
validate_timestamp!(params["auth_timestamp"], timestamp_grace)
validate_key!(key, params["auth_key"])
validate_signature!(secret, method, path, params, params["auth_signature"])
true
end
@doc """
Validate request
Returns true or false
"""
@spec validate(binary, binary, binary | atom, binary, Map.t, integer) :: boolean
def validate(key, secret, method, path, params, timestamp_grace \\ 600) do
try do
validate!(key, secret, method, path, params, timestamp_grace)
rescue
_e in AuthenticationError -> false
end
end
defp validate_version!("1.0"), do: true
defp validate_version!(_) do
raise AuthenticationError, message: "Invalid auth version"
end
defp validate_timestamp!(_, nil), do: true
defp validate_timestamp!(nil, _timestamp_grace) do
raise AuthenticationError, message: "Timestamp missing"
end
defp validate_timestamp!(timestamp, timestamp_grace) when is_binary(timestamp) do
timestamp = timestamp |> String.to_charlist |> List.to_integer
validate_timestamp!(timestamp, timestamp_grace)
end
defp validate_timestamp!(timestamp, timestamp_grace) when is_integer(timestamp) do
if abs(Time.stamp - timestamp) < timestamp_grace do
true
else
raise AuthenticationError, message: "Auth timestamp expired"
end
end
defp validate_key!(_, nil) do
raise AuthenticationError, message: "Auth key missing"
end
defp validate_key!(key, key), do: true
defp validate_key!(_key, _auth_key) do
raise AuthenticationError, message: "Invalid auth key"
end
defp validate_signature!(_secret, _method, _path, _params, nil) do
raise AuthenticationError, message: "Auth signature missing"
end
defp validate_signature!(secret, method, path, params, auth_signature) do
params = build_params(params)
signature = auth_signature(secret, method, path, params)
if CryptoHelper.identical?(signature, auth_signature) do
true
else
raise AuthenticationError, message: "Invalid auth signature"
end
end
@doc """
Sign a request using `key`, `secret`, HTTP `method`,
query string `params` and an optional body
"""
@spec sign(binary, binary, binary | atom, binary, Map.t) :: Map.t
def sign(key, secret, method, path, params) do
auth_data = auth_data(key)
params = build_params(params)
params = Map.merge(params, auth_data)
signature = auth_signature(secret, method, path, params)
Map.put(auth_data, "auth_signature", signature)
end
defp auth_signature(secret, method, path, params) do
method = method |> to_string |> String.upcase
to_sign = "#{method}\n#{path}\n#{encode_query(params)}"
CryptoHelper.hmac256_to_string(secret, to_sign)
end
defp encode_query(params) do
params
|> Enum.into([])
|> Enum.sort(fn({k1, _}, {k2, _}) -> k1 <= k2 end)
|> URI.encode_query
end
defp build_params(params) do
for {k, v} <- params, into: %{} do
k = k |> to_string |> String.downcase
{k, v}
end |> Map.delete("auth_signature")
end
defp auth_data(app_key) do
%{ "auth_key" => app_key,
"auth_timestamp" => Time.stamp,
"auth_version" => "1.0" }
end
defmodule Time do
@spec stamp :: non_neg_integer
def stamp do
{mega, sec, _micro} = :os.timestamp()
mega * 1000000 + sec
end
end
end
| 30.484127 | 84 | 0.690966 |
79eba47eb769d62742d7a742956ce4db3accfa2b | 1,111 | exs | Elixir | apps/amf3/config/config.exs | Kabie/elixir-media-libs | 9750c6dcdffdf8014183a6a4f303c5d0d658f062 | [
"MIT"
] | 75 | 2016-12-23T14:37:18.000Z | 2021-04-26T14:07:20.000Z | apps/amf3/config/config.exs | Kabie/elixir-media-libs | 9750c6dcdffdf8014183a6a4f303c5d0d658f062 | [
"MIT"
] | 19 | 2016-12-22T03:20:43.000Z | 2020-06-11T12:10:37.000Z | apps/amf3/config/config.exs | Kabie/elixir-media-libs | 9750c6dcdffdf8014183a6a4f303c5d0d658f062 | [
"MIT"
] | 3 | 2018-03-29T06:40:40.000Z | 2019-02-13T09:37:19.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :amf3, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:amf3, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 35.83871 | 73 | 0.749775 |
79ebe8bfc0c0581c7303a2dddbb0c261c643827c | 336 | ex | Elixir | lib/queryhub/osquery/pack.ex | blaedj/queryhub | 1605d29e1d2b8a2a66bf911945dab441682083dc | [
"Apache-2.0"
] | null | null | null | lib/queryhub/osquery/pack.ex | blaedj/queryhub | 1605d29e1d2b8a2a66bf911945dab441682083dc | [
"Apache-2.0"
] | null | null | null | lib/queryhub/osquery/pack.ex | blaedj/queryhub | 1605d29e1d2b8a2a66bf911945dab441682083dc | [
"Apache-2.0"
] | null | null | null | defmodule QueryHub.Osquery.Pack do
use Ecto.Schema
import Ecto.Changeset
schema "packs" do
field(:description, :string)
field(:name, :string)
timestamps()
end
@doc false
def changeset(pack, attrs) do
pack
|> cast(attrs, [:name, :description])
|> validate_required([:name, :description])
end
end
| 17.684211 | 47 | 0.660714 |
79ec3a370f37d8b0150be92a7d3e88f9b0b7901d | 12,900 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/api/row_access_policies.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/api/row_access_policies.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/api/row_access_policies.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"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.BigQuery.V2.Api.RowAccessPolicies do
@moduledoc """
API calls for all endpoints tagged `RowAccessPolicies`.
"""
alias GoogleApi.BigQuery.V2.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.BigQuery.V2.Model.GetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_row_access_policies_get_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQuery.V2.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_row_access_policies_get_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/bigquery/v2/{+resource}:getIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQuery.V2.Model.Policy{}])
end
@doc """
Lists all row access policies on the specified table.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. Project ID of the row access policies to list.
* `dataset_id` (*type:* `String.t`) - Required. Dataset ID of row access policies to list.
* `table_id` (*type:* `String.t`) - Required. Table ID of the table to list row access policies.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:pageSize` (*type:* `integer()`) - The maximum number of results to return in a single response page. Leverage the page tokens to iterate through the entire collection.
* `:pageToken` (*type:* `String.t`) - Page token, returned by a previous call, to request the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.ListRowAccessPoliciesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_row_access_policies_list(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQuery.V2.Model.ListRowAccessPoliciesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_row_access_policies_list(
connection,
project_id,
dataset_id,
table_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/bigquery/v2/projects/{+projectId}/datasets/{+datasetId}/tables/{+tableId}/rowAccessPolicies",
%{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"datasetId" => URI.encode(dataset_id, &URI.char_unreserved?/1),
"tableId" => URI.encode(table_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQuery.V2.Model.ListRowAccessPoliciesResponse{}]
)
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy. Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being specified. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.BigQuery.V2.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_row_access_policies_set_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQuery.V2.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_row_access_policies_set_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/bigquery/v2/{+resource}:setIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQuery.V2.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.BigQuery.V2.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_row_access_policies_test_iam_permissions(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQuery.V2.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_row_access_policies_test_iam_permissions(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/bigquery/v2/{+resource}:testIamPermissions", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQuery.V2.Model.TestIamPermissionsResponse{}]
)
end
end
| 42.857143 | 351 | 0.631085 |
79ec4a02033e4742f06f1bbbdbdf66e966767ea2 | 1,125 | exs | Elixir | config/config.exs | kapilpipaliya/clouseau | 6672f2f48b149650906b2b5327a0562a93983fd4 | [
"MIT"
] | 7 | 2017-10-24T00:09:39.000Z | 2022-03-18T21:19:48.000Z | config/config.exs | kapilpipaliya/clouseau | 6672f2f48b149650906b2b5327a0562a93983fd4 | [
"MIT"
] | 2 | 2018-11-23T21:35:26.000Z | 2018-12-31T23:47:22.000Z | config/config.exs | kapilpipaliya/clouseau | 6672f2f48b149650906b2b5327a0562a93983fd4 | [
"MIT"
] | 2 | 2018-11-22T06:48:56.000Z | 2018-12-31T23:37:58.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure your application as:
#
# config :clouseau, key: :value
#
# and access this configuration in your application as:
#
# Application.get_env(:clouseau, :key)
#
# You can also configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 36.290323 | 73 | 0.752 |
79ec718d21b868fa361387b068f0e28109522411 | 484 | exs | Elixir | test/bgg_test.exs | peralmq/bgg-elixir | 50ee895c27d7ffc8a38d4670a4fd34ba9bcd7da8 | [
"MIT"
] | 3 | 2016-01-19T14:40:39.000Z | 2020-07-07T16:37:55.000Z | test/bgg_test.exs | peralmq/bgg-elixir | 50ee895c27d7ffc8a38d4670a4fd34ba9bcd7da8 | [
"MIT"
] | null | null | null | test/bgg_test.exs | peralmq/bgg-elixir | 50ee895c27d7ffc8a38d4670a4fd34ba9bcd7da8 | [
"MIT"
] | null | null | null | defmodule BGGTest do
use ExUnit.Case
test "the truth" do
assert(true)
end
test "game returns a game" do
game = BGG.Game.game("2651")
bgg_game = BGG.Game.as_BGGGame(game)
assert bgg_game.name == "Power Grid"
end
test "search_games returns games" do
games = BGG.Search.search_games("Power Grid")
bgg_games = BGG.Game.as_BGGGames(games)
assert Enum.any?(
bgg_games,
fn(g) ->
g.objectid == "2651"
end
)
end
end
| 17.925926 | 49 | 0.623967 |
79ec776d45e99ac91e064b8540dbaba59ff73115 | 711 | ex | Elixir | webapp/lib/penmark_web/gettext.ex | zmaril/penmark | 992f570da3bdf819f912505ba9b6531db9dcb80b | [
"FSFAP"
] | null | null | null | webapp/lib/penmark_web/gettext.ex | zmaril/penmark | 992f570da3bdf819f912505ba9b6531db9dcb80b | [
"FSFAP"
] | null | null | null | webapp/lib/penmark_web/gettext.ex | zmaril/penmark | 992f570da3bdf819f912505ba9b6531db9dcb80b | [
"FSFAP"
] | null | null | null | defmodule PenmarkWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import PenmarkWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :penmark
end
| 28.44 | 72 | 0.677918 |
79ec8b6a472b18fa5c43d03a20393632d149b838 | 1,608 | exs | Elixir | test/mayo_test.exs | tommy351/mayo | 59df8af91eb12a9a289ca6e699ef4cd1f130d9ed | [
"MIT"
] | 1 | 2016-09-09T09:00:35.000Z | 2016-09-09T09:00:35.000Z | test/mayo_test.exs | tommy351/mayo | 59df8af91eb12a9a289ca6e699ef4cd1f130d9ed | [
"MIT"
] | null | null | null | test/mayo_test.exs | tommy351/mayo | 59df8af91eb12a9a289ca6e699ef4cd1f130d9ed | [
"MIT"
] | null | null | null | defmodule MayoTest do
use ExUnit.Case
doctest Mayo
test "map" do
result = Mayo.validate %{
username: "test"
}, %{
username: Mayo.Any.string |> Mayo.String.min(4)
}
assert result == %{username: "test"}
result = Mayo.validate %{}, %{
username: Mayo.Any.string |> Mayo.Any.required |> Mayo.String.min(4)
}
assert result == {:error, %Mayo.Error{type: "any.required", paths: [:username]}}
end
test "nested map" do
result = Mayo.validate %{
payload: %{
username: "jo"
}
}, %{
payload: %{
username: Mayo.Any.string |> Mayo.String.min(4)
}
}
assert result == {:error, %Mayo.Error{type: "string.min", paths: [:payload, :username]}}
end
test "keyword list" do
result = Mayo.validate [
username: "test"
], [
username: Mayo.Any.string |> Mayo.String.min(4)
]
assert result == [username: "test"]
result = Mayo.validate [], [
username: Mayo.Any.string |> Mayo.Any.required |> Mayo.String.min(4)
]
assert result == {:error, %Mayo.Error{type: "any.required", paths: [:username]}}
end
test "map pipe" do
result = Mayo.validate %{
username: "test"
}, %{
username: Mayo.Any.string
} |> Mayo.Map.with([:username, :password])
assert result == {:error, %Mayo.Error{type: "map.with", paths: [:password]}}
end
test "list pipe" do
result = Mayo.validate [
username: "test"
], [
username: Mayo.Any.string
] |> Mayo.List.min(2)
assert result == {:error, %Mayo.Error{type: "list.min"}}
end
end
| 22.647887 | 92 | 0.56903 |
79ecdcb9db7c134133b7f2e0afaeb54cc31b5744 | 1,562 | ex | Elixir | test/support/data_case.ex | LeonardoSSev/phx-crud-users | 52dabaae0c81adeee39afa48eb17331de261d3c4 | [
"MIT"
] | null | null | null | test/support/data_case.ex | LeonardoSSev/phx-crud-users | 52dabaae0c81adeee39afa48eb17331de261d3c4 | [
"MIT"
] | null | null | null | test/support/data_case.ex | LeonardoSSev/phx-crud-users | 52dabaae0c81adeee39afa48eb17331de261d3c4 | [
"MIT"
] | null | null | null | defmodule PhxCrudUsers.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 PhxCrudUsers.DataCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
alias PhxCrudUsers.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import PhxCrudUsers.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(PhxCrudUsers.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(PhxCrudUsers.Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transforms changeset errors into a map of messages.
assert {:error, changeset} = Accounts.create_user(%{password: "short"})
assert "password is too short" in errors_on(changeset).password
assert %{password: ["password is too short"]} = errors_on(changeset)
"""
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
| 27.892857 | 77 | 0.694622 |
79ed7862960e3ca0aba709576365c73b108e53cd | 255 | ex | Elixir | web/controllers/hello_controller.ex | chris-nelson-mn/hello-phoenix | af72e48ece5b7f3f5bba3f0b5527e3173e13e5b2 | [
"MIT"
] | null | null | null | web/controllers/hello_controller.ex | chris-nelson-mn/hello-phoenix | af72e48ece5b7f3f5bba3f0b5527e3173e13e5b2 | [
"MIT"
] | null | null | null | web/controllers/hello_controller.ex | chris-nelson-mn/hello-phoenix | af72e48ece5b7f3f5bba3f0b5527e3173e13e5b2 | [
"MIT"
] | null | null | null | defmodule HelloPhoenix.HelloController do
use HelloPhoenix.Web, :controller
def index(conn, _params) do
render conn, "index.html"
end
def show(conn, %{"messenger" => messenger}) do
render conn, "show.html", messenger: messenger
end
end | 23.181818 | 50 | 0.713725 |
79ed8470522117789d51e505b8fe696a7067f2dc | 5,743 | ex | Elixir | clients/firestore/lib/google_api/firestore/v1beta1/model/field_transform.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/firestore/lib/google_api/firestore/v1beta1/model/field_transform.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/firestore/lib/google_api/firestore/v1beta1/model/field_transform.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.Firestore.V1beta1.Model.FieldTransform do
@moduledoc """
A transformation of a field of the document.
## Attributes
* `appendMissingElements` (*type:* `GoogleApi.Firestore.V1beta1.Model.ArrayValue.t`, *default:* `nil`) - Append the given elements in order if they are not already present in the current field value. If the field is not an array, or if the field does not yet exist, it is first set to the empty array. Equivalent numbers of different types (e.g. 3L and 3.0) are considered equal when checking if a value is missing. NaN is equal to NaN, and Null is equal to Null. If the input contains multiple equivalent values, only the first will be considered. The corresponding transform_result will be the null value.
* `fieldPath` (*type:* `String.t`, *default:* `nil`) - The path of the field. See Document.fields for the field path syntax reference.
* `increment` (*type:* `GoogleApi.Firestore.V1beta1.Model.Value.t`, *default:* `nil`) - Adds the given value to the field's current value. This must be an integer or a double value. If the field is not an integer or double, or if the field does not yet exist, the transformation will set the field to the given value. If either of the given value or the current field value are doubles, both values will be interpreted as doubles. Double arithmetic and representation of double values follow IEEE 754 semantics. If there is positive/negative integer overflow, the field is resolved to the largest magnitude positive/negative integer.
* `maximum` (*type:* `GoogleApi.Firestore.V1beta1.Model.Value.t`, *default:* `nil`) - Sets the field to the maximum of its current value and the given value. This must be an integer or a double value. If the field is not an integer or double, or if the field does not yet exist, the transformation will set the field to the given value. If a maximum operation is applied where the field and the input value are of mixed types (that is - one is an integer and one is a double) the field takes on the type of the larger operand. If the operands are equivalent (e.g. 3 and 3.0), the field does not change. 0, 0.0, and -0.0 are all zero. The maximum of a zero stored value and zero input value is always the stored value. The maximum of any numeric value x and NaN is NaN.
* `minimum` (*type:* `GoogleApi.Firestore.V1beta1.Model.Value.t`, *default:* `nil`) - Sets the field to the minimum of its current value and the given value. This must be an integer or a double value. If the field is not an integer or double, or if the field does not yet exist, the transformation will set the field to the input value. If a minimum operation is applied where the field and the input value are of mixed types (that is - one is an integer and one is a double) the field takes on the type of the smaller operand. If the operands are equivalent (e.g. 3 and 3.0), the field does not change. 0, 0.0, and -0.0 are all zero. The minimum of a zero stored value and zero input value is always the stored value. The minimum of any numeric value x and NaN is NaN.
* `removeAllFromArray` (*type:* `GoogleApi.Firestore.V1beta1.Model.ArrayValue.t`, *default:* `nil`) - Remove all of the given elements from the array in the field. If the field is not an array, or if the field does not yet exist, it is set to the empty array. Equivalent numbers of the different types (e.g. 3L and 3.0) are considered equal when deciding whether an element should be removed. NaN is equal to NaN, and Null is equal to Null. This will remove all equivalent values if there are duplicates. The corresponding transform_result will be the null value.
* `setToServerValue` (*type:* `String.t`, *default:* `nil`) - Sets the field to the given server value.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:appendMissingElements => GoogleApi.Firestore.V1beta1.Model.ArrayValue.t(),
:fieldPath => String.t(),
:increment => GoogleApi.Firestore.V1beta1.Model.Value.t(),
:maximum => GoogleApi.Firestore.V1beta1.Model.Value.t(),
:minimum => GoogleApi.Firestore.V1beta1.Model.Value.t(),
:removeAllFromArray => GoogleApi.Firestore.V1beta1.Model.ArrayValue.t(),
:setToServerValue => String.t()
}
field(:appendMissingElements, as: GoogleApi.Firestore.V1beta1.Model.ArrayValue)
field(:fieldPath)
field(:increment, as: GoogleApi.Firestore.V1beta1.Model.Value)
field(:maximum, as: GoogleApi.Firestore.V1beta1.Model.Value)
field(:minimum, as: GoogleApi.Firestore.V1beta1.Model.Value)
field(:removeAllFromArray, as: GoogleApi.Firestore.V1beta1.Model.ArrayValue)
field(:setToServerValue)
end
defimpl Poison.Decoder, for: GoogleApi.Firestore.V1beta1.Model.FieldTransform do
def decode(value, options) do
GoogleApi.Firestore.V1beta1.Model.FieldTransform.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Firestore.V1beta1.Model.FieldTransform do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 88.353846 | 773 | 0.750653 |
79edb10909d9785a228cc5122257a0aedb7c00af | 702 | ex | Elixir | lib/elixir_blog_web/router.ex | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | lib/elixir_blog_web/router.ex | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | lib/elixir_blog_web/router.ex | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | defmodule ElixirBlogWeb.Router do
use ElixirBlogWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", ElixirBlogWeb do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
resources "/articles", ArticleController do
resources "/comments", CommentController, except: [:edit, :update]
end
resources "/users", UserController
end
# Other scopes may use custom stacks.
# scope "/api", ElixirBlogWeb do
# pipe_through :api
# end
end
| 21.9375 | 72 | 0.688034 |
79ede5c1fb5d62289676a092304e4332efccd574 | 2,783 | exs | Elixir | test/advent2019_web/controllers/day06_controller_test.exs | jacopofar/advent-of-code-2019-phoenix-react | 762d7053fd8eeb096187fb394e3ce03bbe1854d7 | [
"MIT"
] | 5 | 2019-12-02T08:50:54.000Z | 2021-03-31T22:54:20.000Z | test/advent2019_web/controllers/day06_controller_test.exs | jacopofar/advent-of-code-2019-phoenix-react | 762d7053fd8eeb096187fb394e3ce03bbe1854d7 | [
"MIT"
] | 1 | 2019-12-18T07:19:26.000Z | 2019-12-18T07:19:26.000Z | test/advent2019_web/controllers/day06_controller_test.exs | jacopofar/advent-of-code-2019-phoenix-react | 762d7053fd8eeb096187fb394e3ce03bbe1854d7 | [
"MIT"
] | 2 | 2019-12-16T07:52:16.000Z | 2019-12-17T17:49:05.000Z | defmodule Advent2019Web.Day06ControllerTest do
use Advent2019Web.ConnCase
import Advent2019Web.Day06Controller
test "transitive closure" do
# note that the transitive_closure is slow and not really required.
# The exercise only want the count of the orbits, not to enumerate them!
# So, here it is implemented that way but the closure is kept as well
# NOTE: Erlang has a digraph module but I discovered it after implementing this :/
# Good to know for the future...
input = [
"COM)B",
"B)C",
"C)D",
"D)E",
"E)F",
"B)G",
"G)H",
"D)I",
"E)J",
"J)K",
"K)L"
]
map_representation = represent_as_map(input)
assert map_representation == %{
"COM" => MapSet.new(["B"]),
"B" => MapSet.new(["C", "G"]),
"C" => MapSet.new(["D"]),
"D" => MapSet.new(["E", "I"]),
"E" => MapSet.new(["F", "J"]),
"G" => MapSet.new(["H"]),
"J" => MapSet.new(["K"]),
"K" => MapSet.new(["L"])
}
expanded_orbits = transitive_closure(map_representation)
assert expanded_orbits == %{
"B" => MapSet.new(["C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]),
"C" => MapSet.new(["D", "E", "F", "I", "J", "K", "L"]),
"COM" => MapSet.new(["B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]),
"D" => MapSet.new(["E", "F", "I", "J", "K", "L"]),
"E" => MapSet.new(["F", "J", "K", "L"]),
"G" => MapSet.new(["H"]),
"J" => MapSet.new(["K", "L"]),
"K" => MapSet.new(["L"])
}
assert count_orbits(expanded_orbits) == 42
end
test "shortest path" do
input = [
"COM)B",
"B)C",
"C)D",
"D)E",
"E)F",
"B)G",
"G)H",
"D)I",
"E)J",
"J)K",
"K)L",
"K)YOU",
"I)SAN"
]
map_representation = represent_as_bidirectional_map(input)
assert map_representation == %{
"B" => MapSet.new(["C", "COM", "G"]),
"C" => MapSet.new(["B", "D"]),
"COM" => MapSet.new(["B"]),
"D" => MapSet.new(["C", "E", "I"]),
"E" => MapSet.new(["D", "F", "J"]),
"F" => MapSet.new(["E"]),
"G" => MapSet.new(["B", "H"]),
"H" => MapSet.new(["G"]),
"I" => MapSet.new(["D", "SAN"]),
"J" => MapSet.new(["E", "K"]),
"K" => MapSet.new(["J", "L", "YOU"]),
"L" => MapSet.new(["K"]),
"SAN" => MapSet.new(["I"]),
"YOU" => MapSet.new(["K"])
}
assert shortest_path(map_representation, "YOU", "SAN") == ["K", "J", "E", "D", "I"]
end
end
| 29.924731 | 90 | 0.415738 |
79edf1eab8563049cf81e923ca37704d85eea688 | 1,603 | exs | Elixir | {{APP_NAME}}_umbrella/apps/{{APP_NAME}}_api/mix.exs | Vorzious/Phoenix-Template | 7baa93c97047906afa2557fd0b0980a0bafd320d | [
"MIT"
] | null | null | null | {{APP_NAME}}_umbrella/apps/{{APP_NAME}}_api/mix.exs | Vorzious/Phoenix-Template | 7baa93c97047906afa2557fd0b0980a0bafd320d | [
"MIT"
] | null | null | null | {{APP_NAME}}_umbrella/apps/{{APP_NAME}}_api/mix.exs | Vorzious/Phoenix-Template | 7baa93c97047906afa2557fd0b0980a0bafd320d | [
"MIT"
] | null | null | null | defmodule {{MODULE_NAME}}Api.Mixfile do
use Mix.Project
def project do
[
app: :{{APP_NAME}}_api,
version: "0.0.1",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.6.2",
elixirc_paths: elixirc_paths(Mix.env),
compilers: [:phoenix, :gettext] ++ Mix.compilers,
start_permanent: (Mix.env == :prod || Mix.env == :staging),
aliases: aliases(),
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {{{MODULE_NAME}}Api.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.3.2"},
{:phoenix_pubsub, "1.0.2"},
{:phoenix_ecto, "3.3.0"},
{:phoenix_live_reload, "1.1.3", only: :dev},
{:gettext, "0.14.1"},
{:{{APP_NAME}}, in_umbrella: true},
{:cowboy, "~> 1.0.0"}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, we extend the test task to create and migrate the database.
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
["test": ["ecto.create --quiet", "ecto.migrate", "test"]]
end
end
| 27.637931 | 76 | 0.59451 |
79edf7c1c1b6dda2ce17958937d11a852ddf1d84 | 9,216 | ex | Elixir | lib/elasticlunr/core/index.ex | merchant-ly/ex_elasticlunr | b7d12f3e567f1ecad1bfb402a062edd4d58ef9fd | [
"MIT"
] | null | null | null | lib/elasticlunr/core/index.ex | merchant-ly/ex_elasticlunr | b7d12f3e567f1ecad1bfb402a062edd4d58ef9fd | [
"MIT"
] | null | null | null | lib/elasticlunr/core/index.ex | merchant-ly/ex_elasticlunr | b7d12f3e567f1ecad1bfb402a062edd4d58ef9fd | [
"MIT"
] | null | null | null | defmodule Elasticlunr.Index.IdPipeline do
@moduledoc false
alias Elasticlunr.{Pipeline, Token}
@behaviour Pipeline
@impl true
def call(%Token{} = token), do: token
end
defmodule Elasticlunr.Index do
alias Elasticlunr.{Field, Pipeline, Token}
alias Elasticlunr.Index.IdPipeline
alias Elasticlunr.Dsl.{Query, QueryRepository}
@fields ~w[fields name ref pipeline documents_size store_positions store_documents]a
@enforce_keys @fields
defstruct @fields
@type document_field :: atom() | binary()
@type t :: %__MODULE__{
fields: map(),
documents_size: integer(),
ref: Field.document_ref(),
pipeline: Pipeline.t(),
name: atom() | binary(),
store_positions: boolean(),
store_documents: boolean()
}
@type search_query :: binary() | map()
@type search_result :: any()
@spec new(keyword()) :: t()
def new(opts \\ []) do
ref = Keyword.get(opts, :ref, "id")
pipeline = Keyword.get_lazy(opts, :pipeline, &Pipeline.new/0)
id_field = Field.new(pipeline: Pipeline.new([IdPipeline]))
fields = Map.put(%{}, to_string(ref), id_field)
attrs = %{
documents_size: 0,
ref: ref,
fields: fields,
pipeline: pipeline,
name: Keyword.get_lazy(opts, :name, &UUID.uuid4/0),
store_documents: Keyword.get(opts, :store_documents, true),
store_positions: Keyword.get(opts, :store_positions, true)
}
struct!(__MODULE__, attrs)
end
@spec add_field(t(), document_field(), keyword()) :: t()
def add_field(
%__MODULE__{
fields: fields,
pipeline: pipeline,
store_positions: store_positions,
store_documents: store_documents
} = index,
field,
opts \\ []
)
when is_binary(field) do
opts =
opts
|> Keyword.put_new(:pipeline, pipeline)
|> Keyword.put_new(:store_documents, store_documents)
|> Keyword.put_new(:store_positions, store_positions)
%{index | fields: Map.put(fields, field, Field.new(opts))}
end
@spec update_field(t(), document_field(), Field.t()) :: t()
def update_field(%__MODULE__{fields: fields} = index, name, %Field{} = field) do
if not Map.has_key?(fields, name) do
raise "Unknown field #{name} in index"
end
update_documents_size(%{index | fields: Map.put(fields, name, field)})
end
@spec get_fields(t()) :: list(Field.document_ref() | document_field())
def get_fields(%__MODULE__{fields: fields}), do: Map.keys(fields)
@spec get_field(t(), document_field()) :: Field.t()
def get_field(%__MODULE__{fields: fields}, field) do
Map.get(fields, field)
end
@spec save_document(t(), boolean()) :: t()
def save_document(%__MODULE__{fields: fields} = index, save) do
fields =
fields
|> Enum.map(fn {key, field} -> {key, %{field | store: save}} end)
|> Enum.into(%{})
%{index | fields: fields}
end
@spec add_documents(t(), list(map())) :: t()
def add_documents(%__MODULE__{} = index, documents) do
docs_length = length(documents)
[index] =
transform_documents(index, documents)
|> Stream.with_index(1)
|> Stream.drop_while(fn {_, index} -> index < docs_length end)
|> Stream.map(&elem(&1, 0))
|> Enum.to_list()
update_documents_size(index)
end
@spec update_documents(t(), list(map())) :: t()
def update_documents(%__MODULE__{ref: ref, fields: fields} = index, documents) do
transform_document = fn {key, content}, {document, fields} ->
case Map.get(fields, key) do
nil ->
{document, fields}
%Field{} = field ->
id = Map.get(document, ref)
field = Field.update(field, [%{id: id, content: content}])
fields = Map.put(fields, key, field)
{document, fields}
end
end
fields =
Enum.reduce(documents, fields, fn document, fields ->
document
|> Enum.reduce({document, fields}, transform_document)
|> elem(1)
end)
update_documents_size(%{index | fields: fields})
end
@spec remove_documents(t(), list(Field.document_ref())) :: t()
def remove_documents(%__MODULE__{fields: fields} = index, document_ids) do
fields =
Enum.reduce(fields, fields, fn {key, field}, fields ->
field = Field.remove(field, document_ids)
Map.put(fields, key, field)
end)
update_documents_size(%{index | fields: fields})
end
@spec analyze(t(), document_field(), any(), keyword()) :: Token.t() | list(Token.t())
def analyze(%__MODULE__{fields: fields}, field, content, options) do
fields
|> Map.get(field)
|> Field.analyze(content, options)
end
@spec terms(t(), keyword()) :: any()
def terms(%__MODULE__{fields: fields}, query) do
field = Keyword.get(query, :field)
fields
|> Map.get(field)
|> Field.terms(query)
end
@spec all(t()) :: list(Field.document_ref())
def all(%__MODULE__{ref: ref, fields: fields}) do
fields
|> Map.get(ref)
|> Field.all()
end
@spec search(t(), search_query(), map() | nil) :: list(search_result())
def search(index, query, opts \\ nil)
def search(%__MODULE__{}, nil, _opts), do: []
def search(%__MODULE__{ref: ref} = index, query, nil) when is_binary(query) do
fields = get_fields(index)
matches =
fields
|> Enum.reject(&(&1 == ref))
|> Enum.map(fn field ->
%{"match" => %{field => query}}
end)
elasticsearch(index, %{
"query" => %{
"bool" => %{
"should" => matches
}
}
})
end
def search(%__MODULE__{ref: ref} = index, query, %{"fields" => fields}) when is_binary(query) do
matches =
fields
|> Enum.filter(fn field ->
with true <- field != ref,
true <- Map.has_key?(fields, field),
%{"boost" => boost} <- Map.get(fields, field) do
boost > 0
end
end)
|> Enum.map(fn field ->
%{"boost" => boost} = Map.get(fields, field)
match = %{field => query}
%{"match" => match, "boost" => boost}
end)
elasticsearch(index, %{
"query" => %{
"bool" => %{
"should" => matches
}
}
})
end
def search(%__MODULE__{} = index, %{"query" => _} = query, _opts),
do: elasticsearch(index, query)
def search(%__MODULE__{} = index, query, nil) when is_map(query),
do: search(index, query, %{"operator" => "OR"})
def search(%__MODULE__{} = index, %{} = query, options) do
matches =
query
|> Enum.map(fn {field, content} ->
expand = Map.get(options, "expand", false)
operator =
options
|> Map.get("bool", "or")
|> String.downcase()
%{
"expand" => expand,
"match" => %{"operator" => operator, field => content}
}
end)
elasticsearch(index, %{
"query" => %{
"bool" => %{
"should" => matches
}
}
})
end
defp elasticsearch(index, %{"query" => root}) do
{key, value} = Query.split_root(root)
query = QueryRepository.parse(key, value, root)
query
|> QueryRepository.score(index)
|> Enum.sort(fn a, b -> a.score > b.score end)
end
defp elasticsearch(_index, _query) do
raise "Root object must have a query element"
end
defp update_documents_size(%__MODULE__{fields: fields} = index) do
size =
index
|> get_fields()
|> Enum.map(fn field ->
field = Map.get(fields, field)
Enum.count(field.ids)
end)
|> Enum.reduce(0, fn size, acc ->
case size > acc do
true ->
size
false ->
acc
end
end)
%{index | documents_size: size}
end
defp transform_documents(%{ref: ref} = index, documents) do
add_or_ignore_field = fn index, key, fields ->
case Map.get(fields, key) do
nil ->
add_field(index, key)
%Field{} ->
index
end
end
documents
|> Stream.map(&flatten_document/1)
|> Stream.scan(index, fn document, index ->
%{fields: fields} = index
recognized_keys =
Map.keys(document)
|> Stream.filter(fn attribute ->
[field | _tail] = String.split(attribute, ".")
Map.has_key?(fields, field)
end)
Enum.reduce(recognized_keys, index, fn key, index ->
index = add_or_ignore_field.(index, key, fields)
field = get_field(index, key)
field = Field.add(field, [%{id: Map.get(document, ref), content: Map.get(document, key)}])
patch_field(index, key, field)
end)
end)
end
defp patch_field(%{fields: fields} = index, key, %Field{} = field) do
%{index | fields: Map.put(fields, key, field)}
end
defp flatten_document(document, prefix \\ "") do
Enum.reduce(document, %{}, fn
{key, value}, transformed when is_map(value) ->
mapped = flatten_document(value, "#{prefix}#{key}.")
Map.merge(transformed, mapped)
{key, value}, transformed ->
Map.put(transformed, "#{prefix}#{key}", value)
end)
end
end
| 26.790698 | 98 | 0.581597 |
79edf7cfc35a5e3bb989db9bf6e980aa0bfa6001 | 15,688 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/advertiser_landing_pages.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/advertiser_landing_pages.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/advertiser_landing_pages.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V33.Api.AdvertiserLandingPages do
@moduledoc """
API calls for all endpoints tagged `AdvertiserLandingPages`.
"""
alias GoogleApi.DFAReporting.V33.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets one landing page by ID.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `id` (*type:* `String.t`) - Landing page ID.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V33.Model.LandingPage{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_advertiser_landing_pages_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.LandingPage.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def dfareporting_advertiser_landing_pages_get(
connection,
profile_id,
id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/dfareporting/v3.3/userprofiles/{profileId}/advertiserLandingPages/{id}", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1),
"id" => URI.encode(id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V33.Model.LandingPage{}])
end
@doc """
Inserts a new landing page.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.DFAReporting.V33.Model.LandingPage.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V33.Model.LandingPage{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_advertiser_landing_pages_insert(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.LandingPage.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def dfareporting_advertiser_landing_pages_insert(
connection,
profile_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/dfareporting/v3.3/userprofiles/{profileId}/advertiserLandingPages", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V33.Model.LandingPage{}])
end
@doc """
Retrieves a list of landing pages.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:advertiserIds` (*type:* `list(String.t)`) - Select only landing pages that belong to these advertisers.
* `:archived` (*type:* `boolean()`) - Select only archived landing pages. Don't set this field to select both archived and non-archived landing pages.
* `:campaignIds` (*type:* `list(String.t)`) - Select only landing pages that are associated with these campaigns.
* `:ids` (*type:* `list(String.t)`) - Select only landing pages with these IDs.
* `:maxResults` (*type:* `integer()`) - Maximum number of results to return.
* `:pageToken` (*type:* `String.t`) - Value of the nextPageToken from the previous result page.
* `:searchString` (*type:* `String.t`) - Allows searching for landing pages by name or ID. Wildcards (*) are allowed. For example, "landingpage*2017" will return landing pages with names like "landingpage July 2017", "landingpage March 2017", or simply "landingpage 2017". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "landingpage" will match campaigns with name "my landingpage", "landingpage 2015", or simply "landingpage".
* `:sortField` (*type:* `String.t`) - Field by which to sort the list.
* `:sortOrder` (*type:* `String.t`) - Order of sorted results.
* `:subaccountId` (*type:* `String.t`) - Select only landing pages that belong to this subaccount.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V33.Model.AdvertiserLandingPagesListResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_advertiser_landing_pages_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.AdvertiserLandingPagesListResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def dfareporting_advertiser_landing_pages_list(
connection,
profile_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:advertiserIds => :query,
:archived => :query,
:campaignIds => :query,
:ids => :query,
:maxResults => :query,
:pageToken => :query,
:searchString => :query,
:sortField => :query,
:sortOrder => :query,
:subaccountId => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/dfareporting/v3.3/userprofiles/{profileId}/advertiserLandingPages", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DFAReporting.V33.Model.AdvertiserLandingPagesListResponse{}]
)
end
@doc """
Updates an existing landing page. This method supports patch semantics.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `id` (*type:* `String.t`) - Landing page ID.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.DFAReporting.V33.Model.LandingPage.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V33.Model.LandingPage{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_advertiser_landing_pages_patch(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.LandingPage.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def dfareporting_advertiser_landing_pages_patch(
connection,
profile_id,
id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/dfareporting/v3.3/userprofiles/{profileId}/advertiserLandingPages", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :id, id)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V33.Model.LandingPage{}])
end
@doc """
Updates an existing landing page.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.DFAReporting.V33.Model.LandingPage.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V33.Model.LandingPage{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_advertiser_landing_pages_update(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.LandingPage.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def dfareporting_advertiser_landing_pages_update(
connection,
profile_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/dfareporting/v3.3/userprofiles/{profileId}/advertiserLandingPages", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V33.Model.LandingPage{}])
end
end
| 42.514905 | 518 | 0.627231 |
79ee5d913e538a7f4e4f53a4e60c48034e250481 | 3,897 | ex | Elixir | lib/database/project.ex | irfansharif/bors-ng | 0589d6b6ac929bcc911c1876d77eb7d3eab30b49 | [
"Apache-2.0"
] | null | null | null | lib/database/project.ex | irfansharif/bors-ng | 0589d6b6ac929bcc911c1876d77eb7d3eab30b49 | [
"Apache-2.0"
] | 1 | 2020-07-24T21:49:28.000Z | 2020-07-24T21:49:28.000Z | lib/database/project.ex | irfansharif/bors-ng | 0589d6b6ac929bcc911c1876d77eb7d3eab30b49 | [
"Apache-2.0"
] | null | null | null | defmodule BorsNG.Database.Project do
@moduledoc """
Corresponds to a repo in GitHub, as opposed to a repo in Ecto.
This also corresponds to a queue of batches.
"""
use BorsNG.Database.Model
alias BorsNG.Database.ProjectPermission
@type t :: %__MODULE__{}
@type id :: pos_integer
@spec ping!(id) :: :ok | no_return
@doc """
After modifying the underlying model,
call this to notify the UI.
"""
def ping!(project_id) when not is_binary(project_id) do
ping!(to_string(project_id))
end
def ping!(project_id) do
BorsNG.Endpoint.broadcast!("project_ping:#{project_id}", "new_msg", %{})
end
schema "projects" do
belongs_to(:installation, Installation)
field(:repo_xref, :integer)
field(:name, :string)
many_to_many(:users, User,
join_through: LinkUserProject,
on_replace: :delete
)
many_to_many(:members, User,
join_through: LinkMemberProject,
on_replace: :delete
)
field(:staging_branch, :string, default: "staging")
field(:trying_branch, :string, default: "trying")
field(:batch_poll_period_sec, :integer, default: 60 * 30)
field(:batch_delay_sec, :integer, default: 10)
field(:batch_timeout_sec, :integer, default: 60 * 60 * 2)
field(:auto_reviewer_required_perm, ProjectPermission, default: nil)
field(:auto_member_required_perm, ProjectPermission, default: nil)
timestamps()
end
@spec active() :: Ecto.Queryable.t()
def active do
from(p in Project,
join: b in Batch,
on: p.id == b.project_id,
where:
b.state == ^:waiting or
b.state == ^:running
)
end
@spec installation_project_connection(id, module) ::
{{:installation, Installation.xref()}, repo_xref :: integer()}
def installation_project_connection(project_id, repo) do
{installation_xref, repo_xref} =
from(p in Project,
join: i in Installation,
on: i.id == p.installation_id,
where: p.id == ^project_id,
select: {i.installation_xref, p.repo_xref}
)
|> repo.one!()
{{:installation, installation_xref}, repo_xref}
end
@spec installation_connection(repo_xref, module) ::
{{:installation, Installation.xref()}, repo_xref}
when repo_xref: integer
def installation_connection(repo_xref, repo) do
{installation_xref, repo_xref} =
from(p in Project,
join: i in Installation,
on: i.id == p.installation_id,
where: p.repo_xref == ^repo_xref,
select: {i.installation_xref, p.repo_xref}
)
|> repo.one!()
{{:installation, installation_xref}, repo_xref}
end
@spec changeset(t | Ecto.Changeset.t(), map) :: Ecto.Changeset.t()
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:repo_xref, :name, :auto_reviewer_required_perm, :auto_member_required_perm])
end
@spec changeset_branches(t | Ecto.Changeset.t(), map) :: Ecto.Changeset.t()
def changeset_branches(struct, params \\ %{}) do
struct
|> cast(params, [:staging_branch, :trying_branch])
|> validate_required([:staging_branch, :trying_branch])
end
@spec changeset_reviewer_settings(t | Ecto.Changeset.t(), map) :: Ecto.Changeset.t()
def changeset_reviewer_settings(struct, params \\ %{}) do
struct
|> cast(params, [:auto_reviewer_required_perm])
end
@spec changeset_member_settings(t | Ecto.Changeset.t(), map) :: Ecto.Changeset.t()
def changeset_member_settings(struct, params \\ %{}) do
struct
|> cast(params, [:auto_member_required_perm])
end
# Red flag queries
# These should always return [].
@spec orphans() :: Ecto.Queryable.t()
def orphans do
from(p in Project,
left_join: l in LinkUserProject,
on: p.id == l.project_id,
where: is_nil(l.user_id)
)
end
end
| 28.866667 | 98 | 0.659738 |
79ee7a0eaf8643f4efc62f043ce677a7e182839a | 3,182 | exs | Elixir | test/ex_oneroster/results/results_test.exs | jrissler/ex_oneroster | cec492117bffc14aec91e2448643682ceeb449e9 | [
"Apache-2.0"
] | 3 | 2018-09-06T11:15:07.000Z | 2021-12-27T15:36:51.000Z | test/ex_oneroster/results/results_test.exs | jrissler/ex_oneroster | cec492117bffc14aec91e2448643682ceeb449e9 | [
"Apache-2.0"
] | null | null | null | test/ex_oneroster/results/results_test.exs | jrissler/ex_oneroster | cec492117bffc14aec91e2448643682ceeb449e9 | [
"Apache-2.0"
] | null | null | null | defmodule ExOneroster.ResultsTest do
use ExOneroster.DataCase
alias ExOneroster.Results
describe "results" do
alias ExOneroster.Results.Result
test "list_results/0 returns all results" do
result = base_setup()[:result] |> Repo.preload([:user, :lineitem])
assert Results.list_results() == [result]
end
test "get_result!/1 returns the result with given id" do
result = base_setup()[:result] |> Repo.preload([:user, :lineitem])
assert Results.get_result!(result.id) == result
end
test "create_result/1 with valid data creates a result" do
data = base_setup()
result_params = params_for(:result, user_id: data[:user].id, lineitem_id: data[:line_item].id)
assert {:ok, %Result{} = result} = Results.create_result(result_params)
assert result.comment == result_params.comment
assert result.dateLastModified == result_params.dateLastModified
assert result.lineitem_id == result_params.lineitem_id
assert result.metadata == result_params.metadata
assert Decimal.to_string(result.score) == result_params.score
assert result.scoreDate == Date.from_iso8601!(result_params.scoreDate)
assert result.scoreStatus == result_params.scoreStatus
assert result.sourcedId == result_params.sourcedId
assert result.status == result_params.status
assert result.user_id == result_params.user_id
end
test "create_result/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Results.create_result(params_for(:class, sourcedId: nil))
end
test "update_result/2 with valid data updates the result" do
existing_result = base_setup()[:result]
assert {:ok, result} = Results.update_result(existing_result, %{sourcedId: "Bond..James Bond"})
assert %Result{} = result
assert result.comment == existing_result.comment
assert result.dateLastModified == existing_result.dateLastModified
assert result.lineitem_id == existing_result.lineitem_id
assert result.metadata == existing_result.metadata
assert result.score == existing_result.score
assert result.scoreDate == existing_result.scoreDate
assert result.scoreStatus == existing_result.scoreStatus
assert result.sourcedId == "Bond..James Bond"
assert result.status == existing_result.status
assert result.user_id == existing_result.user_id
end
test "update_result/2 with invalid data returns error changeset" do
result = base_setup()[:result] |> Repo.preload([:user, :lineitem])
assert {:error, %Ecto.Changeset{}} = Results.update_result(result, params_for(:result, dateLastModified: "Not a date"))
assert result == Results.get_result!(result.id)
end
test "delete_result/1 deletes the result" do
result = base_setup()[:result]
assert {:ok, %Result{}} = Results.delete_result(result)
assert_raise Ecto.NoResultsError, fn -> Results.get_result!(result.id) end
end
test "change_result/1 returns a result changeset" do
result = base_setup()[:result]
assert %Ecto.Changeset{} = Results.change_result(result)
end
end
end
| 42.426667 | 125 | 0.712445 |
79ee7f9fa545cf11c79da7eee1a9201a6d54d063 | 95 | ex | Elixir | packages/engine_umbrella/apps/engine/lib/events/driver_accepted_offer.ex | PredictiveMovement/predictivemovement | f5e62d4aed4d2068026aecf3f7f8b6749a0b0563 | [
"MIT"
] | 2 | 2021-12-09T16:06:51.000Z | 2021-12-09T16:06:55.000Z | packages/engine_umbrella/apps/engine/lib/events/driver_accepted_offer.ex | PredictiveMovement/predictivemovement | f5e62d4aed4d2068026aecf3f7f8b6749a0b0563 | [
"MIT"
] | 18 | 2021-09-20T08:04:41.000Z | 2021-11-08T14:58:47.000Z | packages/engine_umbrella/apps/engine/lib/events/driver_accepted_offer.ex | PredictiveMovement/predictivemovement | f5e62d4aed4d2068026aecf3f7f8b6749a0b0563 | [
"MIT"
] | null | null | null | defmodule DriverAcceptedOffer do
@derive Jason.Encoder
defstruct [:vehicle_id, :offer]
end
| 19 | 33 | 0.789474 |
79eeb9712ff7197b7199fc2d8fdf4e09001c6295 | 1,913 | exs | Elixir | config/dev.exs | joakimk/exremit | 6c0a5fb32208b98cc1baac11d6a7bd248a1aa3bc | [
"Unlicense",
"MIT"
] | 27 | 2016-09-21T09:11:25.000Z | 2020-12-16T04:04:50.000Z | config/dev.exs | barsoom/exremit | 6c0a5fb32208b98cc1baac11d6a7bd248a1aa3bc | [
"Unlicense",
"MIT"
] | 2 | 2016-12-02T08:05:13.000Z | 2020-03-27T08:07:59.000Z | config/dev.exs | barsoom/exremit | 6c0a5fb32208b98cc1baac11d6a7bd248a1aa3bc | [
"Unlicense",
"MIT"
] | 4 | 2016-09-25T09:58:17.000Z | 2020-04-27T15:07:36.000Z | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :review, Review.Endpoint,
http: [port: System.get_env("PORT") || 4000],
debug_errors: true,
code_reloader: true,
cache_static_lookup: false,
check_origin: false,
watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin"]]
# Watch static and templates for browser reloading.
config :review, Review.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{web/views/.*(ex)$},
~r{web/templates/.*(eex)$}
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development.
# Do not configure such in production as keeping
# and calculating stacktraces is usually expensive.
config :phoenix, :stacktrace_depth, 20
# Configure your database
if System.get_env("DEVBOX") do
config :review, Review.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "dev",
database: "review_dev",
hostname: "localhost",
port: System.cmd("service_port", ["postgres"]) |> elem(0) |> String.trim(),
pool_size: 10
else
config :review, Review.Repo,
adapter: Ecto.Adapters.Postgres,
username: System.get_env("USER"),
password: "",
database: "review_dev",
hostname: "localhost",
pool_size: 10
end
# Skip db logging in dev, except when doing db imports since
# disabling logging breaks that for some unknown reason.
unless System.get_env("ENABLE_DB_LOGGING") do
config :review, Review.Repo, log: false
end
# no keys needed in dev
config :review,
auth_key: nil,
webhook_secret: nil,
api_secret: nil
| 28.984848 | 79 | 0.704652 |
79eebf2ab367ca0c5ca2649ace15772f9dc04ea9 | 117 | exs | Elixir | config/test.exs | ShockN745/drawcheat | d02fa05c1499e3c91d7dd85342c0b149b203c240 | [
"MIT"
] | null | null | null | config/test.exs | ShockN745/drawcheat | d02fa05c1499e3c91d7dd85342c0b149b203c240 | [
"MIT"
] | null | null | null | config/test.exs | ShockN745/drawcheat | d02fa05c1499e3c91d7dd85342c0b149b203c240 | [
"MIT"
] | null | null | null | use Mix.Config
config :draw_something,
dict_path: "./priv/test.txt",
with_crash: :false,
words_per_crawler: 5
| 16.714286 | 31 | 0.726496 |
79eed0af3111a8388c131bf76ac51657b71761ac | 485 | ex | Elixir | trial_server/lib/trial_server.ex | SteffenBauer/mia_elixir | 569388b1f9ddd09f8e21a4d9275c42a81d469857 | [
"MIT"
] | null | null | null | trial_server/lib/trial_server.ex | SteffenBauer/mia_elixir | 569388b1f9ddd09f8e21a4d9275c42a81d469857 | [
"MIT"
] | null | null | null | trial_server/lib/trial_server.ex | SteffenBauer/mia_elixir | 569388b1f9ddd09f8e21a4d9275c42a81d469857 | [
"MIT"
] | null | null | null | defmodule TrialServer do
use Application
require Logger
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
worker(Registry, [:unique, Registry.Trial]),
worker(Agent, [TrialServer.Store, :init, []]),
supervisor(Task.Supervisor, [[name: TrialServer.TaskSupervisor]]),
worker(TrialServer.UDP, [])
]
opts = [strategy: :one_for_one, name: TrialServer.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 24.25 | 72 | 0.678351 |
79eedbdcb5ef9e64ce13063960b3059cf3673314 | 128 | ex | Elixir | test/support/repo.ex | ibarchenkov/ecto_stream_factory | 4884c82105725a3263f0c3725c03ffb532b4b1a4 | [
"MIT"
] | 5 | 2020-06-22T07:47:20.000Z | 2021-07-15T02:08:30.000Z | test/support/repo.ex | ibarchenkov/ecto_stream_factory | 4884c82105725a3263f0c3725c03ffb532b4b1a4 | [
"MIT"
] | 1 | 2021-04-26T09:57:59.000Z | 2021-04-26T09:57:59.000Z | test/support/repo.ex | ibarchenkov/ecto_stream_factory | 4884c82105725a3263f0c3725c03ffb532b4b1a4 | [
"MIT"
] | null | null | null | defmodule EctoStreamFactory.Repo do
use Ecto.Repo,
otp_app: :ecto_stream_factory,
adapter: Ecto.Adapters.Postgres
end
| 21.333333 | 35 | 0.773438 |
79ef4756afa4955ce708c693e56249191e507dd6 | 153 | exs | Elixir | simple_server/test/simple_server_test.exs | 7Ethan/elixir_notes | e20315b85e490484ead6ed9e2e60b9311d1ff07e | [
"MIT"
] | null | null | null | simple_server/test/simple_server_test.exs | 7Ethan/elixir_notes | e20315b85e490484ead6ed9e2e60b9311d1ff07e | [
"MIT"
] | null | null | null | simple_server/test/simple_server_test.exs | 7Ethan/elixir_notes | e20315b85e490484ead6ed9e2e60b9311d1ff07e | [
"MIT"
] | null | null | null | defmodule SimpleServerTest do
use ExUnit.Case
doctest SimpleServer
test "greets the world" do
assert SimpleServer.hello() == :world
end
end
| 17 | 41 | 0.738562 |
79ef4a8b952b9e9e5967218a9eedf33b79c7a488 | 2,953 | exs | Elixir | apps/storage/test/storage/schema/comment_test.exs | anyex-project/anyex | d04018337bcec621f2e2e8d17773fa2724e3c6e1 | [
"MIT"
] | 12 | 2019-02-21T21:29:08.000Z | 2019-05-14T11:41:10.000Z | apps/storage/test/storage/schema/comment_test.exs | Hentioe/anyex | d04018337bcec621f2e2e8d17773fa2724e3c6e1 | [
"MIT"
] | 18 | 2019-02-05T17:19:33.000Z | 2019-03-13T13:38:08.000Z | apps/storage/test/storage/schema/comment_test.exs | Hentioe/anyex | d04018337bcec621f2e2e8d17773fa2724e3c6e1 | [
"MIT"
] | null | null | null | defmodule Storage.Schema.CommentTest do
use ExUnit.Case, async: false
alias Storage.Repo
alias Storage.Schema.{Comment, Category, Article}
import Storage.Schema.Comment
setup do
on_exit(fn ->
Repo.delete_all(Comment)
Repo.delete_all(Article)
Repo.delete_all(Category)
end)
end
test "add and update comment" do
{status, category} = Category.add(%{path: "c1", name: "类别1"})
assert status == :ok
{status, article} =
Article.add(%{path: "first-article", title: "第一篇文章", category_id: category.id})
assert status == :ok
assert article.category_id == category.id
{status, comment} =
add(%{
author_nickname: "王小明",
author_email: "[email protected]",
content: "评论1",
article_id: article.id
})
assert status == :ok
comment = Map.merge(comment, %{content: "我是修改后的评论1"})
{status, comment} = update(comment)
assert status == :ok
assert comment.content == "我是修改后的评论1"
{status, _sub_comment} =
add(%{
author_nickname: "李小狼",
author_email: "[email protected]",
content: "@王小明 回复你的评论2",
article_id: article.id,
parent_id: comment.id
})
assert status == :ok
end
test "find comment list" do
{status, category} = Category.add(%{path: "c1", name: "类别1"})
assert status == :ok
{status, article} =
Article.add(%{path: "first-article", title: "第一篇文章", category_id: category.id})
assert status == :ok
assert article.category_id == category.id
{status, comment} =
add(%{
author_nickname: "王小明",
author_email: "[email protected]",
content: "评论1",
article_id: article.id
})
assert status == :ok
{status, sub_comment_xiaolang} =
add(%{
author_nickname: "李小狼",
author_email: "[email protected]",
content: "@王小明 回复你的评论2",
owner: true,
article_id: article.id,
parent_id: comment.id
})
assert status == :ok
{status, sub_comment_xiaoming} =
add(%{
author_nickname: "王小明",
author_email: "[email protected]",
content: "@李小狼 感谢你的回复3",
article_id: article.id,
parent_id: comment.id
})
assert status == :ok
{status, list} = find_list(res_status: 1)
assert status == :ok
assert length(list) == 3
list |> Enum.each(fn c -> assert is_list(c.comments) == false end)
{status, list} = find_list(article_id: article.id)
assert status == :ok
assert length(list) == 1
assert Enum.at(Enum.at(list, 0).comments, 0).id == sub_comment_xiaoming.id
{status, _top_comment} = top(sub_comment_xiaolang.id)
assert status == :ok
{status, list} = find_list(article_id: article.id)
assert status == :ok
assert length(list) == 1
assert Enum.at(Enum.at(list, 0).comments, 0).id == sub_comment_xiaolang.id
end
end
| 25.025424 | 85 | 0.606502 |
79efd2b779276c1c2e60429745865f8de345d963 | 3,434 | ex | Elixir | lib/slowpoke_waffle.ex | bytecrow/slowpoke_waffle | efbcb84b11a9ac75a6bb90f2261cae0aa650bcc0 | [
"MIT"
] | 1 | 2021-01-21T09:41:23.000Z | 2021-01-21T09:41:23.000Z | lib/slowpoke_waffle.ex | bytecrow/slowpoke_waffle | efbcb84b11a9ac75a6bb90f2261cae0aa650bcc0 | [
"MIT"
] | null | null | null | lib/slowpoke_waffle.ex | bytecrow/slowpoke_waffle | efbcb84b11a9ac75a6bb90f2261cae0aa650bcc0 | [
"MIT"
] | 1 | 2020-12-27T00:56:59.000Z | 2020-12-27T00:56:59.000Z | defmodule SlowpokeWaffle do
@moduledoc """
Provides a storage module for Waffle.
With this storage method, all images are stored locally first,
then are queued to be uploaded to AWS, and after uploading is
done, the local copy is deleted. Either an uploading is in progress
or is already done, the returned url for the resource is always
valid.
## Examples
To use it, define your configured module:
defmodule MyApp.Storage do
use SlowpokeWaffle
end
and then you can add it to config:
config :waffle, storage: MyApp.Storage
By default it uses `Waffle.Storage.Local` for locally saved files
and `Waffle.Storage.S3` for uploadings, but you can change this
behavior by providing options when using. The example above is
equivalent to the following one:
defmodule MyApp.Storage do
use SlowpokeWaffle,
local_storage: Waffle.Storage.Local,
inet_storage: Waffle.Storage.S3
end
## Configuration
Configuration of storages is pretty much the same as with default waffle
storages:
config :waffle,
storage: MyApp.Storage,
storage_dir: "/pictures_with_cats",
bucket: "<your-bucket-name>",
virtual_host: true
config :ex_aws,
access_key_id: ["<your-key-id>", :instance_role],
secret_access_key: ["<your-secret-key>", :instance_role],
region: "<your-region>"
## Static
You may want to replace your `Plug.Static` with the one that provides
your storage:
plug MyApp.Storage.StaticPlug,
at: "/uploads",
from: {:my_app, "uploads"}
See `SlowpokeWaffle.StaticPlug` for more details.
"""
defmacro __using__(opts) do
local_storage = opts[:local_storage] || Waffle.Storage.Local
inet_storage = opts[:inet_storage] || Waffle.Storage.S3
caller_module = __CALLER__.module
quote do
def __local_storage__, do: unquote(local_storage)
def __inet_storage__, do: unquote(inet_storage)
defmodule LocalStorageDefinition do
@moduledoc false
use Waffle.Definition
def __storage, do: unquote(local_storage)
end
defmodule InetStorageDefinition do
@moduledoc false
use Waffle.Definition
def __storage, do: unquote(inet_storage)
end
defmodule StaticPlug do
@moduledoc """
StaticPlug for #{__MODULE__} storage.
See `SlowpokeWaffle.StaticPlug` for details.
"""
def init(opts), do: opts
def call(conn, static_opts) do
opts = Keyword.put(static_opts, :waffle_definition, unquote(caller_module))
SlowpokeWaffle.StaticPlug.call(conn, opts)
end
end
def put(definition, version, file_and_scope) do
SlowpokeWaffle.Storage.do_put(
{definition, version, file_and_scope},
__local_storage__(),
__inet_storage__()
)
end
def url(definition, version, file_and_scope, opts \\ []) do
SlowpokeWaffle.Storage.do_url(
{definition, version, file_and_scope},
__local_storage__(),
__inet_storage__(),
opts
)
end
def delete(definition, version, file_and_scope) do
SlowpokeWaffle.Storage.do_delete(
{definition, version, file_and_scope},
__local_storage__(),
__inet_storage__()
)
end
end
end
end
| 27.472 | 85 | 0.65463 |
79efd7e2e9a0b572eca2d4db306bc110683d40a6 | 1,616 | ex | Elixir | debian/manpage.1.ex | axia-wish/ctl | e40a18213431124ddce65baa5b23444776fd5c5d | [
"MIT"
] | 25 | 2019-07-17T20:39:04.000Z | 2022-01-29T04:27:14.000Z | debian/manpage.1.ex | axia-wish/ctl | e40a18213431124ddce65baa5b23444776fd5c5d | [
"MIT"
] | 44 | 2019-07-17T19:27:08.000Z | 2021-03-23T23:24:26.000Z | debian/manpage.1.ex | axia-wish/ctl | e40a18213431124ddce65baa5b23444776fd5c5d | [
"MIT"
] | 8 | 2020-02-06T04:14:35.000Z | 2022-02-25T00:52:19.000Z | .\" Hey, EMACS: -*- nroff -*-
.\" (C) Copyright 2019 unknown <[email protected]>,
.\"
.\" First parameter, NAME, should be all caps
.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
.\" other parameters are allowed: see man(7), man(1)
.TH Ctl SECTION "August 20 2019"
.\" Please adjust this date whenever revising the manpage.
.\"
.\" Some roff macros, for reference:
.\" .nh disable hyphenation
.\" .hy enable hyphenation
.\" .ad l left justify
.\" .ad b justify to both left and right margins
.\" .nf disable filling
.\" .fi enable filling
.\" .br insert line break
.\" .sp <n> insert n+1 empty lines
.\" for manpage-specific macros, see man(7)
.SH NAME
ctl \- program to do something
.SH SYNOPSIS
.B ctl
.RI [ options ] " files" ...
.br
.B bar
.RI [ options ] " files" ...
.SH DESCRIPTION
This manual page documents briefly the
.B ctl
and
.B bar
commands.
.PP
.\" TeX users may be more comfortable with the \fB<whatever>\fP and
.\" \fI<whatever>\fP escape sequences to invode bold face and italics,
.\" respectively.
\fBctl\fP is a program that...
.SH OPTIONS
These programs follow the usual GNU command line syntax, with long
options starting with two dashes (`-').
A summary of options is included below.
For a complete description, see the Info files.
.TP
.B \-h, \-\-help
Show summary of options.
.TP
.B \-v, \-\-version
Show version of program.
.SH SEE ALSO
.BR bar (1),
.BR baz (1).
.br
The programs are documented fully by
.IR "The Rise and Fall of a Fooish Bar" ,
available via the Info system.
| 28.350877 | 70 | 0.660272 |
79efdea60657b233c7dd6b2ade84154c02f22cb5 | 1,233 | ex | Elixir | clients/drive_activity/lib/google_api/drive_activity/v2/model/edit.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/drive_activity/lib/google_api/drive_activity/v2/model/edit.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/drive_activity/lib/google_api/drive_activity/v2/model/edit.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DriveActivity.V2.Model.Edit do
@moduledoc """
An empty message indicating an object was edited.
## Attributes
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{}
end
defimpl Poison.Decoder, for: GoogleApi.DriveActivity.V2.Model.Edit do
def decode(value, options) do
GoogleApi.DriveActivity.V2.Model.Edit.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DriveActivity.V2.Model.Edit do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 29.357143 | 74 | 0.755069 |
79f02792956f0251fde3cf1b72e4127c8f886349 | 3,809 | exs | Elixir | test/finch/http2/integration_test.exs | cgerling/finch | 02fc2269a9af853eda18bf19b66028eba1958dbb | [
"MIT"
] | null | null | null | test/finch/http2/integration_test.exs | cgerling/finch | 02fc2269a9af853eda18bf19b66028eba1958dbb | [
"MIT"
] | null | null | null | test/finch/http2/integration_test.exs | cgerling/finch | 02fc2269a9af853eda18bf19b66028eba1958dbb | [
"MIT"
] | null | null | null | defmodule Finch.HTTP2.IntegrationTest do
use ExUnit.Case, async: false
alias Finch.HTTP2Server
alias Finch.TestHelper
@moduletag :capture_log
setup_all do
port = 4002
{:ok, _} = HTTP2Server.start(port)
{:ok, url: "https://localhost:#{port}"}
end
test "sends http2 requests", %{url: url} do
start_supervised!(
{Finch,
name: TestFinch,
pools: %{
default: [
protocol: :http2,
count: 5,
conn_opts: [
transport_opts: [
verify: :verify_none
]
]
]
}}
)
assert {:ok, response} = Finch.build(:get, url) |> Finch.request(TestFinch)
assert response.body == "Hello world!"
end
test "sends the query string", %{url: url} do
start_supervised!(
{Finch,
name: TestFinch,
pools: %{
default: [
protocol: :http2,
count: 5,
conn_opts: [
transport_opts: [
verify: :verify_none
]
]
]
}}
)
query_string = URI.encode_query(test: true, these: "params")
url = url <> "/query?" <> query_string
assert {:ok, response} = Finch.build(:get, url) |> Finch.request(TestFinch)
assert response.body == query_string
end
test "multiplexes requests over a single pool", %{url: url} do
start_supervised!(
{Finch,
name: TestFinch,
pools: %{
default: [
protocol: :http2,
count: 1,
conn_opts: [
transport_opts: [
verify: :verify_none
]
]
]
}}
)
# We create multiple requests here using a single connection. There is a delay
# in the response. But because we allow each request to run simultaneously
# they shouldn't block each other which we check with a rough time estimates
request = Finch.build(:get, url <> "/wait/1000")
results =
1..50
|> Enum.map(fn _ ->
Task.async(fn ->
start = System.monotonic_time()
{:ok, _} = Finch.request(request, TestFinch)
System.monotonic_time() - start
end)
end)
|> Enum.map(&Task.await/1)
for result <- results do
time = System.convert_time_unit(result, :native, :millisecond)
assert time <= 1200
end
end
@tag skip: TestHelper.ssl_version() < [10, 2]
test "writes TLS secrets to SSLKEYLOGFILE file", %{url: url} do
tmp_dir = System.tmp_dir()
log_file = Path.join(tmp_dir, "ssl-key-file.log")
:ok = System.put_env("SSLKEYLOGFILE", log_file)
start_supervised!(
{Finch,
name: TestFinch,
pools: %{
default: [
protocol: :http2,
count: 5,
conn_opts: [
transport_opts: [
verify: :verify_none,
keep_secrets: true,
versions: [:"tlsv1.2", :"tlsv1.3"]
]
]
]
}}
)
try do
assert {:ok, response} = Finch.build(:get, url) |> Finch.request(TestFinch)
assert response.body == "Hello world!"
assert File.stat!(log_file) > 0
after
File.rm!(log_file)
System.delete_env("SSLKEYLOGFILE")
end
end
test "cancel streaming response", %{url: url} do
start_supervised!(
{Finch,
name: TestFinch,
pools: %{
default: [
protocol: :http2,
conn_opts: [
transport_opts: [
verify: :verify_none
]
]
]
}}
)
assert catch_throw(
Finch.stream(Finch.build(:get, url), TestFinch, :ok, fn {:status, _}, :ok ->
throw :error
end)
) == :error
refute_receive _
end
end
| 23.80625 | 82 | 0.525072 |
79f03e52b43e27c1ce81697c934c27ca2532e944 | 4,740 | exs | Elixir | test/acceptances/resources/search_test.exs | DataKrewTech/tirexs | 8238da373f4547d27eea57a10826114e947aa66b | [
"Apache-2.0"
] | 384 | 2015-03-09T05:03:42.000Z | 2022-02-27T00:45:58.000Z | test/acceptances/resources/search_test.exs | DataKrewTech/tirexs | 8238da373f4547d27eea57a10826114e947aa66b | [
"Apache-2.0"
] | 144 | 2015-03-06T11:19:49.000Z | 2021-06-11T11:26:39.000Z | test/acceptances/resources/search_test.exs | DataKrewTech/tirexs | 8238da373f4547d27eea57a10826114e947aa66b | [
"Apache-2.0"
] | 97 | 2015-03-21T13:58:38.000Z | 2022-01-07T14:40:49.000Z | defmodule Acceptances.Resources.SearchTest do
use ExUnit.Case
alias Tirexs.{HTTP, Resources}
setup do
HTTP.delete("bear_test") && :ok
end
test "_explain/4" do
{ :ok, 201, _ } = HTTP.put("/bear_test/my_type/1?refresh=true", [user: "kimchy"])
{ :ok, 200, r } = Resources.bump._explain("bear_test", "my_type", "1", { [q: "user:k*"] })
assert r[:matched]
end
test "_explain/3" do
{ :ok, 201, _ } = HTTP.put("/bear_test/my_type/1?refresh=true", [user: "kimchy"])
search = [query: [ term: [ user: "kimchy" ] ]]
{ :ok, 200, r } = Resources.bump(search)._explain("bear_test", "my_type", "1")
assert r[:matched]
end
test "_explain/2" do
{ :ok, 201, _ } = HTTP.put("/bear_test/my_type/2?refresh=true", [user: "zatvobor"])
{ :ok, 200, r } = Resources.bump._explain("bear_test/my_type/2", { [q: "user:z*"] })
assert r[:matched]
end
test "_explain/1" do
{ :ok, 201, _ } = HTTP.put("/bear_test/my_type/2?refresh=true", [user: "zatvobor"])
search = [query: [ term: [ user: "zatvobor" ] ]]
{ :ok, 200, r } = Resources.bump(search)._explain("bear_test/my_type/2")
assert r[:matched]
end
test "_search_shards/2" do
{ :ok, 200, _ } = HTTP.put("/bear_test")
{ :ok, 200, _ } = Resources.bump._search_shards("bear_test", { [local: true] })
end
test "_validate_query/2" do
{ :ok, 201, _ } = HTTP.put("/bear_test/my_type/1?refresh=true", [user: "kimchy"])
{ :ok, 200, r } = Resources.bump._validate_query("bear_test", { [q: "user1:z*"] })
assert r[:valid]
end
test "_validate_query/1" do
{ :ok, 201, _ } = HTTP.put("/bear_test/my_type/2?refresh=true", [user: "zatvobor"])
search = [query: [ term: [ user: "zatvobor" ] ]]
{ :ok, 200, r } = Resources.bump(search)._validate_query("bear_test")
assert r[:valid]
end
test "_validate_query/0 with request body as macro" do
{ :ok, 201, _ } = HTTP.put("/bear_test/my_type/2?refresh=true", [user: "zatvobor", message: "trying out Elastic Search"])
import Tirexs.Query, only: :macros
query = query do
bool do
must do
term "user", "kimchy"
end
end
end
{ :ok, 200, r } = Resources.bump(query)._validate_query("bear_test")
assert r[:valid]
end
test "_count/2" do
{ :ok, 201, _ } = HTTP.put("/bear_test/my_type/2?refresh=true", [user: "zatvobor"])
search = [query: [ term: [ user: "zatvobor" ] ]]
{ :ok, 200, r } = Resources.bump(search)._count("bear_test", "my_type")
assert r[:count] == 1
end
test "_search/2" do
{ :ok, 201, _ } = HTTP.put("/bear_test/my_type/2?refresh=true", [user: "zatvobor"])
search = [query: [ term: [ user: "zatvobor" ] ]]
{ :ok, 200, r } = Resources.bump(search)._search("bear_test", "my_type")
assert r[:hits][:total] == 1
end
test "_search/2 with macro" do
import Tirexs.Search
{ :ok, 201, _ } = HTTP.put("/bear_test/my_type/2?refresh=true", [user: "zatvobor"])
request = search do
query do
term "user", "zatvobor"
end
end
{ :ok, 200, r } = Resources.bump(request[:search])._search("bear_test", "my_type")
assert r[:hits][:total] == 1
end
test "_search_scroll/0" do
import Tirexs.Bulk
import Tirexs.Search
payload = bulk([index: "bear_test", type: "bear_type"]) do
create [
[ id: 1, title: "bar1", description: "foo bar test" ],
[ id: 2, title: "bar2", description: "foo bar test" ],
[ id: 3, title: "bar3", description: "foo bar test" ],
[ id: 4, title: "bar4", description: "foo bar test" ],
[ id: 5, title: "bar5", description: "foo bar test" ],
[ id: 6, title: "bar6", description: "foo bar test" ],
[ id: 7, title: "bar7", description: "foo bar test" ],
[ id: 8, title: "bar8", description: "foo bar test" ],
[ id: 9, title: "bar9", description: "foo bar test" ],
[ id: 10, title: "bar10", description: "foo bar test" ],
[ id: 11, title: "bar11", description: "foo bar test" ]
]
delete([ [ id: 11 ] ])
index([ [ id: 90, title: "barww" ] ])
end
Tirexs.bump!(payload)._bulk({[refresh: true]})
request = search([index: "bear_test"]) do
query do
string "bar7"
end
end
# { :ok, 200, r } = Query.create_resource(request, [scroll: "5m"])
{ :ok, 200, r } = Tirexs.bump(request[:search])._search("bear_test", {[scroll: "5m"]})
assert r[:_scroll_id]
# { :ok, 200, r } = Tirexs.bump([scroll_id: r[:_scroll_id]])._search_scroll()
{ :ok, 200, r } = Tirexs.bump._search_scroll(r[:_scroll_id])
assert r[:hits][:total] == 1
Tirexs.bump!._search_scroll_all()
end
end
| 34.59854 | 125 | 0.575949 |
79f06f3251917e93d721e64357b80b4af1db3b23 | 609 | exs | Elixir | test/multipster_web/sign_in/link_test.exs | adamniedzielski/multipster | 1abf95d545ab8d6bac3f26e0cfb632e2ba69c7d7 | [
"MIT"
] | 2 | 2018-01-24T08:31:09.000Z | 2019-04-14T11:06:02.000Z | test/multipster_web/sign_in/link_test.exs | adamniedzielski/multipster | 1abf95d545ab8d6bac3f26e0cfb632e2ba69c7d7 | [
"MIT"
] | 5 | 2017-12-20T16:51:06.000Z | 2017-12-28T13:54:08.000Z | test/multipster_web/sign_in/link_test.exs | adamniedzielski/multipster | 1abf95d545ab8d6bac3f26e0cfb632e2ba69c7d7 | [
"MIT"
] | null | null | null | defmodule MultipsterWeb.SignIn.LinkTest do
use Multipster.DataCase, async: true
use Bamboo.Test
describe "send_to_address/1" do
test "send email when user exists" do
Repo.insert!(%Multipster.User{email: "[email protected]"})
MultipsterWeb.SignIn.Link.send_to_address("[email protected]")
assert_delivered_with(
to: [nil: "[email protected]"],
subject: "Sign in to Multipster"
)
end
test "do nothing when user doesn't exist" do
MultipsterWeb.SignIn.Link.send_to_address("[email protected]")
assert_no_emails_delivered()
end
end
end
| 25.375 | 68 | 0.691297 |
79f09512ee1ac14fc119f29172558a2a47457bd7 | 511 | exs | Elixir | spec/inari/jsonapi/resource_spec.exs | NuckChorris/hermes | 401f6669b2811d65877489f64c20d8e2dd800ed7 | [
"MIT"
] | null | null | null | spec/inari/jsonapi/resource_spec.exs | NuckChorris/hermes | 401f6669b2811d65877489f64c20d8e2dd800ed7 | [
"MIT"
] | null | null | null | spec/inari/jsonapi/resource_spec.exs | NuckChorris/hermes | 401f6669b2811d65877489f64c20d8e2dd800ed7 | [
"MIT"
] | null | null | null | defmodule Inari.JSONAPI.ResourceSpec do
use ESpec
alias Inari.JSONAPI.Resource
describe ".parse()" do
context "on a list" do
subject do: Resource.parse([%{id: "foo"}, %{id: "bar"}])
it do: should eq [%Resource{id: "foo"}, %Resource{id: "bar"}]
end
context "on a map" do
subject do: Resource.parse(%{id: "foo"})
it do: should eq %Resource{id: "foo"}
end
context "on nil" do
subject do: Resource.parse(nil)
it do: should be_nil()
end
end
end
| 23.227273 | 67 | 0.598826 |
79f0a884ee53eb20f3125061f7a9ef74495fb9e2 | 4,757 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/model/get_query_results_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/big_query/lib/google_api/big_query/v2/model/get_query_results_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/model/get_query_results_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.BigQuery.V2.Model.GetQueryResultsResponse do
@moduledoc """
## Attributes
* `cacheHit` (*type:* `boolean()`, *default:* `nil`) - Whether the query result was fetched from the query cache.
* `errors` (*type:* `list(GoogleApi.BigQuery.V2.Model.ErrorProto.t)`, *default:* `nil`) - [Output-only] The first errors or warnings encountered during the running of the job. The final message includes the number of errors that caused the process to stop. Errors here do not necessarily mean that the job has completed or was unsuccessful.
* `etag` (*type:* `String.t`, *default:* `nil`) - A hash of this response.
* `jobComplete` (*type:* `boolean()`, *default:* `nil`) - Whether the query has completed or not. If rows or totalRows are present, this will always be true. If this is false, totalRows will not be available.
* `jobReference` (*type:* `GoogleApi.BigQuery.V2.Model.JobReference.t`, *default:* `nil`) - Reference to the BigQuery Job that was created to run the query. This field will be present even if the original request timed out, in which case GetQueryResults can be used to read the results once the query has completed. Since this API only returns the first page of results, subsequent pages can be fetched via the same mechanism (GetQueryResults).
* `kind` (*type:* `String.t`, *default:* `bigquery#getQueryResultsResponse`) - The resource type of the response.
* `numDmlAffectedRows` (*type:* `String.t`, *default:* `nil`) - [Output-only] The number of rows affected by a DML statement. Present only for DML statements INSERT, UPDATE or DELETE.
* `pageToken` (*type:* `String.t`, *default:* `nil`) - A token used for paging results.
* `rows` (*type:* `list(GoogleApi.BigQuery.V2.Model.TableRow.t)`, *default:* `nil`) - An object with as many results as can be contained within the maximum permitted reply size. To get any additional rows, you can call GetQueryResults and specify the jobReference returned above. Present only when the query completes successfully.
* `schema` (*type:* `GoogleApi.BigQuery.V2.Model.TableSchema.t`, *default:* `nil`) - The schema of the results. Present only when the query completes successfully.
* `totalBytesProcessed` (*type:* `String.t`, *default:* `nil`) - The total number of bytes processed for this query.
* `totalRows` (*type:* `String.t`, *default:* `nil`) - The total number of rows in the complete query result set, which can be more than the number of rows in this single page of results. Present only when the query completes successfully.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:cacheHit => boolean(),
:errors => list(GoogleApi.BigQuery.V2.Model.ErrorProto.t()),
:etag => String.t(),
:jobComplete => boolean(),
:jobReference => GoogleApi.BigQuery.V2.Model.JobReference.t(),
:kind => String.t(),
:numDmlAffectedRows => String.t(),
:pageToken => String.t(),
:rows => list(GoogleApi.BigQuery.V2.Model.TableRow.t()),
:schema => GoogleApi.BigQuery.V2.Model.TableSchema.t(),
:totalBytesProcessed => String.t(),
:totalRows => String.t()
}
field(:cacheHit)
field(:errors, as: GoogleApi.BigQuery.V2.Model.ErrorProto, type: :list)
field(:etag)
field(:jobComplete)
field(:jobReference, as: GoogleApi.BigQuery.V2.Model.JobReference)
field(:kind)
field(:numDmlAffectedRows)
field(:pageToken)
field(:rows, as: GoogleApi.BigQuery.V2.Model.TableRow, type: :list)
field(:schema, as: GoogleApi.BigQuery.V2.Model.TableSchema)
field(:totalBytesProcessed)
field(:totalRows)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.GetQueryResultsResponse do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.GetQueryResultsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.GetQueryResultsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 59.4625 | 448 | 0.715787 |
79f0a95c317451b3657330dce8dba8de25fde92e | 2,383 | exs | Elixir | mix.exs | mathieuprog/pathex | 5f896aec67559476cf80405cf299bf0a59b5ba04 | [
"BSD-2-Clause"
] | 51 | 2020-04-23T11:55:36.000Z | 2022-03-28T10:01:39.000Z | mix.exs | mathieuprog/pathex | 5f896aec67559476cf80405cf299bf0a59b5ba04 | [
"BSD-2-Clause"
] | 4 | 2021-03-12T14:44:27.000Z | 2021-12-29T11:00:02.000Z | mix.exs | mathieuprog/pathex | 5f896aec67559476cf80405cf299bf0a59b5ba04 | [
"BSD-2-Clause"
] | 3 | 2020-10-16T18:05:16.000Z | 2021-06-03T21:54:26.000Z | defmodule Pathex.MixProject do
use Mix.Project
@version "1.2.0"
def project do
[
app: :pathex,
version: @version,
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
description: description(),
package: package(),
deps: deps(),
name: "Pathex",
source_url: "https://github.com/hissssst/pathex",
docs: docs()
]
end
def application, do: []
def description do
"Code generation library for functional lenses"
end
defp package() do
[
description: description(),
licenses: ["BSD-2-Clause"],
files: [
"lib",
"mix.exs",
"README.md",
".formatter.exs"
],
maintainers: [
"Georgy Sychev"
],
links: %{GitHub: "https://github.com/hissssst/pathex"}
]
end
defp deps() do
[
{:ex_doc, "~> 0.23.0", only: :dev, runtime: false},
{:dialyxir, "~> 1.0.0", only: :dev, runtime: false},
{:credo, "~> 1.5", only: :dev, runtime: false}
]
end
# Docs section
defp docs() do
[
source_ref: "v#{@version}",
main: "readme",
extra_section: "GUIDES",
groups_for_modules: groups_for_modules(),
extras: ["README.md" | Path.wildcard("guides/*")],
groups_for_extras: groups_for_extras()
]
end
defp groups_for_extras do
[
Tutorials: ~r/guides\/.*/
]
end
defp groups_for_modules() do
[
"Public": [
Pathex,
Pathex.Lenses
],
"Code generation": [
Pathex.Builder,
Pathex.Builder.Code
],
"Operation modes": [
Pathex.Combination,
Pathex.Operations,
Pathex.QuotedParser,
Pathex.Parser
],
"Viewers generation": [
Pathex.Builder.Viewer,
Pathex.Builder.MatchableViewer,
Pathex.Builder.SimpleViewer
],
"Updaters generation": [
Pathex.Builder.Setter,
Pathex.Builder.ForceUpdater,
Pathex.Builder.SimpleUpdater
],
"Compostitions generation": [
Pathex.Builder.Composition,
Pathex.Builder.Composition.And,
Pathex.Builder.Composition.Or,
],
"Utilities": [
Pathex.Common
]
]
end
end
| 21.862385 | 68 | 0.518254 |
79f0b9a57e1e2288712aca9026c44ec31b74f7b8 | 287 | ex | Elixir | lib/lilictocat/github/github_behaviour.ex | volcov/lilictocat | 5e9073933ad1e97748d1ff915ea76d82b37ce057 | [
"MIT"
] | 7 | 2020-08-14T14:38:33.000Z | 2021-08-31T03:02:02.000Z | lib/lilictocat/github/github_behaviour.ex | volcov/lilictocat | 5e9073933ad1e97748d1ff915ea76d82b37ce057 | [
"MIT"
] | 3 | 2020-08-13T19:05:49.000Z | 2020-09-16T04:39:44.000Z | lib/lilictocat/github/github_behaviour.ex | volcov/lilictocat | 5e9073933ad1e97748d1ff915ea76d82b37ce057 | [
"MIT"
] | 1 | 2020-08-14T14:38:20.000Z | 2020-08-14T14:38:20.000Z | defmodule Lilictocat.GithubBehaviour do
@moduledoc false
@callback get_organizations() :: list()
@callback get_organization_repos(String.t()) :: list()
@callback get_open_pulls(String.t(), String.t()) :: list()
@callback get_reviews_of_pr(String.t(), integer()) :: list()
end
| 31.888889 | 62 | 0.71777 |
79f0b9b0df73ecbdf64c9ea65d4f2a1da5b2c430 | 85 | ex | Elixir | lib/archery_competition_web/views/layout_view.ex | barnaba/archery-competition | cd5d302431429218aeb72c71fa96981667d8d95c | [
"MIT"
] | null | null | null | lib/archery_competition_web/views/layout_view.ex | barnaba/archery-competition | cd5d302431429218aeb72c71fa96981667d8d95c | [
"MIT"
] | 6 | 2018-07-11T21:01:51.000Z | 2018-07-11T21:06:07.000Z | lib/archery_competition_web/views/layout_view.ex | barnaba/archery-competition | cd5d302431429218aeb72c71fa96981667d8d95c | [
"MIT"
] | null | null | null | defmodule ArcheryCompetitionWeb.LayoutView do
use ArcheryCompetitionWeb, :view
end
| 21.25 | 45 | 0.858824 |
79f0c7fccebcfb0ede74e55453871b096495b0d5 | 214 | ex | Elixir | elixir-guide/getting-started/chapter8/module_and_function_with_guard.ex | Cate-Lukner/cate-lukner-internship | 43e8b467287ea3a7955e23f18180cb4f849e6620 | [
"MIT"
] | null | null | null | elixir-guide/getting-started/chapter8/module_and_function_with_guard.ex | Cate-Lukner/cate-lukner-internship | 43e8b467287ea3a7955e23f18180cb4f849e6620 | [
"MIT"
] | 8 | 2020-05-18T14:43:21.000Z | 2020-06-03T16:07:37.000Z | elixir-guide/getting-started/chapter8/module_and_function_with_guard.ex | lowlandresearch/cate-lukner-internship | 71fff3bcd2d44905357c99dbff1b1f572f5bcc6f | [
"MIT"
] | 1 | 2020-05-18T14:44:13.000Z | 2020-05-18T14:44:13.000Z | # This file is a module that contains a guard and uses a slightly different syntax
defmodule Boring_Math do
def one?(1), do: :"Yes, that is a one"
def one?(x) when is_integer(x), do: :"No that is not a one"
end
| 30.571429 | 82 | 0.71028 |
79f0cee257d089031a020d83fd9f7ada5e8674a1 | 519 | ex | Elixir | lib/sanbase_web/graphql/resolvers/table_configuration/user_table_configuration_resolver.ex | santiment/sanbase2 | 9ef6e2dd1e377744a6d2bba570ea6bd477a1db31 | [
"MIT"
] | 81 | 2017-11-20T01:20:22.000Z | 2022-03-05T12:04:25.000Z | lib/sanbase_web/graphql/resolvers/table_configuration/user_table_configuration_resolver.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 359 | 2017-10-15T14:40:53.000Z | 2022-01-25T13:34:20.000Z | lib/sanbase_web/graphql/resolvers/table_configuration/user_table_configuration_resolver.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 16 | 2017-11-19T13:57:40.000Z | 2022-02-07T08:13:02.000Z | defmodule SanbaseWeb.Graphql.Resolvers.UserTableConfigurationResolver do
require Logger
alias Sanbase.Accounts.User
def chart_configurations(%User{} = user, _args, _context) do
# Querying user_id is same as the queried user_id so it can access private data
{:ok, Sanbase.TableConfiguration.user_table_configurations(user.id, user.id)}
end
def public_chart_configurations(%User{} = user, _args, _resolution) do
{:ok, Sanbase.TableConfiguration.user_table_configurations(user.id, nil)}
end
end
| 34.6 | 83 | 0.77842 |
79f0edefbd180bb91d118f9c375155ec048e6b7d | 473 | ex | Elixir | apps/concierge_site/lib/views/font_awesome_helpers.ex | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | null | null | null | apps/concierge_site/lib/views/font_awesome_helpers.ex | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | 21 | 2021-03-12T17:05:30.000Z | 2022-02-16T21:48:35.000Z | apps/concierge_site/lib/views/font_awesome_helpers.ex | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | 1 | 2021-12-09T15:09:53.000Z | 2021-12-09T15:09:53.000Z | defmodule ConciergeSite.FontAwesomeHelpers do
@moduledoc """
Conveniences for using Font Awesome
"""
import Phoenix.HTML.Tag, only: [content_tag: 3]
@doc "HTML for a FontAwesome icon, with optional attributes"
def fa(name, attributes \\ []) when is_list(attributes) do
content_tag(:i, [], [
{:"aria-hidden", "true"},
{:class, "fa fa-#{name} " <> Keyword.get(attributes, :class, "")}
| Keyword.delete(attributes, :class)
])
end
end
| 27.823529 | 71 | 0.646934 |
79f0f195ce32e393902b11ea612f38f85bb76e5e | 5,380 | ex | Elixir | lib/exw3/abi.ex | baxterjfinch/exw3 | 0887a2c92410704a7c3ffaa19af77d1eeef26b99 | [
"Apache-2.0"
] | null | null | null | lib/exw3/abi.ex | baxterjfinch/exw3 | 0887a2c92410704a7c3ffaa19af77d1eeef26b99 | [
"Apache-2.0"
] | 11 | 2021-05-01T05:54:50.000Z | 2022-03-01T12:01:49.000Z | lib/exw3/abi.ex | baxterjfinch/exw3 | 0887a2c92410704a7c3ffaa19af77d1eeef26b99 | [
"Apache-2.0"
] | 1 | 2021-11-29T19:31:32.000Z | 2021-11-29T19:31:32.000Z | defmodule ExW3.Abi do
@doc "Decodes event based on given data and provided signature"
@spec decode_event(binary(), binary()) :: any()
def decode_event(data, signature) do
formatted_data =
data
|> String.slice(2..-1)
|> Base.decode16!(case: :lower)
fs = ABI.FunctionSelector.decode(signature)
ABI.TypeDecoder.decode(formatted_data, fs)
|> Enum.zip(fs.types)
|> Enum.map(fn
{value, :address} -> "0x" <> Base.encode16(value, case: :lower)
{value, {:bytes, 32}} -> "0x" <> Base.encode16(value, case: :lower)
{value, _} -> value
end)
end
@doc "Loads the abi at the file path and reformats it to a map"
@spec load_abi_path(binary()) :: list() | {:error, atom()}
def load_abi_path(file_path) do
with {:ok, abi} <- File.read(file_path) do
reformat_abi(Jason.decode!(abi))
end
end
@doc "Loads the abi at the file path and reformats it to a map"
@spec load_abi(binary()) :: list() | {:error, atom()}
def load_abi(file_path) do
with {:ok, cwd} <- File.cwd(),
{:ok, abi} <- File.read(Path.join([cwd, file_path])) do
reformat_abi(Jason.decode!(abi))
end
end
@doc "Loads the bin ar the file path"
@spec load_bin(binary()) :: binary()
def load_bin(file_path) do
with {:ok, cwd} <- File.cwd(),
{:ok, bin} <- File.read(Path.join([cwd, file_path])) do
bin
end
end
@doc "Decodes data based on given type signature"
@spec decode_data(binary(), binary()) :: any()
def decode_data("(address)" = types_signature, data) do
{:ok, trim_data} = String.slice(data, 2..String.length(data)) |> Base.decode16(case: :lower)
{data} = ABI.decode(types_signature, trim_data) |> List.first()
data |> ExW3.Utils.to_address
end
def decode_data(types_signature, data) do
{:ok, trim_data} = String.slice(data, 2..String.length(data)) |> Base.decode16(case: :lower)
{data} = ABI.decode(types_signature, trim_data) |> List.first()
data
end
@doc "Decodes output based on specified functions return signature"
@spec decode_output(map(), binary(), binary()) :: list()
def decode_output(abi, name, output) do
{:ok, trim_output} =
String.slice(output, 2..String.length(output)) |> Base.decode16(case: :lower)
output_types = Enum.map(abi[name]["outputs"], fn x -> x["type"] end)
types_signature = Enum.join(output_types, ",")
output_signature = "#{name}(#{types_signature})"
ABI.decode(output_signature, trim_output)
end
@doc "Returns the type signature of a given function"
@spec types_signature(map(), binary()) :: binary()
def types_signature(abi, name) do
input_types = Enum.map(abi[name]["inputs"], fn x -> x["type"] end)
types_signature = Enum.join(input_types, ",")
types_signature
end
@doc "Returns the 4 character method id based on the hash of the method signature"
@spec method_signature(map(), binary()) :: binary()
def method_signature(abi, name) do
if abi[name] do
{:ok, input_signature} = ExKeccak.hash_256("#{name}(#{types_signature(abi, name)})")
# Take first four bytes
<<init::binary-size(4), _rest::binary>> = input_signature
init
else
raise "#{name} method not found in the given abi"
end
end
@doc "Encodes data into Ethereum hex string based on types signature"
@spec encode_data(binary(), list()) :: binary()
def encode_data(types_signature, data) do
ABI.TypeEncoder.encode_raw(
[List.to_tuple(data)],
ABI.FunctionSelector.decode_raw("(#{types_signature})")
)
end
@doc "Encodes list of options and returns them as a map"
@spec encode_options(map(), list()) :: map()
def encode_options(options, keys) do
keys
|> Enum.filter(fn option ->
Map.has_key?(options, option)
end)
|> Enum.map(fn option ->
{option, encode_option(options[option])}
end)
|> Enum.into(%{})
end
@doc "Encodes options into Ethereum JSON RPC hex string"
@spec encode_option(integer()) :: binary()
def encode_option(0), do: "0x0"
def encode_option(nil), do: nil
def encode_option(value) do
"0x" <>
(value
|> :binary.encode_unsigned()
|> Base.encode16(case: :lower)
|> String.trim_leading("0"))
end
@doc "Encodes data and appends it to the encoded method id"
@spec encode_method_call(map(), binary(), list()) :: binary()
def encode_method_call(abi, name, input) do
encoded_method_call =
method_signature(abi, name) <> encode_data(types_signature(abi, name), input)
encoded_method_call |> Base.encode16(case: :lower)
end
@doc "Encodes input from a method call based on function signature"
@spec encode_input(map(), binary(), list()) :: binary()
def encode_input(abi, name, input) do
if abi[name]["inputs"] do
input_types = Enum.map(abi[name]["inputs"], fn x -> x["type"] end)
types_signature = Enum.join(input_types, ",")
ABI.encode("#{name}(#{types_signature})", input) |> Base.encode16(case: :lower)
else
raise "#{name} method not found with the given abi"
end
end
defp reformat_abi(abi) do
abi
|> Enum.map(&map_abi/1)
|> Map.new()
end
defp map_abi(x) do
case {x["name"], x["type"]} do
{nil, "constructor"} -> {:constructor, x}
{nil, "fallback"} -> {:fallback, x}
{name, _} -> {name, x}
end
end
end
| 32.606061 | 96 | 0.640149 |
79f13540237a4cf0ad5b27eef9237a309172d6df | 1,291 | exs | Elixir | mix.exs | Bluetab/Zippex | 03f2faea934c1b1b440ab9d564d7cda14a56756f | [
"MIT"
] | null | null | null | mix.exs | Bluetab/Zippex | 03f2faea934c1b1b440ab9d564d7cda14a56756f | [
"MIT"
] | null | null | null | mix.exs | Bluetab/Zippex | 03f2faea934c1b1b440ab9d564d7cda14a56756f | [
"MIT"
] | null | null | null | defmodule Zippex.MixProject do
use Mix.Project
def project do
[
app: :zippex,
version: "1.0.0",
elixir: "~> 1.7",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
deps: deps(),
# Hex
description: "A Generic Zipper implementation for Elixir",
package: [
maintainers: ["Tom Crossland"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/Bluetab/Zippex"}
],
# Docs
name: "Zippex",
organization: "Bluetab",
source_url: "https://github.com/Bluetab/Zippex",
homepage_url: "https://github.com/Bluetab/Zippex",
docs: [
logo: "zipper.png",
main: "Zippex",
extras: ["README.md"]
]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:credo, "~> 1.0.0", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.0.0-rc.7", only: [:dev], runtime: false},
{:ex_doc, "~> 0.21", only: :dev, runtime: false}
]
end
end
| 24.358491 | 65 | 0.557707 |
79f155842fbb54be268b074f4a07ead2f2b353a7 | 5,732 | ex | Elixir | lib/plenario_web/controllers/data_set_controller.ex | vforgione/plenario2 | 001526e5c60a1d32794a18f3fd65ead6cade1a29 | [
"Apache-2.0"
] | 13 | 2017-12-11T13:59:42.000Z | 2020-11-16T21:52:31.000Z | lib/plenario_web/controllers/data_set_controller.ex | vforgione/plenario2 | 001526e5c60a1d32794a18f3fd65ead6cade1a29 | [
"Apache-2.0"
] | 310 | 2017-11-13T22:52:26.000Z | 2018-11-19T17:49:30.000Z | lib/plenario_web/controllers/data_set_controller.ex | vforgione/plenario2 | 001526e5c60a1d32794a18f3fd65ead6cade1a29 | [
"Apache-2.0"
] | 3 | 2017-12-05T00:36:12.000Z | 2020-03-10T15:15:29.000Z | defmodule PlenarioWeb.DataSetController do
use PlenarioWeb, :controller
require Logger
alias Plenario.{
Auth.Guardian,
DataSet,
DataSetActions,
Etl,
FieldActions,
VirtualDateActions,
VirtualPointActions
}
plug :authorize_resource, model: DataSet
# CRUD
def new(conn, %{"name" => name, "socrata" => soc?}) do
soc? = if soc? == "true", do: true, else: false
changeset = DataSet.changeset(%DataSet{}, %{
name: name,
socrata?: soc?,
state: "new",
user_id: Plenario.Auth.Guardian.Plug.current_resource(conn).id
})
create_action = Routes.data_set_path(conn, :create)
backout_action = Routes.me_path(conn, :show)
render conn, "new.html",
changeset: changeset,
socrata?: soc?,
fully_editable?: true,
create_action: create_action,
backout_action: backout_action
end
def new(conn, params) when params == %{}, do: render conn, "init.html", action: Routes.data_set_path(conn, :new)
def create(conn, %{"data_set" => form}) do
DataSetActions.create(form)
|> do_create(conn)
end
defp do_create({:ok, data_set}, conn) do
try do
Logger.info("attempting to create fields for #{data_set.name}")
{:ok, _} = FieldActions.create_for_data_set(data_set)
rescue
e in Exception ->
Logger.error(e.message)
end
conn
|> put_flash(:success, "Created #{data_set.name}")
|> redirect(to: Routes.data_set_path(conn, :show, data_set))
end
defp do_create({:error, changeset}, conn) do
socrata? = Ecto.Changeset.get_field(changeset, :socrata?)
create_action = Routes.data_set_path(conn, :create)
backout_action = Routes.me_path(conn, :show)
Logger.debug("#{inspect(changeset)}")
conn
|> put_status(:bad_request)
|> put_error_flashes(changeset)
|> render("new.html",
changeset: changeset,
socrata?: socrata?,
fully_editable?: true,
create_action: create_action,
backout_action: backout_action
)
end
def show(conn, %{"id" => id}) do
user = Guardian.Plug.current_resource(conn)
data_set = DataSetActions.get!(id, with_user: true, with_fields: true)
user_is_owner? = user.is_admin? or data_set.user_id == user.id
ok_to_import? = not Enum.member?(["new", "awaiting_approval", "erred"], data_set.state)
submittable? = data_set.state == "new"
render conn, "show.html",
data_set: data_set,
user_is_owner?: user_is_owner?,
ok_to_import?: ok_to_import?,
submittable?: submittable?,
virtual_dates: VirtualDateActions.list(for_data_set: data_set, with_fields: true),
virtual_points: VirtualPointActions.list(for_data_set: data_set, with_fields: true)
end
def edit(conn, %{"id" => id}) do
data_set = DataSetActions.get!(id)
changeset = DataSet.changeset(data_set, %{})
fully_editable? = data_set.state == "new"
update_action = Routes.data_set_path(conn, :update, data_set)
backout_action = Routes.data_set_path(conn, :show, data_set)
render conn, "edit.html",
data_set: data_set,
changeset: changeset,
fully_editable?: fully_editable?,
update_action: update_action,
backout_action: backout_action
end
def update(conn, %{"id" => id, "data_set" => form}) do
data_set = DataSetActions.get!(id)
DataSetActions.update(data_set, form)
|> do_update(conn, data_set)
end
defp do_update({:ok, data_set}, conn, _) do
conn
|> put_flash(:success, "Updated #{data_set.name}")
|> redirect(to: Routes.data_set_path(conn, :show, data_set))
end
defp do_update({:error, changeset}, conn, data_set) do
update_action = Routes.data_set_path(conn, :update, data_set)
backout_action = Routes.data_set_path(conn, :show, data_set)
fully_editable? = data_set.state == "new"
conn
|> put_status(:bad_request)
|> put_error_flashes(changeset)
|> render("edit.html",
data_set: data_set,
changeset: changeset,
fully_editable?: fully_editable?,
update_action: update_action,
backout_action: backout_action
)
end
def delete(conn, %{"id" => id}) do
data_set = DataSetActions.get!(id)
{:ok, _} = DataSetActions.delete(data_set)
conn
|> put_flash(:info, "Deleted #{data_set.name}")
|> redirect(to: Routes.me_path(conn, :show))
end
# Additional functionality
def reload_fields(conn, %{"id" => id}) do
data_set = DataSetActions.get!(id)
conn =
case data_set.state do
"new" ->
FieldActions.list(for_data_set: data_set)
|> Enum.each(&FieldActions.delete/1)
FieldActions.create_for_data_set(data_set)
put_flash(conn, :info, "Fields have been reloaded")
_ ->
put_flash(conn, :error, "Cannot reload fields when no longer new")
end
redirect(conn, to: Routes.data_set_path(conn, :show, data_set))
end
def submit_for_approval(conn, %{"id" => id}) do
data_set = DataSetActions.get!(id)
conn =
case data_set.state do
"new" ->
{:ok, _} = DataSetActions.update(data_set, state: "awaiting_approval")
put_flash(conn, :success, "#{data_set.name} has been submitted for approval")
_ ->
put_flash(conn, :error, "Cannot submit non-new data sets for approval")
end
redirect(conn, to: Routes.data_set_path(conn, :show, data_set))
end
def ingest_now(conn, %{"id" => id}) do
data_set = DataSetActions.get!(id)
:ok = Etl.import_data_set_on_demand(data_set)
conn
|> put_flash(:info, "#{data_set.name} has been added to the ingest queue")
|> redirect(to: Routes.data_set_path(conn, :show, data_set))
end
end
| 28.66 | 114 | 0.654745 |
79f15d269e3c299eeccc1d30cda8060f73ea8873 | 972 | exs | Elixir | src/test/mock_server/config/config.exs | kuon/java-phoenix-channel | 955bca5010cf625bfdcdc785676ed4f2ed98c581 | [
"Apache-2.0",
"MIT"
] | 18 | 2020-02-20T00:36:57.000Z | 2022-01-18T01:33:25.000Z | src/test/mock_server/config/config.exs | kuon/java-phoenix-channel | 955bca5010cf625bfdcdc785676ed4f2ed98c581 | [
"Apache-2.0",
"MIT"
] | 4 | 2020-04-03T21:06:53.000Z | 2020-05-16T03:49:03.000Z | src/test/mock_server/config/config.exs | kuon/java-phoenix-channel | 955bca5010cf625bfdcdc785676ed4f2ed98c581 | [
"Apache-2.0",
"MIT"
] | 2 | 2020-05-15T09:26:24.000Z | 2021-02-19T10:54:52.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.
# General application configuration
use Mix.Config
# Configures the endpoint
config :mock_server, MockServerWeb.Endpoint,
url: [host: "localhost"],
secret_key_base:
"iCmRSF4xTTt+gJkmbgUFV0c2LPf1/F48AQI7TSkmR+eVy8GOY8tQJk3ErHB7JDYt",
render_errors: [view: MockServerWeb.ErrorView, accepts: ~w(json)],
pubsub: [name: MockServer.PubSub, adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"
| 33.517241 | 71 | 0.770576 |
79f17ee1e7041b49eb6e0c7621488de341304e81 | 3,571 | ex | Elixir | lib/auth.ex | workpathco/firebase-admin-ex | 83305a4bfcc5b1cc7b692eee9d4c93fa080759f2 | [
"MIT"
] | 38 | 2018-05-29T14:22:03.000Z | 2021-11-16T11:33:05.000Z | lib/auth.ex | workpathco/firebase-admin-ex | 83305a4bfcc5b1cc7b692eee9d4c93fa080759f2 | [
"MIT"
] | 8 | 2018-12-05T02:41:12.000Z | 2020-06-24T18:41:21.000Z | lib/auth.ex | workpathco/firebase-admin-ex | 83305a4bfcc5b1cc7b692eee9d4c93fa080759f2 | [
"MIT"
] | 22 | 2018-11-21T03:10:07.000Z | 2022-02-18T01:45:14.000Z | defmodule FirebaseAdminEx.Auth do
alias FirebaseAdminEx.{Request, Response, Errors}
alias FirebaseAdminEx.Auth.ActionCodeSettings
@auth_endpoint "https://www.googleapis.com/identitytoolkit/v3/relyingparty/"
@auth_endpoint_account "https://identitytoolkit.googleapis.com/v1/projects/"
@auth_scope "https://www.googleapis.com/auth/cloud-platform"
@doc """
Get a user's info by UID
"""
@spec get_user(String.t(), String.t() | nil) :: tuple()
def get_user(uid, client_email \\ nil), do: get_user(:localId, uid, client_email)
@doc """
Get a user's info by phone number
"""
@spec get_user_by_phone_number(String.t(), String.t() | nil) :: tuple()
def get_user_by_phone_number(phone_number, client_email \\ nil),
do: get_user(:phone_number, phone_number, client_email)
@doc """
Get a user's info by email
"""
@spec get_user_by_email(String.t(), String.t() | nil) :: tuple()
def get_user_by_email(email, client_email \\ nil),
do: get_user(:email, email, client_email)
defp get_user(key, value, client_email),
do: do_request("getAccountInfo", %{key => value}, client_email)
@doc """
Delete an existing user by UID
"""
@spec delete_user(String.t(), String.t() | nil) :: tuple()
def delete_user(uid, client_email \\ nil),
do: do_request("deleteAccount", %{localId: uid}, client_email)
# TODO: Add other commands:
# list_users
# create_user
# update_user
# import_users
@doc """
Create an email/password user
"""
@spec create_email_password_user(map, String.t() | nil) :: tuple()
def create_email_password_user(
%{"email" => email, "password" => password},
client_email \\ nil
),
do:
do_request(
"signupNewUser",
%{:email => email, :password => password, :returnSecureToken => true},
client_email
)
@doc """
Generates the email action link for sign-in flows, using the action code settings provided
"""
@spec generate_sign_in_with_email_link(ActionCodeSettings.t(), String.t(), String.t()) :: tuple()
def generate_sign_in_with_email_link(action_code_settings, client_email, project_id) do
with {:ok, action_code_settings} <- ActionCodeSettings.validate(action_code_settings) do
do_request("accounts:sendOobCode", action_code_settings, client_email, project_id)
end
end
defp do_request(url_suffix, payload, client_email, project_id) do
with {:ok, response} <-
Request.request(
:post,
"#{@auth_endpoint_account}#{project_id}/#{url_suffix}",
payload,
auth_header(client_email)
),
{:ok, body} <- Response.parse(response) do
{:ok, body}
else
{:error, error} -> raise Errors.ApiError, Kernel.inspect(error)
end
end
defp do_request(url_suffix, payload, client_email) do
with {:ok, response} <-
Request.request(
:post,
@auth_endpoint <> url_suffix,
payload,
auth_header(client_email)
),
{:ok, body} <- Response.parse(response) do
{:ok, body}
else
{:error, error} -> raise Errors.ApiError, Kernel.inspect(error)
end
end
defp auth_header(nil) do
{:ok, token} = Goth.Token.for_scope(@auth_scope)
do_auth_header(token.token)
end
defp auth_header(client_email) do
{:ok, token} = Goth.Token.for_scope({client_email, @auth_scope})
do_auth_header(token.token)
end
defp do_auth_header(token) do
%{"Authorization" => "Bearer #{token}"}
end
end
| 30.784483 | 99 | 0.652758 |
79f198cb4ea9f2b151f046c0c78212217376e630 | 729 | ex | Elixir | apps/gobstopper_service/lib/gobstopper.service/auth/identity/model.ex | ZURASTA/gobstopper | f8d231c4459af6fa44273c3ef80857348410c70b | [
"BSD-2-Clause"
] | 3 | 2017-05-02T12:53:07.000Z | 2017-05-28T11:53:15.000Z | apps/gobstopper_service/lib/gobstopper.service/auth/identity/model.ex | ScrimpyCat/gobstopper | 41a64991d8fb809065a52d09f8f4c6c707ae3403 | [
"BSD-2-Clause"
] | 12 | 2017-07-24T12:29:51.000Z | 2018-04-05T03:58:10.000Z | apps/gobstopper_service/lib/gobstopper.service/auth/identity/model.ex | ZURASTA/gobstopper | f8d231c4459af6fa44273c3ef80857348410c70b | [
"BSD-2-Clause"
] | 4 | 2017-07-24T12:19:23.000Z | 2019-02-19T06:34:46.000Z | defmodule Gobstopper.Service.Auth.Identity.Model do
use Ecto.Schema
import Ecto
import Ecto.Changeset
@moduledoc """
A model representing the different identities.
##Fields
###:id
Is the unique reference to the identity entry. Is an `integer`.
###:identity
Is the unique ID to externally reference the identity entry. Is an `uuid`.
"""
schema "identities" do
field :identity, Ecto.UUID, read_after_writes: true
timestamps()
end
@doc """
Builds a changeset for the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [])
|> unique_constraint(:identity)
end
end
| 23.516129 | 80 | 0.610425 |
79f1fc3086725abdeee54e06f0d6e467c456de25 | 3,309 | exs | Elixir | test/redex/command/lpush_test.exs | esmaeilpour/redex | c2c6e29e3dec0df265fdcd9f24cd2471c8615ee7 | [
"Apache-2.0"
] | 173 | 2019-03-15T15:05:11.000Z | 2022-01-10T08:21:48.000Z | test/redex/command/lpush_test.exs | esmaeilpour/redex | c2c6e29e3dec0df265fdcd9f24cd2471c8615ee7 | [
"Apache-2.0"
] | null | null | null | test/redex/command/lpush_test.exs | esmaeilpour/redex | c2c6e29e3dec0df265fdcd9f24cd2471c8615ee7 | [
"Apache-2.0"
] | 9 | 2019-07-28T01:20:43.000Z | 2021-08-18T03:41:44.000Z | defmodule Redex.Command.LpushTest do
use ExUnit.Case, async: true
use ExUnitProperties
import Mox
import Redex.DataGenerators
import Redex.Command.LPUSH
setup :verify_on_exit!
property "LPUSH a non existing or expired key" do
check all state = %{db: db} <- state(),
nodes <- nodes(state),
key <- binary(),
args <- list_of(binary(), min_length: 1),
list = Enum.reverse(args),
len = length(args),
no_record <- no_or_expired_record(state, key: key) do
MnesiaMock
|> expect(:system_info, fn :running_db_nodes -> nodes end)
|> expect(:sync_transaction, fn f -> {:atomic, f.()} end)
|> expect(:read, fn :redex, {^db, ^key}, :write -> no_record end)
|> expect(:write, fn :redex, {:redex, {^db, ^key}, ^list, nil}, :write -> :ok end)
ProtocolMock
|> expect(:reply, fn ^len, ^state -> state end)
assert state == exec([key | args], state)
end
end
property "LPUSH an existing key" do
check all state <- state(),
nodes <- nodes(state),
record = {:redex, {db, key}, value, expiry} <- record(state, type: :list),
args <- list_of(binary(), min_length: 1),
list = Enum.reverse(args) ++ value,
len = length(list) do
MnesiaMock
|> expect(:system_info, fn :running_db_nodes -> nodes end)
|> expect(:sync_transaction, fn f -> {:atomic, f.()} end)
|> expect(:read, fn :redex, {^db, ^key}, :write -> [record] end)
|> expect(:write, fn :redex, {:redex, {^db, ^key}, ^list, ^expiry}, :write -> :ok end)
ProtocolMock
|> expect(:reply, fn ^len, ^state -> state end)
assert state == exec([key | args], state)
end
end
property "LPUSH a key with a wrong kind of value" do
error = {:error, "WRONGTYPE Operation against a key holding the wrong kind of value"}
check all state <- state(),
nodes <- nodes(state),
args <- list_of(binary(), min_length: 1),
record = {:redex, {db, key}, _, _} <- record(state) do
MnesiaMock
|> expect(:system_info, fn :running_db_nodes -> nodes end)
|> expect(:sync_transaction, fn f -> {:atomic, f.()} end)
|> expect(:read, fn :redex, {^db, ^key}, :write -> [record] end)
ProtocolMock
|> expect(:reply, fn ^error, ^state -> state end)
assert state == exec([key | args], state)
end
end
property "LPUSH in readonly mode" do
error = {:error, "READONLY You can't write against a read only replica."}
check all state <- state(),
nodes <- nodes(state, readonly: true),
args <- list_of(binary(), min_length: 2) do
MnesiaMock
|> expect(:system_info, fn :running_db_nodes -> nodes end)
ProtocolMock
|> expect(:reply, fn ^error, ^state -> state end)
assert state == exec(args, state)
end
end
property "LPUSH with wrong number of arguments" do
error = {:error, "ERR wrong number of arguments for 'LPUSH' command"}
check all state <- state(),
args <- list_of(binary(), max_length: 1) do
ProtocolMock
|> expect(:reply, fn ^error, ^state -> state end)
assert state == exec(args, state)
end
end
end
| 33.424242 | 92 | 0.573285 |
79f22565388b393183bce0d923be1f5e99d7b36c | 234 | ex | Elixir | lib/tilex_web/views/error_view.ex | plicjo/tilex | f3d9cba7f2ca99c75622cd1a9992508614dd455f | [
"MIT"
] | 460 | 2016-12-28T21:50:05.000Z | 2022-03-16T14:34:08.000Z | lib/tilex_web/views/error_view.ex | plicjo/tilex | f3d9cba7f2ca99c75622cd1a9992508614dd455f | [
"MIT"
] | 412 | 2016-12-27T17:32:01.000Z | 2021-09-17T23:51:47.000Z | lib/tilex_web/views/error_view.ex | plicjo/tilex | f3d9cba7f2ca99c75622cd1a9992508614dd455f | [
"MIT"
] | 140 | 2017-01-06T06:55:58.000Z | 2022-02-04T13:35:21.000Z | defmodule TilexWeb.ErrorView do
use TilexWeb, :view
# In case no render clause matches or no
# template is found, let's render it as 500
def template_not_found(_template, assigns) do
render("500.html", assigns)
end
end
| 23.4 | 47 | 0.730769 |
79f2283bfc3d77b14b744e33ed3f5f2e747f337a | 6,513 | ex | Elixir | apps/mishka_html/lib/mishka_html_web/live/components/admin/user/list_component.ex | mojtaba-naserei/mishka-cms | 1f31f61347bab1aae6ba0d47c5515a61815db6c9 | [
"Apache-2.0"
] | 1 | 2021-11-14T11:13:25.000Z | 2021-11-14T11:13:25.000Z | apps/mishka_html/lib/mishka_html_web/live/components/admin/user/list_component.ex | iArazar/mishka-cms | 8b579101d607d91e80834527c1508fe5f4ceefef | [
"Apache-2.0"
] | null | null | null | apps/mishka_html/lib/mishka_html_web/live/components/admin/user/list_component.ex | iArazar/mishka-cms | 8b579101d607d91e80834527c1508fe5f4ceefef | [
"Apache-2.0"
] | null | null | null | defmodule MishkaHtmlWeb.Admin.User.ListComponent do
use MishkaHtmlWeb, :live_component
def render(assigns) do
~H"""
<div class="col bw admin-blog-post-list">
<div class="table-responsive">
<table class="table vazir">
<thead>
<tr>
<th scope="col" id="div-image"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "تصویر") %></th>
<th scope="col" id="div-title"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "نام کامل") %></th>
<th scope="col" id="div-category"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "نام کاربری") %></th>
<th scope="col" id="div-status"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "ایمیل") %></th>
<th scope="col" id="div-priority"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "وضعیت") %></th>
<th scope="col" id="div-update"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "ثبت") %></th>
<th scope="col" id="div-opration"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "عملیات") %></th>
</tr>
</thead>
<tbody>
<%= for {item, color} <- Enum.zip(@users, Stream.cycle(["wlist", "glist"])) do %>
<tr class={"blog-list vazir #{if(color == "glist", do: "odd-list-of-blog-posts", else: "")}"}>
<td class="align-middle col-sm-2 admin-list-img">
<img src="/images/no-user-image.jpg" alt={item.full_name}>
</td>
<td class="align-middle text-center" id={"title-#{item.id}"}>
<%= live_redirect "#{MishkaHtml.full_name_sanitize(item.full_name)}",
to: Routes.live_path(@socket, MishkaHtmlWeb.AdminUserLive, id: item.id)
%>
</td>
<td class="align-middle text-center">
<%= live_redirect "#{MishkaHtml.username_sanitize(item.username)}",
to: Routes.live_path(@socket, MishkaHtmlWeb.AdminUserLive, id: item.id)
%>
</td>
<td class="align-middle text-center">
<%= MishkaHtml.email_sanitize(item.email) %>
</td>
<td class="align-middle text-center">
<%
field = Enum.find(MishkaHtmlWeb.AdminUserLive.basic_menu_list, fn x -> x.type == "status" end)
{title, _type} = Enum.find(field.options, fn {_title, type} -> type == item.status end)
%>
<%= title %>
</td>
<td class="align-middle text-center">
<.live_component module={MishkaHtmlWeb.Public.TimeConverterComponent} id={"inserted-at-#{item.id}-component"} span_id={"inserted-at-#{item.id}-component"} time={item.inserted_at} />
</td>
<td class="align-middle text-center" id={"opration-#{item.id}"}>
<a class="btn btn-outline-primary vazir" phx-click="delete" phx-value-id={item.id}>حذف</a>
<%= live_redirect MishkaTranslator.Gettext.dgettext("html_live_component", "ویرایش"),
to: Routes.live_path(@socket, MishkaHtmlWeb.AdminUserLive, id: item.id),
class: "btn btn-outline-danger vazir"
%>
<% user_role = item.roles %>
<div class="clearfix"></div>
<div class="space20"></div>
<div class="col">
<label for="country" class="form-label">
<%= MishkaTranslator.Gettext.dgettext("html_live_component", "انتخاب دسترسی") %>
</label>
<form phx-change="search_role">
<input class="form-control" type="text" placeholder={MishkaTranslator.Gettext.dgettext("html_live_component", "جستجوی پیشرفته")} name="name">
</form>
<form phx-change="user_role">
<input type="hidden" value={item.id} name="user_id">
<input type="hidden" value={item.full_name} name="full_name">
<select class="form-select" id="role" name="role" size="2" style="min-height: 150px;">
<option value="delete_user_role"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "بدون دسترسی") %></option>
<%= for item <- @roles.entries do %>
<%= if !is_nil(user_role) and item.id == user_role.id do %>
<option value={item.id} selected><%= item.name %></option>
<% else %>
<option value={item.id}><%= item.name %></option>
<% end %>
<% end %>
</select>
</form>
</div>
</td>
</tr>
<% end %>
</tbody>
</table>
<div class="space20"></div>
<div class="col-sm-10">
<%= if @users.entries != [] do %>
<.live_component module={MishkaHtmlWeb.Public.PaginationComponent} id={:pagination} pagination_url={@pagination_url} data={@users} filters={@filters} count={@count} />
<% end %>
</div>
</div>
</div>
"""
end
end
| 65.787879 | 213 | 0.430677 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.