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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7945aa8a2a81e0d0336895659d449aeb4f8601bf | 1,678 | exs | Elixir | test/tirexs/query/bool_test.exs | falood/tirexs | 9c63532cf2f50f77fb437f617d433741771d3619 | [
"Apache-2.0"
] | null | null | null | test/tirexs/query/bool_test.exs | falood/tirexs | 9c63532cf2f50f77fb437f617d433741771d3619 | [
"Apache-2.0"
] | null | null | null | test/tirexs/query/bool_test.exs | falood/tirexs | 9c63532cf2f50f77fb437f617d433741771d3619 | [
"Apache-2.0"
] | null | null | null | Code.require_file "../../../test_helper.exs", __ENV__.file
defmodule Tirexs.Query.Bool.Test do
use ExUnit.Case
import Tirexs.Query
@url "labeled/track"
test :simple_bool do
query = query do
bool do
must do
match "artist_uri", "medianet:artist:261633", operator: "and"
end
end
end
assert query == [query: [bool: [must: [[match: [artist_uri: [query: "medianet:artist:261633", operator: "and"]]]]]]]
end
test :advance_bool do
query = query do
bool do
must do
match "artist", "Madonna", operator: "and"
match "title", "My", operator: "and"
match "color_tune", "red,orange"
match "genre", "Alternative/Indie,Christian/Gospel"
range "release_year", from: 1950, to: 2013
range "energy_mood", from: 0, to: 30
end
should do
match "genre", "Alternative/Indie,Christian/Gospel"
range "release_year", from: 1950, to: 2013
end
must_not do
match "genre", "Alternative/Indie,Christian/Gospel"
end
end
end
assert query == [query: [bool: [must: [[match: [artist: [query: "Madonna", operator: "and"]]],[match: [title: [query: "My", operator: "and"]]],[match: [color_tune: [query: "red,orange"]]],[match: [genre: [query: "Alternative/Indie,Christian/Gospel"]]],[range: [release_year: [from: 1950, to: 2013]]],[range: [energy_mood: [from: 0, to: 30]]]], should: [[match: [genre: [query: "Alternative/Indie,Christian/Gospel"]]],[range: [release_year: [from: 1950, to: 2013]]]], must_not: [[match: [genre: [query: "Alternative/Indie,Christian/Gospel"]]]]]]]
end
end
| 36.478261 | 549 | 0.602503 |
7945b434f5ec130c80e099cb7de2cc96e3547238 | 1,615 | ex | Elixir | clients/ad_sense/lib/google_api/ad_sense/v2/model/time_zone.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/ad_sense/lib/google_api/ad_sense/v2/model/time_zone.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/ad_sense/lib/google_api/ad_sense/v2/model/time_zone.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.AdSense.V2.Model.TimeZone do
@moduledoc """
Represents a time zone from the [IANA Time Zone Database](https://www.iana.org/time-zones).
## Attributes
* `id` (*type:* `String.t`, *default:* `nil`) - IANA Time Zone Database time zone, e.g. "America/New_York".
* `version` (*type:* `String.t`, *default:* `nil`) - Optional. IANA Time Zone Database version number, e.g. "2019a".
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:id => String.t() | nil,
:version => String.t() | nil
}
field(:id)
field(:version)
end
defimpl Poison.Decoder, for: GoogleApi.AdSense.V2.Model.TimeZone do
def decode(value, options) do
GoogleApi.AdSense.V2.Model.TimeZone.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AdSense.V2.Model.TimeZone do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.3 | 120 | 0.708359 |
79460440aae34fc1cab9646c923848a9aa778637 | 3,381 | ex | Elixir | farmbot_celery_script/lib/farmbot_celery_script/sys_calls/stubs.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | 1 | 2019-08-06T11:51:48.000Z | 2019-08-06T11:51:48.000Z | farmbot_celery_script/lib/farmbot_celery_script/sys_calls/stubs.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | null | null | null | farmbot_celery_script/lib/farmbot_celery_script/sys_calls/stubs.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | null | null | null | defmodule FarmbotCeleryScript.SysCalls.Stubs do
@moduledoc """
SysCall implementation that doesn't do anything. Useful for tests.
"""
@behaviour FarmbotCeleryScript.SysCalls
require Logger
@impl true
def log(message), do: error(:log, [message])
@impl true
def sequence_init_log(message), do: error(:log, [message])
@impl true
def sequence_complete_log(message), do: error(:log, [message])
@impl true
def calibrate(axis), do: error(:calibrate, [axis])
@impl true
def change_ownership(email, secret, server),
do: error(:change_ownership, [email, secret, server])
@impl true
def check_update(), do: error(:check_update, [])
@impl true
def coordinate(x, y, z), do: error(:coordinate, [x, y, z])
@impl true
def dump_info(), do: error(:dump_info, [])
@impl true
def emergency_lock(), do: error(:emergency_lock, [])
@impl true
def emergency_unlock(), do: error(:emergency_unlock, [])
@impl true
def execute_script(package, args), do: error(:execute_script, [package, args])
@impl true
def factory_reset(package), do: error(:factory_reset, [package])
@impl true
def find_home(axis), do: error(:find_home, [axis])
@impl true
def firmware_reboot(), do: error(:firmware_reboot, [])
@impl true
def flash_firmware(package), do: error(:flash_firmware, [package])
@impl true
def get_current_x(), do: error(:get_current_x, [])
@impl true
def get_current_y(), do: error(:get_current_y, [])
@impl true
def get_current_z(), do: error(:get_current_z, [])
@impl true
def get_sequence(resource_id), do: error(:get_sequence, [resource_id])
@impl true
def get_toolslot_for_tool(resource_id), do: error(:get_toolslot_for_tool, [resource_id])
@impl true
def home(axis, speed), do: error(:home, [axis, speed])
@impl true
def install_first_party_farmware(), do: error(:install_first_party_farmware, [])
@impl true
def move_absolute(x, y, z, speed), do: error(:move_absolute, [x, y, z, speed])
@impl true
def named_pin(named_pin_type, resource_id), do: error(:named_pin, [named_pin_type, resource_id])
@impl true
def nothing(), do: error(:nothing, [])
@impl true
def point(point_type, resource_id), do: error(:point, [point_type, resource_id])
@impl true
def power_off(), do: error(:power_off, [])
@impl true
def read_pin(pin_num, pin_mode), do: error(:read_pin, [pin_num, pin_mode])
@impl true
def read_status(), do: error(:read_status, [])
@impl true
def reboot(), do: error(:reboot, [])
@impl true
def resource_update(kind, resource_id, data),
do: error(:resource_update, [kind, resource_id, data])
@impl true
def send_message(type, message, channels), do: error(:send_message, [type, message, channels])
@impl true
def set_servo_angle(pin, value), do: error(:set_servo_angle, [pin, value])
@impl true
def set_user_env(env_name, env_value), do: error(:set_user_env, [env_name, env_value])
@impl true
def sync(), do: error(:sync, [])
@impl true
def wait(millis), do: error(:wait, [millis])
@impl true
def write_pin(pin_num, pin_mode, pin_value),
do: error(:write_pin, [pin_num, pin_mode, pin_value])
@impl true
def zero(axis), do: error(:zero, [axis])
defp error(fun, _args) do
msg = """
CeleryScript syscall stubbed: #{fun}
"""
Logger.error(msg)
{:error, msg}
end
end
| 25.044444 | 98 | 0.682343 |
7946063ff8209f0c35ab307075ea8d283d875ff8 | 1,409 | exs | Elixir | mix.exs | myfreeweb/httpotion | 1bcd0b629561d472492bb557d59eecf5fff52644 | [
"Unlicense"
] | 637 | 2015-01-03T08:10:52.000Z | 2021-01-29T15:56:01.000Z | mix.exs | unrelentingtech/httpotion | 1bcd0b629561d472492bb557d59eecf5fff52644 | [
"Unlicense"
] | 95 | 2015-01-01T12:18:12.000Z | 2020-02-26T20:41:44.000Z | mix.exs | unrelentingtech/httpotion | 1bcd0b629561d472492bb557d59eecf5fff52644 | [
"Unlicense"
] | 88 | 2015-01-06T15:38:37.000Z | 2020-04-01T09:19:39.000Z | defmodule HTTPotion.Mixfile do
use Mix.Project
def project do
if Mix.env == :dial, do: Application.ensure_all_started(:ex_unit)
[ app: :httpotion,
name: "httpotion",
source_url: "https://github.com/myfreeweb/httpotion",
version: "3.1.3",
elixir: "~> 1.3",
docs: [ extras: ["README.md", "CODE_OF_CONDUCT.md"] ],
description: description(),
deps: deps(),
package: package(),
elixirc_paths: elixirc_paths(Mix.env),
test_pattern: "*_test.ex",
warn_test_pattern: "*_test.exs",
preferred_cli_env: [ dialyzer: :dial ] ]
end
def application do
[ applications: [:ssl, :ibrowse] ]
end
defp description do
"""
Fancy HTTP client for Elixir, based on ibrowse.
"""
end
defp deps do
[ {:ibrowse, "== 4.4.0"},
{:ssl_verify_fun, "~> 1.1"},
{:ex_doc, "~> 0.18", only: [:dev, :test, :docs]} ]
end
defp package do
[ files: [ "lib", "mix.exs", "README.md", "CODE_OF_CONDUCT.md", "UNLICENSE" ],
maintainers: [ "Greg V", "Aleksei Magusev" ],
licenses: [ "Unlicense" ],
links: %{ "GitHub" => "https://github.com/myfreeweb/httpotion" } ]
end
# http://learningelixir.joekain.com/dialyzer-and-integration-tests/
# modified to only compile for dialyzer, not for running tests
defp elixirc_paths(:dial), do: ["lib", "test"]
defp elixirc_paths(_), do: ["lib"]
end
| 28.755102 | 82 | 0.603974 |
79461d0c89e3c19a89ed37df369c0a16bef95830 | 3,417 | ex | Elixir | lib/live_phone/countries.ex | workwithmax/live_phone | 1a5482a9032735dd201f2468643145f1ee0a3588 | [
"MIT"
] | 3 | 2021-02-28T22:27:58.000Z | 2021-12-08T03:18:10.000Z | lib/live_phone/countries.ex | whitepaperclip/live_phone | bda5d554dd7d3df313fa15cd71eb2bcb8acda897 | [
"MIT"
] | 25 | 2021-02-26T16:15:46.000Z | 2022-03-24T08:10:51.000Z | lib/live_phone/countries.ex | workwithmax/live_phone | 1a5482a9032735dd201f2468643145f1ee0a3588 | [
"MIT"
] | 2 | 2020-11-27T17:33:52.000Z | 2021-01-25T16:05:16.000Z | defmodule LivePhone.Countries do
@moduledoc """
The `LivePhone.Countries` module can be used to list all known countries and return
them ordered alphabetically, and optionally you can ensure your preferred countries
are prepended to the list instead of mixed in with the rest.
"""
alias ISO
alias LivePhone.Country
@type phone() :: %ExPhoneNumber.Model.PhoneNumber{}
@doc """
This function returns all known countries as `LivePhone.Country` structs,
sorted alphabetically by country name.
Optionally you can specify a list of preferred country codes, these will
subsequently be prepended to the list.
```elixir
# This will return everything alphabetically
abc_countries = LivePhone.Countries.list_countries()
# This will return it alphabetically as well, but push
# the US and GB `LivePhone.Country` structs to the top
# of the list.
my_countries = LivePhone.Countries.list_countries(["US", "GB"])
```
"""
@spec list_countries(list(String.t())) :: [Country.t()]
def list_countries(preferred \\ []) when is_list(preferred) do
preferred = preferred |> Enum.uniq() |> Enum.with_index()
ISO.countries()
|> Enum.map(&Country.from_iso/1)
|> Enum.map(&set_preferred_flag(&1, preferred))
|> Enum.filter(&(&1.region_code && &1.region_code != ""))
|> Enum.sort(&sort_by_name/2)
|> Enum.sort_by(&sort_by_preferred(&1, preferred), :desc)
end
@doc """
This function will lookup a `Country` by it's country code.
```elixir
Examples:
iex> LivePhone.Countries.get_country("US")
{:ok, %LivePhone.Country{code: "US", flag_emoji: "🇺🇸", name: "United States of America (the)", preferred: false, region_code: "1"}}
iex> LivePhone.Countries.get_country("FAKE")
{:error, :not_found}
```
"""
@spec get_country(String.t()) :: {:ok, Country.t()} | {:error, :not_found}
def get_country(country_code) do
list_countries()
|> Enum.find(&(&1.code == country_code))
|> case do
nil -> {:error, :not_found}
country -> {:ok, country}
end
end
@doc """
This function can be used to try and find the `Country` for a specific
phone number in the `ExPhoneNumber` format.
"""
@spec lookup(phone()) :: {:ok, Country.t()} | {:error, :not_found}
def lookup(%ExPhoneNumber.Model.PhoneNumber{} = phone) do
country_code = ExPhoneNumber.Metadata.get_region_code_for_number(phone)
list_countries()
|> Enum.find(&(&1.code == country_code))
|> case do
nil -> {:error, :not_found}
country -> {:ok, country}
end
end
@spec set_preferred_flag(Country.t(), list(String.t())) :: Country.t()
defp set_preferred_flag(%Country{} = country, preferred) do
preferred
|> Enum.find(fn {value, _index} -> value == country.code end)
|> case do
nil -> country
{_, _index} -> %{country | preferred: true}
end
end
@spec sort_by_name(%{name: String.t()}, %{name: String.t()}) :: boolean()
defp sort_by_name(%{name: name_1}, %{name: name_2}) do
name_1 < name_2
end
@spec sort_by_preferred(Country.t(), list(String.t())) :: integer()
defp sort_by_preferred(%Country{preferred: false}, _), do: 0
defp sort_by_preferred(%Country{code: country_code}, preferred) do
preferred
|> Enum.find(fn {value, _index} -> value == country_code end)
|> case do
nil -> 0
{_, index} -> length(preferred) - index
end
end
end
| 31.348624 | 135 | 0.661399 |
7946277efe581e5e3e0144910e811c66a53391fe | 13,353 | ex | Elixir | lib/cte/adapter/ecto.ex | scottming/closure_table | 2b567ebe040a5ac5b539bfc3112fec181a025ebc | [
"Apache-2.0"
] | null | null | null | lib/cte/adapter/ecto.ex | scottming/closure_table | 2b567ebe040a5ac5b539bfc3112fec181a025ebc | [
"Apache-2.0"
] | null | null | null | lib/cte/adapter/ecto.ex | scottming/closure_table | 2b567ebe040a5ac5b539bfc3112fec181a025ebc | [
"Apache-2.0"
] | null | null | null | defmodule CTE.Adapter.Ecto do
@moduledoc """
A CTE Adapter implementation using an existing Ecto Repo for persisting the models.
The current implementation is depending on Ecto ~> 3.1; using [Ecto.SubQuery](https://hexdocs.pm/ecto/Ecto.SubQuery.html)!
For this implementation to work you'll have to provide two tables, and the name of the Repo used by your application:
1. a table name containing the nodes. Having the `id`, as a the primary key
2. a table name where the tree paths will be stores.
3. the name of the Ecto.Repo, defined by your app
In a future version we will provide you with a convenient migration template to help you starting, but for now you must supply these tables.
For example, given you have the following Schemas for comments:
defmodule CT.Comment do
use Ecto.Schema
import Ecto.Changeset
@timestamps_opts [type: :utc_datetime]
schema "comments" do
field :text, :string
belongs_to :author, CT.Author
timestamps()
end
end
and a table used for storing the parent-child relationships
defmodule CT.TreePath do
use Ecto.Schema
import Ecto.Changeset
alias CT.Comment
@primary_key false
schema "tree_paths" do
belongs_to :parent_comment, Comment, foreign_key: :ancestor
belongs_to :comment, Comment, foreign_key: :descendant
field :path_length, :integer, default: 0
end
end
we can define the following module:
defmodule CT.MyCTE do
use CTE,
otp_app: :cte,
adapter: CTE.Adapter.Ecto,
repo: CT.Repo,
nodes: CT.Comment,
paths: CT.TreePath
end
We add our CTE Repo to the app's main supervision tree, like this:
defmodule CT.Application do
use Application
def start(_type, _args) do
children = [
CT.Repo,
CT.MyCTE
]
opts = [strategy: :one_for_one, name: CT.Supervisor]
Supervisor.start_link(children, opts)
end
end
restart out app and then using IEx, we can start experimenting. Examples:
iex» CT.MyCTE.ancestors(9)
{:ok, [1, 4, 6]}
iex» CT.MyCTE.tree(6)
{:ok,
%{
nodes: %{
6 => %CT.Comment{
__meta__: #Ecto.Schema.Metadata<:loaded, "comments">,
author: #Ecto.Association.NotLoaded<association :author is not loaded>,
author_id: 2,
id: 6,
inserted_at: ~U[2019-07-21 01:10:35Z],
text: "Everything is easier, than with the Nested Sets.",
updated_at: ~U[2019-07-21 01:10:35Z]
},
8 => %CT.Comment{
__meta__: #Ecto.Schema.Metadata<:loaded, "comments">,
author: #Ecto.Association.NotLoaded<association :author is not loaded>,
author_id: 1,
id: 8,
inserted_at: ~U[2019-07-21 01:10:35Z],
text: "I’m sold! And I’ll use its Elixir implementation! <3",
updated_at: ~U[2019-07-21 01:10:35Z]
},
9 => %CT.Comment{
__meta__: #Ecto.Schema.Metadata<:loaded, "comments">,
author: #Ecto.Association.NotLoaded<association :author is not loaded>,
author_id: 3,
id: 9,
inserted_at: ~U[2019-07-21 01:10:35Z],
text: "w⦿‿⦿t!",
updated_at: ~U[2019-07-21 01:10:35Z]
}
},
paths: [
[6, 6, 0],
[6, 8, 1],
[8, 8, 0],
[6, 9, 1],
[9, 9, 0]
]
}}
Have fun!
Most of the functions implementing the `CTE.Adapter` behavior, will accept the following options:
- `:limit`, to limit the total number of nodes returned, when finding the ancestors or the descendants for nodes
- `:itself`, accepting a boolean value. When `true`, the node used for finding its neighbors are returned as part of the results. Default: true
- `:nodes`, accepting a boolean value. When `true`, the results are containing additional information about the nodes. Default: false
"""
use CTE.Adapter
import Ecto.Query, warn: false
@doc """
Insert a node under an existing ancestor
"""
def insert(pid, leaf, ancestor, opts) do
GenServer.call(pid, {:insert, leaf, ancestor, opts})
end
@doc """
Retrieve the descendants of a node
"""
def descendants(pid, ancestor, opts) do
GenServer.call(pid, {:descendants, ancestor, opts})
end
@doc """
Retrieve the ancestors of a node
"""
def ancestors(pid, descendant, opts) do
GenServer.call(pid, {:ancestors, descendant, opts})
end
@doc """
Delete a leaf or a subtree.
To delete a leaf node set the limit option to: 1, and in this particular case
all the nodes that reference the leaf will be assigned to the leaf's immediate ancestor
If limit is 0, then the leaf and its descendants will be deleted
"""
def delete(pid, leaf, opts \\ [limit: 1])
def delete(pid, leaf, opts) do
leaf? = Keyword.get(opts, :limit, 1) == 1
GenServer.call(pid, {:delete, leaf, leaf?, opts})
end
@doc """
Move a subtree from one location to another.
First, the subtree and its descendants are disconnected from its ancestors. And second, the subtree is inserted under the new parent (ancestor) and the subtree, including its descendants, is declared as descendants of all the new ancestors.
"""
def move(pid, leaf, ancestor, opts) do
GenServer.call(pid, {:move, leaf, ancestor, opts})
end
@doc """
Calculate and return a "tree" structure containing the paths and the nodes under the given leaf/node
"""
def tree(pid, leaf, opts) do
GenServer.call(pid, {:tree, leaf, opts})
end
######################################
# server callbacks
######################################
@doc false
def handle_call({:delete, leaf, true, _opts}, _from, config) do
%CTE{paths: paths, repo: repo} = config
descendants = _descendants(leaf, [itself: false], config) || []
query_delete_leaf =
from p in paths,
where: ^leaf in [p.ancestor, p.descendant] and p.path_length >= 0,
select: %{ancestor: p.ancestor, descendant: p.descendant, path_length: p.path_length}
# repo.all(query_delete_leaf)
# |> IO.inspect(label: "DELETE: ")
query_move_leafs_kids_up =
from p in paths,
where: p.descendant in ^descendants and p.path_length >= 1,
update: [
set: [
path_length: p.path_length - 1
]
]
repo.transaction(fn ->
repo.delete_all(query_delete_leaf)
repo.update_all(query_move_leafs_kids_up, [])
end)
{:reply, :ok, config}
end
@doc false
def handle_call({:delete, leaf, _subtree, _opts}, _from, config) do
%CTE{paths: paths, repo: repo} = config
# DELETE FROM ancestry WHERE descendant IN (SELECT descendant FROM ancestry WHERE ancestor = 100)
sub = from p in paths, where: p.ancestor == ^leaf
query =
from p in paths,
join: sub in subquery(sub),
on: p.descendant == sub.descendant
repo.delete_all(query)
{:reply, :ok, config}
end
@doc false
def handle_call({:move, leaf, ancestor, opts}, _from, config) do
results = _move(leaf, ancestor, opts, config)
{:reply, results, config}
end
@doc false
def handle_call({:descendants, ancestor, opts}, _from, config) do
results = _descendants(ancestor, opts, config)
{:reply, {:ok, results}, config}
end
@doc false
def handle_call({:ancestors, descendant, opts}, _from, config) do
result = _ancestors(descendant, opts, config)
{:reply, {:ok, result}, config}
end
def handle_call({:insert, leaf, ancestor, _opts}, _from, config) do
result = _insert(leaf, ancestor, config)
{:reply, result, config}
end
@doc false
def handle_call({:tree, leaf, opts}, _from, config) do
%CTE{paths: paths, nodes: nodes, repo: repo} = config
descendants_opts = [itself: true] ++ Keyword.take(opts, [:path_length])
descendants = _descendants(leaf, descendants_opts, config)
# subtree = Enum.filter(paths, fn [ancestor, _descendant] -> ancestor in descendants end)
query =
from p in paths,
where: p.ancestor in ^descendants,
select: [p.ancestor, p.descendant, p.path_length]
subtree =
query
|> prune(descendants, opts, config)
|> repo.all()
authors =
subtree
|> List.flatten()
|> Enum.uniq()
query = from n in nodes, where: n.id in ^authors
some_nodes =
repo.all(query)
|> Enum.reduce(%{}, fn node, acc -> Map.put(acc, node.id, node) end)
{:reply, {:ok, %{paths: subtree, nodes: some_nodes}}, config}
end
######################################
# private
######################################
@doc false
defp _insert(leaf, ancestor, config) do
%CTE{paths: paths, repo: repo} = config
# SELECT t.ancestor, #{leaf}, t.path_length + 1
# FROM tree_paths AS t
# WHERE t.descendant = #{ancestor}
descendants =
from p in paths,
where: p.descendant == ^ancestor,
select: %{ancestor: p.ancestor, descendant: type(^leaf, :integer), path_length: p.path_length + 1}
new_records = repo.all(descendants) ++ [%{ancestor: leaf, descendant: leaf, path_length: 0}]
descendants = Enum.map(new_records, fn r -> [r.ancestor, r.descendant] end)
case repo.insert_all(paths, new_records, on_conflict: :nothing) do
{_nr, _r} ->
# l when l == nr <- length(new_records) do
{:ok, descendants}
e ->
{:error, e}
end
end
@doc false
defp _descendants(ancestor, opts, config) do
%CTE{paths: paths, nodes: nodes, repo: repo} = config
# SELECT c. * FROM comments AS c
# JOIN tree_paths AS t ON c.id = t.descendant
# WHERE t.ancestor = ^ancestor;
query =
from n in nodes,
join: p in ^paths,
as: :tree,
on: n.id == p.descendant,
where: p.ancestor == ^ancestor,
order_by: [asc: p.path_length]
query
|> selected(opts, config)
|> include_itself(opts, config)
|> path_length(opts, config)
|> top(opts, config)
|> repo.all()
end
@doc false
defp _ancestors(descendant, opts, config) do
%CTE{paths: paths, nodes: nodes, repo: repo} = config
# SELECT c. * FROM comments AS c
# JOIN tree_paths AS t ON c.id = t.ancestor
# WHERE t.descendant = ^descendant;
query =
from n in nodes,
join: p in ^paths,
as: :tree,
on: n.id == p.ancestor,
where: p.descendant == ^descendant,
order_by: [desc: p.path_length]
query
|> selected(opts, config)
|> include_itself(opts, config)
|> path_length(opts, config)
|> top(opts, config)
|> repo.all()
end
defp _move(leaf, ancestor, _opts, config) do
%CTE{paths: paths, repo: repo} = config
# DELETE FROM ancestry
# WHERE descendant IN (SELECT descendant FROM ancestry WHERE ancestor = ^leaf)
# AND ancestor IN (SELECT ancestor FROM ancestry WHERE descendant = ^leaf
# AND ancestor != descendant);
q_ancestors =
from p in paths,
where: p.descendant == ^leaf,
where: p.ancestor != p.descendant
q_descendants =
from p in paths,
where: p.ancestor == ^leaf
query_delete =
from p in paths,
join: d in subquery(q_descendants),
on: p.descendant == d.descendant,
join: a in subquery(q_ancestors),
on: p.ancestor == a.ancestor
# INSERT INTO ancestry (ancestor, descendant)
# SELECT super_tree.ancestor, sub_tree.descendant FROM ancestry AS super_tree
# CROSS JOIN ancestry AS sub_tree WHERE super_tree.descendant = 3
# AND sub_tree.ancestor = 6;
query_insert =
from super_tree in paths,
cross_join: sub_tree in ^paths,
where: super_tree.descendant == ^ancestor,
where: sub_tree.ancestor == ^leaf,
select: %{
ancestor: super_tree.ancestor,
descendant: sub_tree.descendant,
path_length: super_tree.path_length + sub_tree.path_length + 1
}
repo.transaction(fn ->
repo.delete_all(query_delete)
inserts = repo.all(query_insert)
repo.insert_all(paths, inserts)
end)
end
######################################
# Utils
######################################
defp selected(query, opts, _config) do
if Keyword.get(opts, :nodes, false) do
from(n in query)
else
from n in query, select: n.id
end
end
defp include_itself(query, opts, _config) do
if Keyword.get(opts, :itself, false) do
query
else
from [tree: t] in query, where: t.ancestor != t.descendant
end
end
defp top(query, opts, _config) do
if limit = Keyword.get(opts, :limit) do
from q in query, limit: ^limit
else
query
end
end
defp path_length(query, opts, _config) do
if path_length = Keyword.get(opts, :path_length) do
from [tree: t] in query, where: t.path_length <= ^max(path_length, 0)
else
query
end
end
defp prune(query, descendants, opts, _config) do
if Keyword.get(opts, :path_length) do
from t in query, where: t.descendant in ^descendants
else
query
end
end
end
| 29.155022 | 242 | 0.611473 |
79463947c121830282df20397b0134dd764446f0 | 5,412 | ex | Elixir | lib/stripe/subscriptions/plan.ex | neneboe/stripity_stripe | e86be7cd8f19dd208ee3cb7d9bd6165be3e71f17 | [
"BSD-3-Clause"
] | 2 | 2019-05-02T10:42:09.000Z | 2019-12-02T21:29:17.000Z | lib/stripe/subscriptions/plan.ex | neneboe/stripity_stripe | e86be7cd8f19dd208ee3cb7d9bd6165be3e71f17 | [
"BSD-3-Clause"
] | null | null | null | lib/stripe/subscriptions/plan.ex | neneboe/stripity_stripe | e86be7cd8f19dd208ee3cb7d9bd6165be3e71f17 | [
"BSD-3-Clause"
] | 1 | 2020-02-20T14:09:26.000Z | 2020-02-20T14:09:26.000Z | defmodule Stripe.Plan do
@moduledoc """
Work with Stripe plan objects.
You can:
- Create a plan
- Retrieve a plan
- Update a plan
- Delete a plan
Does not yet render lists or take options.
Stripe API reference: https://stripe.com/docs/api#plan
Example:
```
{
"id": "ivory-extended-580",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 999,
"billing_scheme": "per_unit",
"created": 1531234812,
"currency": "usd",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {
},
"nickname": null,
"product": "prod_DCmtkptv7qHXGE",
"tiers": null,
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
}
```
"""
use Stripe.Entity
import Stripe.Request
@type t :: %__MODULE__{
id: Stripe.id(),
object: String.t(),
active: boolean,
aggregate_usage: String.t() | nil,
amount: non_neg_integer | nil,
billing_scheme: String.t() | nil,
created: Stripe.timestamp(),
currency: String.t(),
deleted: boolean | nil,
interval: String.t(),
interval_count: pos_integer,
livemode: boolean,
metadata: Stripe.Types.metadata(),
name: String.t(),
nickname: String.t() | nil,
product: Stripe.id() | Stripe.Product.t(),
tiers: Stripe.List.t(map) | nil,
tiers_mode: boolean | nil,
transform_usage: map | nil,
trial_period_days: non_neg_integer | nil,
usage_type: String.t() | nil
}
defstruct [
:id,
:object,
:active,
:aggregate_usage,
:amount,
:billing_scheme,
:created,
:currency,
:deleted,
:interval,
:interval_count,
:livemode,
:metadata,
:name,
:nickname,
:product,
:tiers,
:tiers_mode,
:transform_usage,
:trial_period_days,
:usage_type
]
@plural_endpoint "plans"
@doc """
Create a plan.
"""
@spec create(params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params:
%{
:currency => String.t(),
:interval => String.t(),
:product => Stripe.id() | Stripe.Product.t(),
optional(:id) => String.t(),
optional(:amount) => non_neg_integer,
optional(:active) => boolean,
optional(:billing_scheme) => String.t(),
optional(:interval_count) => pos_integer,
optional(:metadata) => Stripe.Types.metadata(),
optional(:nickname) => String.t(),
optional(:tiers) => Stripe.List.t(map),
optional(:tiers_mode) => String.t(),
optional(:transform_usage) => map,
optional(:trial_period_days) => non_neg_integer,
optional(:usage_type) => String.t()
}
| %{}
def create(%{currency: _, interval: _, product: _} = params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint)
|> put_params(params)
|> put_method(:post)
|> make_request()
end
@doc """
Retrieve a plan.
"""
@spec retrieve(Stripe.id() | t, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
def retrieve(id, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:get)
|> make_request()
end
@doc """
Update a plan.
Takes the `id` and a map of changes.
"""
@spec update(Stripe.id() | t, params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params:
%{
optional(:active) => boolean,
optional(:metadata) => Stripe.Types.metadata(),
optional(:nickname) => String.t(),
optional(:product) => Stripe.id() | Stripe.Product.t(),
optional(:trial_period_days) => non_neg_integer
}
| %{}
def update(id, params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:post)
|> put_params(params)
|> make_request()
end
@doc """
Delete a plan.
"""
@spec delete(Stripe.id() | t, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
def delete(id, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:delete)
|> make_request()
end
@doc """
List all plans.
"""
@spec list(params, Stripe.options()) :: {:ok, Stripe.List.t(t)} | {:error, Stripe.Error.t()}
when params:
%{
optional(:active) => boolean,
optional(:created) => Stripe.date_query(),
optional(:ending_before) => t | Stripe.id(),
optional(:limit) => 1..100,
optional(:product) => Stripe.Product.t() | Stripe.id(),
optional(:starting_after) => t | Stripe.id()
}
| %{}
def list(params \\ %{}, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint)
|> put_method(:get)
|> put_params(params)
|> cast_to_id([:ending_before, :starting_after])
|> make_request()
end
end
| 27.612245 | 98 | 0.52901 |
79463b30419c6a8a81d94c30c6b20e2c0ac1bf86 | 1,076 | exs | Elixir | lib/exercism/pig-latin/pig_latin.exs | sprql/experimentex | 6c8a37ea03b74c5bfece1b2bec21c163a2f2df2f | [
"MIT"
] | null | null | null | lib/exercism/pig-latin/pig_latin.exs | sprql/experimentex | 6c8a37ea03b74c5bfece1b2bec21c163a2f2df2f | [
"MIT"
] | null | null | null | lib/exercism/pig-latin/pig_latin.exs | sprql/experimentex | 6c8a37ea03b74c5bfece1b2bec21c163a2f2df2f | [
"MIT"
] | null | null | null | defmodule PigLatin do
@doc """
Given a `phrase`, translate it a word at a time to Pig Latin.
Words beginning with consonants should have the consonant moved to the end of
the word, followed by "ay".
Words beginning with vowels (aeiou) should have "ay" added to the end of the
word.
Some groups of letters are treated like consonants, including "ch", "qu",
"squ", "th", "thr", and "sch".
Some groups are treated like vowels, including "yt" and "xr".
"""
@spec translate(phrase :: String.t()) :: String.t()
def translate(phrase) do
phrase
|> String.split(" ")
|> Enum.map(&translate_word/1)
|> Enum.join(" ")
end
defp translate_word(word) do
vowels_regexp = ~r/^(yt|xr|a|e|i|o|u)(\w+)$/
consonants_regexp = ~r/^(ch|qu|squ|thr|th|sch|b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|w|x|y|z)(\w+)$/
cond do
String.match?(word, vowels_regexp)
-> Regex.replace(vowels_regexp, word, "\\1\\2ay")
String.match?(word, consonants_regexp)
-> Regex.replace(consonants_regexp, word, "\\2\\1ay")
end
end
end
| 29.081081 | 99 | 0.6329 |
79464c8df5c69b71a0828fc2034665180c454c84 | 1,072 | ex | Elixir | benchmarks/bench.ex | NelsonVides/fast_pbkdf2 | 204c07f6373f6a09500b18b7b833582e55ba3ad9 | [
"Apache-2.0"
] | 7 | 2021-02-18T20:44:44.000Z | 2022-01-13T07:41:16.000Z | benchmarks/bench.ex | NelsonVides/fast_pbkdf2 | 204c07f6373f6a09500b18b7b833582e55ba3ad9 | [
"Apache-2.0"
] | null | null | null | benchmarks/bench.ex | NelsonVides/fast_pbkdf2 | 204c07f6373f6a09500b18b7b833582e55ba3ad9 | [
"Apache-2.0"
] | 2 | 2021-03-11T23:18:15.000Z | 2022-03-06T09:56:36.000Z | defmodule PBKDF2.Benchmarks do
def pbkdf2_input itCount do
password = :base64.encode(:crypto.strong_rand_bytes(10))
salt = :base64.encode(:crypto.strong_rand_bytes(16))
{password, salt, itCount}
end
def pbkdf2 {password, salt, it_count} do
:fast_pbkdf2.pbkdf2(:sha256, password, salt, it_count)
end
end
{:ok, :erl_pbkdf2} = :compile.file('./test/erl_pbkdf2.erl')
Benchee.run(
%{
"fast_pbkdf2" => fn {password, salt, it_count} ->
:fast_pbkdf2.pbkdf2(:sha256, password, salt, it_count)
end,
"erl_pbkdf2 " => fn {password, salt, it_count} ->
:erl_pbkdf2.pbkdf2_oneblock(:sha256, password, salt, it_count)
end
},
inputs: %{
"1. 8" => PBKDF2.Benchmarks.pbkdf2_input(8),
"2. 512" => PBKDF2.Benchmarks.pbkdf2_input(512),
"3. 4096" => PBKDF2.Benchmarks.pbkdf2_input(4096),
"4. 10000" => PBKDF2.Benchmarks.pbkdf2_input(10000),
"5. 160000" => PBKDF2.Benchmarks.pbkdf2_input(160000),
"6. 500000" => PBKDF2.Benchmarks.pbkdf2_input(500000)
},
parallel: 12,
time: 5,
memory_time: 5
)
| 28.972973 | 70 | 0.663246 |
79465e2ffee2152b2edd107249d33b980ffc5f92 | 4,322 | exs | Elixir | config/config.exs | theodowling/ex_mustang | 0bf0d96c0e33e8291eb4d911bfdcdc57902fa78d | [
"Apache-2.0"
] | 69 | 2016-08-17T06:50:58.000Z | 2021-01-26T00:43:34.000Z | config/config.exs | theodowling/ex_mustang | 0bf0d96c0e33e8291eb4d911bfdcdc57902fa78d | [
"Apache-2.0"
] | 55 | 2016-08-16T01:05:39.000Z | 2020-10-08T15:53:35.000Z | config/config.exs | theodowling/ex_mustang | 0bf0d96c0e33e8291eb4d911bfdcdc57902fa78d | [
"Apache-2.0"
] | 10 | 2017-01-20T19:45:43.000Z | 2020-09-30T20:32:23.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
config :ex_mustang, ExMustang.Responders.Standup,
time_of_day: "30 10 * * 1-5",
slack_channel: System.get_env("STANDUP_CHANNEL") || "general",
suffix: ["folks", "hackers", "peeps", "avengers"],
msg: "Standup time",
enabled: true
config :ex_mustang, ExMustang.Responders.Github,
repos: ["techgaun/ex_mustang"],
access_token: System.get_env("GITHUB_TOKEN"),
schedule: "0 8-21/3 * * 1-5",
slack_channel: System.get_env("GH_CHANNEL") || "general",
# no old than 3 hours
created_time_threshold: 10800,
# no old than 1 hour
updated_time_threshold: 3600,
enabled: true
config :ex_mustang, ExMustang.Responders.Quote,
quote_src: "files/quotes.txt",
schedule: "1 10 * * *",
slack_channel: System.get_env("QUOTE_CHANNEL") || "general",
enabled: true
config :ex_mustang, ExMustang.Responders.InviteAll,
slack_token: System.get_env("SLACK_INVITEALL_TOKEN")
config :ex_mustang, ExMustang.Responders.Pwned,
schedule: "59 23 */1 * *",
enabled: true,
accounts: [
"[email protected]",
"[email protected]"
],
slack_channel: System.get_env("PWN_CHANNEL") || "general"
config :ex_mustang, ExMustang.Responders.Uptime,
schedule: "*/5 * * * *",
enabled: true,
endpoints: [
[
uri: "https://api.brighterlink.io/status",
status_code: 200,
content: ~s("msg":"ok"),
method: "GET",
content_type: "application/json",
req_headers: [{"User-Agent", "ExMustang"}],
timeout: 20_000
]
],
slack_channel: System.get_env("UPTIME_CHANNEL") || "general"
config :ex_mustang, ExMustang.Responders.HerokuDeploy,
github_token: System.get_env("HEROKU_GITHUB_TOKEN") || System.get_env("GITHUB_TOKEN"),
token: System.get_env("HEROKU_TOKEN"),
apps: [
{"casa-core-stage", %{repo: "casaiq/core", branch: "master"}}
]
config :ex_mustang, ExMustang.Robot,
adapter: Hedwig.Adapters.Slack,
name: "mustang",
aka: "/",
token: System.get_env("SLACK_API_TOKEN"),
responders: [
{Hedwig.Responders.Help, []},
{ExMustang.Responders.GMap, []},
{ExMustang.Responders.Pwned, []},
{ExMustang.Responders.Quote, []},
{ExMustang.Responders.Slap, []},
{ExMustang.Responders.Time, []},
{ExMustang.Responders.TimeConvert, []},
{ExMustang.Responders.EncodeDecode, []},
{ExMustang.Responders.Isup, []},
{ExMustang.Responders.RandomInsult, []},
{ExMustang.Responders.HTTPCat, []},
{ExMustang.Responders.Howdoi, []},
{ExMustang.Responders.CommitMsg, []},
{ExMustang.Responders.CLIFu, []},
{ExMustang.Responders.Whois, []},
{ExMustang.Responders.GitTip, []},
{ExMustang.Responders.Birthday, []},
{ExMustang.Responders.HerokuDeploy, []},
{ExMustang.Responders.InviteAll, []},
{ExMustang.Responders.UrbanDictionary, []},
{ExMustang.Responders.ChuckMe, []},
{ExMustang.Responders.Giphy, []}
]
config :quantum, timezone: System.get_env("SYSTEM_TIME") || "America/Chicago"
config :ex_google,
api_key: System.get_env("GOOGLE_API_KEY"),
output: "json"
config :ex_mustang, ExMustang.Responders.Giphy, api_key: System.get_env("GIPHY_API_KEY")
# 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 :ex_mustang, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:ex_mustang, :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"
cfg_file = "#{Mix.env()}.exs"
if File.exists?("config/#{cfg_file}") do
import_config cfg_file
end
| 32.253731 | 88 | 0.696668 |
794683de8e6ea7fc1c068e2aed0cdf67b9025cda | 17,749 | ex | Elixir | lib/commanded/process_managers/process_router.ex | jwilger/commanded | 2d9950fd3ce76a23a3c410c99857b812f5705d66 | [
"MIT"
] | 1 | 2020-02-19T01:07:32.000Z | 2020-02-19T01:07:32.000Z | lib/commanded/process_managers/process_router.ex | jwilger/commanded | 2d9950fd3ce76a23a3c410c99857b812f5705d66 | [
"MIT"
] | null | null | null | lib/commanded/process_managers/process_router.ex | jwilger/commanded | 2d9950fd3ce76a23a3c410c99857b812f5705d66 | [
"MIT"
] | 1 | 2020-02-18T20:53:39.000Z | 2020-02-18T20:53:39.000Z | defmodule Commanded.ProcessManagers.ProcessRouter do
@moduledoc false
use GenServer
use Commanded.Registration
require Logger
alias Commanded.Event.Upcast
alias Commanded.EventStore
alias Commanded.EventStore.RecordedEvent
alias Commanded.ProcessManagers.FailureContext
alias Commanded.ProcessManagers.ProcessManagerInstance
alias Commanded.ProcessManagers.ProcessRouter
alias Commanded.ProcessManagers.Supervisor
alias Commanded.Subscriptions
defmodule State do
@moduledoc false
defstruct [
:application,
:consistency,
:event_timeout,
:idle_timeout,
:process_manager_name,
:process_manager_module,
:subscribe_from,
:supervisor,
:subscription,
:subscription_ref,
:last_seen_event,
:process_event_timer,
process_managers: %{},
pending_acks: %{},
pending_events: []
]
end
def start_link(application, process_name, process_module, opts \\ []) do
name = {application, ProcessRouter, process_name}
state = %State{
application: application,
process_manager_name: process_name,
process_manager_module: process_module,
consistency: Keyword.get(opts, :consistency, :eventual),
subscribe_from: Keyword.get(opts, :start_from, :origin),
event_timeout: Keyword.get(opts, :event_timeout),
idle_timeout: Keyword.get(opts, :idle_timeout, :infinity)
}
Registration.start_link(application, name, __MODULE__, state)
end
@impl GenServer
def init(%State{} = state) do
:ok = register_subscription(state)
{:ok, state, {:continue, :subscribe_to_events}}
end
# Acknowledge successful handling of the given event by a process manager instance.
def ack_event(process_router, %RecordedEvent{} = event, instance) do
GenServer.cast(process_router, {:ack_event, event, instance})
end
def process_instance(process_router, process_uuid) do
GenServer.call(process_router, {:process_instance, process_uuid})
end
def process_instances(process_router) do
GenServer.call(process_router, :process_instances)
end
@impl GenServer
def handle_continue(:subscribe_to_events, %State{} = state) do
{:noreply, subscribe_to_events(state)}
end
@impl GenServer
def handle_call(:process_instances, _from, %State{} = state) do
%State{process_managers: process_managers} = state
reply = Enum.map(process_managers, fn {process_uuid, pid} -> {process_uuid, pid} end)
{:reply, reply, state}
end
@impl GenServer
def handle_call({:process_instance, process_uuid}, _from, %State{} = state) do
reply = get_process_manager(state, process_uuid)
{:reply, reply, state}
end
@impl GenServer
def handle_cast({:ack_event, event, instance}, %State{} = state) do
%State{pending_acks: pending_acks} = state
%RecordedEvent{event_number: event_number} = event
state =
case pending_acks |> Map.get(event_number, []) |> List.delete(instance) do
[] ->
# Enqueue a message to continue processing any pending events
GenServer.cast(self(), :process_pending_events)
state = %State{state | pending_acks: Map.delete(pending_acks, event_number)}
# no pending acks so confirm receipt of event
confirm_receipt(event, state)
pending ->
# pending acks, don't ack event but wait for outstanding instances
%State{state | pending_acks: Map.put(pending_acks, event_number, pending)}
end
{:noreply, state}
end
@impl GenServer
def handle_cast(:process_pending_events, %State{pending_events: []} = state),
do: {:noreply, state}
@impl GenServer
def handle_cast(:process_pending_events, %State{} = state) do
%State{pending_events: [event | pending_events]} = state
case length(pending_events) do
0 ->
:ok
1 ->
Logger.debug(fn -> describe(state) <> " has 1 pending event to process" end)
count ->
Logger.debug(fn -> describe(state) <> " has #{count} pending events to process" end)
end
case handle_event(event, state) do
%State{} = state -> {:noreply, %State{state | pending_events: pending_events}}
reply -> reply
end
end
# Subscription to event store has successfully subscribed, init process router
@impl GenServer
def handle_info({:subscribed, subscription}, %State{subscription: subscription} = state) do
Logger.debug(fn -> describe(state) <> " has successfully subscribed to event store" end)
{:ok, supervisor} = Supervisor.start_link()
{:noreply, %State{state | supervisor: supervisor}}
end
@impl GenServer
def handle_info({:events, events}, %State{} = state) do
%State{pending_events: pending_events} = state
Logger.debug(fn -> describe(state) <> " received #{length(events)} event(s)" end)
# Exclude already seen events
unseen_events =
events
|> Enum.reject(&event_already_seen?(&1, state))
|> Upcast.upcast_event_stream()
state =
case {pending_events, unseen_events} do
{[], []} ->
# No pending or unseen events, so state is unmodified
state
{[], _} ->
# No pending events, but some unseen events so start processing them
GenServer.cast(self(), :process_pending_events)
%State{state | pending_events: unseen_events}
{_, _} ->
# Already processing pending events, append the unseen events so they are processed afterwards
%State{state | pending_events: pending_events ++ unseen_events}
end
{:noreply, state}
end
# Shutdown process manager when processing an event has taken too long.
@impl GenServer
def handle_info({:event_timeout, event_number}, %State{} = state) do
%State{pending_acks: pending_acks, event_timeout: event_timeout} = state
case Map.get(pending_acks, event_number, []) do
[] ->
{:noreply, state}
_pending ->
Logger.error(fn ->
describe(state) <>
" has taken longer than " <>
inspect(event_timeout) <>
"ms to process event #" <> inspect(event_number) <> " and is now stopping"
end)
{:stop, :event_timeout, state}
end
end
# Stop process manager when event store subscription process terminates.
@impl GenServer
def handle_info(
{:DOWN, ref, :process, pid, reason},
%State{subscription_ref: ref, subscription: pid} = state
) do
Logger.debug(fn -> describe(state) <> " subscription DOWN due to: #{inspect(reason)}" end)
{:stop, reason, state}
end
# Remove a process manager instance that has stopped with a normal exit reason.
@impl GenServer
def handle_info({:DOWN, _ref, :process, pid, :normal}, %State{} = state) do
%State{process_managers: process_managers} = state
state = %State{state | process_managers: remove_process_manager(process_managers, pid)}
{:noreply, state}
end
# Stop process router when a process manager instance terminates abnormally.
@impl GenServer
def handle_info({:DOWN, _ref, :process, _pid, reason}, %State{} = state) do
Logger.warn(fn -> describe(state) <> " is stopping due to: #{inspect(reason)}" end)
{:stop, reason, state}
end
# Register this process manager as a subscription with the given consistency.
defp register_subscription(%State{} = state) do
%State{application: application, consistency: consistency, process_manager_name: name} = state
Subscriptions.register(application, name, consistency)
end
defp subscribe_to_events(%State{} = state) do
%State{
application: application,
process_manager_name: process_manager_name,
subscribe_from: subscribe_from
} = state
{:ok, subscription} =
EventStore.subscribe_to(application, :all, process_manager_name, self(), subscribe_from)
subscription_ref = Process.monitor(subscription)
%State{state | subscription: subscription, subscription_ref: subscription_ref}
end
defp event_already_seen?(
%RecordedEvent{event_number: event_number},
%State{last_seen_event: last_seen_event}
) do
not is_nil(last_seen_event) and event_number <= last_seen_event
end
defp handle_event(%RecordedEvent{} = event, %State{} = state) do
%RecordedEvent{data: data} = event
%State{process_manager_module: process_manager_module} = state
try do
case process_manager_module.interested?(data) do
{:start, []} ->
ack_and_continue(event, state)
{:start, process_uuid} ->
Logger.debug(fn -> describe(state) <> " is interested in event " <> describe(event) end)
process_uuid
|> List.wrap()
|> Enum.reduce(state, fn process_uuid, state ->
{process_instance, state} = start_or_continue_process_manager(process_uuid, state)
delegate_event(process_instance, event, state)
end)
{:start!, []} ->
ack_and_continue(event, state)
{:start!, process_uuid} ->
Logger.debug(fn -> describe(state) <> " is interested in event " <> describe(event) end)
{state, process_instances} =
process_uuid
|> List.wrap()
|> Enum.reduce({state, []}, fn process_uuid, {state, process_instances} ->
{process_instance, state} = start_or_continue_process_manager(process_uuid, state)
if ProcessManagerInstance.new?(process_instance) do
{state, [process_instance | process_instances]}
else
error = {:error, {:start!, :process_already_started}}
reply = handle_routing_error(error, event, state)
throw(reply)
end
end)
process_instances
|> Enum.reverse()
|> Enum.reduce(state, &delegate_event(&1, event, &2))
{:continue, []} ->
ack_and_continue(event, state)
{:continue, process_uuid} ->
Logger.debug(fn -> describe(state) <> " is interested in event " <> describe(event) end)
process_uuid
|> List.wrap()
|> Enum.reduce(state, fn process_uuid, state ->
{process_instance, state} = start_or_continue_process_manager(process_uuid, state)
delegate_event(process_instance, event, state)
end)
{:continue!, []} ->
ack_and_continue(event, state)
{:continue!, process_uuid} ->
Logger.debug(fn -> describe(state) <> " is interested in event " <> describe(event) end)
{state, process_instances} =
process_uuid
|> List.wrap()
|> Enum.reduce({state, []}, fn process_uuid, {state, process_instances} ->
{process_instance, state} = start_or_continue_process_manager(process_uuid, state)
if ProcessManagerInstance.new?(process_instance) do
error = {:error, {:continue!, :process_not_started}}
reply = handle_routing_error(error, event, state)
throw(reply)
else
{state, [process_instance | process_instances]}
end
end)
process_instances
|> Enum.reverse()
|> Enum.reduce(state, &delegate_event(&1, event, &2))
{:stop, process_uuid} ->
Logger.debug(fn ->
describe(state) <> " has been stopped by event " <> describe(event)
end)
state =
process_uuid
|> List.wrap()
|> Enum.reduce(state, &stop_process_manager/2)
ack_and_continue(event, state)
false ->
Logger.debug(fn ->
describe(state) <> " is not interested in event " <> describe(event)
end)
ack_and_continue(event, state)
end
rescue
e -> handle_routing_error({:error, e}, event, state)
catch
reply -> reply
end
end
defp handle_routing_error(error, %RecordedEvent{} = failed_event, %State{} = state) do
%RecordedEvent{data: data} = failed_event
%State{process_manager_module: process_manager_module} = state
failure_context = %FailureContext{last_event: failed_event}
case process_manager_module.error(error, data, failure_context) do
:skip ->
# Skip the problematic event by confirming receipt
Logger.info(fn -> describe(state) <> " is skipping event" end)
ack_and_continue(failed_event, state)
{:stop, reason} ->
Logger.warn(fn -> describe(state) <> " has requested to stop: #{inspect(error)}" end)
{:stop, reason, state}
invalid ->
Logger.warn(fn ->
describe(state) <> " returned an invalid error response: #{inspect(invalid)}"
end)
{:stop, error, state}
end
end
# Continue processing any pending events and confirm receipt of the given event id
defp ack_and_continue(%RecordedEvent{} = event, %State{} = state) do
GenServer.cast(self(), :process_pending_events)
confirm_receipt(event, state)
end
# Confirm receipt of given event
defp confirm_receipt(%RecordedEvent{event_number: event_number} = event, %State{} = state) do
Logger.debug(fn ->
describe(state) <> " confirming receipt of event: #{inspect(event_number)}"
end)
do_ack_event(event, state)
%State{state | last_seen_event: event_number}
end
defp start_or_continue_process_manager(process_uuid, %State{} = state) do
case get_process_manager(state, process_uuid) do
{:ok, process_manager} ->
{process_manager, state}
{:error, :process_manager_not_found} ->
start_process_manager(process_uuid, state)
end
end
defp start_process_manager(process_uuid, %State{} = state) do
%State{
application: application,
idle_timeout: idle_timeout,
process_managers: process_managers,
process_manager_name: process_manager_name,
process_manager_module: process_manager_module,
supervisor: supervisor
} = state
opts = [
application: application,
idle_timeout: idle_timeout,
process_manager_name: process_manager_name,
process_manager_module: process_manager_module,
process_router: self(),
process_uuid: process_uuid
]
{:ok, process_manager} = Supervisor.start_process_manager(supervisor, opts)
_ref = Process.monitor(process_manager)
state = %State{
state
| process_managers: Map.put(process_managers, process_uuid, process_manager)
}
{process_manager, state}
end
defp stop_process_manager(process_uuid, %State{} = state) do
%State{process_managers: process_managers} = state
case get_process_manager(state, process_uuid) do
{:ok, process_manager} ->
:ok = ProcessManagerInstance.stop(process_manager)
%State{state | process_managers: Map.delete(process_managers, process_uuid)}
{:error, :process_manager_not_found} ->
state
end
end
defp remove_process_manager(process_managers, pid) do
Enum.reduce(process_managers, process_managers, fn
{process_uuid, process_manager_pid}, acc when process_manager_pid == pid ->
Map.delete(acc, process_uuid)
_, acc ->
acc
end)
end
defp get_process_manager(%State{} = state, process_uuid) do
%State{process_managers: process_managers} = state
case Map.get(process_managers, process_uuid) do
process_manager when is_pid(process_manager) -> {:ok, process_manager}
nil -> {:error, :process_manager_not_found}
end
end
defp do_ack_event(event, %State{} = state) do
%State{
application: application,
consistency: consistency,
process_manager_name: name,
subscription: subscription
} = state
:ok = EventStore.ack_event(application, subscription, event)
:ok = Subscriptions.ack_event(application, name, consistency, event)
end
# Delegate event to process instance who will ack event processing on success
defp delegate_event(process_instance, %RecordedEvent{} = event, %State{} = state) do
%State{pending_acks: pending_acks} = state
%RecordedEvent{event_number: event_number} = event
:ok = ProcessManagerInstance.process_event(process_instance, event)
pending_acks =
Map.update(pending_acks, event_number, [process_instance], fn
pending -> [process_instance | pending]
end)
state = %State{state | pending_acks: pending_acks}
start_event_timer(event_number, state)
end
# Event timeout not configured
defp start_event_timer(_event_number, %State{event_timeout: nil} = state), do: state
defp start_event_timer(event_number, %State{process_event_timer: process_event_timer} = state)
when is_reference(process_event_timer) do
Process.cancel_timer(process_event_timer)
state = %State{state | process_event_timer: nil}
start_event_timer(event_number, state)
end
defp start_event_timer(event_number, %State{event_timeout: event_timeout} = state)
when is_integer(event_timeout) do
%State{event_timeout: event_timeout} = state
process_event_timer =
Process.send_after(self(), {:event_timeout, event_number}, event_timeout)
%State{state | process_event_timer: process_event_timer}
end
defp describe(%State{process_manager_module: process_manager_module}),
do: inspect(process_manager_module)
defp describe(%RecordedEvent{} = event) do
%RecordedEvent{
event_number: event_number,
stream_id: stream_id,
stream_version: stream_version
} = event
"#{inspect(event_number)} (#{inspect(stream_id)}@#{inspect(stream_version)})"
end
end
| 31.581851 | 104 | 0.664544 |
7946b66c3383e0abb3224b75fd91cebfd9554fd1 | 407 | ex | Elixir | src/elixir/lib-util-db.ex | Yoosuke/GEOSPATIAL_Hackers_Program_Hands-on | 94b0eabc80315de761e4c68637c9fb3a9f1ee2d3 | [
"MIT"
] | null | null | null | src/elixir/lib-util-db.ex | Yoosuke/GEOSPATIAL_Hackers_Program_Hands-on | 94b0eabc80315de761e4c68637c9fb3a9f1ee2d3 | [
"MIT"
] | 1 | 2019-01-16T04:41:16.000Z | 2019-01-16T04:41:16.000Z | src/elixir/lib-util-db.ex | Yoosuke/GEOSPATIAL_Hackers_Program_Hands-on | 94b0eabc80315de761e4c68637c9fb3a9f1ee2d3 | [
"MIT"
] | 1 | 2019-01-16T04:58:34.000Z | 2019-01-16T04:58:34.000Z | defmodule Db do
def query( sql ) when sql != "" do
{ :ok, result } = Ecto.Adapters.SQL.query( Test.Repo , sql, [] )
result
end
def columns_rows( result ) do
result
|> rows
|> Enum.map( fn row -> Enum.into( List.zip( [ columns( result ), row ] ), %{} ) end )
end
def rows( %{ rows: rows } = _result ), do: rows
def columns( %{ columns: columns } = _result ), do: columns
end
| 29.071429 | 89 | 0.574939 |
7946bc97d5735caaf8784167ad3a93a03b0a95d1 | 19,910 | ex | Elixir | lib/nostrum/struct/channel.ex | brettkolodny/nostrum | 3e26af6c106558bfe3fd48dcf3064fbc361605b5 | [
"MIT"
] | null | null | null | lib/nostrum/struct/channel.ex | brettkolodny/nostrum | 3e26af6c106558bfe3fd48dcf3064fbc361605b5 | [
"MIT"
] | null | null | null | lib/nostrum/struct/channel.ex | brettkolodny/nostrum | 3e26af6c106558bfe3fd48dcf3064fbc361605b5 | [
"MIT"
] | 1 | 2021-09-13T20:59:42.000Z | 2021-09-13T20:59:42.000Z | defmodule Nostrum.Struct.Channel do
@moduledoc """
Struct and helper functions for working with channels.
## Channel Struct
The channel struct is used by Nostrum to represent a _Discord Channel Object_. More information can be found on the [Discord API Channel Documentation](https://discord.com/developers/docs/resources/channel#channels-resource).
The struct can have one of several forms depending on the type of channel. You can read more about the individual channel types [below](#module-channel-types).
A typical channel would appear as:
```elixir
%Nostrum.Struct.Channel{
guild_id: 766435015768539156,
id: 827333533688397865,
name: "announcements",
nsfw: false,
permission_overwrites: [],
position: 1,
type: 5,
}
```
The channel struct implements `String.Chars` protocol through the `mention/1` function. This example uses our channel from the previous code block.
```elixir
channel |> to_string()
"<#766435015768539156>"
```
## Channel Cache
The [`ChannelCache`](`Nostrum.Cache.ChannelCache`) module provides functionality for you to retreive information about any channel that your application can see. It provides two functions: [`get/1`](`Nostrum.Cache.ChannelCache.get/1`) and [`get!/1`](`Nostrum.Cache.ChannelCache.get!/1`).
## Example
```elixir
Nostrum.Cache.ChannelCache.get!(827333533688397865)
%Nostrum.Struct.Channel{
application_id: nil,
bitrate: nil,
guild_id: 766435015768539156,
icon: nil,
id: 827333533688397865,
last_message_id: nil,
last_pin_timestamp: nil,
name: "announcements",
nsfw: false,
owner_id: nil,
parent_id: nil,
permission_overwrites: [
%Nostrum.Struct.Overwrite{
allow: 0,
deny: 2048,
id: 766435015768539156,
type: :role
}
],
position: 1,
recipients: nil,
topic: nil,
type: 5,
user_limit: nil
}
```
More details of the cache can be found at `Nostrum.Cache.ChannelCache`.
## Helper Functions
This module contains two functions for assisting with channel structs. `mention/1` to convert the channel into a mention as a string, and `link/1` to convert the channel into a hyperlink as a string. Further details and examples are detailed in the [Functions section of this module.](#functions)
## Api Functions
The Nostrum Api contains numerous functions related to channels. Notable functions relating to channels are shown below.
- `Nostrum.Api.create_guild_channel/2`
- `Nostrum.Api.get_channel/1`
- `Nostrum.Api.modify_channel/3`
- `Nostrum.Api.delete_channel/2`
- `Nostrum.Api.add_pinned_channel_message/2`
- `Nostrum.Api.create_channel_invite/3`
- `Nostrum.Api.get_guild_channels/1`
- `Nostrum.Api.modify_guild_channel_positions/2`
> Note: This is not an exhaustive list, for full details please see the `Nostrum.Api` module documentation.
## Channel Types
Channels take the shape of various types depending on their use and not all fields are always used. The currently implemented channel types are detailed below. The type of channel is determined by the `:type` field.
This diagram represents the regular channel types `0`, `2`, `5` and `13`.

The currently implemented channel types are:
| |Channel Type | |
|---- |-------------------- |--------------------------------------------------------------- |
|`0` |[`GUILD_TEXT`](`t:guild_text_channel/0`) |_A text channel within a server_ |
|`1` |[`DM`](`t:dm_channel/0`) |_A direct message between users_ |
|`2` |[`GUILD_VOICE`](`t:guild_voice_channel/0`) |_A voice channel within a server_ |
|`3` |[`GROUP_DM`](`t:group_dm_channel/0`) |_A direct message between multiple users_ |
|`4` |[`GUILD_CATEGORY`](`t:guild_category_channel/0`) |_A category that contains up to 50 channels_ |
|`5` |[`GUILD_NEWS`](`t:guild_news_channel/0`) |_A channel that users can follow and crosspost_ |
|`6` |[`GUILD_STORE`](`t:guild_store_channel/0`) |_A channel to sell games on Discord_ |
|`10` |[`GUILD_NEWS_THREAD`](`t:guild_news_thread_channel/0`) |_A temporary sub-channel within a news channel_ |
|`11` |[`GUILD_PUBLIC_THREAD`](`t:guild_public_thread_channel/0`) |_A temporary sub-channel within a text channel_ |
|`12` |[`GUILD_PRIVATE_THREAD`](`t:guild_private_thread_channel/0`) |_A temporary private sub-channel within a text channel_ |
|`13` |[`GUILD_STAGE_VOICE`](`t:guild_stage_voice_channel/0`) |_A voice channel for hosting events with an audience_ |
More information about _Discord Channel Types_ can be found on the [Discord API Channel Type Documentation](https://discord.com/developers/docs/resources/channel#channel-object-channel-types).
"""
defimpl String.Chars do
@spec to_string(Nostrum.Struct.Channel.t()) :: String.t()
def to_string(channel), do: @for.mention(channel)
end
alias Nostrum.Struct.{Channel, Guild, Message, Overwrite, User}
alias Nostrum.{Snowflake, Util}
defstruct [
:id,
:type,
:guild_id,
:position,
:permission_overwrites,
:name,
:topic,
:nsfw,
:last_message_id,
:bitrate,
:user_limit,
:rate_limit_per_user,
:recipients,
:icon,
:owner_id,
:application_id,
:parent_id,
:last_pin_timestamp,
:rtc_region,
:video_quality_mode,
:message_count,
:member_count,
:thread_metadata,
:member,
:default_auto_archive_duration,
:permissions
]
@typedoc """
The id of the channel object.
"""
@type id :: Snowflake.t()
@typedoc """
The type of channel.
More information about _Discord Channel Types_ can be found under the [`types`](#module-channel-types) on the [Discord API Channel Type Documentation](https://discord.com/developers/docs/resources/channel#channel-object-channel-types).
"""
@type type :: integer()
@typedoc """
The id of the guild the channel is located in.
"""
@type guild_id :: Guild.id()
@typedoc """
The position of the channel in the sidebar of the guild.
"""
@type position :: integer()
@typedoc """
A list of permission overwrites applied to the channel.
"""
@type permission_overwrites :: [Overwrite.t()]
@typedoc """
The name of the channel.
"""
@type name :: String.t()
@typedoc """
The topic of the channel.
"""
@type topic :: String.t()
@typedoc """
Whether the NSFW setting is enabled for this channel.
"""
@type nsfw :: boolean()
@typedoc """
The id of the last message sent in the channel.
"""
@type last_message_id :: Message.id() | nil
@typedoc """
The bitate of the voice channel.
"""
@type bitrate :: integer()
@typedoc """
The users rate limit.
Amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages or manage_channel, are unaffected
"""
@typedoc since: "0.5"
@type rate_limit_per_user :: integer() | nil
@typedoc """
The user limit of a voice channel.
"""
@type user_limit :: integer()
@typedoc """
A list of users in a group DM.
"""
@type recipients :: [User.t()]
@typedoc """
The hash of the channels icon.
"""
@type icon :: String.t() | nil
@typedoc """
The id of the user of a group direct message or thread.
This applies to user created channels.
"""
@type owner_id :: User.id()
@typedoc """
The id of the application that created a group direct message or thread.
This applies to bot created channels.
"""
@type application_id :: Snowflake.t() | nil
@typedoc """
The id of the parent channel that this channel is located under.
For threads, that is the channel that contains the thread. For regular channels, it is the category that the channel is located under.
"""
@type parent_id :: Channel.id() | nil
@typedoc """
Timestamp for the last pinned message.
"""
@type last_pin_timestamp :: DateTime.t() | nil
@typedoc """
Region id for the channel.
More information about _region ids_ can be found on the [Discord API Voice Region Object Documentation](https://discord.com/developers/docs/resources/voice#voice-region-object).
"""
@typedoc since: "0.5"
@type rtc_region :: String.t() | nil
@typedoc """
The video quality mode of the channel.
More information about _video quality modes_ can be found on the [Discord API Video Quality Mode Documentation](https://discord.com/developers/docs/resources/channel#channel-object-video-quality-modes).
"""
@typedoc since: "0.5"
@type video_quality_mode :: integer() | nil
@typedoc """
Approximate count of messages in a thread, capped at 50.
"""
@typedoc since: "0.5"
@type message_count :: integer() | nil
@typedoc """
Approximate count of members in a thread, capped at 50.
"""
@typedoc since: "0.5"
@type member_count :: integer() | nil
@typedoc """
The video quality mode of the voice channel.
More information about _video quality modes_ can be found on the [Discord API Video Quality Mode Documentation](https://discord.com/developers/docs/resources/channel#channel-object-video-quality-modes).
"""
@typedoc since: "0.5"
@type thread_metadata :: %{
archived: archived,
auto_archive_duration: auto_archive_duration,
archive_timestamp: archive_timestamp,
locked: boolean()
}
@typedoc """
When the thread was archived.
"""
@typedoc since: "0.5"
@type archive_timestamp :: DateTime.t() | nil
@typedoc """
The threads locked status.
"""
@typedoc since: "0.5"
@type locked :: boolean()
@typedoc """
The threads archived status.
"""
@typedoc since: "0.5"
@type archived :: boolean()
@typedoc """
Archive duration for the thread in minutes.
- 60, 1 hour
- 1440, 24 hours
- 4320, 3 days
- 10080, 7 days
"""
@typedoc since: "0.5"
@type auto_archive_duration :: integer()
@typedoc """
Present when the bot joins a thread.
Note: This is omitted on threads that the bot can immediately access on `:GUILD_CREATE` events received.
"""
@typedoc since: "0.5"
@type member :: %{
id: id,
user_id: user_id,
join_timestamp: join_timestamp,
flags: flags
}
@typedoc """
User id of the threads creator.
"""
@typedoc since: "0.5"
@type user_id :: Snowflake.t() | nil
@typedoc """
When the user joined the thread.
"""
@typedoc since: "0.5"
@type join_timestamp :: DateTime.t()
@typedoc """
User thread settings, currently only used for notifications.
"""
@typedoc since: "0.5"
@type flags :: integer()
@typedoc """
Default duration for newly created threads in minutes.
- 60, 1 hour
- 1440, 24 hours
- 4320, 3 days
- 10080, 7 days
"""
@typedoc since: "0.5"
@type default_auto_archive_duration :: integer()
@typedoc """
Computed permissions of the invoking user.
Permissions for the invoking user in the channel, including overwrites, only included when part of the resolved data received on a slash command interaction
"""
@typedoc since: "0.5"
@type permissions :: String.t()
@typedoc """
Type 0 partial channel object representing a text channel within a guild.
"""
@type guild_text_channel :: %__MODULE__{
id: id,
guild_id: guild_id,
name: name,
type: type,
position: position,
permission_overwrites: permission_overwrites,
rate_limit_per_user: rate_limit_per_user,
nsfw: nsfw,
topic: topic,
last_message_id: last_message_id,
parent_id: parent_id,
default_auto_archive_duration: default_auto_archive_duration
}
@typedoc """
Type 1 partial channel object representing a direct message.
"""
@type dm_channel :: %__MODULE__{
id: id,
type: 1,
last_message_id: last_message_id,
recipients: recipients,
last_pin_timestamp: last_pin_timestamp
}
@typedoc """
Type 2 partial channel object representing an audio channel within a guild.
"""
@type guild_voice_channel :: %__MODULE__{
id: id,
type: 2,
guild_id: guild_id,
position: position,
permission_overwrites: permission_overwrites,
name: name,
nsfw: nsfw,
bitrate: bitrate,
user_limit: user_limit,
parent_id: parent_id,
rtc_region: rtc_region
}
@typedoc """
Type 3 partial channel object representing a group direct message.
"""
@type group_dm_channel :: %__MODULE__{
id: id,
type: 3,
name: name,
last_message_id: last_message_id,
recipients: recipients,
icon: icon,
owner_id: owner_id,
application_id: application_id
}
@typedoc """
Type 4 partial channel object representing a channel category.
> Note: Other channels `parent_id` field refers to this type of object.
"""
@type guild_category_channel :: %__MODULE__{
id: id,
type: 4,
guild_id: guild_id,
position: position,
permission_overwrites: permission_overwrites,
name: name,
nsfw: nsfw,
parent_id: parent_id
}
@typedoc """
Type 5 partial channel object representing a news channel.
"""
@typedoc since: "0.5"
@type guild_news_channel :: %__MODULE__{
id: id,
type: 5,
guild_id: guild_id,
name: name,
position: position,
permission_overwrites: permission_overwrites,
nsfw: nsfw,
topic: topic,
last_message_id: last_message_id,
parent_id: parent_id,
default_auto_archive_duration: default_auto_archive_duration
}
@typedoc """
Type 6 partial channel object representing a store channel.
"""
@typedoc since: "0.5"
@type guild_store_channel :: %__MODULE__{
id: id,
guild_id: guild_id,
name: name,
type: type,
position: position,
permission_overwrites: permission_overwrites,
nsfw: nsfw,
parent_id: parent_id
}
@typedoc """
Type 10 partial channel object representing a news thread.
"""
@typedoc since: "0.5"
@type guild_news_thread_channel :: %__MODULE__{
id: id,
guild_id: guild_id,
parent_id: parent_id,
owner_id: owner_id,
name: name,
type: type,
last_message_id: last_message_id,
message_count: message_count,
member_count: member_count,
rate_limit_per_user: rate_limit_per_user,
thread_metadata: thread_metadata
}
@typedoc """
Type 11 partial channel object representing a standard thread.
"""
@typedoc since: "0.5"
@type guild_public_thread_channel :: %__MODULE__{
id: id,
guild_id: guild_id,
parent_id: parent_id,
owner_id: owner_id,
name: name,
type: type,
last_message_id: last_message_id,
message_count: message_count,
member_count: member_count,
rate_limit_per_user: rate_limit_per_user,
thread_metadata: thread_metadata
}
@typedoc """
Type 12 partial channel object representing a private thread.
"""
@typedoc since: "0.5"
@type guild_private_thread_channel :: %__MODULE__{
id: id,
guild_id: guild_id,
parent_id: parent_id,
owner_id: owner_id,
name: name,
type: type,
last_message_id: last_message_id,
message_count: message_count,
member_count: member_count,
rate_limit_per_user: rate_limit_per_user,
thread_metadata: thread_metadata
}
@typedoc """
Type 13 channel object representing a stage channel.
"""
@typedoc since: "0.5"
@type guild_stage_voice_channel :: %__MODULE__{
id: id,
guild_id: guild_id,
parent_id: parent_id,
owner_id: owner_id,
name: name,
type: type,
last_message_id: last_message_id,
message_count: message_count,
member_count: member_count,
rate_limit_per_user: rate_limit_per_user,
thread_metadata: thread_metadata
}
@typedoc """
A partial channel object representing a channel mention.
More information about the _Discord Channel Mention Object_ can be found at the [Discord API Channel Mention Object
Documentation](https://discord.com/developers/docs/resources/channel#channel-mention-object).
"""
@type channel_mention :: %__MODULE__{
id: id,
guild_id: guild_id,
type: type,
name: name
}
@typedoc """
Guild channel types
"""
@typedoc deprecated: "See t.0"
@type guild_channel ::
guild_text_channel
| guild_voice_channel
| guild_category_channel
@typedoc """
All valid text channels.
"""
@typedoc deprecated: "See t.0"
@type text_channel ::
guild_text_channel
| dm_channel
| group_dm_channel
@typedoc """
A `Nostrum.Struct.Channel` that represents a voice channel
"""
@typedoc deprecated: "See t:guild_voice_channel/0"
@type voice_channel :: guild_voice_channel
@typedoc """
All valid channel types.
"""
@type t ::
guild_text_channel
| dm_channel
| guild_voice_channel
| group_dm_channel
| guild_category_channel
| guild_news_channel
| guild_store_channel
| guild_news_thread_channel
| guild_public_thread_channel
| guild_private_thread_channel
| guild_stage_voice_channel
@doc """
Convert a channel into a mention.
Handles the conversion of a `Nostrum.Struct.Channel` into the required format to _mention_ the channel within a message. Mentioning the channel will provide a clickable link to take the user to the channel.
## Parameters
- channel: `t:Nostrum.Struct.Channel.t/0`
## Examples
```elixir
Nostrum.Cache.ChannelCache.get(381889573426429952)
|> Nostrum.Struct.Channel.mention()
"<#381889573426429952>"
```
"""
@spec mention(t) :: String.t()
def mention(%__MODULE__{id: id}), do: "<##{id}>"
@doc false
def to_struct(map) do
new =
map
|> Map.new(fn {k, v} -> {Util.maybe_to_atom(k), v} end)
|> Map.update(:id, nil, &Util.cast(&1, Snowflake))
|> Map.update(:guild_id, nil, &Util.cast(&1, Snowflake))
|> Map.update(:permission_overwrites, nil, &Util.cast(&1, {:list, {:struct, Overwrite}}))
|> Map.update(:last_message_id, nil, &Util.cast(&1, Snowflake))
|> Map.update(:recipients, nil, &Util.cast(&1, {:list, {:struct, User}}))
|> Map.update(:owner_id, nil, &Util.cast(&1, Snowflake))
|> Map.update(:application_id, nil, &Util.cast(&1, Snowflake))
|> Map.update(:parent_id, nil, &Util.cast(&1, Snowflake))
|> Map.update(:last_pin_timestamp, nil, &Util.maybe_to_datetime/1)
|> Map.update(:archive_timestamp, nil, &Util.maybe_to_datetime/1)
|> Map.update(:join_timestamp, nil, &Util.maybe_to_datetime/1)
struct(__MODULE__, new)
end
end
| 30.630769 | 298 | 0.633752 |
7946d2b637f0f54c41a4a07db5c6f7a5e0785dda | 831 | exs | Elixir | code/spawn/spawn4.exs | alvarocamillont/introdu-o_elixir | 1d72d4f4b01d9312c4b066ce3c0fe8d9bfaaade1 | [
"MIT"
] | null | null | null | code/spawn/spawn4.exs | alvarocamillont/introdu-o_elixir | 1d72d4f4b01d9312c4b066ce3c0fe8d9bfaaade1 | [
"MIT"
] | 1 | 2021-03-09T16:27:25.000Z | 2021-03-09T16:27:25.000Z | programming-elixir-book/code/spawn/spawn4.exs | jordanhubbard/elixir-projects | dee341d672e83a45a17a4a85abd54a480f95c506 | [
"BSD-2-Clause"
] | null | null | null | #---
# Excerpted from "Programming Elixir ≥ 1.6",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/elixir16 for more book information.
#---
defmodule Spawn4 do
def greet do
receive do
{sender, msg} ->
send sender, { :ok, "Hello, #{msg}" }
greet()
end
end
end
# here's a client
pid = spawn(Spawn4, :greet, [])
send pid, {self(), "World!"}
receive do
{:ok, message} ->
IO.puts message
end
send pid, {self(), "Kermit!"}
receive do
{:ok, message} ->
IO.puts message
after 500 ->
IO.puts "The greeter has gone away"
end
| 23.742857 | 85 | 0.655836 |
7946fb50bc3053a58b88f4c0dc7dd00ef69324c2 | 88 | exs | Elixir | test/battleships_web/views/page_view_test.exs | alexander-lazarov/battleships | e35fcb1fc48281881f2976cd7ec8cf7a6cb1f707 | [
"MIT"
] | null | null | null | test/battleships_web/views/page_view_test.exs | alexander-lazarov/battleships | e35fcb1fc48281881f2976cd7ec8cf7a6cb1f707 | [
"MIT"
] | 2 | 2020-07-17T13:59:03.000Z | 2021-05-09T20:35:32.000Z | test/battleships_web/views/page_view_test.exs | alexander-lazarov/battleships | e35fcb1fc48281881f2976cd7ec8cf7a6cb1f707 | [
"MIT"
] | null | null | null | defmodule BattleshipsWeb.PageViewTest do
use BattleshipsWeb.ConnCase, async: true
end
| 22 | 42 | 0.840909 |
794700bb8087caeecd5f6912b54c00673eecf059 | 8,119 | ex | Elixir | lib/prom_ex/plugins/plug_cowboy.ex | dvic/prom_ex | 36cd5e0850e3e1ccc369011fbd15d5b442024a1e | [
"MIT"
] | 1 | 2022-02-20T10:42:44.000Z | 2022-02-20T10:42:44.000Z | lib/prom_ex/plugins/plug_cowboy.ex | dvic/prom_ex | 36cd5e0850e3e1ccc369011fbd15d5b442024a1e | [
"MIT"
] | null | null | null | lib/prom_ex/plugins/plug_cowboy.ex | dvic/prom_ex | 36cd5e0850e3e1ccc369011fbd15d5b442024a1e | [
"MIT"
] | null | null | null | if Code.ensure_loaded?(Plug.Cowboy) do
defmodule PromEx.Plugins.PlugCowboy do
@moduledoc """
This plugin captures HTTP request metrics emitted by Plug.Cowboy.
This plugin exposes the following metric group:
- `:plug_cowboy_http_event_metrics`
## Plugin options
- `routers`: **Required** This is a list with the full module names of your Routers (e.g MyAppWeb.Router).
Phoenix and Plug routers are supported. When the Phoenix dependency is present in your project, a list of Phoenix Routers is expected. Otherwise a list of Plug.Router modules must be provided
- `event_prefix`: **Optional**, allows you to set the event prefix for the Telemetry events.
- `metric_prefix`: This option is OPTIONAL and is used to override the default metric prefix of
`[otp_app, :prom_ex, :plug_cowboy]`. If this changes you will also want to set `plug_cowboy_metric_prefix`
in your `dashboard_assigns` to the snakecase version of your prefix, the default
`plug_cowboy_metric_prefix` is `{otp_app}_prom_ex_plug_cowboy`.
To use plugin in your application, add the following to your PromEx module:
```
defmodule WebApp.PromEx do
use PromEx, otp_app: :web_app
@impl true
def plugins do
[
...
{PromEx.Plugins.PlugCowboy, routers: [MyApp.Router]}
]
end
@impl true
def dashboards do
[
...
{:prom_ex, "plug_cowboy.json"}
]
end
end
```
To ignore certain paths, pass a list of routes using the `:ignore_routes` option
```
defmodule WebApp.PromEx do
use PromEx, otp_app: :web_app
@impl true
def plugins do
[
...
{PromEx.Plugins.PlugCowboy, routers: [MyApp.Router], ignore_routes: ["/metrics"]}
]
end
@impl true
def dashboards do
[
...
{:prom_ex, "plug_cowboy.json"}
]
end
end
```
"""
use PromEx.Plugin
require Logger
# alias Plug.Cowboy.Conn
@default_route "Unknown"
@impl true
def event_metrics(opts) do
otp_app = Keyword.fetch!(opts, :otp_app)
metric_prefix = Keyword.get(opts, :metric_prefix, PromEx.metric_prefix(otp_app, :plug_cowboy))
[
http_events(metric_prefix, opts)
]
end
defp http_events(metric_prefix, opts) do
# Shared configuration
cowboy_stop_event = [:cowboy, :request, :stop]
http_metrics_tags = [:status, :method, :path]
ignore_routes =
opts
|> Keyword.get(:ignore_routes, [])
|> MapSet.new()
routers =
opts
|> Keyword.fetch!(:routers)
|> MapSet.new()
Event.build(
:plug_cowboy_http_event_metrics,
[
# Capture request duration information
distribution(
metric_prefix ++ [:http, :request, :duration, :milliseconds],
event_name: cowboy_stop_event,
measurement: :duration,
description: "The time it takes for the application to process HTTP requests.",
reporter_options: [
buckets: [10, 100, 500, 1_000, 5_000, 10_000, 30_000]
],
drop: drop_ignored(ignore_routes),
tag_values: &get_tags(&1, routers),
tags: http_metrics_tags,
unit: {:native, :millisecond}
),
distribution(
metric_prefix ++ [:http, :response, :duration, :milliseconds],
event_name: cowboy_stop_event,
measurement: :resp_duration,
description: "The time it takes for the application to send the HTTP response.",
reporter_options: [
buckets: [10, 100, 500, 1_000, 5_000, 10_000, 30_000]
],
drop: drop_ignored(ignore_routes),
tag_values: &get_tags(&1, routers),
tags: http_metrics_tags,
unit: {:native, :millisecond}
),
distribution(
metric_prefix ++ [:http, :request_body, :duration, :milliseconds],
event_name: cowboy_stop_event,
measurement: :req_body_duration,
description: "The time it takes for the application to receive the HTTP request body.",
reporter_options: [
buckets: [10, 100, 500, 1_000, 5_000, 10_000, 30_000]
],
drop: drop_ignored(ignore_routes),
tag_values: &get_tags(&1, routers),
tags: http_metrics_tags,
unit: {:native, :millisecond}
),
# Capture response payload size information
distribution(
metric_prefix ++ [:http, :response, :size, :bytes],
event_name: cowboy_stop_event,
measurement: :resp_body_length,
description: "The size of the HTTP response payload.",
reporter_options: [
buckets: [64, 512, 4_096, 65_536, 262_144, 1_048_576, 4_194_304, 16_777_216]
],
drop: drop_ignored(ignore_routes),
tag_values: &get_tags(&1, routers),
tags: http_metrics_tags,
unit: :byte
),
# Capture the number of requests that have been serviced
counter(
metric_prefix ++ [:http, :requests, :total],
event_name: cowboy_stop_event,
description: "The number of requests that have been serviced.",
drop: drop_ignored(ignore_routes),
tag_values: &get_tags(&1, routers),
tags: http_metrics_tags
)
]
)
end
defp get_tags(%{resp_status: resp_status, req: %{method: method} = req}, routers) do
case get_http_status(resp_status) do
status when is_binary(status) ->
%{
status: status,
method: method,
path: maybe_get_parametrized_path(req, routers)
}
:undefined ->
%{
status: :undefined,
method: method,
path: maybe_get_parametrized_path(req, routers)
}
nil ->
Logger.warn("Cowboy failed to provide valid response status #{inspect(resp_status)}")
%{}
end
end
defp maybe_get_parametrized_path(req, routers) do
# credo:disable-for-next-line
cond do
Code.ensure_loaded?(Phoenix) ->
find_phoenix_route(routers, req)
# TODO: This needs to be further investigated to see how the normalized route can be extracted
# Code.ensure_loaded?(Plug.Router) ->
# find_plug_route(routers, req)
true ->
@default_route
end
end
defp find_phoenix_route(routers, %{method: method, path: path}) do
routers
|> Enum.find_value(@default_route, fn router ->
case Phoenix.Router.route_info(router, method, path, "") do
:error ->
false
%{route: route} ->
route
end
end)
end
# defp find_plug_route(routers, req) do
# conn = Conn.conn(req)
#
# routers
# |> Enum.find_value(@default_route, fn router ->
# case router.call(conn, []) do
# %{private: %{plug_route: {route, _fn}}} -> route
# _ -> false
# end
# end)
# end
defp get_http_status(resp_status) when is_integer(resp_status) do
to_string(resp_status)
end
defp get_http_status(resp_status) when is_bitstring(resp_status) do
[code | _rest] = String.split(resp_status)
code
end
defp get_http_status(nil) do
nil
end
defp get_http_status(_resp_status) do
:undefined
end
defp drop_ignored(ignored_routes) do
fn
%{req: %{path: path}} ->
ignored_routes
|> MapSet.member?(path)
_meta ->
false
end
end
end
else
defmodule PromEx.Plugins.PlugCowboy do
@moduledoc false
use PromEx.Plugin
@impl true
def event_metrics(_opts) do
PromEx.Plugin.no_dep_raise(__MODULE__, "Plug.Cowboy")
end
end
end
| 29.205036 | 197 | 0.586033 |
79470ec50cf553a71af772a9b255796593fdf5a2 | 138 | exs | Elixir | test/board_test.exs | infiniteNIL/exgopigo | 01599e3ef367f378d9263d1fbab211f5f6502315 | [
"MIT"
] | 5 | 2015-05-30T23:51:26.000Z | 2016-05-05T21:10:48.000Z | test/board_test.exs | infiniteNIL/exgopigo | 01599e3ef367f378d9263d1fbab211f5f6502315 | [
"MIT"
] | null | null | null | test/board_test.exs | infiniteNIL/exgopigo | 01599e3ef367f378d9263d1fbab211f5f6502315 | [
"MIT"
] | null | null | null | defmodule BoardTest do
use ExUnit.Case
alias ExGoPiGo.Board
test "Can initialize the board" do
assert Board.init() != nil
end
end | 13.8 | 35 | 0.73913 |
794729c484a6fe8dc29cb18a8ed135b01544f5a7 | 2,156 | exs | Elixir | bench/builder/attribute_bench.exs | gamesrol/ja_serializer | c48d8fb0fb742bd96c30acd40e24f7395f25af2c | [
"Apache-2.0"
] | null | null | null | bench/builder/attribute_bench.exs | gamesrol/ja_serializer | c48d8fb0fb742bd96c30acd40e24f7395f25af2c | [
"Apache-2.0"
] | null | null | null | bench/builder/attribute_bench.exs | gamesrol/ja_serializer | c48d8fb0fb742bd96c30acd40e24f7395f25af2c | [
"Apache-2.0"
] | null | null | null | defmodule Builder.AttributeBench do
use Benchfella
@big 1..20
|> Enum.map(&{String.to_atom("key_#{&1}"), &1})
|> Enum.into(%{})
@small 1..5
|> Enum.map(&{String.to_atom("key_#{&1}"), &1})
|> Enum.into(%{})
bench "no opts to process small data",
[context: data_no_opts(@small)],
do: JaSerializer.Builder.Attribute.build(context)
bench "no opts to process big data",
[context: data_no_opts(@big)],
do: JaSerializer.Builder.Attribute.build(context)
bench "no field opts to process small data",
[context: data_opts(@small)],
do: JaSerializer.Builder.Attribute.build(context)
bench "no field opts to process big data",
[context: data_opts(@big)],
do: JaSerializer.Builder.Attribute.build(context)
bench "field opts for wrong serializer small data",
[context: data_opts(@small, fields: %{"seabass"=>"fin,scale"})],
do: JaSerializer.Builder.Attribute.build(context)
bench "field opts for wrong serializer big data",
[context: data_opts(@big, fields: %{"seabass"=>"fin,scale"})],
do: JaSerializer.Builder.Attribute.build(context)
bench "fields opts for correct serializer small data",
[context: data_opts(@small, fields: %{"widget"=>"key_1,key_5"})],
do: JaSerializer.Builder.Attribute.build(context)
bench "fields opts for correct serializer big data",
[context: data_opts(@small, fields: %{"widget"=>"key_1,key_5"})],
do: JaSerializer.Builder.Attribute.build(context)
bench "optimized opts for correct serializer small data",
[context: data_opts(@small, fields: %{"widget"=>[:key_2, :key_8]})],
do: JaSerializer.Builder.Attribute.build(context)
bench "optimized opts for correct serializer big data",
[context: data_opts(@big, fields: %{"widget"=>[:key_2, :key_8]})],
do: JaSerializer.Builder.Attribute.build(context)
defmodule Serializer do
def type, do: "widget"
def attributes(data, _), do: data
end
defp data_no_opts(data),
do: %{data: data, serializer: Serializer, conn: nil}
defp data_opts(data, opts \\ []),
do: %{data: data, serializer: Serializer, conn: nil, opts: opts}
end
| 34.222222 | 72 | 0.673933 |
79476c77ab1e92ed379fc87ba0f0b541ddd13703 | 951 | exs | Elixir | config/config.exs | cabol/distcount | b0b42f66dcc130ec6e349ab8b915cfb6f5b77c7b | [
"MIT"
] | null | null | null | config/config.exs | cabol/distcount | b0b42f66dcc130ec6e349ab8b915cfb6f5b77c7b | [
"MIT"
] | null | null | null | config/config.exs | cabol/distcount | b0b42f66dcc130ec6e349ab8b915cfb6f5b77c7b | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
# General application configuration
import Config
config :distcount,
ecto_repos: [Distcount.Repo]
# Configures the endpoint
config :distcount, DistcountWeb.Endpoint,
url: [host: "localhost"],
render_errors: [view: DistcountWeb.ErrorView, accepts: ~w(json), layout: false],
pubsub_server: Distcount.PubSub,
live_view: [signing_salt: "cejkna/Y"]
# 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 "#{config_env()}.exs"
| 30.677419 | 82 | 0.763407 |
794770ea23de20b066b358431abd9daabca61399 | 401 | ex | Elixir | lib/exq/adapters/queue/mock.ex | onpointvn/exq | ee4db22624fb8a00ddc01c35a135e24de31b5a66 | [
"Apache-2.0"
] | 1,406 | 2015-01-16T03:00:32.000Z | 2022-03-28T11:38:22.000Z | lib/exq/adapters/queue/mock.ex | onpointvn/exq | ee4db22624fb8a00ddc01c35a135e24de31b5a66 | [
"Apache-2.0"
] | 372 | 2015-01-08T05:15:11.000Z | 2022-03-18T18:05:34.000Z | lib/exq/adapters/queue/mock.ex | onpointvn/exq | ee4db22624fb8a00ddc01c35a135e24de31b5a66 | [
"Apache-2.0"
] | 217 | 2015-02-01T20:21:36.000Z | 2022-01-28T16:19:55.000Z | defmodule Exq.Adapters.Queue.Mock do
@moduledoc """
Mock queue.
Designed to be used when testing your application.
"""
@behaviour Exq.Adapters.Queue
defdelegate enqueue(pid, queue, worker, args, options), to: Exq.Mock
defdelegate enqueue_at(pid, queue, time, worker, args, options), to: Exq.Mock
defdelegate enqueue_in(pid, queue, offset, worker, args, options), to: Exq.Mock
end
| 25.0625 | 81 | 0.725686 |
79477c255acaa9bb4fa70c03a122d1b40555dfb7 | 218 | ex | Elixir | lib/sanbase_web/admin/notifications/notification.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | 81 | 2017-11-20T01:20:22.000Z | 2022-03-05T12:04:25.000Z | lib/sanbase_web/admin/notifications/notification.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 359 | 2017-10-15T14:40:53.000Z | 2022-01-25T13:34:20.000Z | lib/sanbase_web/admin/notifications/notification.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | 16 | 2017-11-19T13:57:40.000Z | 2022-02-07T08:13:02.000Z | defmodule SanbaseWeb.ExAdmin.Notifications.Notification do
use ExAdmin.Register
register_resource Sanbase.Notifications.Notification do
show notification do
attributes_table(all: true)
end
end
end
| 21.8 | 58 | 0.788991 |
7947c0ea7360f6931feefa28862c62e536a612cd | 3,370 | ex | Elixir | apps/snitch_core/lib/core/data/schema/shipping_rules/shipping_rule.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 456 | 2018-09-20T02:40:59.000Z | 2022-03-07T08:53:48.000Z | apps/snitch_core/lib/core/data/schema/shipping_rules/shipping_rule.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 273 | 2018-09-19T06:43:43.000Z | 2021-08-07T12:58:26.000Z | apps/snitch_core/lib/core/data/schema/shipping_rules/shipping_rule.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 122 | 2018-09-26T16:32:46.000Z | 2022-03-13T11:44:19.000Z | defmodule Snitch.Data.Schema.ShippingRule do
@moduledoc """
Models the rules to be used while calculating shipping cost for
a shipping category.
"""
use Snitch.Data.Schema
alias Snitch.Data.Schema.{ShippingCategory, ShippingRuleIdentifier}
@type t :: %__MODULE__{}
@doc """
Returns the shipping cost applied.
Returns {:halt, Money.t()} if the shipping rule is of highest order
and the shipping rule overrides all other in a single run of
`Snitch.Domain.ShippingCalculator.calculate/1`.
Returns {:cont, Money.t()} if further rules can also be applied in a
single run of `Snitch.Domain.ShippingCalculator.calculate/1`.
The `prev_cost` field is overriden by the module adopting the
behaviour if the rule applies.
"""
@callback calculate(
package :: Package.t(),
currency_code :: atom(),
rule :: ShippingRule.t(),
prev_cost :: Money.t()
) ::
{:halt, cost :: Money.t()}
| {:cont, cost :: Money.t()}
schema "snitch_shipping_rules" do
field(:active?, :boolean, default: false)
field(:preferences, :map)
# associations
belongs_to(:shipping_rule_identifier, ShippingRuleIdentifier)
belongs_to(:shipping_category, ShippingCategory)
timestamps()
end
@required_fields ~w(shipping_rule_identifier_id shipping_category_id)a
@optional_fields ~w(active? preferences)a ++ @required_fields
def changeset(%__MODULE__{} = rule, params) do
rule
|> cast(params, @optional_fields)
|> validate_required(@required_fields)
|> validate_preference_with_target()
|> foreign_key_constraint(:shipping_rule_identifier_id)
|> foreign_key_constraint(:shipping_category_id)
|> unique_constraint(:unique_identifier_for_category,
name: :unique_rule_per_category_for_identifier
)
end
defp validate_preference_with_target(%Ecto.Changeset{valid?: true} = changeset) do
with {:ok, preferences} <- fetch_change(changeset, :preferences) do
module = get_preference_module(changeset)
preference_changeset = module.changeset(struct(module), preferences)
add_preferences_change(preference_changeset, changeset)
else
:error ->
changeset
end
end
defp validate_preference_with_target(changeset), do: changeset
defp add_preferences_change(%Ecto.Changeset{valid?: true} = pref_changeset, changeset) do
data = pref_changeset.changes
put_change(changeset, :preferences, data)
end
defp add_preferences_change(pref_changeset, changeset) do
message =
pref_changeset
|> traverse_errors(fn {msg, opts} ->
Enum.reduce(opts, msg, fn {key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end)
|> Enum.reduce("", fn {key, value}, acc ->
acc <> "#{key} #{value}. "
end)
add_error(changeset, :preferences, message)
end
defp get_preference_module(changeset) do
identifier_id =
with {:ok, id} <- fetch_change(changeset, :shipping_rule_identifier_id) do
id
else
:error ->
changeset.data.shipping_rule_identifier_id
end
identifier = Repo.get(ShippingRuleIdentifier, identifier_id)
identifiers = ShippingRuleIdentifier.identifier_with_module()
identifiers[identifier.code].module
end
end
| 30.636364 | 91 | 0.68724 |
7947cc5e5ccaea59e7ee5957d534d7dd764d564c | 777 | ex | Elixir | test/support/channel_case.ex | elixir-sea/typo_paint | 61183f0a450e62ce1f561635ed39965fc9fe770d | [
"CC-BY-4.0"
] | 4 | 2019-07-31T03:34:19.000Z | 2019-08-03T04:53:48.000Z | test/support/channel_case.ex | elixir-sea/typo_kart | 61183f0a450e62ce1f561635ed39965fc9fe770d | [
"CC-BY-4.0"
] | 3 | 2019-07-31T04:18:58.000Z | 2019-08-05T00:00:07.000Z | test/support/channel_case.ex | elixir-sea/typo_paint | 61183f0a450e62ce1f561635ed39965fc9fe770d | [
"CC-BY-4.0"
] | 3 | 2019-07-31T05:55:25.000Z | 2019-09-15T22:31:32.000Z | defmodule TypoPaintWeb.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
use Phoenix.ChannelTest
# The default endpoint for testing
@endpoint TypoPaintWeb.Endpoint
end
end
setup _tags do
:ok
end
end
| 24.28125 | 59 | 0.728443 |
7947cd29a80034abe503429179981c23549854b0 | 11,585 | ex | Elixir | lib/plugs/validate.ex | mogorman/openapivalidator | fa99180c73a06702b3abcb5101cbdd3d61bc5397 | [
"MIT"
] | 1 | 2019-10-18T15:33:44.000Z | 2019-10-18T15:33:44.000Z | lib/plugs/validate.ex | mogorman/openapivalidator | fa99180c73a06702b3abcb5101cbdd3d61bc5397 | [
"MIT"
] | null | null | null | lib/plugs/validate.ex | mogorman/openapivalidator | fa99180c73a06702b3abcb5101cbdd3d61bc5397 | [
"MIT"
] | null | null | null | defmodule OpenapiValidator.Plugs.Validate do
@moduledoc ~S"""
Validates input and output according to one or more OpenAPI specs.
Usage:
Add the plug at the bottom of one or more pipelines in `router.ex`:
pipeline "api" do
# ...
plug Api.Plugs.OASValidator, spec: Appcues.MobileApiSpecs.sdk()
end
"""
require Logger
import Plug.Conn
alias OpenapiValidator.Helpers.Errors
@behaviour Plug
@type path :: String.t()
@type path_regex :: {path, Regex.t()}
@type open_api_spec :: map()
@impl Plug
def init(%{specs: raw_specs} = opts) do
resolved_specs =
OpenapiValidator.compile_specs(raw_specs)
# set empty defaults for specs and paths just in case
Map.merge(opts, %{
paths: %{},
specs: %{},
all_paths_required: Map.get(opts, :all_paths_required, false),
custom_error: Map.get(opts, :custom_error, nil),
explain_error: Map.get(opts, :explain_error, true),
validate_params: Map.get(opts, :validate_params, true),
validate_body: Map.get(opts, :validate_body, true),
validate_response: Map.get(opts, :validate_response, true),
output_stubs: Map.get(opts, :output_stubs, false),
allow_invalid_input: Map.get(opts, :allow_invalid_input, false),
allow_invalid_output: Map.get(opts, :allow_invalid_output, false),
})
|> Map.merge(resolved_specs)
end
def init(_opts) do
Logger.error(
"#{inspect(__MODULE__)}: specs are required but were not provided."
)
nil
end
@impl Plug
def call(conn, opts) do
# if validate output
# Plug.Conn.register_before_send(conn, &HTML.minify_body/1)
{method, schema_url} = get_schema_url_from_request(conn)
schema = OpenapiValidator.find_schema({method, schema_url}, opts)
found_schema_body(conn, opts, {schema, method, schema_url})
end
defp error_handler(conn, opts, error, info) do
case Map.get(opts, :custom_error) do
nil ->
standard_error_handler(conn, opts, error, info)
custom ->
custom.error_handler(conn, opts, error, info)
end
end
defp standard_error_handler(conn, opts, error, info) do
message =
case Map.get(opts, :explain_error) do
true ->
Jason.encode!(Errors.get_stock_message(error, info))
false ->
""
end
conn
|> put_resp_header("content-type", "application/json")
|> resp(
Errors.get_stock_code(error),
message
)
|> halt()
end
defp found_schema_body(conn, opts, {schema, method, schema_url} = open_api)
when schema == %{} do
case Map.get(opts, :all_paths_required) do
true ->
Logger.info("No spec found for #{method}:#{schema_url}")
error_handler(conn, opts, :not_found, {method, schema_url, nil})
false ->
Logger.info("No spec found for #{method}:#{schema_url}")
conn
end
end
defp found_schema_body(conn, opts, {schema, method, schema_url} = open_api) do
case Map.get(opts, :validate_body) do
true ->
body_schema = get_body_fragment(open_api)
is_body_required = is_body_required?(open_api)
conn = conn |> Plug.Conn.fetch_query_params()
case attempt_validate_body(
body_schema,
is_body_required,
schema,
conn.body_params
) do
:ok ->
validated_body(conn, opts, open_api)
{false, errors} ->
invalid_body(conn, opts, errors, open_api)
end
false ->
validated_body(conn, opts, open_api)
end
end
defp validated_body(conn, opts, {schema, _method, _schema_url} = open_api) do
case Map.get(opts, :validate_params) do
true ->
params_schema = get_params_fragments_or_object(open_api)
conn = conn |> Plug.Conn.fetch_query_params()
case attempt_validate_params(params_schema, schema, conn) do
:ok ->
validated_params(conn, opts, open_api)
{false, errors} ->
invalid_params(conn, opts, errors, open_api)
end
false ->
validated_params(conn, opts, open_api)
end
end
defp validated_params(conn, opts, open_api) do
case Map.get(opts, :validate_response) do
true ->
Plug.Conn.register_before_send(conn, fn conn ->
validate_response(conn, Map.put(opts, :open_api, open_api))
end)
false ->
conn
end
end
def validate_response(conn, opts) do
open_api = Map.get(opts, :open_api, {nil, nil, nil})
{schema, method, schema_url} = open_api
fragment = get_response_fragment({schema, method, schema_url}, conn.status)
is_body_required = true
body =
case Jason.decode(conn.resp_body) do
{:ok, json} -> json
_ -> %{"error" => "invalid json"}
end
case attempt_validate_body(fragment, is_body_required, schema, body) do
:ok ->
conn
{false, errors} ->
case Map.get(opts, :allow_invalid_output) do
true ->
conn
false ->
error_handler(
conn,
opts,
:invalid_response,
{method, schema_url, %{body: body, errors: errors}}
)
end
end
end
defp invalid_body(conn, opts, errors, {schema, method, schema_url} = open_api) do
case Map.get(opts, :allow_invalid_input) do
true ->
Logger.info("Invalid request on #{method} #{schema_url}")
validated_body(conn, opts, open_api)
false ->
Logger.warn("Invalid request on #{method} #{schema_url}")
error_handler(conn, opts, :invalid_body, {method, schema_url, errors})
end
end
defp invalid_params(
conn,
opts,
errors,
{schema, method, schema_url} = open_api
) do
case Map.get(opts, :allow_invalid_input) do
true ->
Logger.info("Invalid request on #{method} #{schema_url}")
validated_params(conn, opts, open_api)
false ->
Logger.warn("Invalid request on #{method} #{schema_url}")
error_handler(conn, opts, :invalid_params, {method, schema_url, errors})
end
end
defp attempt_validate_body(false, _is_body_required, _schema, payload)
when payload == %{} do
:ok
end
defp attempt_validate_body(false, false, _schema, _payload) do
:ok
end
defp attempt_validate_body(false, _is_body_required, _schema, payload) do
{false, %{unmatched_payload: payload}}
end
defp attempt_validate_body(fragment, _is_body_required, schema, payload) do
case ExJsonSchema.Validator.validate_fragment(schema, fragment, payload) do
:ok ->
:ok
{:error, result} ->
name = String.split(fragment, "/") |> Enum.reverse() |> Enum.at(0)
{false, %{name: name, reason: result |> Map.new()}}
end
end
defp attempt_validate_params(false, schema, conn) do
:ok
end
defp attempt_validate_params([], schema, conn) do
:ok
end
defp attempt_validate_params(fragments, schema, conn) do
headers = conn.req_headers |> Map.new()
results =
Enum.map(
fragments,
fn item ->
fragment =
case is_binary(item) do
true -> ExJsonSchema.Schema.get_fragment!(schema, item)
false -> item
end
name = Map.get(fragment, "name")
fragment_schema = Map.get(fragment, "schema")
required = Map.get(fragment, "required", true)
input_data =
case Map.get(fragment, "in") do
"path" ->
Map.get(conn.path_params, name)
"query" ->
Map.get(conn.query_params, name)
"header" ->
Map.get(headers, name)
end
case is_nil(input_data) and required == false do
true ->
:ok
false ->
case ExJsonSchema.Validator.validate_fragment(
schema,
fragment_schema,
input_data
) do
:ok ->
:ok
{:error, reason} ->
%{name: name, reason: reason |> Map.new()}
end
end
end
)
|> Enum.reject(fn elem -> elem == :ok end)
case results do
[] ->
:ok
items ->
{false, items}
end
end
defp get_params_fragments_or_object({schema, method, schema_url}) do
method = String.downcase(method)
case ExJsonSchema.Schema.get_fragment(schema, [
:root,
"paths",
schema_url,
method,
"parameters",
]) do
{:error, _} ->
false
{:ok, result} ->
Enum.map(result, fn elem ->
case Map.get(elem, "$ref") do
nil ->
elem
ref ->
Enum.reduce(ref, "", fn sub_elem, acc ->
case sub_elem do
:root -> "#"
_ -> acc <> "/" <> sub_elem
end
end)
end
end)
end
end
defp is_body_required?({schema, method, schema_url}) do
method = String.downcase(method)
case ExJsonSchema.Schema.get_fragment(schema, [
:root,
"paths",
schema_url,
method,
"requestBody",
"required",
]) do
{:error, _} ->
true
{:ok, result} ->
result
end
end
defp get_body_fragment({schema, method, schema_url}) do
method = String.downcase(method)
case ExJsonSchema.Schema.get_fragment(schema, [
:root,
"paths",
schema_url,
method,
"requestBody",
"content",
"application/json",
"schema",
]) do
{:error, _} ->
false
{:ok, result} ->
case Map.get(result, "$ref") do
nil ->
result
ref ->
Enum.reduce(ref, "", fn sub_elem, acc ->
case sub_elem do
:root -> "#"
_ -> acc <> "/" <> sub_elem
end
end)
end
end
end
defp get_response_fragment({schema, method, schema_url}, response_code) do
method = String.downcase(method)
case ExJsonSchema.Schema.get_fragment(schema, [
:root,
"paths",
schema_url,
method,
"responses",
"#{response_code}",
"content",
"application/json",
"schema",
"$ref",
]) do
{:error, _} ->
false
{:ok, result} ->
Enum.reduce(result, "", fn elem, acc ->
case elem do
:root -> "#"
_ -> acc <> "/" <> elem
end
end)
end
end
defp get_schema_url_from_request(conn) do
router = (Map.get(conn, :private) || %{}) |> Map.get(:phoenix_router)
case router do
nil ->
{nil, nil}
_ ->
route =
Phoenix.Router.route_info(
router,
conn.method,
conn.request_path,
conn.host
)
schema_url =
Enum.reduce(route.path_params, route.route, fn {param, _value},
path ->
String.replace(path, ":#{param}", "{#{param}}")
end)
{conn.method, schema_url}
end
end
end
| 25.801782 | 83 | 0.552093 |
7947d74d54fcdce2bbd0e1c7c37b921b1e708ed7 | 1,135 | exs | Elixir | config/config.exs | dazzlerocks/absinthe_apollo_sockets | 675be982a28760fac1f61e8a4b6223c28298392e | [
"MIT"
] | 19 | 2018-09-24T19:55:31.000Z | 2021-12-12T20:46:17.000Z | config/config.exs | dazzlerocks/absinthe_apollo_sockets | 675be982a28760fac1f61e8a4b6223c28298392e | [
"MIT"
] | 8 | 2018-10-17T13:48:15.000Z | 2021-11-04T05:09:55.000Z | config/config.exs | dazzlerocks/absinthe_apollo_sockets | 675be982a28760fac1f61e8a4b6223c28298392e | [
"MIT"
] | 6 | 2018-10-11T13:59:25.000Z | 2022-02-14T14:04: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 your application as:
#
# config :apollo_socket, key: :value
#
# and access this configuration in your application as:
#
# Application.get_env(:apollo_socket, :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.612903 | 73 | 0.754185 |
7947ee2d81e170216ebcee61f13d3baccbdcead0 | 17,382 | ex | Elixir | lib/codes/codes_s26.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_s26.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_s26.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_S26 do
alias IcdCode.ICDCode
def _S2600XA do
%ICDCode{full_code: "S2600XA",
category_code: "S26",
short_code: "00XA",
full_name: "Unspecified injury of heart with hemopericardium, initial encounter",
short_name: "Unspecified injury of heart with hemopericardium, initial encounter",
category_name: "Unspecified injury of heart with hemopericardium, initial encounter"
}
end
def _S2600XD do
%ICDCode{full_code: "S2600XD",
category_code: "S26",
short_code: "00XD",
full_name: "Unspecified injury of heart with hemopericardium, subsequent encounter",
short_name: "Unspecified injury of heart with hemopericardium, subsequent encounter",
category_name: "Unspecified injury of heart with hemopericardium, subsequent encounter"
}
end
def _S2600XS do
%ICDCode{full_code: "S2600XS",
category_code: "S26",
short_code: "00XS",
full_name: "Unspecified injury of heart with hemopericardium, sequela",
short_name: "Unspecified injury of heart with hemopericardium, sequela",
category_name: "Unspecified injury of heart with hemopericardium, sequela"
}
end
def _S2601XA do
%ICDCode{full_code: "S2601XA",
category_code: "S26",
short_code: "01XA",
full_name: "Contusion of heart with hemopericardium, initial encounter",
short_name: "Contusion of heart with hemopericardium, initial encounter",
category_name: "Contusion of heart with hemopericardium, initial encounter"
}
end
def _S2601XD do
%ICDCode{full_code: "S2601XD",
category_code: "S26",
short_code: "01XD",
full_name: "Contusion of heart with hemopericardium, subsequent encounter",
short_name: "Contusion of heart with hemopericardium, subsequent encounter",
category_name: "Contusion of heart with hemopericardium, subsequent encounter"
}
end
def _S2601XS do
%ICDCode{full_code: "S2601XS",
category_code: "S26",
short_code: "01XS",
full_name: "Contusion of heart with hemopericardium, sequela",
short_name: "Contusion of heart with hemopericardium, sequela",
category_name: "Contusion of heart with hemopericardium, sequela"
}
end
def _S26020A do
%ICDCode{full_code: "S26020A",
category_code: "S26",
short_code: "020A",
full_name: "Mild laceration of heart with hemopericardium, initial encounter",
short_name: "Mild laceration of heart with hemopericardium, initial encounter",
category_name: "Mild laceration of heart with hemopericardium, initial encounter"
}
end
def _S26020D do
%ICDCode{full_code: "S26020D",
category_code: "S26",
short_code: "020D",
full_name: "Mild laceration of heart with hemopericardium, subsequent encounter",
short_name: "Mild laceration of heart with hemopericardium, subsequent encounter",
category_name: "Mild laceration of heart with hemopericardium, subsequent encounter"
}
end
def _S26020S do
%ICDCode{full_code: "S26020S",
category_code: "S26",
short_code: "020S",
full_name: "Mild laceration of heart with hemopericardium, sequela",
short_name: "Mild laceration of heart with hemopericardium, sequela",
category_name: "Mild laceration of heart with hemopericardium, sequela"
}
end
def _S26021A do
%ICDCode{full_code: "S26021A",
category_code: "S26",
short_code: "021A",
full_name: "Moderate laceration of heart with hemopericardium, initial encounter",
short_name: "Moderate laceration of heart with hemopericardium, initial encounter",
category_name: "Moderate laceration of heart with hemopericardium, initial encounter"
}
end
def _S26021D do
%ICDCode{full_code: "S26021D",
category_code: "S26",
short_code: "021D",
full_name: "Moderate laceration of heart with hemopericardium, subsequent encounter",
short_name: "Moderate laceration of heart with hemopericardium, subsequent encounter",
category_name: "Moderate laceration of heart with hemopericardium, subsequent encounter"
}
end
def _S26021S do
%ICDCode{full_code: "S26021S",
category_code: "S26",
short_code: "021S",
full_name: "Moderate laceration of heart with hemopericardium, sequela",
short_name: "Moderate laceration of heart with hemopericardium, sequela",
category_name: "Moderate laceration of heart with hemopericardium, sequela"
}
end
def _S26022A do
%ICDCode{full_code: "S26022A",
category_code: "S26",
short_code: "022A",
full_name: "Major laceration of heart with hemopericardium, initial encounter",
short_name: "Major laceration of heart with hemopericardium, initial encounter",
category_name: "Major laceration of heart with hemopericardium, initial encounter"
}
end
def _S26022D do
%ICDCode{full_code: "S26022D",
category_code: "S26",
short_code: "022D",
full_name: "Major laceration of heart with hemopericardium, subsequent encounter",
short_name: "Major laceration of heart with hemopericardium, subsequent encounter",
category_name: "Major laceration of heart with hemopericardium, subsequent encounter"
}
end
def _S26022S do
%ICDCode{full_code: "S26022S",
category_code: "S26",
short_code: "022S",
full_name: "Major laceration of heart with hemopericardium, sequela",
short_name: "Major laceration of heart with hemopericardium, sequela",
category_name: "Major laceration of heart with hemopericardium, sequela"
}
end
def _S2609XA do
%ICDCode{full_code: "S2609XA",
category_code: "S26",
short_code: "09XA",
full_name: "Other injury of heart with hemopericardium, initial encounter",
short_name: "Other injury of heart with hemopericardium, initial encounter",
category_name: "Other injury of heart with hemopericardium, initial encounter"
}
end
def _S2609XD do
%ICDCode{full_code: "S2609XD",
category_code: "S26",
short_code: "09XD",
full_name: "Other injury of heart with hemopericardium, subsequent encounter",
short_name: "Other injury of heart with hemopericardium, subsequent encounter",
category_name: "Other injury of heart with hemopericardium, subsequent encounter"
}
end
def _S2609XS do
%ICDCode{full_code: "S2609XS",
category_code: "S26",
short_code: "09XS",
full_name: "Other injury of heart with hemopericardium, sequela",
short_name: "Other injury of heart with hemopericardium, sequela",
category_name: "Other injury of heart with hemopericardium, sequela"
}
end
def _S2610XA do
%ICDCode{full_code: "S2610XA",
category_code: "S26",
short_code: "10XA",
full_name: "Unspecified injury of heart without hemopericardium, initial encounter",
short_name: "Unspecified injury of heart without hemopericardium, initial encounter",
category_name: "Unspecified injury of heart without hemopericardium, initial encounter"
}
end
def _S2610XD do
%ICDCode{full_code: "S2610XD",
category_code: "S26",
short_code: "10XD",
full_name: "Unspecified injury of heart without hemopericardium, subsequent encounter",
short_name: "Unspecified injury of heart without hemopericardium, subsequent encounter",
category_name: "Unspecified injury of heart without hemopericardium, subsequent encounter"
}
end
def _S2610XS do
%ICDCode{full_code: "S2610XS",
category_code: "S26",
short_code: "10XS",
full_name: "Unspecified injury of heart without hemopericardium, sequela",
short_name: "Unspecified injury of heart without hemopericardium, sequela",
category_name: "Unspecified injury of heart without hemopericardium, sequela"
}
end
def _S2611XA do
%ICDCode{full_code: "S2611XA",
category_code: "S26",
short_code: "11XA",
full_name: "Contusion of heart without hemopericardium, initial encounter",
short_name: "Contusion of heart without hemopericardium, initial encounter",
category_name: "Contusion of heart without hemopericardium, initial encounter"
}
end
def _S2611XD do
%ICDCode{full_code: "S2611XD",
category_code: "S26",
short_code: "11XD",
full_name: "Contusion of heart without hemopericardium, subsequent encounter",
short_name: "Contusion of heart without hemopericardium, subsequent encounter",
category_name: "Contusion of heart without hemopericardium, subsequent encounter"
}
end
def _S2611XS do
%ICDCode{full_code: "S2611XS",
category_code: "S26",
short_code: "11XS",
full_name: "Contusion of heart without hemopericardium, sequela",
short_name: "Contusion of heart without hemopericardium, sequela",
category_name: "Contusion of heart without hemopericardium, sequela"
}
end
def _S2612XA do
%ICDCode{full_code: "S2612XA",
category_code: "S26",
short_code: "12XA",
full_name: "Laceration of heart without hemopericardium, initial encounter",
short_name: "Laceration of heart without hemopericardium, initial encounter",
category_name: "Laceration of heart without hemopericardium, initial encounter"
}
end
def _S2612XD do
%ICDCode{full_code: "S2612XD",
category_code: "S26",
short_code: "12XD",
full_name: "Laceration of heart without hemopericardium, subsequent encounter",
short_name: "Laceration of heart without hemopericardium, subsequent encounter",
category_name: "Laceration of heart without hemopericardium, subsequent encounter"
}
end
def _S2612XS do
%ICDCode{full_code: "S2612XS",
category_code: "S26",
short_code: "12XS",
full_name: "Laceration of heart without hemopericardium, sequela",
short_name: "Laceration of heart without hemopericardium, sequela",
category_name: "Laceration of heart without hemopericardium, sequela"
}
end
def _S2619XA do
%ICDCode{full_code: "S2619XA",
category_code: "S26",
short_code: "19XA",
full_name: "Other injury of heart without hemopericardium, initial encounter",
short_name: "Other injury of heart without hemopericardium, initial encounter",
category_name: "Other injury of heart without hemopericardium, initial encounter"
}
end
def _S2619XD do
%ICDCode{full_code: "S2619XD",
category_code: "S26",
short_code: "19XD",
full_name: "Other injury of heart without hemopericardium, subsequent encounter",
short_name: "Other injury of heart without hemopericardium, subsequent encounter",
category_name: "Other injury of heart without hemopericardium, subsequent encounter"
}
end
def _S2619XS do
%ICDCode{full_code: "S2619XS",
category_code: "S26",
short_code: "19XS",
full_name: "Other injury of heart without hemopericardium, sequela",
short_name: "Other injury of heart without hemopericardium, sequela",
category_name: "Other injury of heart without hemopericardium, sequela"
}
end
def _S2690XA do
%ICDCode{full_code: "S2690XA",
category_code: "S26",
short_code: "90XA",
full_name: "Unspecified injury of heart, unspecified with or without hemopericardium, initial encounter",
short_name: "Unspecified injury of heart, unspecified with or without hemopericardium, initial encounter",
category_name: "Unspecified injury of heart, unspecified with or without hemopericardium, initial encounter"
}
end
def _S2690XD do
%ICDCode{full_code: "S2690XD",
category_code: "S26",
short_code: "90XD",
full_name: "Unspecified injury of heart, unspecified with or without hemopericardium, subsequent encounter",
short_name: "Unspecified injury of heart, unspecified with or without hemopericardium, subsequent encounter",
category_name: "Unspecified injury of heart, unspecified with or without hemopericardium, subsequent encounter"
}
end
def _S2690XS do
%ICDCode{full_code: "S2690XS",
category_code: "S26",
short_code: "90XS",
full_name: "Unspecified injury of heart, unspecified with or without hemopericardium, sequela",
short_name: "Unspecified injury of heart, unspecified with or without hemopericardium, sequela",
category_name: "Unspecified injury of heart, unspecified with or without hemopericardium, sequela"
}
end
def _S2691XA do
%ICDCode{full_code: "S2691XA",
category_code: "S26",
short_code: "91XA",
full_name: "Contusion of heart, unspecified with or without hemopericardium, initial encounter",
short_name: "Contusion of heart, unspecified with or without hemopericardium, initial encounter",
category_name: "Contusion of heart, unspecified with or without hemopericardium, initial encounter"
}
end
def _S2691XD do
%ICDCode{full_code: "S2691XD",
category_code: "S26",
short_code: "91XD",
full_name: "Contusion of heart, unspecified with or without hemopericardium, subsequent encounter",
short_name: "Contusion of heart, unspecified with or without hemopericardium, subsequent encounter",
category_name: "Contusion of heart, unspecified with or without hemopericardium, subsequent encounter"
}
end
def _S2691XS do
%ICDCode{full_code: "S2691XS",
category_code: "S26",
short_code: "91XS",
full_name: "Contusion of heart, unspecified with or without hemopericardium, sequela",
short_name: "Contusion of heart, unspecified with or without hemopericardium, sequela",
category_name: "Contusion of heart, unspecified with or without hemopericardium, sequela"
}
end
def _S2692XA do
%ICDCode{full_code: "S2692XA",
category_code: "S26",
short_code: "92XA",
full_name: "Laceration of heart, unspecified with or without hemopericardium, initial encounter",
short_name: "Laceration of heart, unspecified with or without hemopericardium, initial encounter",
category_name: "Laceration of heart, unspecified with or without hemopericardium, initial encounter"
}
end
def _S2692XD do
%ICDCode{full_code: "S2692XD",
category_code: "S26",
short_code: "92XD",
full_name: "Laceration of heart, unspecified with or without hemopericardium, subsequent encounter",
short_name: "Laceration of heart, unspecified with or without hemopericardium, subsequent encounter",
category_name: "Laceration of heart, unspecified with or without hemopericardium, subsequent encounter"
}
end
def _S2692XS do
%ICDCode{full_code: "S2692XS",
category_code: "S26",
short_code: "92XS",
full_name: "Laceration of heart, unspecified with or without hemopericardium, sequela",
short_name: "Laceration of heart, unspecified with or without hemopericardium, sequela",
category_name: "Laceration of heart, unspecified with or without hemopericardium, sequela"
}
end
def _S2699XA do
%ICDCode{full_code: "S2699XA",
category_code: "S26",
short_code: "99XA",
full_name: "Other injury of heart, unspecified with or without hemopericardium, initial encounter",
short_name: "Other injury of heart, unspecified with or without hemopericardium, initial encounter",
category_name: "Other injury of heart, unspecified with or without hemopericardium, initial encounter"
}
end
def _S2699XD do
%ICDCode{full_code: "S2699XD",
category_code: "S26",
short_code: "99XD",
full_name: "Other injury of heart, unspecified with or without hemopericardium, subsequent encounter",
short_name: "Other injury of heart, unspecified with or without hemopericardium, subsequent encounter",
category_name: "Other injury of heart, unspecified with or without hemopericardium, subsequent encounter"
}
end
def _S2699XS do
%ICDCode{full_code: "S2699XS",
category_code: "S26",
short_code: "99XS",
full_name: "Other injury of heart, unspecified with or without hemopericardium, sequela",
short_name: "Other injury of heart, unspecified with or without hemopericardium, sequela",
category_name: "Other injury of heart, unspecified with or without hemopericardium, sequela"
}
end
end
| 45.148052 | 121 | 0.677022 |
79481d36e4a92a2e1172cd84c4140b8b81d74cde | 1,482 | ex | Elixir | example/reactive/api/lib/api_web/endpoint.ex | farolanf/phoenix-socket-dart | 3fb441c53a25e2f7ea6f8f0ca9e7bfc25e45cdfd | [
"BSD-3-Clause"
] | 30 | 2020-11-10T07:32:36.000Z | 2022-02-06T20:34:34.000Z | example/reactive/api/lib/api_web/endpoint.ex | farolanf/phoenix-socket-dart | 3fb441c53a25e2f7ea6f8f0ca9e7bfc25e45cdfd | [
"BSD-3-Clause"
] | 22 | 2020-11-28T20:23:34.000Z | 2022-03-23T22:32:52.000Z | example/reactive/api/lib/api_web/endpoint.ex | farolanf/phoenix-socket-dart | 3fb441c53a25e2f7ea6f8f0ca9e7bfc25e45cdfd | [
"BSD-3-Clause"
] | 19 | 2020-11-10T14:22:05.000Z | 2022-02-15T10:22:43.000Z | defmodule ApiWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :api
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_api_key",
signing_salt: "LhpIGfl1"
]
socket "/socket", ApiWeb.UserSocket,
websocket: true,
longpoll: false
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :api,
gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :api
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug ApiWeb.Router
end
| 27.962264 | 97 | 0.709177 |
79483486099ee2e52f425951183bfef3809e76fe | 769 | ex | Elixir | lib/adyen_checkout_ex/model/google_pay_details.ex | rsystem-se/adyen_checkout_ex | 4210f1c7150152e81f350dc6ca55aeb19665b85b | [
"MIT"
] | 1 | 2021-05-30T20:45:10.000Z | 2021-05-30T20:45:10.000Z | lib/adyen_checkout_ex/model/google_pay_details.ex | rsystem-se/adyen_checkout_ex | 4210f1c7150152e81f350dc6ca55aeb19665b85b | [
"MIT"
] | null | null | null | lib/adyen_checkout_ex/model/google_pay_details.ex | rsystem-se/adyen_checkout_ex | 4210f1c7150152e81f350dc6ca55aeb19665b85b | [
"MIT"
] | null | null | null | # NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
# https://openapi-generator.tech
# Do not edit the class manually.
defmodule AdyenCheckoutEx.Model.GooglePayDetails do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:"fundingSource",
:"googlePayToken",
:"recurringDetailReference",
:"storedPaymentMethodId",
:"type"
]
@type t :: %__MODULE__{
:"fundingSource" => String.t | nil,
:"googlePayToken" => String.t,
:"recurringDetailReference" => String.t | nil,
:"storedPaymentMethodId" => String.t | nil,
:"type" => String.t | nil
}
end
defimpl Poison.Decoder, for: AdyenCheckoutEx.Model.GooglePayDetails do
def decode(value, _options) do
value
end
end
| 22.617647 | 91 | 0.673602 |
794834d9d9f091387c954786deb367682aa01a90 | 982 | ex | Elixir | clients/poly/lib/google_api/poly/v1/connection.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/poly/lib/google_api/poly/v1/connection.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/poly/lib/google_api/poly/v1/connection.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.Poly.V1.Connection do
@moduledoc """
Handle Tesla connections for GoogleApi.Poly.V1.
"""
@type t :: Tesla.Env.client()
use GoogleApi.Gax.Connection,
scopes: [],
otp_app: :google_api_poly,
base_url: "https://poly.googleapis.com/"
end
| 32.733333 | 77 | 0.741344 |
7948368e625c9ffaa1bdaca7167ca404a46653e9 | 4,388 | ex | Elixir | clients/android_publisher/lib/google_api/android_publisher/v3/model/track_release.ex | EVLedger/elixir-google-api | 61edef19a5e2c7c63848f7030c6d8d651e4593d4 | [
"Apache-2.0"
] | null | null | null | clients/android_publisher/lib/google_api/android_publisher/v3/model/track_release.ex | EVLedger/elixir-google-api | 61edef19a5e2c7c63848f7030c6d8d651e4593d4 | [
"Apache-2.0"
] | null | null | null | clients/android_publisher/lib/google_api/android_publisher/v3/model/track_release.ex | EVLedger/elixir-google-api | 61edef19a5e2c7c63848f7030c6d8d651e4593d4 | [
"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.AndroidPublisher.V3.Model.TrackRelease do
@moduledoc """
## Attributes
* `controls` (*type:* `list(GoogleApi.AndroidPublisher.V3.Model.Control.t)`, *default:* `nil`) -
* `countryTargeting` (*type:* `GoogleApi.AndroidPublisher.V3.Model.CountryTargeting.t`, *default:* `nil`) -
* `inAppUpdatePriority` (*type:* `integer()`, *default:* `nil`) - In-app update priority of the release. All newly added APKs in the release will be considered at this priority. in_app_update_priority can take values between [0, 5]. 5 is the highest priority. Default priority is 0. in_app_update_priority can not be updated once the release is rolled out. See https://developer.android.com/guide/playcore/in-app-updates.
* `name` (*type:* `String.t`, *default:* `nil`) - The release name, used to identify this release in the Play Console UI. Not required to be unique. This is optional, if not set it will be generated from the version_name in the APKs.
* `pinnedVersions` (*type:* `list(GoogleApi.AndroidPublisher.V3.Model.TrackReleasePin.t)`, *default:* `nil`) -
* `releaseNotes` (*type:* `list(GoogleApi.AndroidPublisher.V3.Model.LocalizedText.t)`, *default:* `nil`) - The description of what is new in the app in this release.
* `rollbackEnabled` (*type:* `boolean()`, *default:* `nil`) -
* `sampling` (*type:* `GoogleApi.AndroidPublisher.V3.Model.Sampling.t`, *default:* `nil`) -
* `status` (*type:* `String.t`, *default:* `nil`) - The desired status of this release.
* `userFraction` (*type:* `float()`, *default:* `nil`) - Fraction of users who are eligible to receive the release. 0 < fraction < 1. To be set, release status must be "inProgress" or "halted".
* `versionCodes` (*type:* `list(String.t)`, *default:* `nil`) - A list of all version codes of APKs that will be exposed to the users of this track when this release is rolled out. Note that this list should contain all versions you wish to be active, including those you wish to retain from previous releases.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:controls => list(GoogleApi.AndroidPublisher.V3.Model.Control.t()),
:countryTargeting => GoogleApi.AndroidPublisher.V3.Model.CountryTargeting.t(),
:inAppUpdatePriority => integer(),
:name => String.t(),
:pinnedVersions => list(GoogleApi.AndroidPublisher.V3.Model.TrackReleasePin.t()),
:releaseNotes => list(GoogleApi.AndroidPublisher.V3.Model.LocalizedText.t()),
:rollbackEnabled => boolean(),
:sampling => GoogleApi.AndroidPublisher.V3.Model.Sampling.t(),
:status => String.t(),
:userFraction => float(),
:versionCodes => list(String.t())
}
field(:controls, as: GoogleApi.AndroidPublisher.V3.Model.Control, type: :list)
field(:countryTargeting, as: GoogleApi.AndroidPublisher.V3.Model.CountryTargeting)
field(:inAppUpdatePriority)
field(:name)
field(:pinnedVersions, as: GoogleApi.AndroidPublisher.V3.Model.TrackReleasePin, type: :list)
field(:releaseNotes, as: GoogleApi.AndroidPublisher.V3.Model.LocalizedText, type: :list)
field(:rollbackEnabled)
field(:sampling, as: GoogleApi.AndroidPublisher.V3.Model.Sampling)
field(:status)
field(:userFraction)
field(:versionCodes, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.AndroidPublisher.V3.Model.TrackRelease do
def decode(value, options) do
GoogleApi.AndroidPublisher.V3.Model.TrackRelease.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AndroidPublisher.V3.Model.TrackRelease do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 56.987013 | 425 | 0.717639 |
79484056305038a17a0add1f2dab8cdeea38dce3 | 286 | ex | Elixir | api/lib/responda_me_web/plugs/auth_error_handler.ex | mendes13/responda.me | 42facc3de1c5cc503459457b2bb452f0ad6fac37 | [
"MIT"
] | null | null | null | api/lib/responda_me_web/plugs/auth_error_handler.ex | mendes13/responda.me | 42facc3de1c5cc503459457b2bb452f0ad6fac37 | [
"MIT"
] | null | null | null | api/lib/responda_me_web/plugs/auth_error_handler.ex | mendes13/responda.me | 42facc3de1c5cc503459457b2bb452f0ad6fac37 | [
"MIT"
] | null | null | null | defmodule Responda.MeWeb.AuthErrorHandler do
import Plug.Conn
@behaviour Guardian.Plug.ErrorHandler
@impl Guardian.Plug.ErrorHandler
def auth_error(conn, {type, _reason}, _opts) do
body = Jason.encode!(%{message: to_string(type)})
send_resp(conn, 401, body)
end
end
| 23.833333 | 53 | 0.737762 |
7948461752d9598b81b851bf4c479463bce22d2b | 554 | ex | Elixir | lib/hex.ex | hrzndhrn/hex | f74e2ed979e74130bdc4a6974660aa986333f33f | [
"Apache-2.0"
] | 824 | 2015-01-05T09:12:36.000Z | 2022-03-28T12:02:29.000Z | lib/hex.ex | hrzndhrn/hex | f74e2ed979e74130bdc4a6974660aa986333f33f | [
"Apache-2.0"
] | 737 | 2015-01-01T05:48:46.000Z | 2022-03-29T12:56:12.000Z | lib/hex.ex | hrzndhrn/hex | f74e2ed979e74130bdc4a6974660aa986333f33f | [
"Apache-2.0"
] | 220 | 2015-03-14T17:55:11.000Z | 2022-03-23T22:17:07.000Z | defmodule Hex do
@moduledoc false
def start() do
{:ok, _} = Application.ensure_all_started(:hex)
end
def stop() do
case Application.stop(:hex) do
:ok -> :ok
{:error, {:not_started, :hex}} -> :ok
end
end
# For compatibility during development
def start(start_type, start_args) do
Hex.Application.start(start_type, start_args)
end
def version(), do: unquote(Mix.Project.config()[:version])
def elixir_version(), do: unquote(System.version())
def otp_version(), do: unquote(Hex.Utils.otp_version())
end
| 23.083333 | 60 | 0.669675 |
7948978ededa2127c0b9901e950a3bb5bef9e79d | 1,269 | ex | Elixir | lib/slacketon_chat/resolvers/weather_resolver.ex | matthewoden/slackerton | 0604122884cf08087432f2e32d80eca42a878c37 | [
"MIT"
] | 1 | 2022-02-19T17:49:37.000Z | 2022-02-19T17:49:37.000Z | lib/slacketon_chat/resolvers/weather_resolver.ex | matthewoden/slackerton | 0604122884cf08087432f2e32d80eca42a878c37 | [
"MIT"
] | 4 | 2018-07-14T16:30:17.000Z | 2022-02-10T16:23:23.000Z | lib/slacketon_chat/resolvers/weather_resolver.ex | matthewoden/slackerton | 0604122884cf08087432f2e32d80eca42a878c37 | [
"MIT"
] | null | null | null | defmodule SlackertonChat.WeatherResolver do
require Logger
alias Slackerton.Weather
alias SlackertonChat.Robot
alias Hedwig.Responder
def add_alert(%{ private: %{ "robot" => robot }, room: room } = msg, _slots) do
with {:ok, _ } <- Weather.subscribe_channel(robot, room) do
Robot.thread(msg, "Gotcha. I'll post all weather updates in here going forward.")
else
otherwise ->
Logger.info(inspect(otherwise))
Robot.thread(msg, "Uh, sorry. I couldn't do that.")
end
end
def remove_alert(%{ private: %{ "robot" => robot } } = msg, _slots) do
with {:ok, _ } <- Weather.unsubscribe_channel(robot) do
Robot.thread(msg, "Understood. I'll stop posting weather updates.")
else
otherwise ->
Logger.info(inspect(otherwise))
Robot.thread(msg, "Uh, sorry. I couldn't do that.")
end
end
def detail_alert(msg, _slots) do
Responder.reply(msg, Weather.severe_weather_full())
end
def broadcast_alert() do
with {:ok, {subscribers, text}} <- Weather.check_severe_weather() do
Enum.each(subscribers, fn {team, room} -> Robot.broadcast(team, text, room) end)
else
_ ->
Logger.debug("SEVERE WEATHER: No weather alerts.")
:ok
end
end
end | 30.95122 | 87 | 0.646966 |
7948a171d7547d95142e05828eece0683f967b1b | 6,077 | ex | Elixir | lib/ext/api/reconciler.ex | FarmBot/farmbot_os | 5ebdca3afd672eb6b0af5c71cfca02488b32569a | [
"MIT"
] | 843 | 2016-10-05T23:46:05.000Z | 2022-03-14T04:31:55.000Z | lib/ext/api/reconciler.ex | FarmBot/farmbot_os | 5ebdca3afd672eb6b0af5c71cfca02488b32569a | [
"MIT"
] | 455 | 2016-10-15T08:49:16.000Z | 2022-03-15T12:23:04.000Z | lib/ext/api/reconciler.ex | FarmBot/farmbot_os | 5ebdca3afd672eb6b0af5c71cfca02488b32569a | [
"MIT"
] | 261 | 2016-10-10T04:37:06.000Z | 2022-03-13T21:07:38.000Z | defmodule FarmbotExt.API.Reconciler do
@moduledoc """
Handles additions, deletions and changes of remote API resources
Uses the `updated_at` and `created_at` common fields of api resources
to determine if FarmbotOS or the API's resource is more current
"""
require Logger
alias Ecto.Changeset
import Ecto.Query
alias FarmbotExt.{API, EagerLoader}
alias API.SyncGroup
alias FarmbotCore.Asset.{Command, Repo, Sync, Sync.Item}
import FarmbotCore.TimeUtils, only: [compare_datetimes: 2]
@doc """
Reconcile remote updates. The following steps are wrapped in a tranaction
that is treated as an `all or nothing` sync.
* get sync object from API
* start a new Transaction
* `sync_group` for groups 1-4, aborting the transaction if there are failures.
* add the `sync` to the Transaction
* apply the Transaction.
"""
def sync do
with {:ok, sc} <- API.get_changeset(Sync),
%Changeset{valid?: true} = sc <- sync_group(sc, SyncGroup.group_0()),
%Changeset{valid?: true} = sc <- sync_group(sc, SyncGroup.group_1()),
%Changeset{valid?: true} = sc <- sync_group(sc, SyncGroup.group_2()),
%Changeset{valid?: true} = sc <- sync_group(sc, SyncGroup.group_3()),
%Changeset{valid?: true} <- sync_group(sc, SyncGroup.group_4()) do
:ok
end
end
@doc """
Sync a group (list) of modules into a transaction.
For each item in the `sync` object, belonging to a `module` does the following:
* checks EagerLoader cache
* if no cache exists:
* downloads changeset via HTTP
* if cache exists:
* check if cache matches data on the `sync` object
* if cache is valid: uses cached changeset
* if cache is _not_ valid, falls back to http
* applies changeset if there was any changes from cache or http
"""
def sync_group(%Changeset{} = sync_changeset, [module | rest]) do
with sync_changeset <- do_sync_group(sync_changeset, module) do
sync_group(sync_changeset, rest)
end
end
def sync_group(%Changeset{valid?: true} = ok, []), do: ok
def sync_group(%Changeset{valid?: false} = error, []), do: {:error, error}
defp do_sync_group(%Changeset{} = sync_changeset, module)
when is_atom(module) do
table = module.__schema__(:source) |> String.to_atom()
# items is a list of changesets
items = Changeset.get_field(sync_changeset, table)
items || raise("Could not find #{table} in sync")
# TODO(Connor) maybe move this into Asset.Query
ids_fbos_knows_about =
Repo.all(from(d in module, where: not is_nil(d.id), select: d.id))
|> Enum.sort()
ids_the_api_knows_about =
Enum.map(items, &Map.fetch!(&1, :id))
|> Enum.sort()
ids_that_were_deleted = ids_fbos_knows_about -- ids_the_api_knows_about
sync_changeset =
Enum.reduce(ids_that_were_deleted, sync_changeset, fn id,
sync_changeset ->
Command.update(module, id, nil)
sync_changeset
end)
Enum.reduce(items, sync_changeset, &sync_reduce(module, &1, &2))
end
@doc false
def sync_reduce(module, %Item{} = item, %Changeset{} = sync_changeset)
when is_atom(module) do
cached_cs = EagerLoader.get_cache(module, item.id)
local_item = Repo.one(from(d in module, where: d.id == ^item.id))
case get_changeset(local_item || module, item, cached_cs) do
{:insert, %Changeset{} = cs} -> handle_change(module, cs)
{:update, %Changeset{} = cs} -> handle_change(module, cs)
nil -> nil
end
sync_changeset
end
defp handle_change(module, cs) do
item = module.render(Changeset.apply_changes(cs))
:ok = Command.update(module, item.id, item)
end
defp get_changeset(local_item, sync_item, cached_changeset)
# A module is passed in if there is no local copy of the data.
defp get_changeset(module, %Item{} = sync_item, nil) when is_atom(module) do
{:ok, changeset} = API.get_changeset(module, "#{sync_item.id}")
{:insert, changeset}
end
defp get_changeset(module, %Item{} = sync_item, %Changeset{} = cached)
when is_atom(module) do
cached_updated_at = Changeset.get_field(cached, :updated_at)
sync_item_updated_at = sync_item.updated_at
if compare_datetimes(sync_item_updated_at, cached_updated_at) == :eq do
{:insert, cached}
else
# Logger.info("Cached item is out of date")
get_changeset(module, sync_item, nil)
end
end
# no cache available
# If the `sync_item.updated_at` is newer than `local_item.updated_at`
# HTTP get the data.
defp get_changeset(%{} = local_item, %Item{} = sync_item, nil) do
sync_item_updated_at = sync_item.updated_at
sync_item_id = sync_item.id
# Check if remote data is newer
if compare_datetimes(sync_item_updated_at, local_item.updated_at) == :gt do
result = API.get_changeset(local_item, "#{sync_item_id}")
case result do
{:ok, changeset} ->
{:update, changeset}
other ->
msg = "Can't get changeset: #{inspect(other)}"
Logger.info(msg)
nil
end
end
end
# We have a cache.
# First check if it is the same `updated_at` as what the API has.
# If the cache is the same `updated_at` as the API, check if the cache
# is newer than `local_item.updated_at`
# if the cache is not the same `updated_at` as the API, fallback to HTTP.
defp get_changeset(
%{} = local_item,
%Item{} = sync_item,
%Changeset{} = cached
) do
cached_updated_at = Changeset.get_field(cached, :updated_at)
sync_item_updated_at = sync_item.updated_at
cache_compare = compare_datetimes(sync_item_updated_at, cached_updated_at)
if cache_compare == :eq || cache_compare == :gt do
# Logger.info(
# "Local data: #{local_item.__struct__} is out of date. Using cache do get newer data."
# )
{:update, cached}
else
# Logger.info("Cached item is out of date")
get_changeset(local_item, sync_item, nil)
end
end
end
| 33.574586 | 95 | 0.665295 |
7948ad3392c9bd90b7e7fd000824ac72b591a194 | 335 | ex | Elixir | lib/beatbot/token_plug.ex | daph/beatbot | 37a2de733c114a9f1a6c69cbc92763ac1a98f842 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2019-10-16T23:37:00.000Z | 2019-10-16T23:37:00.000Z | lib/beatbot/token_plug.ex | daph/beatbot | 37a2de733c114a9f1a6c69cbc92763ac1a98f842 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | lib/beatbot/token_plug.ex | daph/beatbot | 37a2de733c114a9f1a6c69cbc92763ac1a98f842 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | defmodule Beatbot.TokenPlug do
import Plug.Conn
def init(opts) do
opts
end
def call(conn, _opts) do
token =
__MODULE__
|> Application.get_application
|> Application.get_env(:slack_token)
in_token = Map.get(conn.params, "token", "")
assign(conn, :token_valid, (in_token == token))
end
end
| 18.611111 | 51 | 0.650746 |
7948df0c0fe5a8dc04bc787521fa18aac81b2003 | 1,383 | ex | Elixir | test/support/data_case.ex | pankaryp/Phoenix-server-demo | 7a028bb14ad58400e0215281e09627e168cf5792 | [
"MIT"
] | null | null | null | test/support/data_case.ex | pankaryp/Phoenix-server-demo | 7a028bb14ad58400e0215281e09627e168cf5792 | [
"MIT"
] | null | null | null | test/support/data_case.ex | pankaryp/Phoenix-server-demo | 7a028bb14ad58400e0215281e09627e168cf5792 | [
"MIT"
] | null | null | null | defmodule WebDemo.DataCase do
@moduledoc """
This module defines the setup for tests requiring
access to the application's data layer.
You may define functions here to be used as helpers in
your tests.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
alias WebDemo.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import WebDemo.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(WebDemo.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(WebDemo.Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transform changeset errors to a map of messages.
assert {:error, changeset} = Accounts.create_user(%{password: "short"})
assert "password is too short" in errors_on(changeset).password
assert %{password: ["password is too short"]} = errors_on(changeset)
"""
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Enum.reduce(opts, message, fn {key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end)
end
end
| 25.611111 | 77 | 0.679682 |
7948e29b9b930b7ca5699c2c94896ec9512de11d | 6,167 | ex | Elixir | lib/calypte/changeset.ex | liveforeverx/calypte | 161e137ace124647b005c4d92ed5fe8014072556 | [
"Apache-2.0"
] | 7 | 2019-07-17T22:48:57.000Z | 2021-04-14T20:22:46.000Z | lib/calypte/changeset.ex | liveforeverx/calypte | 161e137ace124647b005c4d92ed5fe8014072556 | [
"Apache-2.0"
] | null | null | null | lib/calypte/changeset.ex | liveforeverx/calypte | 161e137ace124647b005c4d92ed5fe8014072556 | [
"Apache-2.0"
] | 1 | 2019-08-06T11:26:11.000Z | 2019-08-06T11:26:11.000Z | defmodule Calypte.Changeset do
@moduledoc """
Structure to represent changes for
"""
alias Calypte.{Binding, Graph, Value, Utils}
import Utils
@type t :: %__MODULE__{changes: []}
defstruct changes: []
defmodule Change do
@type t :: %__MODULE__{
type: :edge | :node,
id: any,
delete: nil,
add: nil,
meta: any
}
defstruct type: :node, id: nil, delete: %{}, add: %{}, meta: nil
end
@creation_key :created
@doc """
Build changeset from a json
"""
def from_json(graph, json) do
%__MODULE__{changes: graph |> do_build(json) |> List.flatten()}
end
def do_build(graph, json) when is_list(json), do: Enum.map(json, &do_build(graph, &1))
def do_build(%Graph{id_key: id_key} = graph, json) when is_map(json) do
case json do
%{^id_key => id} -> build_changes(graph, id, json)
_ -> []
end
end
def build_changes(graph, id, json) do
%Graph{id_key: id_key, type_key: type_key, nodes: nodes} = graph
{edges, node} = Enum.split_with(json, fn {_, value} -> is_edge(value) end)
node = valuefy_node(node)
{old_node, node} = fetch_or_create(nodes, id, node)
{delete_attrs, add_attrs} = partial_diff_attrs(old_node, node)
nested_jsons = for {_, json} <- edges, do: json
type = from_value(old_node[type_key] || node[type_key])
[
%Change{id: id, delete: delete_attrs, add: add_attrs, meta: List.wrap(type)},
do_build(graph, nested_jsons),
edge_changes(id, edges, id_key, graph)
]
end
defp fetch_or_create(container, id, new_entity) do
case Map.get(container, id) do
nil -> {%{}, Map.put(new_entity, @creation_key, Utils.timestamp())}
old_entity -> {old_entity, new_entity}
end
end
defp is_edge([%{} | _]), do: true
defp is_edge(%{}), do: true
defp is_edge(_), do: false
defp valuefy_node(node) do
for {key, value} <- node, !String.contains?(key, "|"), into: %{}, do: {key, Value.new(value)}
end
defp valuefy_edge(node, edge_name) do
Enum.reduce(node, %{}, fn {key, value}, acc ->
case String.split(key, "|") do
[^edge_name, edge_attr] -> Map.put(acc, edge_attr, Value.new(value))
_ -> acc
end
end)
end
defp partial_diff_attrs(old_attrs, new_attrs) do
{delete_attrs, add_attrs} = do_partial_diff(old_attrs, new_attrs)
{Map.new(delete_attrs), Map.new(add_attrs)}
end
defp do_partial_diff(old_attrs, new_attrs) do
Enum.reduce(new_attrs, {[], []}, fn {key, values}, {delete, add} ->
values = List.wrap(values)
old_values = List.wrap(old_attrs[key])
to_delete = diff_real_values(key, old_values, values)
to_add = diff_real_values(key, values, old_values)
{to_delete ++ delete, to_add ++ add}
end)
end
defp diff_real_values(key, values, to_diff) do
to_diff = Enum.map(to_diff, &from_value(&1))
values = Enum.filter(values, fn value -> not (from_value(value) in to_diff) end)
key_diff(key, values)
end
defp key_diff(_key, []), do: []
defp key_diff(key, values), do: [{key, unwrap(values)}]
defp edge_changes(id, edge_jsons, id_key, %Graph{edges: edges}) do
for {edge, jsons} <- edge_jsons,
%{^id_key => in_id} = json <- List.wrap(jsons) do
edge_id = {id, edge, in_id}
new_edge = valuefy_edge(json, edge)
{old_edge, new_edge} = fetch_or_create(edges, edge_id, new_edge)
{delete_attrs, add_attrs} = partial_diff_attrs(old_edge, new_edge)
%Change{type: :edge, id: edge_id, delete: delete_attrs, add: add_attrs}
end
end
@doc """
Build changeset from binding diff
"""
def from_binding(binding) do
%Binding{matches: old_matches, updated_matches: new_matches, types: _types} = binding
changes =
for {var, {to_delete, to_add}} <- diff_matches(old_matches, new_matches) do
{id, types} = id_types(binding, var, to_delete, to_add)
%Change{id: id, delete: to_delete, add: to_add, meta: types}
end
%__MODULE__{changes: changes}
end
defp id_types(%{type_key: type_key} = binding, var, to_delete, to_add) do
{id, types} = Binding.var_info(binding, var)
types = (wrap(types) -- values(to_delete, type_key)) ++ values(to_add, type_key)
{id, Enum.map(types, &from_value/1)}
end
defp values(map, type_key), do: map |> Map.get(type_key) |> wrap()
defp diff_matches(old_matches, new_matches) do
{diffs, old_matches} =
Enum.flat_map_reduce(new_matches, old_matches, fn {var, attrs}, old_matches ->
{old_attrs, old_matches} = Map.pop(old_matches, var, %{})
{flat_diff(var, old_attrs, attrs), old_matches}
end)
deletes = Enum.flat_map(old_matches, fn {var, values} -> flat_diff(var, values, %{}) end)
deletes ++ diffs
end
defp flat_diff(var, old_attrs, new_attrs) do
case diff_attrs(old_attrs, new_attrs) do
{[], []} -> []
{to_delete, to_add} -> [{var, {Map.new(to_delete), Map.new(to_add)}}]
end
end
defp diff_attrs(old_attrs, new_attrs) do
{delete, add, old_attrs} =
Enum.reduce(new_attrs, {[], [], old_attrs}, fn {attr, values}, {delete, add, old_attrs} ->
{old_values, old_attrs} = Map.pop(old_attrs, attr)
{to_delete, to_add} = diff_values(attr, old_values, values)
{to_delete ++ delete, to_add ++ add, old_attrs}
end)
to_delete =
Enum.flat_map(old_attrs, fn {attr, values} -> key_diff(attr, non_virtual(values)) end)
{to_delete ++ delete, add}
end
defp diff_values(attr, old_values, new_values) do
old_values = old_values |> wrap() |> non_virtual()
new_values = new_values |> wrap() |> non_virtual()
{key_diff(attr, old_values -- new_values), key_diff(attr, new_values -- old_values)}
end
defp non_virtual(attrs), do: Enum.filter(attrs, &(not match?(%{virtual: true}, &1)))
@doc """
Revert changeset
"""
def revert(%__MODULE__{changes: changes} = changeset) do
%{changeset | changes: Enum.reduce(changes, [], &[revert_change(&1) | &2])}
end
defp revert_change(%Change{delete: delete, add: add} = change),
do: %{change | delete: add, add: delete}
end
| 31.953368 | 97 | 0.638884 |
7948efe61507641c20993d189d5be197a0aa6fbd | 731 | ex | Elixir | test/support/live_views/live_in_component.ex | feliperenan/phoenix_live_view | af65bb51fe12ea88e7c66808d2b1118e1c491ddd | [
"MIT"
] | 4,659 | 2019-03-14T20:22:43.000Z | 2022-03-31T20:13:30.000Z | test/support/live_views/live_in_component.ex | feliperenan/phoenix_live_view | af65bb51fe12ea88e7c66808d2b1118e1c491ddd | [
"MIT"
] | 1,745 | 2019-03-14T22:04:38.000Z | 2022-03-31T17:26:25.000Z | test/support/live_views/live_in_component.ex | feliperenan/phoenix_live_view | af65bb51fe12ea88e7c66808d2b1118e1c491ddd | [
"MIT"
] | 744 | 2019-03-14T20:48:05.000Z | 2022-03-25T14:35:04.000Z | defmodule Phoenix.LiveViewTest.LiveInComponent.Root do
use Phoenix.LiveView
def mount(_params, _session, socket) do
{:ok, socket}
end
def render(assigns) do
~H"<%= live_component Phoenix.LiveViewTest.LiveInComponent.Component, id: :nested_component %>"
end
end
defmodule Phoenix.LiveViewTest.LiveInComponent.Component do
use Phoenix.LiveComponent
def render(assigns) do
~H"""
<div>
<%= live_render @socket, Phoenix.LiveViewTest.LiveInComponent.Live, id: :nested_live %>"
</div>
"""
end
end
defmodule Phoenix.LiveViewTest.LiveInComponent.Live do
use Phoenix.LiveView
def mount(_params, _session, socket) do
{:ok, socket}
end
def render(assigns) do
~H""
end
end
| 20.305556 | 99 | 0.709986 |
7948fda9c2b46c37a5edd47e1c276210364df5f0 | 903 | ex | Elixir | graphql-elixir/test/support/conn_case.ex | ma2gedev/graphql-samples | f6e8efba22777ed27aee0fa597d23f991987ca6b | [
"MIT"
] | 1 | 2019-04-14T04:19:37.000Z | 2019-04-14T04:19:37.000Z | graphql-elixir/test/support/conn_case.ex | ma2gedev/graphql-samples | f6e8efba22777ed27aee0fa597d23f991987ca6b | [
"MIT"
] | null | null | null | graphql-elixir/test/support/conn_case.ex | ma2gedev/graphql-samples | f6e8efba22777ed27aee0fa597d23f991987ca6b | [
"MIT"
] | null | null | null | defmodule GraphqlSampleWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
alias GraphqlSampleWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint GraphqlSampleWeb.Endpoint
end
end
setup _tags do
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 27.363636 | 59 | 0.734219 |
79491330c44980473cb3e111d43660cb514b1fb9 | 2,291 | exs | Elixir | test/pg/postgres_test.exs | jesenko/ecto_enum | 9639bb23fb56bbac8a0c71d6824d724f243780fd | [
"MIT"
] | null | null | null | test/pg/postgres_test.exs | jesenko/ecto_enum | 9639bb23fb56bbac8a0c71d6824d724f243780fd | [
"MIT"
] | null | null | null | test/pg/postgres_test.exs | jesenko/ecto_enum | 9639bb23fb56bbac8a0c71d6824d724f243780fd | [
"MIT"
] | 1 | 2020-02-06T12:59:54.000Z | 2020-02-06T12:59:54.000Z | defmodule EctoEnum.PostgresTest do
use ExUnit.Case, async: false
import EctoEnum
defenum(StatusEnum, :status, [:registered, :active, :inactive, :archived])
defmodule User do
use Ecto.Schema
schema "users_pg" do
field(:status, StatusEnum)
end
end
alias Ecto.Integration.TestRepo
test "accepts atom and string on save" do
user = TestRepo.insert!(%User{status: :registered})
user = TestRepo.get(User, user.id)
assert user.status == :registered
user = Ecto.Changeset.change(user, status: :active)
user = TestRepo.update!(user)
assert user.status == :active
user = Ecto.Changeset.change(user, status: "inactive")
user = TestRepo.update!(user)
assert user.status == "inactive"
user = TestRepo.get(User, user.id)
assert user.status == :inactive
TestRepo.insert!(%User{status: :archived})
user = TestRepo.get_by(User, status: :archived)
assert user.status == :archived
end
test "casts binary to atom" do
%{errors: errors} = Ecto.Changeset.cast(%User{}, %{"status" => 3}, [:status])
error = {:status, {"is invalid", [type: EctoEnum.PostgresTest.StatusEnum, validation: :cast]}}
assert error in errors
%{changes: changes} = Ecto.Changeset.cast(%User{}, %{"status" => "active"}, [:status])
assert changes.status == :active
%{changes: changes} = Ecto.Changeset.cast(%User{}, %{"status" => :inactive}, [:status])
assert changes.status == :inactive
end
test "raises when input is not in the enum map" do
error = {:status, {"is invalid", [type: EctoEnum.PostgresTest.StatusEnum, validation: :cast]}}
changeset = Ecto.Changeset.cast(%User{}, %{"status" => "retroactive"}, [:status])
assert error in changeset.errors
changeset = Ecto.Changeset.cast(%User{}, %{"status" => :retroactive}, [:status])
assert error in changeset.errors
changeset = Ecto.Changeset.cast(%User{}, %{"status" => 4}, [:status])
assert error in changeset.errors
assert_raise Ecto.ChangeError, fn ->
TestRepo.insert!(%User{status: "retroactive"})
end
assert_raise Ecto.ChangeError, fn ->
TestRepo.insert!(%User{status: :retroactive})
end
assert_raise Ecto.ChangeError, fn ->
TestRepo.insert!(%User{status: 5})
end
end
end
| 30.546667 | 98 | 0.659974 |
794957d2247a2739be4e54ac2f81f55b91ca4192 | 582 | exs | Elixir | exercises/04-links-tasks-and-genservers/02-tasks/02-parallel-factorials/solution.exs | DennisWinnepenninckx/distributed-applications | 06743e4e2a09dc52ff52be831e486bb073916173 | [
"BSD-3-Clause"
] | 1 | 2021-09-22T09:52:11.000Z | 2021-09-22T09:52:11.000Z | exercises/04-links-tasks-and-genservers/02-tasks/02-parallel-factorials/solution.exs | DennisWinnepenninckx/distributed-applications | 06743e4e2a09dc52ff52be831e486bb073916173 | [
"BSD-3-Clause"
] | 22 | 2019-06-19T18:58:13.000Z | 2020-03-16T14:43:06.000Z | exercises/04-links-tasks-and-genservers/02-tasks/02-parallel-factorials/solution.exs | DennisWinnepenninckx/distributed-applications | 06743e4e2a09dc52ff52be831e486bb073916173 | [
"BSD-3-Clause"
] | 32 | 2019-09-19T03:25:11.000Z | 2020-10-06T15:01:47.000Z | defmodule Factorial do
def calc(n), do: calc(n, 1)
defp calc(1, acc), do: acc
defp calc(n, acc), do: calc(n - 1, acc * n)
def benchmark(f) do
t1 = DateTime.utc_now()
f.()
t2 = DateTime.utc_now()
DateTime.diff(t2, t1, :millisecond)
end
end
n = 2_000
t1 = Factorial.benchmark(fn ->
Enum.map(1..n, &Factorial.calc(&1))
end)
IO.puts("Sequential: #{t1}ms")
t2 = Factorial.benchmark(fn ->
tasks = Enum.map(
1..n,
fn k -> Task.async(fn -> Factorial.calc(k) end) end
)
Task.yield_many(tasks, :infinity)
end)
IO.puts("Parallelized: #{t2}ms")
| 18.1875 | 55 | 0.611684 |
79495e4892b1d7fedef759854e2e8964961c2aaa | 164 | ex | Elixir | lib/political/message.ex | wisq/political | 7a28dd9da95bc461be8f39411361519b471fa4c3 | [
"MIT"
] | null | null | null | lib/political/message.ex | wisq/political | 7a28dd9da95bc461be8f39411361519b471fa4c3 | [
"MIT"
] | null | null | null | lib/political/message.ex | wisq/political | 7a28dd9da95bc461be8f39411361519b471fa4c3 | [
"MIT"
] | null | null | null | defmodule Political.Message do
@enforce_keys [:author, :timestamp, :text]
defstruct(
author: nil,
timestamp: nil,
text: nil,
embeds: []
)
end
| 16.4 | 44 | 0.634146 |
7949bf8cd2a0332672f8576dca1f2e37c1ce937a | 1,388 | ex | Elixir | lib/mix/tasks/torch.gen.html.ex | r-icarus/torch | c5c94001b91fc459d727b18fa137b6936a65918d | [
"MIT"
] | null | null | null | lib/mix/tasks/torch.gen.html.ex | r-icarus/torch | c5c94001b91fc459d727b18fa137b6936a65918d | [
"MIT"
] | null | null | null | lib/mix/tasks/torch.gen.html.ex | r-icarus/torch | c5c94001b91fc459d727b18fa137b6936a65918d | [
"MIT"
] | null | null | null | defmodule Mix.Tasks.Torch.Gen.Html do
@moduledoc """
Light wrapper module around `mix phx.gen.html` which generates slightly
modified HTML.
Takes all the same params as the `phx.gen.html` task.
## Example
mix torch.gen.html Accounts User users --no-schema
"""
@commands ~w[phx.gen.html phx.gen.context]
def run(args) do
%{format: format} = Mix.Torch.parse_config!("torch.gen.html", args)
# Inject the torch templates for the generator into the priv/
# directory so they will be picked up by the Phoenix generator
Enum.each(@commands, &Mix.Torch.inject_templates(&1, format))
# Run the Phoenix generator
Mix.Task.run("phx.gen.html", args)
# Remove the injected templates from priv/ so they will not
# affect future Phoenix generator commands
Enum.each(@commands, &Mix.Torch.remove_templates/1)
Mix.shell().info("""
Ensure the following is added to your endpoint.ex:
plug(
Plug.Static,
at: "/torch",
from: {:torch, "priv/static"},
gzip: true,
cache_control_for_etags: "public, max-age=86400",
headers: [{"access-control-allow-origin", "*"}]
)
""")
Mix.shell().info("""
Also don't forget to add a link to layouts/torch.html.
<nav class="torch-nav">
<!-- nav links here -->
</nav>
""")
end
end
| 27.215686 | 73 | 0.626081 |
7949d858045db51c8b67aa77014ba10097cd8f4e | 1,033 | exs | Elixir | final-projects/shop_website/config/config.exs | anitabenites/elixir-and-phoenix-mentoring-sessions | 0fa283a8d4a8884edd54c8e16d788e2ca65e4592 | [
"MIT"
] | 3 | 2019-07-31T20:06:34.000Z | 2021-11-16T11:19:45.000Z | final-projects/shop_website/config/config.exs | anitabenites/elixir-and-phoenix-mentoring-sessions | 0fa283a8d4a8884edd54c8e16d788e2ca65e4592 | [
"MIT"
] | null | null | null | final-projects/shop_website/config/config.exs | anitabenites/elixir-and-phoenix-mentoring-sessions | 0fa283a8d4a8884edd54c8e16d788e2ca65e4592 | [
"MIT"
] | 1 | 2019-07-31T16:46:14.000Z | 2019-07-31T16:46:14.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
config :shop_website,
ecto_repos: [ShopWebsite.Repo]
# Configures the endpoint
config :shop_website, ShopWebsiteWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "FmJbQCzuHCxP3uds4ID8m0i2GHGAAA7rIhi1kIgSkiAXNpJeHOfwjDEwQFo3fThW",
render_errors: [view: ShopWebsiteWeb.ErrorView, accepts: ~w(html json)],
pubsub: [name: ShopWebsite.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.322581 | 86 | 0.777348 |
7949e0ecdd2105c25f749157c7403f684512e01a | 98 | ex | Elixir | lib/aph/repo.ex | tometoproject/tometo | ed91069b11a020723edb9a143de29d9bac86a2b0 | [
"BlueOak-1.0.0",
"Apache-2.0"
] | 8 | 2019-09-26T13:59:25.000Z | 2020-03-30T21:26:48.000Z | lib/aph/repo.ex | tometoproject/tometo | ed91069b11a020723edb9a143de29d9bac86a2b0 | [
"BlueOak-1.0.0",
"Apache-2.0"
] | 39 | 2019-11-16T02:24:28.000Z | 2020-01-14T16:40:28.000Z | lib/aph/repo.ex | tometoproject/tometo | ed91069b11a020723edb9a143de29d9bac86a2b0 | [
"BlueOak-1.0.0",
"Apache-2.0"
] | 2 | 2019-12-16T07:55:14.000Z | 2020-06-11T04:14:00.000Z | defmodule Aph.Repo do
use Ecto.Repo,
otp_app: :aph,
adapter: Ecto.Adapters.Postgres
end
| 16.333333 | 35 | 0.704082 |
7949e27028c29e31e34421567215e2930d769c94 | 181 | ex | Elixir | lib/algae/reader/generator.ex | doma-engineering/algae | da85c5a9e78591c707859f07f9d485ed68019349 | [
"MIT"
] | 191 | 2016-08-22T17:34:45.000Z | 2019-05-28T19:02:39.000Z | lib/algae/reader/generator.ex | doma-engineering/algae | da85c5a9e78591c707859f07f9d485ed68019349 | [
"MIT"
] | 35 | 2016-08-30T20:56:22.000Z | 2019-05-02T17:32:31.000Z | lib/algae/reader/generator.ex | doma-engineering/algae | da85c5a9e78591c707859f07f9d485ed68019349 | [
"MIT"
] | 10 | 2016-08-30T18:41:54.000Z | 2019-02-14T14:14:55.000Z | defimpl TypeClass.Property.Generator, for: Algae.Reader do
def generate(_) do
fn -> nil end
|> TypeClass.Property.Generator.generate()
|> Algae.Reader.new()
end
end
| 22.625 | 58 | 0.690608 |
7949e4dccc53a4b01835e11fa54835e83db099f6 | 1,123 | ex | Elixir | lib/phoenix_component_folders_web/components/component_helpers.ex | kimlindholm/phoenix_component_folders | 2d07f4966fe473063183e97009955b82a93b181f | [
"MIT"
] | 30 | 2017-05-05T09:30:06.000Z | 2021-03-29T15:08:02.000Z | lib/phoenix_component_folders_web/components/component_helpers.ex | kimlindholm/phoenix_component_folders | 2d07f4966fe473063183e97009955b82a93b181f | [
"MIT"
] | 4 | 2017-05-01T18:53:57.000Z | 2020-11-22T06:46:55.000Z | lib/phoenix_component_folders_web/components/component_helpers.ex | kimlindholm/phoenix_component_folders | 2d07f4966fe473063183e97009955b82a93b181f | [
"MIT"
] | 7 | 2017-11-09T06:34:07.000Z | 2021-03-01T20:14:18.000Z | defmodule PhoenixComponentFoldersWeb.Components.ComponentHelpers do
alias Phoenix.Naming
alias PhoenixComponentFoldersWeb.Components
@moduledoc """
Conveniences for reusable UI components
"""
def c(namespace, name \\ :index, assigns \\ []) do
component(namespace, template(name), assigns)
end
def c(namespace, name, assigns, opts) do
component(namespace, template(name), assigns, opts)
end
def component(namespace, template, assigns) do
apply(
view(namespace),
:render,
[template, assigns]
)
end
def component(namespace, template, assigns, do: block) do
apply(
view(namespace),
:render,
[template, Keyword.merge(assigns, do: block)]
)
end
def view_opts(namespace) do
%{
root: "lib/phoenix_component_folders_web/components/#{namespace}/templates",
namespace: PhoenixComponentFoldersWeb,
path: ""
}
end
defp view(name) do
module_name = Naming.camelize("#{name}") <> "View"
Module.concat(Components, module_name)
end
defp template(name) when is_atom(name) do
"#{name}.html"
end
end
| 22.46 | 82 | 0.673197 |
794a32fc9259532ae03444f8c601b61356edfb88 | 4,000 | ex | Elixir | lib/faker/lorem/shakespeare/en.ex | vforvova/faker | 9e600d5f3ca0c34e30f7923d415050786d9832cb | [
"MIT"
] | null | null | null | lib/faker/lorem/shakespeare/en.ex | vforvova/faker | 9e600d5f3ca0c34e30f7923d415050786d9832cb | [
"MIT"
] | null | null | null | lib/faker/lorem/shakespeare/en.ex | vforvova/faker | 9e600d5f3ca0c34e30f7923d415050786d9832cb | [
"MIT"
] | null | null | null | defmodule Faker.Lorem.Shakespeare.En do
@moduledoc """
Random quotes from William Shakespeare's plays, sonnets and poems in English.
"""
@data ["To be, or not to be: that is the question.", "Neither a borrower nor a lender be; For loan oft loses both itself and friend, and borrowing dulls the edge of husbandry.", "This above all: to thine own self be true.", "Though this be madness, yet there is method in 't.", "That it should come to this!", "There is nothing either good or bad, but thinking makes it so.", "What a piece of work is man! how noble in reason! how infinite in faculty! in form and moving how express and admirable! in action how like an angel! in apprehension how like a god! the beauty of the world, the paragon of animals! .", "The lady doth protest too much, methinks.", "In my mind's eye.", "A little more than kin, and less than kind.", "The play 's the thing wherein I'll catch the conscience of the king.", "And it must follow, as the night the day, thou canst not then be false to any man.", "Brevity is the soul of wit.", "Doubt that the sun doth move, doubt truth to be a liar, but never doubt I love.", "Rich gifts wax poor when givers prove unkind.", "Do you think I am easier to be played on than a pipe?", "I will speak daggers to her, but use none.", "When sorrows come, they come not single spies, but in battalions."]
@data_count Enum.count(@data)
@doc """
Return random quote from "The Tragedy of Hamlet, Prince of Denmark" tragedy.
"""
@spec hamlet() :: String.t
def hamlet do
Enum.at(@data, :crypto.rand_uniform(0, @data_count))
end
@data ["All the world's a stage, and all the men and women merely players. They have their exits and their entrances; And one man in his time plays many parts.", "Can one desire too much of a good thing?.", "I like this place and willingly could waste my time in it.", "How bitter a thing it is to look into happiness through another man's eyes!", "Blow, blow, thou winter wind! Thou art not so unkind as man's ingratitude.", "True is it that we have seen better days.", "For ever and a day.", "The fool doth think he is wise, but the wise man knows himself to be a fool."]
@data_count Enum.count(@data)
@doc """
Return random quote from "As You Like It" comedy.
"""
@spec as_you_like_it() :: String.t
def as_you_like_it do
Enum.at(@data, :crypto.rand_uniform(0, @data_count))
end
@data ["Now is the winter of our discontent.", "A horse! a horse! my kingdom for a horse!", "Conscience is but a word that cowards use, devised at first to keep the strong in awe.", "So wise so young, they say, do never live long.", "Off with his head!", "An honest tale speeds best, being plainly told.", "The king's name is a tower of strength.", "The world is grown so bad, that wrens make prey where eagles dare not perch."]
@data_count Enum.count(@data)
@doc """
Return random quote from "Richard III" play.
"""
@spec king_richard_iii() :: String.t
def king_richard_iii do
Enum.at(@data, :crypto.rand_uniform(0, @data_count))
end
@data ["O Romeo, Romeo! wherefore art thou Romeo?.", "It is the east, and Juliet is the sun.", "Good Night, Good night! Parting is such sweet sorrow, that I shall say good night till it be morrow.", "What's in a name? That which we call a rose by any other name would smell as sweet.", "Wisely and slow; they stumble that run fast.", "Tempt not a desperate man.", "For you and I are past our dancing days.", "O! she doth teach the torches to burn bright.", "It seems she hangs upon the cheek of night like a rich jewel in an Ethiope's ear.", "See, how she leans her cheek upon her hand! O that I were a glove upon that hand, that I might touch that cheek!.", "Not stepping o'er the bounds of modesty."]
@data_count Enum.count(@data)
@doc """
Return random quote from "Romeo and Juliet" tragedy.
"""
@spec romeo_and_juliet() :: String.t
def romeo_and_juliet do
Enum.at(@data, :crypto.rand_uniform(0, @data_count))
end
end
| 86.956522 | 1,219 | 0.71175 |
794a46541627de3861f3c7f9d214e9bd3779a111 | 391 | exs | Elixir | mix.exs | azukiapp/exjson | 6021434570092b5e31ff379b17a12abb47e7a45c | [
"Apache-2.0"
] | 1 | 2015-06-13T03:35:41.000Z | 2015-06-13T03:35:41.000Z | mix.exs | azukiapp/exjson | 6021434570092b5e31ff379b17a12abb47e7a45c | [
"Apache-2.0"
] | null | null | null | mix.exs | azukiapp/exjson | 6021434570092b5e31ff379b17a12abb47e7a45c | [
"Apache-2.0"
] | null | null | null | defmodule Exjson.Mixfile do
use Mix.Project
def project do
[ app: :exjson,
version: "0.0.1",
deps: deps,
compile: "make" ]
end
# Configuration for the OTP application
def application do
[]
end
# Returns the list of dependencies in the format:
# { :foobar, "0.1", git: "https://github.com/elixir-lang/foobar.git" }
defp deps do
[]
end
end
| 17.772727 | 72 | 0.616368 |
794a5354be4c976213627d3e67a17be0f1e51266 | 1,582 | ex | Elixir | clients/iam/lib/google_api/iam/v1/model/list_service_account_keys_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/iam/lib/google_api/iam/v1/model/list_service_account_keys_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/iam/lib/google_api/iam/v1/model/list_service_account_keys_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.IAM.V1.Model.ListServiceAccountKeysResponse do
@moduledoc """
The service account keys list response.
## Attributes
* `keys` (*type:* `list(GoogleApi.IAM.V1.Model.ServiceAccountKey.t)`, *default:* `nil`) - The public keys for the service account.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:keys => list(GoogleApi.IAM.V1.Model.ServiceAccountKey.t()) | nil
}
field(:keys, as: GoogleApi.IAM.V1.Model.ServiceAccountKey, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.IAM.V1.Model.ListServiceAccountKeysResponse do
def decode(value, options) do
GoogleApi.IAM.V1.Model.ListServiceAccountKeysResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.IAM.V1.Model.ListServiceAccountKeysResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.659574 | 134 | 0.747155 |
794a5eab30800c92bb4eb83c1998c4c70fa3f523 | 2,125 | ex | Elixir | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/trigger_status.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/trigger_status.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/trigger_status.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.CloudRun.V1alpha1.Model.TriggerStatus do
@moduledoc """
TriggerStatus represents the current state of a Trigger.
## Attributes
* `conditions` (*type:* `list(GoogleApi.CloudRun.V1alpha1.Model.TriggerCondition.t)`, *default:* `nil`) - Array of observed TriggerConditions, indicating the current state
of the Trigger.
* `observedGeneration` (*type:* `integer()`, *default:* `nil`) - ObservedGeneration is the 'Generation' of the Trigger that
was last processed by the controller.
* `subscriberUri` (*type:* `String.t`, *default:* `nil`) - SubscriberURI is the resolved URI of the receiver for this Trigger.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:conditions => list(GoogleApi.CloudRun.V1alpha1.Model.TriggerCondition.t()),
:observedGeneration => integer(),
:subscriberUri => String.t()
}
field(:conditions, as: GoogleApi.CloudRun.V1alpha1.Model.TriggerCondition, type: :list)
field(:observedGeneration)
field(:subscriberUri)
end
defimpl Poison.Decoder, for: GoogleApi.CloudRun.V1alpha1.Model.TriggerStatus do
def decode(value, options) do
GoogleApi.CloudRun.V1alpha1.Model.TriggerStatus.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudRun.V1alpha1.Model.TriggerStatus do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.636364 | 175 | 0.736941 |
794a7df3c38ca1541ecdfce2b82d124cf8073e48 | 728 | ex | Elixir | Microsoft.Azure.Management.Compute/lib/microsoft/azure/management/compute/model/instance_view_status.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | 4 | 2018-09-29T03:43:15.000Z | 2021-04-01T18:30:46.000Z | Microsoft.Azure.Management.Compute/lib/microsoft/azure/management/compute/model/instance_view_status.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | Microsoft.Azure.Management.Compute/lib/microsoft/azure/management/compute/model/instance_view_status.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | # 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 Microsoft.Azure.Management.Compute.Model.InstanceViewStatus do
@moduledoc """
Instance view status.
"""
@derive [Poison.Encoder]
defstruct [
:"code",
:"level",
:"displayStatus",
:"message",
:"time"
]
@type t :: %__MODULE__{
:"code" => String.t,
:"level" => String.t,
:"displayStatus" => String.t,
:"message" => String.t,
:"time" => DateTime.t
}
end
defimpl Poison.Decoder, for: Microsoft.Azure.Management.Compute.Model.InstanceViewStatus do
def decode(value, _options) do
value
end
end
| 21.411765 | 91 | 0.660714 |
794ade839449c47e983feb39b1ba0257422c597e | 14,054 | ex | Elixir | lib/codes/codes_f18.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_f18.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_f18.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_F18 do
alias IcdCode.ICDCode
def _F1810 do
%ICDCode{full_code: "F1810",
category_code: "F18",
short_code: "10",
full_name: "Inhalant abuse, uncomplicated",
short_name: "Inhalant abuse, uncomplicated",
category_name: "Inhalant abuse, uncomplicated"
}
end
def _F18120 do
%ICDCode{full_code: "F18120",
category_code: "F18",
short_code: "120",
full_name: "Inhalant abuse with intoxication, uncomplicated",
short_name: "Inhalant abuse with intoxication, uncomplicated",
category_name: "Inhalant abuse with intoxication, uncomplicated"
}
end
def _F18121 do
%ICDCode{full_code: "F18121",
category_code: "F18",
short_code: "121",
full_name: "Inhalant abuse with intoxication delirium",
short_name: "Inhalant abuse with intoxication delirium",
category_name: "Inhalant abuse with intoxication delirium"
}
end
def _F18129 do
%ICDCode{full_code: "F18129",
category_code: "F18",
short_code: "129",
full_name: "Inhalant abuse with intoxication, unspecified",
short_name: "Inhalant abuse with intoxication, unspecified",
category_name: "Inhalant abuse with intoxication, unspecified"
}
end
def _F1814 do
%ICDCode{full_code: "F1814",
category_code: "F18",
short_code: "14",
full_name: "Inhalant abuse with inhalant-induced mood disorder",
short_name: "Inhalant abuse with inhalant-induced mood disorder",
category_name: "Inhalant abuse with inhalant-induced mood disorder"
}
end
def _F18150 do
%ICDCode{full_code: "F18150",
category_code: "F18",
short_code: "150",
full_name: "Inhalant abuse with inhalant-induced psychotic disorder with delusions",
short_name: "Inhalant abuse with inhalant-induced psychotic disorder with delusions",
category_name: "Inhalant abuse with inhalant-induced psychotic disorder with delusions"
}
end
def _F18151 do
%ICDCode{full_code: "F18151",
category_code: "F18",
short_code: "151",
full_name: "Inhalant abuse with inhalant-induced psychotic disorder with hallucinations",
short_name: "Inhalant abuse with inhalant-induced psychotic disorder with hallucinations",
category_name: "Inhalant abuse with inhalant-induced psychotic disorder with hallucinations"
}
end
def _F18159 do
%ICDCode{full_code: "F18159",
category_code: "F18",
short_code: "159",
full_name: "Inhalant abuse with inhalant-induced psychotic disorder, unspecified",
short_name: "Inhalant abuse with inhalant-induced psychotic disorder, unspecified",
category_name: "Inhalant abuse with inhalant-induced psychotic disorder, unspecified"
}
end
def _F1817 do
%ICDCode{full_code: "F1817",
category_code: "F18",
short_code: "17",
full_name: "Inhalant abuse with inhalant-induced dementia",
short_name: "Inhalant abuse with inhalant-induced dementia",
category_name: "Inhalant abuse with inhalant-induced dementia"
}
end
def _F18180 do
%ICDCode{full_code: "F18180",
category_code: "F18",
short_code: "180",
full_name: "Inhalant abuse with inhalant-induced anxiety disorder",
short_name: "Inhalant abuse with inhalant-induced anxiety disorder",
category_name: "Inhalant abuse with inhalant-induced anxiety disorder"
}
end
def _F18188 do
%ICDCode{full_code: "F18188",
category_code: "F18",
short_code: "188",
full_name: "Inhalant abuse with other inhalant-induced disorder",
short_name: "Inhalant abuse with other inhalant-induced disorder",
category_name: "Inhalant abuse with other inhalant-induced disorder"
}
end
def _F1819 do
%ICDCode{full_code: "F1819",
category_code: "F18",
short_code: "19",
full_name: "Inhalant abuse with unspecified inhalant-induced disorder",
short_name: "Inhalant abuse with unspecified inhalant-induced disorder",
category_name: "Inhalant abuse with unspecified inhalant-induced disorder"
}
end
def _F1820 do
%ICDCode{full_code: "F1820",
category_code: "F18",
short_code: "20",
full_name: "Inhalant dependence, uncomplicated",
short_name: "Inhalant dependence, uncomplicated",
category_name: "Inhalant dependence, uncomplicated"
}
end
def _F1821 do
%ICDCode{full_code: "F1821",
category_code: "F18",
short_code: "21",
full_name: "Inhalant dependence, in remission",
short_name: "Inhalant dependence, in remission",
category_name: "Inhalant dependence, in remission"
}
end
def _F18220 do
%ICDCode{full_code: "F18220",
category_code: "F18",
short_code: "220",
full_name: "Inhalant dependence with intoxication, uncomplicated",
short_name: "Inhalant dependence with intoxication, uncomplicated",
category_name: "Inhalant dependence with intoxication, uncomplicated"
}
end
def _F18221 do
%ICDCode{full_code: "F18221",
category_code: "F18",
short_code: "221",
full_name: "Inhalant dependence with intoxication delirium",
short_name: "Inhalant dependence with intoxication delirium",
category_name: "Inhalant dependence with intoxication delirium"
}
end
def _F18229 do
%ICDCode{full_code: "F18229",
category_code: "F18",
short_code: "229",
full_name: "Inhalant dependence with intoxication, unspecified",
short_name: "Inhalant dependence with intoxication, unspecified",
category_name: "Inhalant dependence with intoxication, unspecified"
}
end
def _F1824 do
%ICDCode{full_code: "F1824",
category_code: "F18",
short_code: "24",
full_name: "Inhalant dependence with inhalant-induced mood disorder",
short_name: "Inhalant dependence with inhalant-induced mood disorder",
category_name: "Inhalant dependence with inhalant-induced mood disorder"
}
end
def _F18250 do
%ICDCode{full_code: "F18250",
category_code: "F18",
short_code: "250",
full_name: "Inhalant dependence with inhalant-induced psychotic disorder with delusions",
short_name: "Inhalant dependence with inhalant-induced psychotic disorder with delusions",
category_name: "Inhalant dependence with inhalant-induced psychotic disorder with delusions"
}
end
def _F18251 do
%ICDCode{full_code: "F18251",
category_code: "F18",
short_code: "251",
full_name: "Inhalant dependence with inhalant-induced psychotic disorder with hallucinations",
short_name: "Inhalant dependence with inhalant-induced psychotic disorder with hallucinations",
category_name: "Inhalant dependence with inhalant-induced psychotic disorder with hallucinations"
}
end
def _F18259 do
%ICDCode{full_code: "F18259",
category_code: "F18",
short_code: "259",
full_name: "Inhalant dependence with inhalant-induced psychotic disorder, unspecified",
short_name: "Inhalant dependence with inhalant-induced psychotic disorder, unspecified",
category_name: "Inhalant dependence with inhalant-induced psychotic disorder, unspecified"
}
end
def _F1827 do
%ICDCode{full_code: "F1827",
category_code: "F18",
short_code: "27",
full_name: "Inhalant dependence with inhalant-induced dementia",
short_name: "Inhalant dependence with inhalant-induced dementia",
category_name: "Inhalant dependence with inhalant-induced dementia"
}
end
def _F18280 do
%ICDCode{full_code: "F18280",
category_code: "F18",
short_code: "280",
full_name: "Inhalant dependence with inhalant-induced anxiety disorder",
short_name: "Inhalant dependence with inhalant-induced anxiety disorder",
category_name: "Inhalant dependence with inhalant-induced anxiety disorder"
}
end
def _F18288 do
%ICDCode{full_code: "F18288",
category_code: "F18",
short_code: "288",
full_name: "Inhalant dependence with other inhalant-induced disorder",
short_name: "Inhalant dependence with other inhalant-induced disorder",
category_name: "Inhalant dependence with other inhalant-induced disorder"
}
end
def _F1829 do
%ICDCode{full_code: "F1829",
category_code: "F18",
short_code: "29",
full_name: "Inhalant dependence with unspecified inhalant-induced disorder",
short_name: "Inhalant dependence with unspecified inhalant-induced disorder",
category_name: "Inhalant dependence with unspecified inhalant-induced disorder"
}
end
def _F1890 do
%ICDCode{full_code: "F1890",
category_code: "F18",
short_code: "90",
full_name: "Inhalant use, unspecified, uncomplicated",
short_name: "Inhalant use, unspecified, uncomplicated",
category_name: "Inhalant use, unspecified, uncomplicated"
}
end
def _F18920 do
%ICDCode{full_code: "F18920",
category_code: "F18",
short_code: "920",
full_name: "Inhalant use, unspecified with intoxication, uncomplicated",
short_name: "Inhalant use, unspecified with intoxication, uncomplicated",
category_name: "Inhalant use, unspecified with intoxication, uncomplicated"
}
end
def _F18921 do
%ICDCode{full_code: "F18921",
category_code: "F18",
short_code: "921",
full_name: "Inhalant use, unspecified with intoxication with delirium",
short_name: "Inhalant use, unspecified with intoxication with delirium",
category_name: "Inhalant use, unspecified with intoxication with delirium"
}
end
def _F18929 do
%ICDCode{full_code: "F18929",
category_code: "F18",
short_code: "929",
full_name: "Inhalant use, unspecified with intoxication, unspecified",
short_name: "Inhalant use, unspecified with intoxication, unspecified",
category_name: "Inhalant use, unspecified with intoxication, unspecified"
}
end
def _F1894 do
%ICDCode{full_code: "F1894",
category_code: "F18",
short_code: "94",
full_name: "Inhalant use, unspecified with inhalant-induced mood disorder",
short_name: "Inhalant use, unspecified with inhalant-induced mood disorder",
category_name: "Inhalant use, unspecified with inhalant-induced mood disorder"
}
end
def _F18950 do
%ICDCode{full_code: "F18950",
category_code: "F18",
short_code: "950",
full_name: "Inhalant use, unspecified with inhalant-induced psychotic disorder with delusions",
short_name: "Inhalant use, unspecified with inhalant-induced psychotic disorder with delusions",
category_name: "Inhalant use, unspecified with inhalant-induced psychotic disorder with delusions"
}
end
def _F18951 do
%ICDCode{full_code: "F18951",
category_code: "F18",
short_code: "951",
full_name: "Inhalant use, unspecified with inhalant-induced psychotic disorder with hallucinations",
short_name: "Inhalant use, unspecified with inhalant-induced psychotic disorder with hallucinations",
category_name: "Inhalant use, unspecified with inhalant-induced psychotic disorder with hallucinations"
}
end
def _F18959 do
%ICDCode{full_code: "F18959",
category_code: "F18",
short_code: "959",
full_name: "Inhalant use, unspecified with inhalant-induced psychotic disorder, unspecified",
short_name: "Inhalant use, unspecified with inhalant-induced psychotic disorder, unspecified",
category_name: "Inhalant use, unspecified with inhalant-induced psychotic disorder, unspecified"
}
end
def _F1897 do
%ICDCode{full_code: "F1897",
category_code: "F18",
short_code: "97",
full_name: "Inhalant use, unspecified with inhalant-induced persisting dementia",
short_name: "Inhalant use, unspecified with inhalant-induced persisting dementia",
category_name: "Inhalant use, unspecified with inhalant-induced persisting dementia"
}
end
def _F18980 do
%ICDCode{full_code: "F18980",
category_code: "F18",
short_code: "980",
full_name: "Inhalant use, unspecified with inhalant-induced anxiety disorder",
short_name: "Inhalant use, unspecified with inhalant-induced anxiety disorder",
category_name: "Inhalant use, unspecified with inhalant-induced anxiety disorder"
}
end
def _F18988 do
%ICDCode{full_code: "F18988",
category_code: "F18",
short_code: "988",
full_name: "Inhalant use, unspecified with other inhalant-induced disorder",
short_name: "Inhalant use, unspecified with other inhalant-induced disorder",
category_name: "Inhalant use, unspecified with other inhalant-induced disorder"
}
end
def _F1899 do
%ICDCode{full_code: "F1899",
category_code: "F18",
short_code: "99",
full_name: "Inhalant use, unspecified with unspecified inhalant-induced disorder",
short_name: "Inhalant use, unspecified with unspecified inhalant-induced disorder",
category_name: "Inhalant use, unspecified with unspecified inhalant-induced disorder"
}
end
end
| 41.335294 | 113 | 0.663512 |
794b0e17ee2fbce76521648d9101531d3d6b149e | 9,933 | ex | Elixir | lib/elixir/lib/module/locals_tracker.ex | diogovk/elixir | 7b8213affaad38b50afaa3dfc3a43717f35ba4e7 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/module/locals_tracker.ex | diogovk/elixir | 7b8213affaad38b50afaa3dfc3a43717f35ba4e7 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/module/locals_tracker.ex | diogovk/elixir | 7b8213affaad38b50afaa3dfc3a43717f35ba4e7 | [
"Apache-2.0"
] | null | null | null | # This is an Elixir module responsible for tracking
# calls in order to extract Elixir modules' behaviour
# during compilation time.
#
# ## Implementation
#
# The implementation uses the digraph module to track
# all dependencies. The graph starts with one main vertex:
#
# * `:local` - points to local functions
#
# We can also have the following vertices:
#
# * `Module` - a module that was invoked via an import
# * `{name, arity}` - a local function/arity pair
# * `{:import, name, arity}` - an invoked function/arity import
#
# Each of those vertices can associate to other vertices
# as described below:
#
# * `Module`
# * in neighbours: `{:import, name, arity}`
#
# * `{name, arity}`
# * in neighbours: `:local`, `{name, arity}`
# * out neighbours: `{:import, name, arity}`
#
# * `{:import, name, arity}`
# * in neighbours: `{name, arity}`
# * out neighbours: `Module`
#
# Note that since this is required for bootstrap, we can't use
# any of the `GenServer` conveniences.
defmodule Module.LocalsTracker do
@moduledoc false
@timeout 30_000
@behaviour :gen_server
@type ref :: pid | module
@type name :: atom
@type name_arity :: {name, arity}
@type local :: {name, arity}
@type import :: {:import, name, arity}
# Public API
@doc """
Returns all imported modules that had the given
`{name, arity}` invoked.
"""
@spec imports_with_dispatch(ref, name_arity) :: [module]
def imports_with_dispatch(ref, {name, arity}) do
d = :gen_server.call(to_pid(ref), :digraph, @timeout)
:digraph.out_neighbours(d, {:import, name, arity})
end
@doc """
Returns all locals that are reachable.
By default, all public functions are reachable.
A private function is only reachable if it has
a public function that it invokes directly.
"""
@spec reachable(ref) :: [local]
def reachable(ref) do
reachable_from(:gen_server.call(to_pid(ref), :digraph, @timeout), :local)
end
defp reachable_from(d, starting) do
:sets.to_list(reduce_reachable(d, starting, :sets.new))
end
defp reduce_reachable(d, vertex, vertices) do
neighbours = :digraph.out_neighbours(d, vertex)
neighbours = (for {_, _} = t <- neighbours, do: t) |> :sets.from_list
remaining = :sets.subtract(neighbours, vertices)
vertices = :sets.union(neighbours, vertices)
:sets.fold(&reduce_reachable(d, &1, &2), vertices, remaining)
end
defp to_pid(pid) when is_pid(pid), do: pid
defp to_pid(mod) when is_atom(mod) do
table = :elixir_module.data_table(mod)
[{_, val}] = :ets.lookup(table, {:elixir, :locals_tracker})
val
end
# Internal API
# Starts the tracker and returns its pid.
@doc false
def start_link do
:gen_server.start_link(__MODULE__, [], [])
end
# Adds a definition into the tracker. A public
# definition is connected with the :local node
# while a private one is left unreachable until
# a call is made to.
@doc false
def add_definition(pid, kind, tuple) when kind in [:def, :defp, :defmacro, :defmacrop] do
:gen_server.cast(pid, {:add_definition, kind, tuple})
end
# Adds and tracks defaults for a definition into the tracker.
@doc false
def add_defaults(pid, kind, tuple, defaults) when kind in [:def, :defp, :defmacro, :defmacrop] do
:gen_server.cast(pid, {:add_defaults, kind, tuple, defaults})
end
# Adds a local dispatch to the given target.
def add_local(pid, to) when is_tuple(to) do
:gen_server.cast(pid, {:add_local, :local, to})
end
# Adds a local dispatch from-to the given target.
@doc false
def add_local(pid, from, to) when is_tuple(from) and is_tuple(to) do
:gen_server.cast(pid, {:add_local, from, to})
end
# Adds a import dispatch to the given target.
@doc false
def add_import(pid, function, module, target) when is_atom(module) and is_tuple(target) do
:gen_server.cast(pid, {:add_import, function, module, target})
end
# Yanks a local node. Returns its in and out vertices in a tuple.
@doc false
def yank(pid, local) do
:gen_server.call(to_pid(pid), {:yank, local}, @timeout)
end
# Reattach a previously yanked node
@doc false
def reattach(pid, kind, tuple, neighbours) do
:gen_server.cast(to_pid(pid), {:reattach, kind, tuple, neighbours})
end
# Collecting all conflicting imports with the given functions
@doc false
def collect_imports_conflicts(pid, all_defined) do
d = :gen_server.call(pid, :digraph, @timeout)
for {name, arity} <- all_defined,
:digraph.in_neighbours(d, {:import, name, arity}) != [],
n = :digraph.out_neighbours(d, {:import, name, arity}),
n != [] do
{n, name, arity}
end
end
# Collect all unused definitions based on the private
# given also accounting the expected amount of default
# clauses a private function have.
@doc false
def collect_unused_locals(ref, private) do
d = :gen_server.call(to_pid(ref), :digraph, @timeout)
{unreachable(d, private), collect_warnings(d, private)}
end
defp unreachable(d, private) do
unreachable = for {tuple, _, _} <- private, do: tuple
private =
for {tuple, :defp, _} <- private do
neighbours = :digraph.in_neighbours(d, tuple)
neighbours = for {_, _} = t <- neighbours, do: t
{tuple, :sets.from_list(neighbours)}
end
reduce_unreachable(private, [], :sets.from_list(unreachable))
end
defp reduce_unreachable([{vertex, callers} | t], acc, unreachable) do
if :sets.is_subset(callers, unreachable) do
reduce_unreachable(t, [{vertex, callers} | acc], unreachable)
else
reduce_unreachable(acc ++ t, [], :sets.del_element(vertex, unreachable))
end
end
defp reduce_unreachable([], _acc, unreachable) do
:sets.to_list(unreachable)
end
defp collect_warnings(d, private) do
reachable = reachable_from(d, :local)
:lists.foldl(&collect_warnings(&1, &2, reachable), [], private)
end
defp collect_warnings({tuple, kind, 0}, acc, reachable) do
if :lists.member(tuple, reachable) do
acc
else
[{:unused_def, tuple, kind} | acc]
end
end
defp collect_warnings({tuple, kind, default}, acc, reachable) when default > 0 do
{name, arity} = tuple
min = arity - default
max = arity
invoked = for {n, a} <- reachable, n == name, a in min..max, do: a
if invoked == [] do
[{:unused_def, tuple, kind} | acc]
else
case :lists.min(invoked) - min do
0 -> acc
^default -> [{:unused_args, tuple} | acc]
unused_args -> [{:unused_args, tuple, unused_args} | acc]
end
end
end
@doc false
def cache_env(pid, env) do
:gen_server.call(pid, {:cache_env, env}, @timeout)
end
@doc false
def get_cached_env(pid, ref) do
:gen_server.call(pid, {:get_cached_env, ref}, @timeout)
end
# Stops the gen server
@doc false
def stop(pid) do
:gen_server.cast(pid, :stop)
end
# Callbacks
def init([]) do
d = :digraph.new([:protected])
:digraph.add_vertex(d, :local)
{:ok, {d, []}}
end
@doc false
def handle_call({:cache_env, env}, _from, {d, cache}) do
case cache do
[{i, ^env} | _] ->
{:reply, i, {d, cache}}
t ->
i = length(t)
{:reply, i, {d, [{i, env} | t]}}
end
end
def handle_call({:get_cached_env, ref}, _from, {_, cache} = state) do
{^ref, env} = :lists.keyfind(ref, 1, cache)
{:reply, env, state}
end
def handle_call({:yank, local}, _from, {d, _} = state) do
out_vertices = :digraph.out_neighbours(d, local)
:digraph.del_edges(d, :digraph.out_edges(d, local))
{:reply, {[], out_vertices}, state}
end
def handle_call(:digraph, _from, {d, _} = state) do
{:reply, d, state}
end
@doc false
def handle_info(_msg, state) do
{:noreply, state}
end
def handle_cast({:add_local, from, to}, {d, _} = state) do
handle_add_local(d, from, to)
{:noreply, state}
end
def handle_cast({:add_import, function, module, {name, arity}}, {d, _} = state) do
handle_import(d, function, module, name, arity)
{:noreply, state}
end
def handle_cast({:add_definition, kind, tuple}, {d, _} = state) do
handle_add_definition(d, kind, tuple)
{:noreply, state}
end
def handle_cast({:add_defaults, kind, {name, arity}, defaults}, {d, _} = state) do
for i <- :lists.seq(arity - defaults, arity - 1) do
handle_add_definition(d, kind, {name, i})
handle_add_local(d, {name, i}, {name, i + 1})
end
{:noreply, state}
end
def handle_cast({:reattach, _kind, tuple, {in_neigh, out_neigh}}, {d, _} = state) do
for from <- in_neigh do
:digraph.add_vertex(d, from)
replace_edge!(d, from, tuple)
end
for to <- out_neigh do
:digraph.add_vertex(d, to)
replace_edge!(d, tuple, to)
end
{:noreply, state}
end
def handle_cast(:stop, state) do
{:stop, :normal, state}
end
@doc false
def terminate(_reason, _state) do
:ok
end
@doc false
def code_change(_old, state, _extra) do
{:ok, state}
end
defp handle_import(d, function, module, name, arity) do
:digraph.add_vertex(d, module)
tuple = {:import, name, arity}
:digraph.add_vertex(d, tuple)
replace_edge!(d, tuple, module)
if function != nil do
replace_edge!(d, function, tuple)
end
:ok
end
defp handle_add_local(d, from, to) do
:digraph.add_vertex(d, to)
replace_edge!(d, from, to)
end
defp handle_add_definition(d, public, tuple) when public in [:def, :defmacro] do
:digraph.add_vertex(d, tuple)
replace_edge!(d, :local, tuple)
end
defp handle_add_definition(d, private, tuple) when private in [:defp, :defmacrop] do
:digraph.add_vertex(d, tuple)
end
defp replace_edge!(d, from, to) do
_ = unless :lists.member(to, :digraph.out_neighbours(d, from)) do
[:"$e" | _] = :digraph.add_edge(d, from, to)
end
:ok
end
end
| 27.515235 | 99 | 0.648948 |
794b1443187fd3e2ee50234bea6d50e865f9c1a2 | 3,334 | ex | Elixir | lib/codes/codes_f60.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_f60.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_f60.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_F60 do
alias IcdCode.ICDCode
def _F600 do
%ICDCode{full_code: "F600",
category_code: "F60",
short_code: "0",
full_name: "Paranoid personality disorder",
short_name: "Paranoid personality disorder",
category_name: "Paranoid personality disorder"
}
end
def _F601 do
%ICDCode{full_code: "F601",
category_code: "F60",
short_code: "1",
full_name: "Schizoid personality disorder",
short_name: "Schizoid personality disorder",
category_name: "Schizoid personality disorder"
}
end
def _F602 do
%ICDCode{full_code: "F602",
category_code: "F60",
short_code: "2",
full_name: "Antisocial personality disorder",
short_name: "Antisocial personality disorder",
category_name: "Antisocial personality disorder"
}
end
def _F603 do
%ICDCode{full_code: "F603",
category_code: "F60",
short_code: "3",
full_name: "Borderline personality disorder",
short_name: "Borderline personality disorder",
category_name: "Borderline personality disorder"
}
end
def _F604 do
%ICDCode{full_code: "F604",
category_code: "F60",
short_code: "4",
full_name: "Histrionic personality disorder",
short_name: "Histrionic personality disorder",
category_name: "Histrionic personality disorder"
}
end
def _F605 do
%ICDCode{full_code: "F605",
category_code: "F60",
short_code: "5",
full_name: "Obsessive-compulsive personality disorder",
short_name: "Obsessive-compulsive personality disorder",
category_name: "Obsessive-compulsive personality disorder"
}
end
def _F606 do
%ICDCode{full_code: "F606",
category_code: "F60",
short_code: "6",
full_name: "Avoidant personality disorder",
short_name: "Avoidant personality disorder",
category_name: "Avoidant personality disorder"
}
end
def _F607 do
%ICDCode{full_code: "F607",
category_code: "F60",
short_code: "7",
full_name: "Dependent personality disorder",
short_name: "Dependent personality disorder",
category_name: "Dependent personality disorder"
}
end
def _F6081 do
%ICDCode{full_code: "F6081",
category_code: "F60",
short_code: "81",
full_name: "Narcissistic personality disorder",
short_name: "Narcissistic personality disorder",
category_name: "Narcissistic personality disorder"
}
end
def _F6089 do
%ICDCode{full_code: "F6089",
category_code: "F60",
short_code: "89",
full_name: "Other specific personality disorders",
short_name: "Other specific personality disorders",
category_name: "Other specific personality disorders"
}
end
def _F609 do
%ICDCode{full_code: "F609",
category_code: "F60",
short_code: "9",
full_name: "Personality disorder, unspecified",
short_name: "Personality disorder, unspecified",
category_name: "Personality disorder, unspecified"
}
end
end
| 31.45283 | 68 | 0.617277 |
794b15e0fdb4a81e488693af215d29de952115fb | 1,717 | exs | Elixir | lib/mix/test/mix/tasks/deps.path_test.exs | enokd/elixir | e39b32f235082b8a29fcb22d250c822cca98609f | [
"Apache-2.0"
] | 1 | 2015-11-12T19:23:45.000Z | 2015-11-12T19:23:45.000Z | lib/mix/test/mix/tasks/deps.path_test.exs | enokd/elixir | e39b32f235082b8a29fcb22d250c822cca98609f | [
"Apache-2.0"
] | null | null | null | lib/mix/test/mix/tasks/deps.path_test.exs | enokd/elixir | e39b32f235082b8a29fcb22d250c822cca98609f | [
"Apache-2.0"
] | null | null | null | Code.require_file "../../test_helper.exs", __DIR__
defmodule Mix.Tasks.DepsPathTest do
use MixTest.Case
defmodule DepsApp do
def project do
[
app: :raw_sample,
version: "0.1.0",
deps: [
{ :raw_repo, "0.1.0", path: "custom/raw_repo" }
]
]
end
end
test "marks for compilation across environments on get/update" do
Mix.Project.push DepsApp
in_fixture "deps_status", fn ->
File.mkdir_p!("_build/dev/lib/raw_repo")
File.mkdir_p!("_build/test/lib/raw_repo")
Mix.Tasks.Deps.Get.run ["--all"]
assert File.exists?("_build/dev/lib/raw_repo/.compile")
assert File.exists?("_build/test/lib/raw_repo/.compile")
Mix.Tasks.Run.run ["-e", "Mix.shell.info RawRepo.hello"]
assert_received { :mix_shell, :info, ["* Compiling raw_repo"] }
assert_received { :mix_shell, :info, ["world"] }
end
end
test "compiles ands runs even if lock does not match" do
Mix.Project.push DepsApp
in_fixture "deps_status", fn ->
Mix.Dep.Lock.write [raw_repo: "abcdef"]
Mix.Tasks.Run.run ["-e", "Mix.shell.info RawRepo.hello"]
assert_received { :mix_shell, :info, ["* Compiling raw_repo"] }
assert_received { :mix_shell, :info, ["world"] }
end
end
defmodule InvalidPathDepsApp do
def project do
[
app: :rebar_as_dep,
version: "0.1.0",
deps: [{ :rebar_dep, path: MixTest.Case.tmp_path("rebar_dep") }]
]
end
end
test "raises on non-mix path deps" do
Mix.Project.push InvalidPathDepsApp
assert_raise Mix.Error, ~r/:path option can only be used with mix projects/, fn ->
Mix.Tasks.Deps.Get.run []
end
end
end
| 27.253968 | 86 | 0.623762 |
794b18829a8cc4ae2907681596fefd59ec326854 | 75 | ex | Elixir | web/views/home_view.ex | ShadowBan/health-inspector | 47a05a97031d2d4dce411fc06bf8612087ba31cb | [
"MIT"
] | null | null | null | web/views/home_view.ex | ShadowBan/health-inspector | 47a05a97031d2d4dce411fc06bf8612087ba31cb | [
"MIT"
] | null | null | null | web/views/home_view.ex | ShadowBan/health-inspector | 47a05a97031d2d4dce411fc06bf8612087ba31cb | [
"MIT"
] | null | null | null | defmodule HealthInspector.HomeView do
use HealthInspector.Web, :view
end
| 18.75 | 37 | 0.826667 |
794b2b1fec37124172d2a156aef96118a2f808c7 | 2,133 | ex | Elixir | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p3beta1_bounding_poly.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p3beta1_bounding_poly.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p3beta1_bounding_poly.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.Vision.V1.Model.GoogleCloudVisionV1p3beta1BoundingPoly do
@moduledoc """
A bounding polygon for the detected image annotation.
## Attributes
* `normalizedVertices` (*type:* `list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1NormalizedVertex.t)`, *default:* `nil`) - The bounding polygon normalized vertices.
* `vertices` (*type:* `list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1Vertex.t)`, *default:* `nil`) - The bounding polygon vertices.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:normalizedVertices =>
list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1NormalizedVertex.t()) | nil,
:vertices => list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1Vertex.t()) | nil
}
field(:normalizedVertices,
as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1NormalizedVertex,
type: :list
)
field(:vertices, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1Vertex, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1BoundingPoly do
def decode(value, options) do
GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1BoundingPoly.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1BoundingPoly do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.781818 | 177 | 0.759962 |
794b566692ccc7cf421bbd7bfe0cf87ca07c8362 | 748 | ex | Elixir | elixir/minimal_dsl.ex | ztk37/snippets | 17354149a1c673365d164cbd114d26dfe2dd83c7 | [
"MIT"
] | null | null | null | elixir/minimal_dsl.ex | ztk37/snippets | 17354149a1c673365d164cbd114d26dfe2dd83c7 | [
"MIT"
] | null | null | null | elixir/minimal_dsl.ex | ztk37/snippets | 17354149a1c673365d164cbd114d26dfe2dd83c7 | [
"MIT"
] | null | null | null | defmodule Store do
use Agent
@initial_state %{
:items => []
}
def start_link() do
Agent.start_link(fn -> @initial_state end)
end
def add_item(pid, item) do
# IO.inspect(item)
Agent.update(pid, fn state ->
%{state | :items => [item | state.items ]}
end)
end
def get_items(pid) do
Agent.get(pid, fn state -> state[:items] end)
end
end
defmodule DSL do
defmacro __using__(_opts) do
{:ok, pid} = Store.start_link()
quote do
def item(item), do: Store.add_item(unquote(pid), item)
def items(), do: Store.get_items(unquote(pid))
end
end
end
defmodule Main do
use DSL
def run() do
item(1)
item(2)
item(3)
items() |> IO.inspect()
end
end
Main.run()
| 15.265306 | 60 | 0.601604 |
794bb6fffa8447decd5b8d1bd0260be1009a346d | 461 | ex | Elixir | lib/igwet/admin/mailer.ex | TheSwanFactory/igwet | 0a450686d1d222eb8e39e23ba5d2ea83657862d1 | [
"MIT"
] | null | null | null | lib/igwet/admin/mailer.ex | TheSwanFactory/igwet | 0a450686d1d222eb8e39e23ba5d2ea83657862d1 | [
"MIT"
] | 18 | 2018-02-25T11:13:46.000Z | 2022-03-28T03:43:38.000Z | lib/igwet/admin/mailer.ex | TheSwanFactory/igwet | 0a450686d1d222eb8e39e23ba5d2ea83657862d1 | [
"MIT"
] | 1 | 2019-01-04T12:16:47.000Z | 2019-01-04T12:16:47.000Z | defmodule Igwet.Admin.Mailer do
@moduledoc """
Use Mailgun to generate email messages
"""
use Bamboo.Mailer, otp_app: :igwet
@doc """
Return email address generated from key of node
## Examples
iex> alias Igwet.Admin.Mailer
iex> Mailer.keyed_email %{key: "test"}
"[email protected]"
"""
def keyed_email(%{key: key}) do
domain = Application.get_env(:igwet, Igwet.Admin.Mailer)[:domain]
"#{key}@#{domain}"
end
end
| 21.952381 | 69 | 0.650759 |
794be3c1197879566040d03d028b40084e667e06 | 4,106 | ex | Elixir | clients/vision/lib/google_api/vision/v1/request_builder.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/vision/lib/google_api/vision/v1/request_builder.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/vision/lib/google_api/vision/v1/request_builder.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Vision.V1.RequestBuilder do
@moduledoc """
Helper functions for building Tesla requests
"""
@doc """
Specify the request method when building a request
## Parameters
- request (Map) - Collected request options
- m (String) - Request method
## Returns
Map
"""
@spec method(map(), String.t) :: map()
def method(request, m) do
Map.put_new(request, :method, m)
end
@doc """
Specify the request method when building a request
## Parameters
- request (Map) - Collected request options
- u (String) - Request URL
## Returns
Map
"""
@spec url(map(), String.t) :: map()
def url(request, u) do
Map.put_new(request, :url, u)
end
@doc """
Add optional parameters to the request
## Parameters
- request (Map) - Collected request options
- definitions (Map) - Map of parameter name to parameter location.
- options (KeywordList) - The provided optional parameters
## Returns
Map
"""
@spec add_optional_params(map(), %{optional(:atom) => :atom}, keyword()) :: map()
def add_optional_params(request, _, []), do: request
def add_optional_params(request, definitions, [{key, value} | tail]) do
case definitions do
%{^key => location} ->
request
|> add_param(location, key, value)
|> add_optional_params(definitions, tail)
_ ->
add_optional_params(request, definitions, tail)
end
end
@doc """
Add optional parameters to the request
## Parameters
- request (Map) - Collected request options
- location (atom) - Where to put the parameter
- key (atom) - The name of the parameter
- value (any) - The value of the parameter
## Returns
Map
"""
@spec add_param(map(), :atom, :atom, any()) :: map()
def add_param(request, :body, :body, value), do: Map.put(request, :body, value)
def add_param(request, :body, key, value) do
request
|> Map.put_new_lazy(:body, &Tesla.Multipart.new/0)
|> Map.update!(:body, &(Tesla.Multipart.add_field(&1, key, Poison.encode!(value), headers: [{:"Content-Type", "application/json"}])))
end
def add_param(request, :file, name, path) do
request
|> Map.put_new_lazy(:body, &Tesla.Multipart.new/0)
|> Map.update!(:body, &(Tesla.Multipart.add_file(&1, path, name: name)))
end
def add_param(request, :form, name, value) do
request
|> Map.update(:body, %{name => value}, &(Map.put(&1, name, value)))
end
def add_param(request, location, key, value) do
Map.update(request, location, [{key, value}], &(&1 ++ [{key, value}]))
end
@doc """
Handle the response for a Tesla request
## Parameters
- env (Tesla.Env) - The response object
- struct - The shape of the struct to deserialize into
## Returns
{:ok, struct} on success
{:error, info} on failure
"""
@spec decode(Tesla.Env.t) :: {:ok, struct()} | {:error, Tesla.Env.t}
def decode(%Tesla.Env{status: 200, body: body}), do: Poison.decode(body)
def decode(response) do
{:error, response}
end
@spec decode(Tesla.Env.t, struct()) :: {:ok, struct()} | {:error, Tesla.Env.t}
def decode(%Tesla.Env{status: 200} = env, false), do: {:ok, env}
def decode(%Tesla.Env{status: 200, body: body}, struct) do
Poison.decode(body, as: struct)
end
def decode(response, _struct) do
{:error, response}
end
end
| 28.123288 | 137 | 0.663419 |
794bee756cf38c8e4e25358d08e70f8925354140 | 690 | exs | Elixir | test/test_helper.exs | amilkr/nebulex_ext | ac76ed3b56823450f79e6dec56d1247192a2abc3 | [
"MIT"
] | 8 | 2018-07-19T06:02:30.000Z | 2019-04-19T18:14:37.000Z | test/test_helper.exs | amilkr/nebulex_ext | ac76ed3b56823450f79e6dec56d1247192a2abc3 | [
"MIT"
] | 1 | 2018-11-01T15:06:52.000Z | 2018-11-01T15:06:52.000Z | test/test_helper.exs | amilkr/nebulex_ext | ac76ed3b56823450f79e6dec56d1247192a2abc3 | [
"MIT"
] | 2 | 2019-06-25T16:45:46.000Z | 2019-10-07T22:07:51.000Z | # Load support files
support_files =
for file <- File.ls!("test/support") do
{file, Code.require_file("support/" <> file, __DIR__)}
end
# Load Nebulex helper
File.cd!("deps/nebulex", fn ->
Code.require_file "test/test_helper.exs"
end)
# Load support files on remote nodes if clustered is present
unless :clustered in Keyword.get(ExUnit.configuration(), :exclude, []) do
nodes = Node.list()
Enum.each(support_files, fn({file, loaded}) ->
Enum.each(loaded, fn({mod, bin}) ->
expected = List.duplicate({:module, mod}, length(nodes))
{^expected, []} = :rpc.multicall(nodes, :code, :load_binary, [mod, to_charlist(file), bin])
end)
end)
end
ExUnit.start()
| 28.75 | 97 | 0.671014 |
794bf6ce6a6b1d8f54c29f7fa48a7d3a19610b72 | 2,565 | ex | Elixir | lib/codes/codes_q67.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_q67.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_q67.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_Q67 do
alias IcdCode.ICDCode
def _Q670 do
%ICDCode{full_code: "Q670",
category_code: "Q67",
short_code: "0",
full_name: "Congenital facial asymmetry",
short_name: "Congenital facial asymmetry",
category_name: "Congenital facial asymmetry"
}
end
def _Q671 do
%ICDCode{full_code: "Q671",
category_code: "Q67",
short_code: "1",
full_name: "Congenital compression facies",
short_name: "Congenital compression facies",
category_name: "Congenital compression facies"
}
end
def _Q672 do
%ICDCode{full_code: "Q672",
category_code: "Q67",
short_code: "2",
full_name: "Dolichocephaly",
short_name: "Dolichocephaly",
category_name: "Dolichocephaly"
}
end
def _Q673 do
%ICDCode{full_code: "Q673",
category_code: "Q67",
short_code: "3",
full_name: "Plagiocephaly",
short_name: "Plagiocephaly",
category_name: "Plagiocephaly"
}
end
def _Q674 do
%ICDCode{full_code: "Q674",
category_code: "Q67",
short_code: "4",
full_name: "Other congenital deformities of skull, face and jaw",
short_name: "Other congenital deformities of skull, face and jaw",
category_name: "Other congenital deformities of skull, face and jaw"
}
end
def _Q675 do
%ICDCode{full_code: "Q675",
category_code: "Q67",
short_code: "5",
full_name: "Congenital deformity of spine",
short_name: "Congenital deformity of spine",
category_name: "Congenital deformity of spine"
}
end
def _Q676 do
%ICDCode{full_code: "Q676",
category_code: "Q67",
short_code: "6",
full_name: "Pectus excavatum",
short_name: "Pectus excavatum",
category_name: "Pectus excavatum"
}
end
def _Q677 do
%ICDCode{full_code: "Q677",
category_code: "Q67",
short_code: "7",
full_name: "Pectus carinatum",
short_name: "Pectus carinatum",
category_name: "Pectus carinatum"
}
end
def _Q678 do
%ICDCode{full_code: "Q678",
category_code: "Q67",
short_code: "8",
full_name: "Other congenital deformities of chest",
short_name: "Other congenital deformities of chest",
category_name: "Other congenital deformities of chest"
}
end
end
| 29.147727 | 78 | 0.591423 |
794bfe5aab4eee94a5ed74d3c7ccb361de6bc81c | 4,051 | ex | Elixir | clients/games/lib/google_api/games/v1/model/achievement_definition.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/games/lib/google_api/games/v1/model/achievement_definition.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/achievement_definition.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.Games.V1.Model.AchievementDefinition do
@moduledoc """
This is a JSON template for an achievement definition object.
## Attributes
* `achievementType` (*type:* `String.t`, *default:* `nil`) - The type of the achievement.
Possible values are:
- "STANDARD" - Achievement is either locked or unlocked.
- "INCREMENTAL" - Achievement is incremental.
* `description` (*type:* `String.t`, *default:* `nil`) - The description of the achievement.
* `experiencePoints` (*type:* `String.t`, *default:* `nil`) - Experience points which will be earned when unlocking this achievement.
* `formattedTotalSteps` (*type:* `String.t`, *default:* `nil`) - The total steps for an incremental achievement as a string.
* `id` (*type:* `String.t`, *default:* `nil`) - The ID of the achievement.
* `initialState` (*type:* `String.t`, *default:* `nil`) - The initial state of the achievement.
Possible values are:
- "HIDDEN" - Achievement is hidden.
- "REVEALED" - Achievement is revealed.
- "UNLOCKED" - Achievement is unlocked.
* `isRevealedIconUrlDefault` (*type:* `boolean()`, *default:* `nil`) - Indicates whether the revealed icon image being returned is a default image, or is provided by the game.
* `isUnlockedIconUrlDefault` (*type:* `boolean()`, *default:* `nil`) - Indicates whether the unlocked icon image being returned is a default image, or is game-provided.
* `kind` (*type:* `String.t`, *default:* `games#achievementDefinition`) - Uniquely identifies the type of this resource. Value is always the fixed string games#achievementDefinition.
* `name` (*type:* `String.t`, *default:* `nil`) - The name of the achievement.
* `revealedIconUrl` (*type:* `String.t`, *default:* `nil`) - The image URL for the revealed achievement icon.
* `totalSteps` (*type:* `integer()`, *default:* `nil`) - The total steps for an incremental achievement.
* `unlockedIconUrl` (*type:* `String.t`, *default:* `nil`) - The image URL for the unlocked achievement icon.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:achievementType => String.t(),
:description => String.t(),
:experiencePoints => String.t(),
:formattedTotalSteps => String.t(),
:id => String.t(),
:initialState => String.t(),
:isRevealedIconUrlDefault => boolean(),
:isUnlockedIconUrlDefault => boolean(),
:kind => String.t(),
:name => String.t(),
:revealedIconUrl => String.t(),
:totalSteps => integer(),
:unlockedIconUrl => String.t()
}
field(:achievementType)
field(:description)
field(:experiencePoints)
field(:formattedTotalSteps)
field(:id)
field(:initialState)
field(:isRevealedIconUrlDefault)
field(:isUnlockedIconUrlDefault)
field(:kind)
field(:name)
field(:revealedIconUrl)
field(:totalSteps)
field(:unlockedIconUrl)
end
defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.AchievementDefinition do
def decode(value, options) do
GoogleApi.Games.V1.Model.AchievementDefinition.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.AchievementDefinition do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 45.011111 | 186 | 0.683535 |
794c0136a3aac9897783aa28fe775c52e8321b5c | 211 | exs | Elixir | config/test.exs | cnsa/ex_machina | 8a55155df735b2d0c143676f451a7a1ee191dc85 | [
"MIT"
] | 1 | 2019-05-20T04:59:57.000Z | 2019-05-20T04:59:57.000Z | config/test.exs | ByteDecoder/ex_machina | 012e957e7ab1e22eca18b62e8f3fcc2a98a7f286 | [
"MIT"
] | null | null | null | config/test.exs | ByteDecoder/ex_machina | 012e957e7ab1e22eca18b62e8f3fcc2a98a7f286 | [
"MIT"
] | null | null | null | use Mix.Config
config :ex_machina, ExMachina.TestRepo,
hostname: "localhost",
database: "ex_machina_test",
adapter: Ecto.Adapters.Postgres,
pool: Ecto.Adapters.SQL.Sandbox
config :logger, level: :warn
| 21.1 | 39 | 0.753555 |
794c11d2f8a040f3d72ec2d283b8820ea37d5799 | 550 | ex | Elixir | apps/banking_api_challenge/lib/banking_api_challenge/operations/inputs/deposit_input.ex | jhonndabi/banking-api-challenge | 1e13c675b02c8e62a76e82b0a0dd6a44306a211e | [
"Apache-2.0"
] | null | null | null | apps/banking_api_challenge/lib/banking_api_challenge/operations/inputs/deposit_input.ex | jhonndabi/banking-api-challenge | 1e13c675b02c8e62a76e82b0a0dd6a44306a211e | [
"Apache-2.0"
] | null | null | null | apps/banking_api_challenge/lib/banking_api_challenge/operations/inputs/deposit_input.ex | jhonndabi/banking-api-challenge | 1e13c675b02c8e62a76e82b0a0dd6a44306a211e | [
"Apache-2.0"
] | 1 | 2021-04-20T19:05:48.000Z | 2021-04-20T19:05:48.000Z | defmodule BankingApiChallenge.Operations.Inputs.DepositInput do
@moduledoc """
Deposit operation data
"""
use Ecto.Schema
import Ecto.Changeset
@required_fields [:account_id, :amount]
@primary_key false
embedded_schema do
field :operation_type, :string, default: "deposit"
field :account_id, :binary_id
field :amount, :integer
end
def changeset(params) do
%__MODULE__{}
|> cast(params, @required_fields)
|> validate_required(@required_fields)
|> validate_number(:amount, greater_than: 0)
end
end
| 22 | 63 | 0.716364 |
794c246d1330f660dd1fb469b2f6ba6d0262050c | 2,098 | exs | Elixir | test/bitcrowd_ecto/schema_test.exs | bitcrowd/bitcrowd_ecto | 6e2d41d7dbe1fa1398b545c12385cde2db94285c | [
"Apache-2.0"
] | 2 | 2022-01-11T08:03:49.000Z | 2022-02-11T10:25:30.000Z | test/bitcrowd_ecto/schema_test.exs | bitcrowd/bitcrowd_ecto | 6e2d41d7dbe1fa1398b545c12385cde2db94285c | [
"Apache-2.0"
] | 3 | 2022-02-03T21:28:14.000Z | 2022-03-25T09:03:15.000Z | test/bitcrowd_ecto/schema_test.exs | bitcrowd/bitcrowd_ecto | 6e2d41d7dbe1fa1398b545c12385cde2db94285c | [
"Apache-2.0"
] | null | null | null | defmodule BitcrowdEcto.SchemaTest do
use ExUnit.Case, async: true
import BitcrowdEcto.Schema
defmodule TestEnumSchema do
use Ecto.Schema
schema "test_schema" do
field(:some_enum, Ecto.Enum, values: [:foo, :bar])
field(:some_other_field, :integer)
end
end
doctest BitcrowdEcto.Schema
describe "to_enum_member/3" do
test "returns the atom representation if string value is a member of the enum" do
assert to_enum_member(TestEnumSchema, :some_enum, "foo") == :foo
assert to_enum_member(TestEnumSchema, :some_enum, "bar") == :bar
end
test "accepts atoms as well" do
assert to_enum_member(TestEnumSchema, :some_enum, :foo) == :foo
end
test "returns nil if value is not a member of the enum" do
assert to_enum_member(TestEnumSchema, :some_enum, "baz") == nil
assert to_enum_member(TestEnumSchema, :some_enum, :baz) == nil
end
test "raises an exception if field is not an Ecto.Enum" do
assert_raise ArgumentError, ~r/is not an Ecto.Enum field/, fn ->
to_enum_member(TestEnumSchema, :some_other_field, "baz")
end
end
end
describe "to_enum_member!/3" do
test "returns the atom representation if string value is a member of the enum" do
assert to_enum_member!(TestEnumSchema, :some_enum, "foo") == :foo
assert to_enum_member!(TestEnumSchema, :some_enum, "bar") == :bar
end
test "accepts atoms as well" do
assert to_enum_member!(TestEnumSchema, :some_enum, :foo) == :foo
end
test "raises an exception if value is not a member of the enum" do
assert_raise ArgumentError, ~r/is not a member/, fn ->
to_enum_member!(TestEnumSchema, :some_enum, "baz")
end
assert_raise ArgumentError, ~r/is not a member/, fn ->
to_enum_member!(TestEnumSchema, :some_enum, :baz)
end
end
test "raises an exception if field is not an Ecto.Enum" do
assert_raise ArgumentError, ~r/is not an Ecto.Enum field/, fn ->
to_enum_member!(TestEnumSchema, :some_other_field, "baz")
end
end
end
end
| 32.276923 | 85 | 0.681125 |
794c3ce4bb52b719b5f0dbe12635e2284f74665b | 2,971 | ex | Elixir | clients/blogger/lib/google_api/blogger/v3/model/page.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/blogger/lib/google_api/blogger/v3/model/page.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/blogger/lib/google_api/blogger/v3/model/page.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.Blogger.V3.Model.Page do
@moduledoc """
## Attributes
- author (PageAuthor): Defaults to: `null`.
- blog (PageBlog): Defaults to: `null`.
- content (String.t): The body content of this Page, in HTML. Defaults to: `null`.
- etag (String.t): Etag of the resource. Defaults to: `null`.
- id (String.t): The identifier for this resource. Defaults to: `null`.
- kind (String.t): The kind of this entity. Always blogger#page Defaults to: `null`.
- published (DateTime.t): RFC 3339 date-time when this Page was published. Defaults to: `null`.
- selfLink (String.t): The API REST URL to fetch this resource from. Defaults to: `null`.
- status (String.t): The status of the page for admin resources (either LIVE or DRAFT). Defaults to: `null`.
- title (String.t): The title of this entity. This is the name displayed in the Admin user interface. Defaults to: `null`.
- updated (DateTime.t): RFC 3339 date-time when this Page was last updated. Defaults to: `null`.
- url (String.t): The URL that this Page is displayed at. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:author => GoogleApi.Blogger.V3.Model.PageAuthor.t(),
:blog => GoogleApi.Blogger.V3.Model.PageBlog.t(),
:content => any(),
:etag => any(),
:id => any(),
:kind => any(),
:published => DateTime.t(),
:selfLink => any(),
:status => any(),
:title => any(),
:updated => DateTime.t(),
:url => any()
}
field(:author, as: GoogleApi.Blogger.V3.Model.PageAuthor)
field(:blog, as: GoogleApi.Blogger.V3.Model.PageBlog)
field(:content)
field(:etag)
field(:id)
field(:kind)
field(:published, as: DateTime)
field(:selfLink)
field(:status)
field(:title)
field(:updated, as: DateTime)
field(:url)
end
defimpl Poison.Decoder, for: GoogleApi.Blogger.V3.Model.Page do
def decode(value, options) do
GoogleApi.Blogger.V3.Model.Page.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Blogger.V3.Model.Page do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.679012 | 124 | 0.676876 |
794c6f8272cbcf49709e235ee659896653cb4cc5 | 1,638 | ex | Elixir | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_resource_files.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_resource_files.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_resource_files.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.Apigee.V1.Model.GoogleCloudApigeeV1ResourceFiles do
@moduledoc """
List of resource files.
## Attributes
* `resourceFile` (*type:* `list(GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ResourceFile.t)`, *default:* `nil`) - List of resource files.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:resourceFile => list(GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ResourceFile.t())
}
field(:resourceFile, as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ResourceFile, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ResourceFiles do
def decode(value, options) do
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ResourceFiles.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ResourceFiles do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.851064 | 142 | 0.760684 |
794c717ad493045759af0bf0cdb08030a53a4ac1 | 1,040 | exs | Elixir | test/integration/broken_consumer_throws_test.exs | renderedtext/ex-tackle | 403623f9be6919998fea6871f34aa07ff2655c49 | [
"MIT"
] | 49 | 2016-07-30T13:45:12.000Z | 2021-08-08T13:45:05.000Z | test/integration/broken_consumer_throws_test.exs | renderedtext/ex-tackle | 403623f9be6919998fea6871f34aa07ff2655c49 | [
"MIT"
] | 20 | 2016-08-05T11:54:35.000Z | 2021-06-02T19:43:06.000Z | test/integration/broken_consumer_throws_test.exs | renderedtext/ex-tackle | 403623f9be6919998fea6871f34aa07ff2655c49 | [
"MIT"
] | 14 | 2016-08-05T09:39:51.000Z | 2021-11-29T14:22:28.000Z | defmodule Tackle.BrokenConsumerThrowsTest do
use ExSpec
alias Support
alias Support.MessageTrace
defmodule BrokenConsumer do
use Tackle.Consumer,
url: "amqp://localhost",
exchange: "test-exchange",
routing_key: "test-messages",
service: "broken-service-throw",
retry_delay: 1,
retry_limit: 3
def handle_message(message) do
message |> MessageTrace.save("broken-service-throw")
throw({1, 3, 4})
end
end
@publish_options %{
url: "amqp://localhost",
exchange: "test-exchange",
routing_key: "test-messages"
}
setup do
Support.purge_queue("broken-service-throw.test-messages")
MessageTrace.clear("broken-service-throw")
{:ok, _} = BrokenConsumer.start_link()
:timer.sleep(1000)
end
describe "healthy consumer" do
it "receives the message multiple times" do
Tackle.publish("Hi!", @publish_options)
:timer.sleep(5000)
assert MessageTrace.content("broken-service-throw") == "Hi!Hi!Hi!Hi!"
end
end
end
| 21.22449 | 75 | 0.6625 |
794cb132b65c9adbc12c34d97a8208e1e6777bf5 | 904 | ex | Elixir | lib/exscript/stdlib/enum.ex | craigspaeth/exscript | c3a24790dff0eac592060ba3ae349be7c567e0a7 | [
"MIT"
] | 1 | 2017-12-15T23:55:05.000Z | 2017-12-15T23:55:05.000Z | lib/exscript/stdlib/enum.ex | craigspaeth/exscript | c3a24790dff0eac592060ba3ae349be7c567e0a7 | [
"MIT"
] | null | null | null | lib/exscript/stdlib/enum.ex | craigspaeth/exscript | c3a24790dff0eac592060ba3ae349be7c567e0a7 | [
"MIT"
] | null | null | null | defmodule ExScript.Stdlib.Enum do
def map(e, fun) do
for i <- e do
fun.(i)
end
end
def reduce(enumerable, arg2, arg3) do
JS.embed("const reducer = arg3 || arg2")
JS.embed("const initVal = arg3 ? arg2 : enumerable[0]")
JS.embed("const callback = (acc, val, i) => reducer(val, acc)")
JS.embed("Array.prototype.reduce.call(enumerable, callback, initVal)")
end
def join(e, char) do
JS.embed("Array.prototype.join.call(e, char)")
end
def at(e, index) do
JS.embed("e[index]")
end
def member?(enumerable, element) do
reduce enumerable, false, fn (i, acc) -> acc or i == element end
end
def with_index(enumerable) do
JS.embed "let __i = 0"
for i <- enumerable do
JS.embed "__i++"
index = JS.embed("__i - 1")
{i, index}
end
end
def reverse(enumerable) do
JS.embed "enumerable.slice().reverse()"
end
end
| 22.6 | 74 | 0.613938 |
794cbc67a13f0ecbba1cac11d7da7e82340657c3 | 217 | ex | Elixir | lib/doctor_schedule_web/live/header_component.ex | theguuholi/doctor_schedule | a92dfa92d1398c59718be2428d36bb326d6bc361 | [
"MIT"
] | 2 | 2022-03-11T12:15:01.000Z | 2022-03-11T13:53:21.000Z | lib/doctor_schedule_web/live/header_component.ex | theguuholi/doctor_schedule | a92dfa92d1398c59718be2428d36bb326d6bc361 | [
"MIT"
] | 3 | 2020-12-12T22:10:17.000Z | 2021-04-05T12:53:12.000Z | lib/doctor_schedule_web/live/header_component.ex | theguuholi/doctor_schedule | a92dfa92d1398c59718be2428d36bb326d6bc361 | [
"MIT"
] | 1 | 2021-02-26T04:24:34.000Z | 2021-02-26T04:24:34.000Z | defmodule DoctorScheduleWeb.HeaderComponent do
use Phoenix.LiveComponent
alias DoctorScheduleWeb.PageView
alias Phoenix.View
def render(assigns) do
View.render(PageView, "header.html", assigns)
end
end
| 21.7 | 49 | 0.788018 |
794cdf90eea39fc020ede1ae8e632979fe220f50 | 3,830 | ex | Elixir | lib/oban/notifier.ex | hartzell/oban | 2901cd4655d61eda95813cc1880b003f37cd8983 | [
"Apache-2.0"
] | 1 | 2021-11-20T19:16:24.000Z | 2021-11-20T19:16:24.000Z | lib/oban/notifier.ex | hartzell/oban | 2901cd4655d61eda95813cc1880b003f37cd8983 | [
"Apache-2.0"
] | null | null | null | lib/oban/notifier.ex | hartzell/oban | 2901cd4655d61eda95813cc1880b003f37cd8983 | [
"Apache-2.0"
] | null | null | null | defmodule Oban.Notifier do
@moduledoc false
# The notifier has several different responsibilities and some nuanced behavior:
#
# On Start:
# 1. Create a connection
# 2. Listen for insert/signal events
# 3. If connection fails then log the error, break the circuit, and attempt to connect later
#
# On Exit:
# 1. Trip the circuit breaker
# 2. Schedule a reconnect with backoff
#
# On Listen:
# 1. Put the producer into the listeners map
# 2. Monitor the pid so that we can clean up if the producer dies
#
# On Notification:
# 1. Iterate through the listeners and forward the message
use GenServer
import Oban.Breaker, only: [open_circuit: 1, trip_circuit: 2]
alias Oban.Config
alias Postgrex.Notifications
@type option :: {:name, module()} | {:conf, Config.t()}
@type channel :: :gossip | :insert | :signal
@type queue :: atom()
@mappings %{
gossip: "oban_gossip",
insert: "oban_insert",
signal: "oban_signal"
}
@channels Map.keys(@mappings)
defmodule State do
@moduledoc false
@enforce_keys [:conf]
defstruct [
:conf,
:conn,
:name,
circuit: :enabled,
listeners: %{}
]
end
defmacro gossip, do: @mappings[:gossip]
defmacro insert, do: @mappings[:insert]
defmacro signal, do: @mappings[:signal]
defguardp is_server(server) when is_pid(server) or is_atom(server)
@spec start_link([option]) :: GenServer.on_start()
def start_link(opts) do
name = Keyword.get(opts, :name, __MODULE__)
GenServer.start_link(__MODULE__, Map.new(opts), name: name)
end
@spec listen(module()) :: :ok
def listen(server, channels \\ @channels) when is_server(server) and is_list(channels) do
GenServer.call(server, {:listen, channels})
end
@impl GenServer
def init(opts) do
Process.flag(:trap_exit, true)
{:ok, struct!(State, opts), {:continue, :start}}
end
@impl GenServer
def handle_continue(:start, state) do
{:noreply, connect_and_listen(state)}
end
@impl GenServer
def handle_info({:DOWN, _ref, :process, pid, _reason}, %State{listeners: listeners} = state) do
{:noreply, %{state | listeners: Map.delete(listeners, pid)}}
end
def handle_info({:notification, _, _, prefixed_channel, payload}, state) do
[_prefix, channel] = String.split(prefixed_channel, ".")
decoded = Jason.decode!(payload)
for {pid, channels} <- state.listeners, channel in channels do
send(pid, {:notification, channel, decoded})
end
{:noreply, state}
end
def handle_info({:EXIT, _pid, error}, %State{} = state) do
state = trip_circuit(error, state)
{:noreply, %{state | conn: nil}}
end
def handle_info(:reset_circuit, %State{circuit: :disabled} = state) do
state =
state
|> open_circuit()
|> connect_and_listen()
{:noreply, state}
end
def handle_info(_message, state) do
{:noreply, state}
end
@impl GenServer
def handle_call({:listen, channels}, {pid, _}, %State{listeners: listeners} = state) do
if Map.has_key?(listeners, pid) do
{:reply, :ok, state}
else
Process.monitor(pid)
full_channels =
@mappings
|> Map.take(channels)
|> Map.values()
{:reply, :ok, %{state | listeners: Map.put(listeners, pid, full_channels)}}
end
end
defp connect_and_listen(%State{conf: conf, conn: nil} = state) do
case Notifications.start_link(conf.repo.config()) do
{:ok, conn} ->
Notifications.listen(conn, "#{conf.prefix}.#{gossip()}")
Notifications.listen(conn, "#{conf.prefix}.#{insert()}")
Notifications.listen(conn, "#{conf.prefix}.#{signal()}")
%{state | conn: conn}
{:error, error} ->
trip_circuit(error, state)
end
end
defp connect_and_listen(state), do: state
end
| 25.197368 | 97 | 0.648564 |
794ce42e47bf20b65522dff24be75b8e01bd83aa | 18,253 | exs | Elixir | test/mastani_server_web/query/cms/cms_test.exs | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | 1 | 2019-05-07T15:03:54.000Z | 2019-05-07T15:03:54.000Z | test/mastani_server_web/query/cms/cms_test.exs | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | null | null | null | test/mastani_server_web/query/cms/cms_test.exs | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | null | null | null | defmodule MastaniServer.Test.Query.CMS.Basic do
use MastaniServer.TestTools
alias MastaniServer.Accounts.User
alias MastaniServer.CMS
alias CMS.{Community, Category}
setup do
guest_conn = simu_conn(:guest)
{:ok, community} = db_insert(:community)
{:ok, user} = db_insert(:user)
{:ok, ~m(guest_conn community user)a}
end
describe "[cms communities]" do
@query """
query($id: ID, $raw: String) {
community(id: $id, raw: $raw) {
id
title
threadsCount
tagsCount
threads {
id
raw
index
}
}
}
"""
# @tag :cache
# test "make sure apollo cache works", ~m(guest_conn)a do
# {:ok, _community} = db_insert(:community, %{raw: "cacheme"})
# variables = %{raw: "cacheme"}
# guest_conn |> query_result(@query, variables, "community")
# variables = %{raw: "cacheme"}
# guest_conn |> query_result(@query, variables, "community")
# end
test "can get from alias community name", ~m(guest_conn)a do
{:ok, _community} = db_insert(:community, %{raw: "kubernetes", aka: "k8s"})
variables = %{raw: "k8s"}
aka_results = guest_conn |> query_result(@query, variables, "community")
variables = %{raw: "kubernetes"}
results = guest_conn |> query_result(@query, variables, "community")
assert results["id"] == aka_results["id"]
end
test "can get threads count ", ~m(community guest_conn)a do
{:ok, threads} = db_insert_multi(:thread, 5)
Enum.map(threads, fn thread ->
CMS.set_thread(community, thread)
end)
variables = %{raw: community.raw}
results = guest_conn |> query_result(@query, variables, "community")
assert results["threadsCount"] == 5
end
test "can get tags count ", ~m(community guest_conn user)a do
{:ok, _tags} = db_insert_multi(:tag, 5)
CMS.create_tag(community, :post, mock_attrs(:tag), user)
CMS.create_tag(community, :post, mock_attrs(:tag), user)
variables = %{raw: community.raw}
results = guest_conn |> query_result(@query, variables, "community")
assert results["tagsCount"] == 2
end
test "guest use get community threads with default asc sort index",
~m(guest_conn community)a do
{:ok, threads} = db_insert_multi(:thread, 5)
Enum.map(threads, fn thread ->
CMS.set_thread(community, thread)
end)
variables = %{id: community.id}
results = guest_conn |> query_result(@query, variables, "community")
first_idx = results["threads"] |> List.first() |> Map.get("index")
last_idx = results["threads"] |> List.last() |> Map.get("index")
assert first_idx < last_idx
end
@query """
query($filter: CommunitiesFilter!) {
pagedCommunities(filter: $filter) {
entries {
id
title
index
categories {
id
title
raw
}
}
totalCount
totalPages
pageSize
pageNumber
}
}
"""
test "guest user can get paged communities", ~m(guest_conn)a do
{:ok, _communities} = db_insert_multi(:community, 5)
variables = %{filter: %{page: 1, size: 20}}
results = guest_conn |> query_result(@query, variables, "pagedCommunities")
assert results |> is_valid_pagination?
# 1 is for setup community
assert results["totalCount"] == 5 + 1
end
test "community has default index = 100000", ~m(guest_conn)a do
{:ok, _communities} = db_insert_multi(:community, 5)
variables = %{filter: %{page: 1, size: 20}}
results = guest_conn |> query_result(@query, variables, "pagedCommunities")
results["entries"] |> Enum.all?(fn x -> x["index"] == 100_000 end)
end
test "guest user can get paged communities based on category", ~m(guest_conn)a do
{:ok, category1} = db_insert(:category)
{:ok, category2} = db_insert(:category)
{:ok, communities} = db_insert_multi(:community, 10)
community1 = communities |> Enum.at(0)
community2 = communities |> Enum.at(1)
communityn = communities |> List.last()
# [community1, community2, _] = communities
CMS.set_category(%Community{id: community1.id}, %Category{id: category1.id})
CMS.set_category(%Community{id: community2.id}, %Category{id: category2.id})
CMS.set_category(%Community{id: communityn.id}, %Category{id: category2.id})
variables = %{filter: %{page: 1, size: 20, category: category1.raw}}
results = guest_conn |> query_result(@query, variables, "pagedCommunities")
assert results["entries"]
|> List.first()
|> Map.get("categories")
|> Enum.any?(&(&1["id"] == to_string(category1.id)))
assert results["totalCount"] == 1
variables = %{filter: %{page: 1, size: 20, category: category2.raw}}
results = guest_conn |> query_result(@query, variables, "pagedCommunities")
assert results["totalCount"] == 2
assert results["entries"]
|> List.first()
|> Map.get("categories")
|> Enum.any?(&(&1["id"] == to_string(category2.id)))
variables = %{filter: %{page: 1, size: 20}}
results = guest_conn |> query_result(@query, variables, "pagedCommunities")
assert results["totalCount"] == 10 + 1
end
end
describe "[cms threads]" do
@query """
query($filter: ThreadsFilter!) {
pagedThreads(filter: $filter) {
entries {
id
title
raw
index
}
totalCount
totalPages
pageSize
pageNumber
}
}
"""
test "can get whole threads", ~m(guest_conn)a do
{:ok, _threads} = db_insert_multi(:thread, 5)
variables = %{filter: %{page: 1, size: 20}}
results = guest_conn |> query_result(@query, variables, "pagedThreads")
assert results |> is_valid_pagination?
assert results["totalCount"] == 5
end
test "can get sorted thread based on index", ~m(guest_conn)a do
{:ok, _threads} = db_insert_multi(:thread, 10)
variables = %{filter: %{page: 1, size: 20, sort: "DESC_INDEX"}}
results = guest_conn |> query_result(@query, variables, "pagedThreads")
first_idx = results["entries"] |> List.first() |> Map.get("index")
last_idx = results["entries"] |> List.last() |> Map.get("index")
assert first_idx > last_idx
variables = %{filter: %{page: 1, size: 20, sort: "ASC_INDEX"}}
results = guest_conn |> query_result(@query, variables, "pagedThreads")
first_idx = results["entries"] |> List.first() |> Map.get("index")
last_idx = results["entries"] |> List.last() |> Map.get("index")
assert first_idx < last_idx
end
end
describe "[cms query categories]" do
@query """
query($filter: PagedFilter!) {
pagedCategories(filter: $filter) {
entries {
id
title
author {
id
nickname
}
communities {
id
title
}
}
totalCount
totalPages
pageSize
pageNumber
}
}
"""
test "guest user can get paged categories", ~m(guest_conn user)a do
variables = %{filter: %{page: 1, size: 10}}
valid_attrs = mock_attrs(:category)
~m(title raw)a = valid_attrs
{:ok, _} = CMS.create_category(~m(title raw)a, %User{id: user.id})
results = guest_conn |> query_result(@query, variables, "pagedCategories")
author = results["entries"] |> List.first() |> Map.get("author")
assert results |> is_valid_pagination?
assert author["id"] == to_string(user.id)
end
test "paged categories containes communities info", ~m(guest_conn user community)a do
variables = %{filter: %{page: 1, size: 10}}
valid_attrs = mock_attrs(:category)
~m(title raw)a = valid_attrs
{:ok, category} = CMS.create_category(~m(title raw)a, %User{id: user.id})
{:ok, _} = CMS.set_category(%Community{id: community.id}, %Category{id: category.id})
results = guest_conn |> query_result(@query, variables, "pagedCategories")
contain_communities = results["entries"] |> List.first() |> Map.get("communities")
assert contain_communities |> List.first() |> Map.get("id") == to_string(community.id)
end
end
describe "[cms query tags]" do
@query """
query($filter: PagedFilter!) {
tags(filter: $filter) {
entries {
id
title
author {
id
nickname
avatar
}
}
totalCount
totalPages
pageSize
pageNumber
}
}
"""
test "guest user can get paged tags", ~m(guest_conn community user)a do
variables = %{filter: %{page: 1, size: 10}}
valid_attrs = mock_attrs(:tag, %{user_id: user.id})
{:ok, _} = CMS.create_tag(community, :post, valid_attrs, user)
results = guest_conn |> query_result(@query, variables, "tags")
assert results |> is_valid_pagination?
end
@query """
query($communityId: ID, $community: String, $thread: CmsThread, $topic: String, $all: Boolean ) {
partialTags(communityId: $communityId, community: $community, thread: $thread, topic: $topic, all: $all) {
id
title
color
thread
community {
id
title
logo
}
}
}
"""
test "guest user can get all partial tags belongs to a community",
~m(guest_conn community)a do
{:ok, _tag} = db_insert(:tag, %{thread: "post", community: community})
{:ok, _tag2} = db_insert(:tag, %{thread: "job", community: community})
variables = %{all: true, communityId: community.id}
results = guest_conn |> query_result(@query, variables, "partialTags")
assert results |> length == 2
variables = %{all: true, community: community.raw}
results = guest_conn |> query_result(@query, variables, "partialTags")
assert results |> length == 2
end
test "guest user can get partial tags by communityId and thread", ~m(guest_conn community)a do
{:ok, tag} = db_insert(:tag, %{thread: "post", community: community})
{:ok, tag2} = db_insert(:tag, %{thread: "job", community: community})
variables = %{thread: "POST", communityId: community.id}
results = guest_conn |> query_result(@query, variables, "partialTags")
assert results |> Enum.any?(&(&1["id"] == to_string(tag.id)))
assert results |> Enum.any?(&(&1["id"] != to_string(tag2.id)))
end
test "user can get partial tags by default index topic", ~m(guest_conn community user)a do
valid_attrs = mock_attrs(:tag)
{:ok, _tag} = CMS.create_tag(community, :post, valid_attrs, user)
variables = %{thread: "POST", communityId: community.id, topic: "posts"}
results = guest_conn |> query_result(@query, variables, "partialTags")
assert results |> length == 1
end
@query """
query($community: String, $thread: CmsThread!) {
partialTags(community: $community, thread: $thread) {
id
title
color
thread
community {
id
title
logo
}
}
}
"""
test "guest user can get partial tags by communityRaw", ~m(guest_conn community)a do
{:ok, tag} = db_insert(:tag, %{thread: "post", community: community})
{:ok, tag2} = db_insert(:tag, %{thread: "job", community: community})
variables = %{thread: "POST", community: community.raw}
results = guest_conn |> query_result(@query, variables, "partialTags")
assert results |> Enum.any?(&(&1["id"] == to_string(tag.id)))
assert results |> Enum.any?(&(&1["id"] != to_string(tag2.id)))
end
test "get partial tags with no community info fails", ~m(guest_conn community)a do
{:ok, _tag} = db_insert(:tag, %{thread: "post", community: community})
{:ok, _tag2} = db_insert(:tag, %{thread: "job", community: community})
variables = %{thread: "POST"}
assert guest_conn |> mutation_get_error?(@query, variables)
end
end
describe "[cms query community]" do
@query """
query($id: ID, $title: String) {
community(id: $id, title: $title) {
id
title
desc
}
}
"""
test "guest user can get badic info of a community by id", ~m(guest_conn community)a do
variables = %{id: community.id}
results = guest_conn |> query_result(@query, variables, "community")
assert results["id"] == to_string(community.id)
assert results["title"] == community.title
assert results["desc"] == community.desc
end
test "guest user can get badic info of a community by title", ~m(guest_conn community)a do
variables = %{title: community.title}
results = guest_conn |> query_result(@query, variables, "community")
assert results["id"] == to_string(community.id)
assert results["title"] == community.title
assert results["desc"] == community.desc
end
test "guest user can get community info without args fails", ~m(guest_conn)a do
variables = %{}
assert guest_conn |> query_get_error?(@query, variables)
end
end
describe "[cms community editors]" do
@query """
query($id: ID!) {
community(id: $id) {
id
editorsCount
editors {
id
nickname
}
}
}
"""
test "guest can get editors list and count of a community", ~m(guest_conn community)a do
title = "chief editor"
{:ok, users} = db_insert_multi(:user, inner_page_size())
Enum.each(
users,
&CMS.set_editor(community, title, %User{id: &1.id})
)
variables = %{id: community.id}
results = guest_conn |> query_result(@query, variables, "community")
editors = results["editors"]
editors_count = results["editorsCount"]
[user_1, user_2, user_3, user_x] = users |> firstn_and_last(3)
assert results["id"] == to_string(community.id)
assert editors |> Enum.any?(&(&1["id"] == to_string(user_1.id)))
assert editors |> Enum.any?(&(&1["id"] == to_string(user_2.id)))
assert editors |> Enum.any?(&(&1["id"] == to_string(user_3.id)))
assert editors |> Enum.any?(&(&1["id"] == to_string(user_x.id)))
assert editors_count == inner_page_size()
end
@query """
query($id: ID!, $filter: PagedFilter!) {
communityEditors(id: $id, filter: $filter) {
entries {
nickname
}
totalCount
totalPages
pageSize
pageNumber
}
}
"""
test "guest user can get paged editors", ~m(guest_conn community)a do
title = "chief editor"
{:ok, users} = db_insert_multi(:user, 25)
Enum.each(
users,
&CMS.set_editor(community, title, %User{id: &1.id})
)
variables = %{id: community.id, filter: %{page: 1, size: 10}}
results = guest_conn |> query_result(@query, variables, "communityEditors")
assert results |> is_valid_pagination?
end
end
describe "[cms community subscribe]" do
@query """
query($id: ID!) {
community(id: $id) {
id
subscribersCount
subscribers {
id
nickname
}
}
}
"""
test "guest can get subscribers list and count of a community", ~m(guest_conn community)a do
{:ok, users} = db_insert_multi(:user, inner_page_size())
Enum.each(
users,
&CMS.subscribe_community(community, %User{id: &1.id})
)
variables = %{id: community.id}
results = guest_conn |> query_result(@query, variables, "community")
subscribers = results["subscribers"]
subscribers_count = results["subscribersCount"]
[user_1, user_2, user_3, user_x] = users |> firstn_and_last(3)
assert results["id"] == to_string(community.id)
assert subscribers |> Enum.any?(&(&1["id"] == to_string(user_1.id)))
assert subscribers |> Enum.any?(&(&1["id"] == to_string(user_2.id)))
assert subscribers |> Enum.any?(&(&1["id"] == to_string(user_3.id)))
assert subscribers |> Enum.any?(&(&1["id"] == to_string(user_x.id)))
assert subscribers_count == inner_page_size()
end
test "guest user can get subscribers count of 20 at most", ~m(guest_conn community)a do
{:ok, users} = db_insert_multi(:user, inner_page_size() + 1)
Enum.each(
users,
&CMS.subscribe_community(community, %User{id: &1.id})
)
variables = %{id: community.id}
results = guest_conn |> query_result(@query, variables, "community")
subscribers = results["subscribers"]
assert length(subscribers) == inner_page_size()
end
@query """
query($id: ID, $community: String, $filter: PagedFilter!) {
communitySubscribers(id: $id, community: $community, filter: $filter) {
entries {
id
nickname
avatar
}
totalCount
totalPages
pageSize
pageNumber
}
}
"""
test "guest user can get paged subscribers by community id", ~m(guest_conn community)a do
{:ok, users} = db_insert_multi(:user, 25)
Enum.each(
users,
&CMS.subscribe_community(community, %User{id: &1.id})
)
variables = %{id: community.id, filter: %{page: 1, size: 10}}
results = guest_conn |> query_result(@query, variables, "communitySubscribers")
assert results |> is_valid_pagination?
end
test "guest user can get paged subscribers by community raw", ~m(guest_conn community)a do
{:ok, users} = db_insert_multi(:user, 25)
Enum.each(
users,
&CMS.subscribe_community(community, %User{id: &1.id})
)
variables = %{community: community.raw, filter: %{page: 1, size: 10}}
results = guest_conn |> query_result(@query, variables, "communitySubscribers")
assert results |> is_valid_pagination?
end
end
end
| 30.83277 | 112 | 0.593491 |
794d0dd491221ec52e6a4a44b8ce78a2e9e11560 | 2,949 | ex | Elixir | clients/cloud_asset/lib/google_api/cloud_asset/v1/model/audit_config.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/cloud_asset/lib/google_api/cloud_asset/v1/model/audit_config.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/cloud_asset/lib/google_api/cloud_asset/v1/model/audit_config.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.CloudAsset.V1.Model.AuditConfig do
@moduledoc """
Specifies the audit configuration for a service. The configuration determines which permission types are logged, and what identities, if any, are exempted from logging. An AuditConfig must have one or more AuditLogConfigs. If there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is used for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each AuditLogConfig are exempted. Example Policy with multiple AuditConfigs: { "audit_configs": [ { "service": "allServices", "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:[email protected]" ] }, { "log_type": "DATA_WRITE" }, { "log_type": "ADMIN_READ" } ] }, { "service": "sampleservice.googleapis.com", "audit_log_configs": [ { "log_type": "DATA_READ" }, { "log_type": "DATA_WRITE", "exempted_members": [ "user:[email protected]" ] } ] } ] } For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ logging. It also exempts [email protected] from DATA_READ logging, and [email protected] from DATA_WRITE logging.
## Attributes
* `auditLogConfigs` (*type:* `list(GoogleApi.CloudAsset.V1.Model.AuditLogConfig.t)`, *default:* `nil`) - The configuration for logging of each type of permission.
* `service` (*type:* `String.t`, *default:* `nil`) - Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:auditLogConfigs => list(GoogleApi.CloudAsset.V1.Model.AuditLogConfig.t()),
:service => String.t()
}
field(:auditLogConfigs, as: GoogleApi.CloudAsset.V1.Model.AuditLogConfig, type: :list)
field(:service)
end
defimpl Poison.Decoder, for: GoogleApi.CloudAsset.V1.Model.AuditConfig do
def decode(value, options) do
GoogleApi.CloudAsset.V1.Model.AuditConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudAsset.V1.Model.AuditConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 58.98 | 1,106 | 0.746694 |
794d1c36fff65e0a2f11bfa784cb704a31757ed9 | 848 | ex | Elixir | lib/dogma/rule/windows_line_endings.ex | lpil/dogma | e0f55c27ec3053be0313ac93f3d036437ee590a1 | [
"MIT"
] | 558 | 2015-06-21T18:20:59.000Z | 2021-12-30T16:25:47.000Z | lib/dogma/rule/windows_line_endings.ex | lpil/dogma | e0f55c27ec3053be0313ac93f3d036437ee590a1 | [
"MIT"
] | 252 | 2015-06-19T13:00:47.000Z | 2021-04-21T08:04:16.000Z | lib/dogma/rule/windows_line_endings.ex | lpil/dogma | e0f55c27ec3053be0313ac93f3d036437ee590a1 | [
"MIT"
] | 79 | 2015-06-21T14:18:30.000Z | 2021-12-30T16:26:09.000Z | use Dogma.RuleBuilder
defrule Dogma.Rule.WindowsLineEndings do
@moduledoc ~S"""
A rule that disallows any lines terminated with `\r\n`, the line terminator
commonly used on the Windows operating system.
The preferred line terminator is is the Unix style `\n`.
If you are a Windows user you should be able to configure your editor to
write files with Unix style `\n` line terminators.
"""
@violation_regex ~r/\r\z/
def test(_rule, script) do
Enum.reduce( script.lines, [], &check_line(&1, &2) )
end
defp check_line({i, line}, acc) do
case @violation_regex |> Regex.match?(line) do
true -> [error(i) | acc]
_ -> acc
end
end
defp error(pos) do
%Error{
rule: __MODULE__,
message: "Windows line ending detected (\r\n)",
line: Dogma.Script.line(pos),
}
end
end
| 24.228571 | 77 | 0.653302 |
794d35464e508e5a59dd1a17375891c0aa71870f | 1,132 | exs | Elixir | test/ex_permissions/user_test.exs | mtwilliams/ex_permissions | 1842f27f41b5d404d2e2409ad3c421de08970843 | [
"Unlicense"
] | null | null | null | test/ex_permissions/user_test.exs | mtwilliams/ex_permissions | 1842f27f41b5d404d2e2409ad3c421de08970843 | [
"Unlicense"
] | 3 | 2015-05-03T05:15:56.000Z | 2015-05-03T05:20:02.000Z | test/ex_permissions/user_test.exs | mtwilliams/ex_permissions | 1842f27f41b5d404d2e2409ad3c421de08970843 | [
"Unlicense"
] | null | null | null | defmodule ExPermissions.User.Test do
use ExUnit.Case
defmodule UserWithoutImplementations do
use ExPermissions.User
defstruct foo: nil,
bar: nil
end
test "passing nil instead of a proper 'object'" do
assert_raise ExPermissions.User.CannotTell, fn -> nil |> ExPermissions.User.is? :foo end
assert_raise ExPermissions.User.CannotTell, fn -> nil |> ExPermissions.User.not? :foo end
assert_raise ExPermissions.User.CannotTell, fn -> nil |> ExPermissions.User.is? :bar end
assert_raise ExPermissions.User.CannotTell, fn -> nil |> ExPermissions.User.not? :bar end
end
test "user without implementations(s) has no flags" do
user = %UserWithoutImplementations{}
assert_raise ExPermissions.User.CannotTell, fn -> user |> UserWithoutImplementations.is? :foo end
assert_raise ExPermissions.User.CannotTell, fn -> user |> UserWithoutImplementations.not? :foo end
assert_raise ExPermissions.User.CannotTell, fn -> user |> UserWithoutImplementations.is? :bar end
assert_raise ExPermissions.User.CannotTell, fn -> user |> UserWithoutImplementations.not? :bar end
end
end
| 43.538462 | 102 | 0.743816 |
794d4c11723f031f3eb856f2d35a4c14c40474f3 | 1,590 | ex | Elixir | lib/app/poller.ex | 4DA/bleroma | 26a533373f121e54f49d7ce59fd6e246fe51f738 | [
"MIT"
] | 5 | 2020-06-30T14:12:21.000Z | 2021-11-14T21:16:02.000Z | lib/app/poller.ex | 4DA/bleroma | 26a533373f121e54f49d7ce59fd6e246fe51f738 | [
"MIT"
] | null | null | null | lib/app/poller.ex | 4DA/bleroma | 26a533373f121e54f49d7ce59fd6e246fe51f738 | [
"MIT"
] | null | null | null | # Poller receives responses from Telegram and sends them to Bleroma.Matcher
defmodule Bleroma.Poller do
use GenServer
require Logger
# Server
def start_link do
Logger.log(:info, "Started poller")
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
def init(:ok) do
update()
{:ok, 0}
end
def handle_cast(:update, offset) do
new_offset =
Nadia.get_updates(offset: offset)
|> process_messages
{:noreply, new_offset + 1, 100}
end
def handle_info({:ssl_closed, _}, state) do
Logger.log(:error, "FIXME: ssl_closed. issue: https://github.com/benoitc/hackney/issues/464")
update()
{:noreply, state}
end
def handle_info(:timeout, offset) do
update()
{:noreply, offset}
end
# Client
def update do
GenServer.cast(__MODULE__, :update)
end
# Helpers
defp process_messages({:ok, []}), do: -1
defp process_messages({:ok, results}) do
results
|> Enum.map(fn %{update_id: id} = message ->
message
|> process_message
id
end)
|> List.last()
end
defp process_messages({:error, %Nadia.Model.Error{reason: reason}}) do
Logger.log(:error, "Nadia model error: #{inspect reason}")
-1
end
defp process_messages({:error, error}) do
Logger.log(:error, error)
-1
end
defp process_message(nil), do: IO.puts("nil")
defp process_message(message) do
try do
Bleroma.Matcher.match(message)
rescue
err in MatchError ->
Logger.log(:warn, "Errored with #{err} at #{Poison.encode!(message)}")
end
end
end
| 19.390244 | 97 | 0.641509 |
794da1942cc608cca8bda5ca863de133ce604ec3 | 9,658 | ex | Elixir | lib/phoenix/live_dashboard/components/table_component.ex | sabiwara/phoenix_live_dashboard | cfadca62af16b0af356f497ae6ddbb095be5a8f5 | [
"MIT"
] | null | null | null | lib/phoenix/live_dashboard/components/table_component.ex | sabiwara/phoenix_live_dashboard | cfadca62af16b0af356f497ae6ddbb095be5a8f5 | [
"MIT"
] | null | null | null | lib/phoenix/live_dashboard/components/table_component.ex | sabiwara/phoenix_live_dashboard | cfadca62af16b0af356f497ae6ddbb095be5a8f5 | [
"MIT"
] | null | null | null | defmodule Phoenix.LiveDashboard.TableComponent do
use Phoenix.LiveDashboard.Web, :live_component
@limit [50, 100, 500, 1000, 5000]
@type params() :: %{
limit: pos_integer(),
sort_by: :atom,
sort_dir: :desc | :asc,
search: binary(),
hint: binary() | nil
}
@impl true
def mount(socket) do
{:ok, socket}
end
def normalize_params(params) do
params
|> validate_required([:columns, :id, :row_fetcher, :title])
|> normalize_columns()
|> validate_required_one_sortable_column()
|> Map.put_new(:search, true)
|> Map.put_new(:limit, @limit)
|> Map.put_new(:row_attrs, [])
|> Map.put_new(:hint, nil)
|> Map.update(:default_sort_by, nil, &(&1 && to_string(&1)))
|> Map.put_new_lazy(:rows_name, fn ->
Phoenix.Naming.humanize(params.title) |> String.downcase()
end)
end
defp validate_required(params, list) do
case Enum.find(list, &(not Map.has_key?(params, &1))) do
nil -> :ok
key -> raise ArgumentError, "the #{inspect(key)} parameter is expected in table component"
end
params
end
defp normalize_columns(%{columns: columns} = params) when is_list(columns) do
%{params | columns: Enum.map(columns, &normalize_column/1)}
end
defp normalize_columns(%{columns: columns}) do
raise ArgumentError, ":columns must be a list, got: #{inspect(columns)}"
end
defp normalize_column(column) do
case Access.fetch(column, :field) do
{:ok, nil} ->
msg = ":field parameter must not be nil, got: #{inspect(column)}"
raise ArgumentError, msg
{:ok, field} when is_atom(field) or is_binary(field) ->
column
|> Map.new()
|> Map.put_new_lazy(:header, fn -> Phoenix.Naming.humanize(field) end)
|> Map.put_new(:header_attrs, [])
|> Map.put_new(:format, & &1)
|> Map.put_new(:cell_attrs, [])
|> Map.put_new(:sortable, nil)
{:ok, _} ->
msg = ":field parameter must be an atom or a string, got: "
raise ArgumentError, msg <> inspect(column)
:error ->
msg = "the :field parameter is expected, got: #{inspect(column)}"
raise ArgumentError, msg
end
end
defp validate_required_one_sortable_column(%{columns: columns} = params) do
sortable_columns = sortable_columns(columns)
if sortable_columns == [] do
raise ArgumentError, "must have at least one column with :sortable parameter"
else
params
end
end
@impl true
def update(assigns, socket) do
assigns = normalize_table_params(assigns)
%{
table_params: table_params,
page: page,
row_fetcher: row_fetcher
} = assigns
{rows, total, socket} = fetch_rows(row_fetcher, table_params, page.node, socket)
assigns = Map.merge(assigns, %{rows: rows, total: total})
{:ok, assign(socket, assigns)}
end
defp fetch_rows(row_fetcher, table_params, page_node, socket)
when is_function(row_fetcher, 2) do
{rows, total} = row_fetcher.(table_params, page_node)
{rows, total, socket}
end
defp fetch_rows({row_fetcher, initial_state}, table_params, page_node, socket)
when is_function(row_fetcher, 3) do
state = Map.get(socket.assigns, :row_fetcher_state, initial_state)
{rows, total, state} = row_fetcher.(table_params, page_node, state)
{rows, total, assign(socket, :row_fetcher_state, state)}
end
defp normalize_table_params(assigns) do
%{columns: columns, page: %{params: all_params}, default_sort_by: sort_by} = assigns
sortable_columns = sortable_columns(columns)
sort_by =
all_params
|> get_in_or_first("sort_by", sort_by, sortable_columns)
|> String.to_atom()
sort_dir =
all_params
|> get_in_or_first("sort_dir", sortable_dirs(columns, sort_by))
|> String.to_atom()
limit =
if assigns.limit do
all_params
|> get_in_or_first("limit", Enum.map(assigns.limit, &to_string/1))
|> String.to_integer()
else
nil
end
search = all_params["search"]
search = if search == "", do: nil, else: search
table_params = %{sort_by: sort_by, sort_dir: sort_dir, limit: limit, search: search}
Map.put(assigns, :table_params, table_params)
end
defp sortable_columns(columns) do
for column <- columns, column.sortable, do: to_string(column.field)
end
defp sortable_dirs(columns, field) do
case Enum.find(columns, &(&1.field == field)) do
%{sortable: :desc} -> ~w(desc asc)
%{sortable: :asc} -> ~w(asc desc)
end
end
defp get_in_or_first(params, key, default \\ nil, valid) do
value = params[key]
if value in valid, do: value, else: default || hd(valid)
end
@impl true
def render(assigns) do
~L"""
<div class="tabular">
<h5 class="card-title"><%= @title %> <%= @hint && hint(do: @hint) %></h5>
<%= if @search do %>
<div class="tabular-search">
<form phx-change="search" phx-submit="search" phx-target="<%= @myself %>" class="form-inline">
<div class="form-row align-items-center">
<div class="col-auto">
<input type="search" name="search" class="form-control form-control-sm" value="<%= @table_params.search %>" placeholder="Search" phx-debounce="300">
</div>
</div>
</form>
</div>
<% end %>
<form phx-change="select_limit" phx-target="<%= @myself %>" class="form-inline">
<div class="form-row align-items-center">
<%= if @limit do %>
<div class="col-auto">Showing at most</div>
<div class="col-auto">
<div class="input-group input-group-sm">
<select name="limit" class="custom-select" id="limit-select">
<%= options_for_select(@limit, @table_params.limit) %>
</select>
</div>
</div>
<div class="col-auto">
<%= @rows_name %> out of <%= @total %>
</div>
<% else %>
<div class="col-auto">
Showing <%= @total %> <%= @rows_name %>
</div>
<% end %>
</div>
</form>
<div class="card tabular-card mb-4 mt-4">
<div class="card-body p-0">
<div class="dash-table-wrapper">
<table class="table table-hover mt-0 dash-table">
<thead>
<tr>
<%= for column <- @columns do %>
<%= tag_with_attrs(:th, column.header_attrs, [column]) %>
<%= if direction = column.sortable do %>
<%= sort_link(@socket, @page, @table_params, column, direction) %>
<% else %>
<%= column.header %>
<% end %>
</th>
<% end %>
</tr>
</thead>
<tbody>
<%= for row <- @rows do %>
<%= tag_with_attrs(:tr, @row_attrs, [row]) %>
<%= for column <- @columns do %>
<%= tag_with_attrs(:td, column.cell_attrs, [row]) %>
<%= column.format.(row[column.field]) %>
</td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
</div>
</div>
</div>
</div>
"""
end
defp tag_with_attrs(name, fun, args), do: tag(name, calc_attrs(fun, args))
defp calc_attrs(falsy, _) when falsy in [nil, false], do: []
defp calc_attrs(list, _) when is_list(list), do: list
defp calc_attrs(fun, args) when is_function(fun), do: apply(fun, args)
defp column_header(column) do
column.header || column.field |> to_string() |> String.capitalize()
end
@impl true
def handle_event("search", %{"search" => search}, socket) do
table_params = %{socket.assigns.table_params | search: search}
to = live_dashboard_path(socket, socket.assigns.page, table_params)
{:noreply, push_patch(socket, to: to)}
end
def handle_event("select_limit", %{"limit" => limit}, socket) do
table_params = %{socket.assigns.table_params | limit: limit}
to = live_dashboard_path(socket, socket.assigns.page, table_params)
{:noreply, push_patch(socket, to: to)}
end
defp sort_link(socket, page, table_params, column, direction) do
field = column.field
case table_params do
%{sort_by: ^field, sort_dir: sort_dir} ->
table_params = %{table_params | sort_dir: opposite_sort_dir(table_params), sort_by: field}
column
|> column_header()
|> sort_link_body(sort_dir)
|> live_patch(to: live_dashboard_path(socket, page, table_params))
%{} ->
table_params = %{table_params | sort_dir: direction, sort_by: field}
column
|> column_header()
|> sort_link_body()
|> live_patch(to: live_dashboard_path(socket, page, table_params))
end
end
defp sort_link_body(link_name), do: link_name
defp sort_link_body(link_name, sort_dir) do
[link_name | sort_link_icon(sort_dir)]
end
defp sort_link_icon(:desc) do
{:safe,
"""
<div class="dash-table-icon">
<span class="icon-sort icon-desc"></span>
</div>
"""}
end
defp sort_link_icon(:asc) do
{:safe,
"""
<div class="dash-table-icon">
<span class="icon-sort icon-asc"></span>
</div>
"""}
end
defp opposite_sort_dir(%{sort_dir: :desc}), do: :asc
defp opposite_sort_dir(_), do: :desc
end
| 31.357143 | 164 | 0.578381 |
794db67cf162058208cedd0045f3e4c327f4ae00 | 616 | exs | Elixir | test/pixela_ex/client_test.exs | niku/pixela_ex | 7f2bbf143519927e2a906b1c2e3d721e16e115e5 | [
"CC0-1.0"
] | 2 | 2018-10-20T10:01:05.000Z | 2018-10-23T22:48:53.000Z | test/pixela_ex/client_test.exs | niku/pixela_ex | 7f2bbf143519927e2a906b1c2e3d721e16e115e5 | [
"CC0-1.0"
] | 5 | 2018-10-24T00:55:24.000Z | 2018-11-07T00:37:50.000Z | test/pixela_ex/client_test.exs | niku/pixela_ex | 7f2bbf143519927e2a906b1c2e3d721e16e115e5 | [
"CC0-1.0"
] | 1 | 2018-10-23T21:55:32.000Z | 2018-10-23T21:55:32.000Z | defmodule PixelaEx.ClientTest do
use ExUnit.Case
test "process_request_body" do
assert PixelaEx.Client.process_request_body("") == ""
assert PixelaEx.Client.process_request_body(%{hogeFuga: true}) == Poison.encode!(%{"hogeFuga" => "yes"})
end
test "_format_key" do
assert PixelaEx.Client._format_key(:hogeFuga) == "hogeFuga"
assert PixelaEx.Client._format_key("hogeFuga") == "hogeFuga"
end
test "_format_value" do
assert PixelaEx.Client._format_value(true) == "yes"
assert PixelaEx.Client._format_value(false) == "no"
assert PixelaEx.Client._format_value(1) == 1
end
end
| 30.8 | 108 | 0.714286 |
794dbff0c6474a8ee477e31485da13617231d3a1 | 153 | ex | Elixir | lib/firestorm_web/forums/slugs/category_title_slug.ex | palindrom615/firestorm | 0690493c9dcae5c04c63c5321532a7db923e5be7 | [
"MIT"
] | null | null | null | lib/firestorm_web/forums/slugs/category_title_slug.ex | palindrom615/firestorm | 0690493c9dcae5c04c63c5321532a7db923e5be7 | [
"MIT"
] | 4 | 2021-03-01T21:25:42.000Z | 2022-02-10T23:50:11.000Z | lib/firestorm_web/forums/slugs/category_title_slug.ex | palindrom615/firestorm | 0690493c9dcae5c04c63c5321532a7db923e5be7 | [
"MIT"
] | 1 | 2020-03-20T12:58:37.000Z | 2020-03-20T12:58:37.000Z | defmodule FirestormWeb.Forums.Slugs.CategoryTitleSlug do
@moduledoc false
use FirestormWeb.Forums.Slugs.TitleSlug, FirestormWeb.Forums.Category
end
| 25.5 | 71 | 0.843137 |
794dfba5bde7f36754d671b7abe186ed3da636c5 | 817 | ex | Elixir | lib/changelog_web/views/sponsor_view.ex | type1fool/changelog.com | fbec3528cc3f5adfdc75b008bb92b17efc4f248f | [
"MIT"
] | 1 | 2020-05-20T16:58:17.000Z | 2020-05-20T16:58:17.000Z | lib/changelog_web/views/sponsor_view.ex | type1fool/changelog.com | fbec3528cc3f5adfdc75b008bb92b17efc4f248f | [
"MIT"
] | null | null | null | lib/changelog_web/views/sponsor_view.ex | type1fool/changelog.com | fbec3528cc3f5adfdc75b008bb92b17efc4f248f | [
"MIT"
] | null | null | null | defmodule ChangelogWeb.SponsorView do
use ChangelogWeb, :public_view
alias Changelog.Files.{Avatar, ColorLogo, DarkLogo, LightLogo}
alias ChangelogWeb.Endpoint
def avatar_path(sponsor, version) do
{sponsor.avatar, sponsor}
|> Avatar.url(version)
|> String.replace_leading("/priv", "")
end
def avatar_url(sponsor), do: avatar_url(sponsor, :small)
def avatar_url(sponsor, version) do
Routes.static_url(Endpoint, avatar_path(sponsor, version))
end
def logo_url(sponsor, type, version) do
{module, file} = case type do
:color_logo -> {ColorLogo, sponsor.color_logo}
:dark_logo -> {DarkLogo, sponsor.dark_logo}
:light_logo -> {LightLogo, sponsor.light_logo}
end
module.url({file, sponsor}, version)
|> String.replace_leading("/priv", "")
end
end
| 28.172414 | 64 | 0.700122 |
794e429ed686877f61061dda92a9092d97dfbefa | 1,664 | ex | Elixir | lib/credo/check/consistency/parameter_pattern_matching.ex | sevenseacat/credo | 48837401040d9c2340b5fb9c7d786d31f89f6426 | [
"MIT"
] | 1 | 2020-01-31T10:23:37.000Z | 2020-01-31T10:23:37.000Z | lib/credo/check/consistency/parameter_pattern_matching.ex | sevenseacat/credo | 48837401040d9c2340b5fb9c7d786d31f89f6426 | [
"MIT"
] | null | null | null | lib/credo/check/consistency/parameter_pattern_matching.ex | sevenseacat/credo | 48837401040d9c2340b5fb9c7d786d31f89f6426 | [
"MIT"
] | null | null | null | defmodule Credo.Check.Consistency.ParameterPatternMatching do
@moduledoc """
When capturing a parameter using pattern matching you can either put the name before or after the value
i.e.
def parse({:ok, values} = pair)
or
def parse(pair = {:ok, values})
While this is not necessarily a concern for the correctness of your code,
you should use a consistent style throughout your codebase.
"""
@explanation [check: @moduledoc]
@code_patterns [
Credo.Check.Consistency.ParameterPatternMatching.PositionCollector
]
alias Credo.Check.Consistency.Helper
alias Credo.Check.PropertyValue
use Credo.Check, run_on_all: true, base_priority: :high
@doc false
def run(source_files, params \\ []) when is_list(source_files) do
source_files
|> Helper.run_code_patterns(@code_patterns, params)
|> Helper.append_issues_via_issue_service(&issue_for/5, params)
:ok
end
defp message_for(:after) do
"the variable name after the pattern"
end
defp message_for(:before) do
"the variable name before the pattern"
end
defp issue_for(_issue_meta, _actual_props, nil, _picked_count, _total_count), do: nil
defp issue_for(_issue_meta, [], _expected_prop, _picked_count, _total_count), do: nil
defp issue_for(issue_meta, actual_prop, expected_prop, _picked_count, _total_count) do
line_no = PropertyValue.meta(actual_prop, :line_no)
actual_prop = PropertyValue.get(actual_prop)
format_issue issue_meta,
message: "File has #{message_for(actual_prop)} while most of the files have #{message_for(expected_prop)} when naming parameter pattern matches",
line_no: line_no
end
end
| 30.814815 | 151 | 0.745192 |
794e4490f79ecfb78de2ac4048fa9fb961f2a038 | 1,657 | exs | Elixir | apps/ewallet_config/test/ewallet_config/setting_loader_test.exs | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | 1 | 2018-12-07T06:21:21.000Z | 2018-12-07T06:21:21.000Z | apps/ewallet_config/test/ewallet_config/setting_loader_test.exs | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | null | null | null | apps/ewallet_config/test/ewallet_config/setting_loader_test.exs | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | null | null | null | defmodule EWalletConfig.SettingLoaderTest do
use EWalletConfig.SchemaCase, async: true
alias EWalletConfig.{Config, SettingLoader}
describe "load_settings/2" do
test "loads the settings" do
{:ok, _} = Config.insert(%{key: "my_setting_1", value: "value_1", type: "string"})
{:ok, _} = Config.insert(%{key: "my_setting_2", value: "value_2", type: "string"})
SettingLoader.load_settings(:my_app, [:my_setting_1, :my_setting_2])
assert Application.get_env(:my_app, :my_setting_1) == "value_1"
assert Application.get_env(:my_app, :my_setting_2) == "value_2"
end
end
describe "load_setting/2" do
test "sets nil when the setting doesn't exist" do
SettingLoader.load_settings(:my_app, [:my_setting_1])
assert Application.get_env(:my_app, :my_setting_1) == nil
end
test "load one setting when not secret" do
{:ok, _} = Config.insert(%{key: "my_setting", value: "value", type: "string"})
SettingLoader.load_settings(:my_app, [:my_setting])
assert Application.get_env(:my_app, :my_setting) == "value"
end
test "load one setting when secret" do
{:ok, _} = Config.insert(%{key: "my_setting", value: "value", secret: true, type: "string"})
SettingLoader.load_settings(:my_app, [:my_setting])
assert Application.get_env(:my_app, :my_setting) == "value"
end
test "load key with mapped name" do
{:ok, _} = Config.insert(%{key: "email_adapter", value: "smtp", type: "string"})
SettingLoader.load_settings(:my_app, [:email_adapter])
assert Application.get_env(:my_app, :email_adapter) == Bamboo.SMTPAdapter
end
end
end
| 37.659091 | 98 | 0.673506 |
794e5b0f2d5ec1bbbeda6ea30e2b99f450d6ad92 | 374 | ex | Elixir | web/views/error_view.ex | marnen/contraq-elixir | 69798c1b92a08c76a63e200eadeeb19986d56d91 | [
"MIT"
] | null | null | null | web/views/error_view.ex | marnen/contraq-elixir | 69798c1b92a08c76a63e200eadeeb19986d56d91 | [
"MIT"
] | 3 | 2016-11-25T20:35:54.000Z | 2016-11-26T19:45:35.000Z | web/views/error_view.ex | marnen/contraq-elixir | 69798c1b92a08c76a63e200eadeeb19986d56d91 | [
"MIT"
] | null | null | null | defmodule Contraq.ErrorView do
use Contraq.Web, :view
def render("404.html", _assigns) do
"Page not found"
end
def render("500.html", _assigns) do
"Internal server error"
end
# In case no render clause matches or no
# template is found, let's render it as 500
def template_not_found(_template, assigns) do
render "500.html", assigns
end
end
| 20.777778 | 47 | 0.697861 |
794e657d3116b918ceabcd608e7eea0fb3308ccf | 159 | ex | Elixir | lib/hl7/2.3/datatypes/ts.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.3/datatypes/ts.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.3/datatypes/ts.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | defmodule HL7.V2_3.DataTypes.Ts do
@moduledoc false
use HL7.DataType,
fields: [
time_of_an_event: nil,
degree_of_precision: nil
]
end
| 15.9 | 34 | 0.672956 |
794e7752086b53ab96202922c07bd0388cbaf4d7 | 1,553 | ex | Elixir | clients/web_security_scanner/lib/google_api/web_security_scanner/v1alpha/model/vulnerable_parameters.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/web_security_scanner/lib/google_api/web_security_scanner/v1alpha/model/vulnerable_parameters.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/web_security_scanner/lib/google_api/web_security_scanner/v1alpha/model/vulnerable_parameters.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.WebSecurityScanner.V1alpha.Model.VulnerableParameters do
@moduledoc """
Information about vulnerable request parameters.
## Attributes
* `parameterNames` (*type:* `list(String.t)`, *default:* `nil`) - The vulnerable parameter names.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:parameterNames => list(String.t())
}
field(:parameterNames, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.WebSecurityScanner.V1alpha.Model.VulnerableParameters do
def decode(value, options) do
GoogleApi.WebSecurityScanner.V1alpha.Model.VulnerableParameters.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.WebSecurityScanner.V1alpha.Model.VulnerableParameters do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.042553 | 101 | 0.754668 |
794e953cff0675933ca503b4ddf27602a2e40ec8 | 1,871 | ex | Elixir | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_summary_result.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_summary_result.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_summary_result.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.DLP.V2.Model.GooglePrivacyDlpV2SummaryResult do
@moduledoc """
A collection that informs the user the number of times a particular
`TransformationResultCode` and error details occurred.
## Attributes
* `code` (*type:* `String.t`, *default:* `nil`) - Outcome of the transformation.
* `count` (*type:* `String.t`, *default:* `nil`) - Number of transformations counted by this result.
* `details` (*type:* `String.t`, *default:* `nil`) - A place for warnings or errors to show up if a transformation didn't
work as expected.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:code => String.t(),
:count => String.t(),
:details => String.t()
}
field(:code)
field(:count)
field(:details)
end
defimpl Poison.Decoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2SummaryResult do
def decode(value, options) do
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2SummaryResult.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2SummaryResult do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.018182 | 125 | 0.718867 |
794e989fb9cf2ed8ffc24c6ebfb3f8fe63d66e1b | 1,122 | exs | Elixir | test/bookings/create_or_update_test.exs | felipe-jm/ignite-elixir-flightex | cef013b2f7fee1b38572f4d81cf433cc5a863b0a | [
"MIT"
] | 1 | 2021-03-23T13:53:16.000Z | 2021-03-23T13:53:16.000Z | test/bookings/create_or_update_test.exs | felipe-jm/ignite-elixir-flightex | cef013b2f7fee1b38572f4d81cf433cc5a863b0a | [
"MIT"
] | null | null | null | test/bookings/create_or_update_test.exs | felipe-jm/ignite-elixir-flightex | cef013b2f7fee1b38572f4d81cf433cc5a863b0a | [
"MIT"
] | null | null | null | defmodule Flightex.Bookings.CreateOrUpdateTest do
use ExUnit.Case
alias Flightex.Bookings.CreateOrUpdate
alias Flightex.Users.Agent, as: UserAgent
import Flightex.Factory
describe "call/1" do
setup do
user = build(:user)
Flightex.start_agents()
{:ok, uuid} = UserAgent.save(user)
{:ok, id_usuario: uuid}
end
test "when all params are valid, saves the booking", %{
id_usuario: id_usuario
} do
params = %{
data_completa: "2015-01-23T23:50:07",
cidade_origem: "Cuiabá",
cidade_destino: "Londres",
id_usuario: id_usuario
}
response = CreateOrUpdate.call(params)
assert {:ok, _uuid} = response
end
test "when there is no user with given id, returns an error" do
params = %{
data_completa: "2015-01-23T23:50:07",
cidade_origem: "Cuiabá",
cidade_destino: "Londres",
id_usuario: "invalid-id"
}
response = CreateOrUpdate.call(params)
expected_response = {:error, "User not found"}
assert response == expected_response
end
end
end
| 22 | 67 | 0.627451 |
794ef4f1db989d424e6fc723f1f491f9c3f26142 | 1,059 | exs | Elixir | test/sql/query_test.exs | juancgalvis/sobelow | 9ae3874c26ab7cfa6c8a8517ccd02af98e187585 | [
"Apache-2.0"
] | 1,305 | 2017-05-12T21:09:40.000Z | 2022-03-31T04:31:49.000Z | test/sql/query_test.exs | juancgalvis/sobelow | 9ae3874c26ab7cfa6c8a8517ccd02af98e187585 | [
"Apache-2.0"
] | 95 | 2017-05-15T09:45:41.000Z | 2022-03-23T03:35:48.000Z | test/sql/query_test.exs | juancgalvis/sobelow | 9ae3874c26ab7cfa6c8a8517ccd02af98e187585 | [
"Apache-2.0"
] | 86 | 2017-05-15T20:18:59.000Z | 2022-02-11T22:10:34.000Z | defmodule SobelowTest.SQL.QueryTest do
use ExUnit.Case
import Sobelow, only: [is_vuln?: 1]
alias Sobelow.SQL.Query
test "SQL injection in `SQL`" do
func = """
def query(%{"sql" => sql}) do
SQL.query(Repo, sql, [])
end
"""
{_, ast} = Code.string_to_quoted(func)
assert Query.parse_sql_def(ast) |> is_vuln?
end
test "Safe `SQL`" do
func = """
def query(%{"sql" => sql}) do
SQL.query(Repo, "SELECT * FROM users", [])
end
"""
{_, ast} = Code.string_to_quoted(func)
refute Query.parse_sql_def(ast) |> is_vuln?
end
test "SQL injection in `Repo`" do
func = """
def query(%{"sql" => sql}) do
Repo.query(sql)
end
"""
{_, ast} = Code.string_to_quoted(func)
assert Query.parse_repo_query_def(ast) |> is_vuln?
end
test "safe `Repo`" do
func = """
def query(%{"sql" => sql}) do
Repo.query("SELECT * FROM users")
end
"""
{_, ast} = Code.string_to_quoted(func)
refute Query.parse_repo_query_def(ast) |> is_vuln?
end
end
| 19.611111 | 54 | 0.578848 |
794f149f82b3a1fbb6d491ff893588add5f00ea7 | 838 | exs | Elixir | test/cluster_gig_test.exs | florinpatrascu/libcluster_gig | 703c13767db53c4366581bfd8d34cfe09bed37d3 | [
"Apache-2.0"
] | 5 | 2020-01-11T18:16:16.000Z | 2021-12-14T02:30:38.000Z | test/cluster_gig_test.exs | florinpatrascu/libcluster_gig | 703c13767db53c4366581bfd8d34cfe09bed37d3 | [
"Apache-2.0"
] | null | null | null | test/cluster_gig_test.exs | florinpatrascu/libcluster_gig | 703c13767db53c4366581bfd8d34cfe09bed37d3 | [
"Apache-2.0"
] | null | null | null | defmodule Cluster.Strategy.GigTest do
use ExUnit.Case
alias Cluster.Strategy.GoogleInstanceGroups
alias Cluster.Strategy.Test.Nodes
require Nodes
import ExUnit.CaptureLog
test "calls strategy" do
capture_log(fn ->
start_supervised!(
{GoogleInstanceGroups,
[
%Cluster.Strategy.State{
topology: :gig,
config: [
project: "4thehorde",
zone: "kekw",
instance_group: "omegalul",
adapter: Cluster.Strategy.Adapter.Test
],
connect: {Nodes, :connect, [self()]},
disconnect: {Nodes, :disconnect, [self()]},
list_nodes: {Nodes, :list_nodes, [[]]}
}
]}
)
assert_receive {:connect, :"[email protected]"}, 5_000
end)
end
end
| 23.942857 | 56 | 0.541766 |
794f1c4c75a21719da332fda447e15a4c05142ae | 90 | exs | Elixir | test/todo_test.exs | mickeyr/elixir-todo | 915e53b7450cd08d0ecef500a9544b664907a9bd | [
"MIT"
] | 1 | 2015-02-26T22:44:56.000Z | 2015-02-26T22:44:56.000Z | test/todo_test.exs | mickeyr/elixir-todo | 915e53b7450cd08d0ecef500a9544b664907a9bd | [
"MIT"
] | null | null | null | test/todo_test.exs | mickeyr/elixir-todo | 915e53b7450cd08d0ecef500a9544b664907a9bd | [
"MIT"
] | null | null | null | defmodule TodoTest do
use ExUnit.Case
test "the truth" do
assert(true)
end
end
| 11.25 | 21 | 0.688889 |
794f2957883561bf3ef002daff6edf445a8780df | 4,507 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/model/csv_options.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/big_query/lib/google_api/big_query/v2/model/csv_options.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/big_query/lib/google_api/big_query/v2/model/csv_options.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.BigQuery.V2.Model.CsvOptions do
@moduledoc """
## Attributes
* `allowJaggedRows` (*type:* `boolean()`, *default:* `nil`) - [Optional] Indicates if BigQuery should accept rows that are missing trailing optional columns. If true, BigQuery treats missing trailing columns as null values. If false, records with missing trailing columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false.
* `allowQuotedNewlines` (*type:* `boolean()`, *default:* `nil`) - [Optional] Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file. The default value is false.
* `encoding` (*type:* `String.t`, *default:* `nil`) - [Optional] The character encoding of the data. The supported values are UTF-8 or ISO-8859-1. The default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split using the values of the quote and fieldDelimiter properties.
* `fieldDelimiter` (*type:* `String.t`, *default:* `nil`) - [Optional] The separator for fields in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. BigQuery also supports the escape sequence "\\t" to specify a tab separator. The default value is a comma (',').
* `null_marker` (*type:* `String.t`, *default:* `nil`) - [Optional] An custom string that will represent a NULL value in CSV import data.
* `quote` (*type:* `String.t`, *default:* `"`) - [Optional] The value that is used to quote data sections in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. The default value is a double-quote ('"'). If your data does not contain quoted sections, set the property value to an empty string. If your data contains quoted newline characters, you must also set the allowQuotedNewlines property to true.
* `skipLeadingRows` (*type:* `String.t`, *default:* `nil`) - [Optional] The number of rows at the top of a CSV file that BigQuery will skip when reading the data. The default value is 0. This property is useful if you have header rows in the file that should be skipped. When autodetect is on, the behavior is the following: * skipLeadingRows unspecified - Autodetect tries to detect headers in the first row. If they are not detected, the row is read as data. Otherwise data is read starting from the second row. * skipLeadingRows is 0 - Instructs autodetect that there are no headers and data should be read starting from the first row. * skipLeadingRows = N > 0 - Autodetect skips N-1 rows and tries to detect headers in row N. If headers are not detected, row N is just skipped. Otherwise row N is used to extract column names for the detected schema.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:allowJaggedRows => boolean() | nil,
:allowQuotedNewlines => boolean() | nil,
:encoding => String.t() | nil,
:fieldDelimiter => String.t() | nil,
:null_marker => String.t() | nil,
:quote => String.t() | nil,
:skipLeadingRows => String.t() | nil
}
field(:allowJaggedRows)
field(:allowQuotedNewlines)
field(:encoding)
field(:fieldDelimiter)
field(:null_marker)
field(:quote)
field(:skipLeadingRows)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.CsvOptions do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.CsvOptions.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.CsvOptions do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 69.338462 | 859 | 0.731085 |
794f4a8b2acaa8ad438b9fd04555004aefc27189 | 446 | ex | Elixir | lib/secret_keeper/services/v1/cryptography_module/cryptography_service.ex | cosmos-sajal/secret_keeper | b5ae5e01ed4cd30afb91ae02fedf2f1de9366bf0 | [
"MIT"
] | 2 | 2019-09-14T14:32:37.000Z | 2020-06-05T15:17:34.000Z | lib/secret_keeper/services/v1/cryptography_module/cryptography_service.ex | cosmos-sajal/secret_keeper | b5ae5e01ed4cd30afb91ae02fedf2f1de9366bf0 | [
"MIT"
] | null | null | null | lib/secret_keeper/services/v1/cryptography_module/cryptography_service.ex | cosmos-sajal/secret_keeper | b5ae5e01ed4cd30afb91ae02fedf2f1de9366bf0 | [
"MIT"
] | null | null | null | defmodule SecretKeeper.Services.V1.CryptographyModule.CryptographyService do
@moduledoc false
@encryption_algo :aes_ecb
def encrypt(plaintext, key) do
@encryption_algo
|> :crypto.block_encrypt(:crypto.hash(:sha256, key), plaintext)
|> Base.encode16()
end
def decrypt(ciphertext, key) do
:crypto.block_decrypt(
@encryption_algo,
:crypto.hash(:sha256, key),
Base.decode16!(ciphertext)
)
end
end
| 22.3 | 76 | 0.701794 |
794f70163364dfce43c7b732d74a620b12bc0474 | 1,702 | exs | Elixir | umbrella/apps/sunulator_web/mix.exs | plasticine/sunulator | f202518bae70cad06ea9d38e183c1b9873a77b18 | [
"MIT"
] | 2 | 2019-06-05T23:28:44.000Z | 2019-06-05T23:41:20.000Z | umbrella/apps/sunulator_web/mix.exs | plasticine/sunulator | f202518bae70cad06ea9d38e183c1b9873a77b18 | [
"MIT"
] | 3 | 2021-03-09T12:30:08.000Z | 2021-09-01T19:32:06.000Z | umbrella/apps/sunulator_web/mix.exs | plasticine/sunulator | f202518bae70cad06ea9d38e183c1b9873a77b18 | [
"MIT"
] | null | null | null | defmodule SunulatorWeb.MixProject do
use Mix.Project
def project do
[
app: :sunulator_web,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.5",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix, :gettext] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
aliases: aliases(),
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {SunulatorWeb.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:phoenix, "~> 1.4.0"},
{:phoenix_pubsub, "~> 1.1"},
{:phoenix_ecto, "~> 4.0"},
{:phoenix_html, "~> 2.11"},
{:phoenix_live_view, github: "phoenixframework/phoenix_live_view"},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:gettext, "~> 0.11"},
{:sunulator, in_umbrella: true},
{:jason, "~> 1.0"},
{:plug_cowboy, "~> 2.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.901639 | 76 | 0.59812 |
794f76014453857c9348cf0b9684ab3830707e8a | 1,580 | exs | Elixir | test/new_relixir/instrumenters/plug_test.exs | sergioaugrod/new-relixir | ebb32bcbb2c74b48227791648d70ad835b4cd5c1 | [
"MIT"
] | null | null | null | test/new_relixir/instrumenters/plug_test.exs | sergioaugrod/new-relixir | ebb32bcbb2c74b48227791648d70ad835b4cd5c1 | [
"MIT"
] | null | null | null | test/new_relixir/instrumenters/plug_test.exs | sergioaugrod/new-relixir | ebb32bcbb2c74b48227791648d70ad835b4cd5c1 | [
"MIT"
] | null | null | null | defmodule NewRelixir.Instrumenters.PlugTest do
use ExUnit.Case
use Plug.Test
import TestHelpers.Assertions
alias NewRelixir.CurrentTransaction
@moduletag configured: true
defmodule FakePlugApp do
use Plug.Router
plug NewRelixir.Instrumenters.Plug
plug :match
plug :dispatch
get "/hello" do
conn = fetch_query_params(conn)
wait = conn.query_params["wait"]
if wait, do: wait |> String.to_integer |> :timer.sleep
send_resp(conn, 200, "Hello!")
end
end
setup %{configured: configured} do
previous_setting = Application.get_env(:new_relixir, :active)
Application.put_env(:new_relixir, :active, configured)
on_exit fn -> Application.put_env(:new_relixir, :active, previous_setting) end
:ok
end
test "it generates a transaction name based on request method and path" do
FakePlugApp.call(conn(:get, "/hello"), [])
assert {:ok, "hello#GET"} == CurrentTransaction.get()
assert [{"hello#GET", :total}] == get_metric_keys()
end
test "it records the elapsed time of the controller action" do
{elapsed_time, _} = :timer.tc(fn() ->
FakePlugApp.call(conn(:get, "/hello?wait=42"), [])
end)
[recorded_time] = get_metric_by_key({"hello#GET", :total})
assert_between(recorded_time, 42_000, elapsed_time)
end
@tag configured: false
test "does not record a transaction when New Relic is not configured" do
FakePlugApp.call(conn(:get, "/hello"), [])
assert {:error, :not_found} == CurrentTransaction.get()
assert [] == get_metric_keys()
end
end
| 26.333333 | 82 | 0.685443 |
794f9531697744201f37502efc5992b6718a05c4 | 294 | exs | Elixir | .iex.exs | remerle/asciinema-server | 895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57 | [
"Apache-2.0"
] | 893 | 2017-09-14T14:18:29.000Z | 2022-03-31T21:45:08.000Z | .iex.exs | remerle/asciinema-server | 895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57 | [
"Apache-2.0"
] | 103 | 2017-09-29T22:15:33.000Z | 2022-03-27T21:47:43.000Z | .iex.exs | remerle/asciinema-server | 895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57 | [
"Apache-2.0"
] | 152 | 2017-09-07T12:43:15.000Z | 2022-03-10T18:47:47.000Z | import_if_available(Ecto)
import_if_available(Ecto.Query)
import_if_available(Ecto.Changeset)
import_if_available(Enum, only: [map: 2, filter: 2, reduce: 2, reduce: 3])
alias Asciinema.{Repo, Asciicasts, Accounts}
alias Asciinema.Asciicasts.Asciicast
alias Asciinema.Accounts.{User, ApiToken}
| 32.666667 | 74 | 0.809524 |
794fdded6bc4cd787345f7ea27097e7760f70003 | 309 | exs | Elixir | priv/repo/migrations/20160808151518_remove_irc_provider.exs | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 1,003 | 2016-02-23T17:21:12.000Z | 2022-02-20T14:39:35.000Z | priv/repo/migrations/20160808151518_remove_irc_provider.exs | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 906 | 2016-02-22T22:54:19.000Z | 2022-03-11T15:19:43.000Z | priv/repo/migrations/20160808151518_remove_irc_provider.exs | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 95 | 2016-02-23T13:42:31.000Z | 2021-11-30T14:39:55.000Z | defmodule Cog.Repo.Migrations.RemoveIrcProvider do
use Ecto.Migration
def up do
execute """
DELETE FROM chat_providers WHERE name = 'irc'
"""
end
def down do
execute """
INSERT INTO chat_providers(name, inserted_at, updated_at)
VALUES('irc', 'now', 'now')
"""
end
end
| 17.166667 | 61 | 0.647249 |
794ff37389165707e5bb811534b4a0bda74380b5 | 834 | ex | Elixir | lib/liblink/socket/recvmsg/init_state.ex | Xerpa/liblink | 7b983431c5b391bb8cf182edd9ca4937601eea35 | [
"Apache-2.0"
] | 3 | 2018-10-26T12:55:15.000Z | 2019-05-03T22:41:34.000Z | lib/liblink/socket/recvmsg/init_state.ex | Xerpa/liblink | 7b983431c5b391bb8cf182edd9ca4937601eea35 | [
"Apache-2.0"
] | 4 | 2018-08-26T14:43:57.000Z | 2020-09-23T21:14:56.000Z | lib/liblink/socket/recvmsg/init_state.ex | Xerpa/liblink | 7b983431c5b391bb8cf182edd9ca4937601eea35 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 (c) Xerpa
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule Liblink.Socket.Recvmsg.InitState do
use Liblink.Socket.Recvmsg.Fsm
alias Liblink.Socket.Device
alias Liblink.Socket.Recvmsg.Transition
@impl true
def attach(device = %Device{}, data) do
Transition.init_to_recv(device, data)
end
end
| 32.076923 | 74 | 0.758993 |
79501eec5615edc84924cc82eb82285db3f87715 | 869 | ex | Elixir | lib/koans/01_equalities.ex | remusa/elixir-koans | 1b55724771f6af18580a16cb3f38b75a9f57f427 | [
"MIT"
] | null | null | null | lib/koans/01_equalities.ex | remusa/elixir-koans | 1b55724771f6af18580a16cb3f38b75a9f57f427 | [
"MIT"
] | null | null | null | lib/koans/01_equalities.ex | remusa/elixir-koans | 1b55724771f6af18580a16cb3f38b75a9f57f427 | [
"MIT"
] | null | null | null | defmodule Equalities do
use Koans
@intro """
Welcome to the Elixir koans.
Let these be your first humble steps towards learning a new language.
The path laid in front of you is one of many.
"""
# Replace ___ with the answer to make the koan pass.
koan "We shall contemplate truth by testing reality, via equality" do
assert true == true
end
koan "Not something is the opposite of it" do
assert !true == false
end
koan "To understand reality, we must compare our expectations against reality" do
assert 2 == 1 + 1
end
koan "Some things may appear different, but be the same" do
assert 1 == 2 / 2
end
koan "Unless they actually are different" do
assert 3.2 != 3.14
end
koan "Some may be looking for bigger things" do
assert 4 > 3
end
koan "Others are happy with less" do
assert 2 < 3
end
end
| 21.725 | 83 | 0.680092 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.