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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
79a884f3cc76a51408a1c0c314671a873e946aa3 | 2,952 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/site_video_settings.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/site_video_settings.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/site_video_settings.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V34.Model.SiteVideoSettings do
@moduledoc """
Video Settings
## Attributes
* `companionSettings` (*type:* `GoogleApi.DFAReporting.V34.Model.SiteCompanionSetting.t`, *default:* `nil`) - Settings for the companion creatives of video creatives served to this site.
* `kind` (*type:* `String.t`, *default:* `dfareporting#siteVideoSettings`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#siteVideoSettings".
* `orientation` (*type:* `String.t`, *default:* `nil`) - Orientation of a site template used for video. This will act as default for new placements created under this site.
* `skippableSettings` (*type:* `GoogleApi.DFAReporting.V34.Model.SiteSkippableSetting.t`, *default:* `nil`) - Settings for the skippability of video creatives served to this site. This will act as default for new placements created under this site.
* `transcodeSettings` (*type:* `GoogleApi.DFAReporting.V34.Model.SiteTranscodeSetting.t`, *default:* `nil`) - Settings for the transcodes of video creatives served to this site. This will act as default for new placements created under this site.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:companionSettings => GoogleApi.DFAReporting.V34.Model.SiteCompanionSetting.t(),
:kind => String.t(),
:orientation => String.t(),
:skippableSettings => GoogleApi.DFAReporting.V34.Model.SiteSkippableSetting.t(),
:transcodeSettings => GoogleApi.DFAReporting.V34.Model.SiteTranscodeSetting.t()
}
field(:companionSettings, as: GoogleApi.DFAReporting.V34.Model.SiteCompanionSetting)
field(:kind)
field(:orientation)
field(:skippableSettings, as: GoogleApi.DFAReporting.V34.Model.SiteSkippableSetting)
field(:transcodeSettings, as: GoogleApi.DFAReporting.V34.Model.SiteTranscodeSetting)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.SiteVideoSettings do
def decode(value, options) do
GoogleApi.DFAReporting.V34.Model.SiteVideoSettings.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.SiteVideoSettings do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 50.033898 | 252 | 0.752371 |
79a8ac42d1e2347e7b9426755c977fd9fa03fbf5 | 1,402 | ex | Elixir | lib/exchema_coercion.ex | victorprs/exchema_coercion | 3c1d0bbec9b6976fdbd2a18e8c36926232e13e44 | [
"Apache-2.0"
] | 7 | 2018-08-29T09:28:31.000Z | 2020-08-20T12:56:43.000Z | lib/exchema_coercion.ex | victorprs/exchema_coercion | 3c1d0bbec9b6976fdbd2a18e8c36926232e13e44 | [
"Apache-2.0"
] | 3 | 2018-10-08T21:33:04.000Z | 2019-07-22T16:38:02.000Z | lib/exchema_coercion.ex | victorprs/exchema_coercion | 3c1d0bbec9b6976fdbd2a18e8c36926232e13e44 | [
"Apache-2.0"
] | 2 | 2018-10-15T13:36:03.000Z | 2019-03-15T19:00:37.000Z | defmodule ExchemaCoercion do
@moduledoc """
Automagically coercion for Exchema Types
"""
alias Exchema.Type
@type result :: {:ok, any} | {:error, any} | :error
@type coercion :: (any, Type.t(), [coercion] -> result)
@spec coerce(any, Type.t(), [coercion]) :: any
def coerce(input, type, coercions \\ ExchemaCoercion.Coercions.all())
def coerce(input, type, coercions) do
case try_coerce(input, type, coercions) do
{:ok, value} ->
value
_ ->
input
end
end
@doc false
@spec try_coerce(any, Type.t(), [coercion]) :: any
def try_coerce(_, :any, _), do: :error
def try_coerce(input, type, coercions) do
coercions
|> Stream.map(&apply(&1, [input, normalize_type(type), coercions]))
|> Stream.filter(&is_ok?/1)
|> Enum.at(0)
|> case do
{:ok, val} ->
{:ok, val}
_ ->
try_coerce(input, unfold_type(type), coercions)
end
end
defp is_ok?({:ok, _}), do: true
defp is_ok?(_), do: false
defp unfold_type({:ref, supertype, _}),
do: normalize_type(supertype)
defp unfold_type(type),
do: type |> Type.resolve_type() |> normalize_type
@spec normalize_type(Type.t()) :: Type.t()
defp normalize_type({type, {}}), do: type
defp normalize_type({type, {arg}}), do: {type, arg}
defp normalize_type({type, args}), do: {type, args}
defp normalize_type(type), do: type
end
| 24.596491 | 71 | 0.614123 |
79a8b3c6757af4de7f30bc818a33702b2936ea88 | 184 | exs | Elixir | config/config.exs | rbkmoney/pathfinder | fdb3102f524b6f58cba579389047b425fdbd4c92 | [
"Apache-2.0"
] | null | null | null | config/config.exs | rbkmoney/pathfinder | fdb3102f524b6f58cba579389047b425fdbd4c92 | [
"Apache-2.0"
] | null | null | null | config/config.exs | rbkmoney/pathfinder | fdb3102f524b6f58cba579389047b425fdbd4c92 | [
"Apache-2.0"
] | 1 | 2021-12-07T09:25:32.000Z | 2021-12-07T09:25:32.000Z | import Config
# Common compile-time app env
config :pathfinder, ecto_repos: [NewWay.Repo]
# Dont use Elixir's logger
config :logger, backends: []
import_config("#{Mix.env()}.exs")
| 16.727273 | 45 | 0.722826 |
79a8e928f6ab1b8808463774b5b3b9eaa564c82e | 1,998 | exs | Elixir | mix.exs | elixir-geolix/geolix_adapter_mmdb2_caching | 935d2db3fa3199321b8eb74cad49a17ff13292bc | [
"Apache-2.0"
] | null | null | null | mix.exs | elixir-geolix/geolix_adapter_mmdb2_caching | 935d2db3fa3199321b8eb74cad49a17ff13292bc | [
"Apache-2.0"
] | null | null | null | mix.exs | elixir-geolix/geolix_adapter_mmdb2_caching | 935d2db3fa3199321b8eb74cad49a17ff13292bc | [
"Apache-2.0"
] | null | null | null | defmodule Geolix.Adapter.LookupCache.MixProject do
use Mix.Project
@url_github "https://github.com/elixir-geolix/adapter_lookup_cache"
def project do
[
app: :geolix_adapter_lookup_cache,
name: "Geolix Adapter: Lookup Cache",
version: "0.3.0-dev",
elixir: "~> 1.7",
deps: deps(),
description: "Lookup cache adapter for Geolix",
dialyzer: dialyzer(),
docs: docs(),
package: package(),
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test
],
test_coverage: [tool: ExCoveralls]
]
end
def application do
[extra_applications: [:logger]]
end
defp deps do
[
{:cachex, "~> 3.0", optional: true},
{:con_cache, "~> 1.0", optional: true},
{:credo, "~> 1.0", only: :dev, runtime: false},
{:dialyxir, "~> 1.0", only: :dev, runtime: false},
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:excoveralls, "~> 0.14.0", only: :test, runtime: false},
{:geolix, "~> 2.0"}
]
end
defp dialyzer do
[
flags: [
:error_handling,
:race_conditions,
:underspecs,
:unmatched_returns
],
plt_add_apps: [:cachex, :con_cache],
plt_core_path: "plts",
plt_file: {:no_warn, "plts/dialyzer.plt"}
]
end
defp docs do
[
groups_for_modules: [
Adapters: [
Geolix.Adapter.LookupCache.CacheAdapter.Cachex,
Geolix.Adapter.LookupCache.CacheAdapter.ConCache,
Geolix.Adapter.LookupCache.CacheAdapter.Fake
]
],
main: "Geolix.Adapter.LookupCache",
nest_modules_by_prefix: [
Geolix.Adapter,
Geolix.Adapter.LookupCache.CacheAdapter
],
source_ref: "master",
source_url: @url_github
]
end
defp package do
%{
files: ["CHANGELOG.md", "LICENSE", "mix.exs", "README.md", "lib"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => @url_github}
}
end
end
| 24.365854 | 72 | 0.571572 |
79a8ead4bb2a6681206fa1c3b642247cd77aefc4 | 1,739 | exs | Elixir | apps/magnetissimo_web/mix.exs | moonbuggy/magnetissimo | 5faa37e7618ed2556e4158733a7e713f3f6e706c | [
"MIT"
] | null | null | null | apps/magnetissimo_web/mix.exs | moonbuggy/magnetissimo | 5faa37e7618ed2556e4158733a7e713f3f6e706c | [
"MIT"
] | null | null | null | apps/magnetissimo_web/mix.exs | moonbuggy/magnetissimo | 5faa37e7618ed2556e4158733a7e713f3f6e706c | [
"MIT"
] | 1 | 2022-02-05T14:10:49.000Z | 2022-02-05T14:10:49.000Z | defmodule MagnetissimoWeb.MixProject do
use Mix.Project
def project do
[
app: :magnetissimo_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: {MagnetissimoWeb.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.1"},
{:phoenix_pubsub, "~> 1.1"},
{:phoenix_ecto, "~> 4.0"},
{:phoenix_html, "~> 2.11"},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:gettext, "~> 0.11"},
{:health_checkup, "~> 0.1.0"},
{:magnetissimo, in_umbrella: true},
{:jason, "~> 1.0"},
{:plug_cowboy, "~> 2.0"},
{:scrivener_html, "~> 1.8"},
{:size, "~> 0.1.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.603175 | 76 | 0.583094 |
79a8ec257874a3781d91d485f9e639bac5ac57c3 | 1,440 | exs | Elixir | test/stun_test.exs | xirsys/xturn-website | bf3c924e5d3112772fbb9f674a0d7105497c29ae | [
"Apache-2.0"
] | 73 | 2018-11-13T01:10:41.000Z | 2022-01-30T17:58:45.000Z | test/stun_test.exs | xirsys/xturn-website | bf3c924e5d3112772fbb9f674a0d7105497c29ae | [
"Apache-2.0"
] | 1 | 2019-02-21T19:32:51.000Z | 2019-02-22T11:12:09.000Z | test/stun_test.exs | xirsys/xturn-website | bf3c924e5d3112772fbb9f674a0d7105497c29ae | [
"Apache-2.0"
] | 8 | 2019-03-27T01:44:16.000Z | 2022-01-12T12:34:12.000Z | defmodule StunTest do
# bring in the test functionality
use ExUnit.Case
require Logger
alias XMediaLib.Stun
alias Xirsys.Sockets.Conn
alias Xirsys.XTurn.Pipeline
alias Xirsys.Sockets.Socket
@conn %Conn{
client_ip: {127, 0, 0, 2},
client_port: 8881,
server_ip: {127, 0, 0, 3},
server_port: 8882
}
@stun %Stun{
class: :request,
method: :binding,
transactionid: 123_456_789_012
}
setup do
{:ok, stun: Stun.encode(@stun)}
end
test "valid stun packet format", %{stun: stun} do
# is at least 16 bits and starts with 00 bits
assert valid_stun(stun)
end
test "returns valid response", %{stun: stun} do
conn = Pipeline.process_message(%Conn{@conn | message: stun})
assert conn.response.class == :success,
"STUN request should be valid"
assert Map.get(conn.response.attrs || %{}, :xor_mapped_address) ==
{@conn.client_ip, @conn.client_port},
"must return a xor-mapped-address"
assert Map.get(conn.response.attrs || %{}, :mapped_address) ==
{@conn.client_ip, @conn.client_port},
"must return a mapped-address"
assert Map.get(conn.response.attrs || %{}, :response_origin) ==
{Socket.server_ip(), @conn.server_port},
"must return a response-origin"
end
defp valid_stun(<<0::2, _::14, _rest::binary>>) do
true
end
defp valid_stun(_) do
false
end
end
| 24.40678 | 70 | 0.632639 |
79a90dbaa18aa3c93f0592677cd4719264da7499 | 2,285 | ex | Elixir | lib/blog_linter.ex | buys-fran/blog_linter_ex | bf0debb5b66b196d06b3c29e612ad416d720c971 | [
"MIT"
] | 2 | 2021-04-30T04:15:25.000Z | 2021-05-13T17:31:17.000Z | lib/blog_linter.ex | buys-fran/blog_linter_ex | bf0debb5b66b196d06b3c29e612ad416d720c971 | [
"MIT"
] | null | null | null | lib/blog_linter.ex | buys-fran/blog_linter_ex | bf0debb5b66b196d06b3c29e612ad416d720c971 | [
"MIT"
] | 2 | 2021-04-30T04:15:29.000Z | 2021-06-08T13:08:23.000Z | defmodule BlogLinter do
@moduledoc """
Documentation for `BlogLinter`.
"""
@doc """
iex> BlogLinter.clean_path("./blogposts")
"blogposts"
"""
def clean_path(path) do
String.replace(path, ~r/.*\//, "")
end
def file_names(path) do
path = clean_path(path)
Path.wildcard("./#{path}/*.markdown")
|> Enum.map(fn filename -> String.replace(filename, ~r/#{path}\//, "") end)
end
def process_path(path) do
file_names(path) # ["post1.markdown", "post2.markdown"]
|> Enum.map(fn filename -> process_file(path, filename) end)
# TODO: the last function will produce a list of {filename, list_of_errors}
# we have to process that list, display errors if any and change the exit
# code of the script
end
def process_file(path, filename) do
case File.read("#{path}/#{filename}") do
{:ok, content} -> {filename, check_errors(content)}
{:error, reason} -> {filename, reason}
end
end
def check_errors(content) do
metadata = extract_metadata(content)
[]
|> check_layout(metadata)
|> check_author(metadata)
end
def extract_metadata(content) do
metadata_string =
hd(hd(Regex.scan(~r/---.*---/s, content)))
|> String.replace(~r/\n?---\n?/, "")
case YamlElixir.read_from_string(metadata_string) do
{:ok, yaml_map} -> yaml_map
end
end
@spec check_layout(any, any) :: any
@doc """
iex> BlogLinter.check_layout([], %{"layout" => "post", author: ""})
[]
iex> BlogLinter.check_layout([], %{"layout" => "landing", author: ""})
["Layout must be post"]
iex> BlogLinter.check_layout([], %{})
["Layout must be post"]
"""
def check_layout(errors, %{"layout" => "post"}), do: errors
def check_layout(errors, _), do: ["Layout must be post" | errors]
# TODO: add doc tests here
def check_author(errors, %{"author" => author}) when is_binary(author) and author != "" do
errors
end
def check_author(errors, %{"author" => _}), do: ["Author must be present" | errors]
# TODO: Validate `authors` key
# def check_author(errors, %{authors: authors}) when valid_authors(authors) do
# errors
# end
# TODO: add a generic check_author function to catch if both author and authors keys are missing
end
| 28.209877 | 98 | 0.628009 |
79a94867736bc0c0b35bbdf1e5c8bcceefbe4f9c | 155 | exs | Elixir | priv/repo/migrations/20200811204826_add_index_to_events_table.exs | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 83 | 2018-05-31T14:49:10.000Z | 2022-03-27T16:49:49.000Z | priv/repo/migrations/20200811204826_add_index_to_events_table.exs | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 267 | 2018-05-22T23:19:02.000Z | 2022-03-31T04:31:06.000Z | priv/repo/migrations/20200811204826_add_index_to_events_table.exs | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 18 | 2018-11-20T05:15:54.000Z | 2022-03-28T08:20:13.000Z | defmodule Console.Repo.Migrations.AddIndexToEventsTable do
use Ecto.Migration
def change do
create index(:events, [:reported_at_naive])
end
end
| 19.375 | 58 | 0.774194 |
79a970d287d58ff3392c50e65607165148c25d71 | 821 | ex | Elixir | daniel/almeida/ch6/dungeon_crawl/lib/dungeon_crawl/enemies.ex | jdashton/glowing-succotash | 44580c2d4cb300e33156d42e358e8a055948a079 | [
"MIT"
] | null | null | null | daniel/almeida/ch6/dungeon_crawl/lib/dungeon_crawl/enemies.ex | jdashton/glowing-succotash | 44580c2d4cb300e33156d42e358e8a055948a079 | [
"MIT"
] | 1 | 2020-02-26T14:55:23.000Z | 2020-02-26T14:55:23.000Z | daniel/almeida/ch6/dungeon_crawl/lib/dungeon_crawl/enemies.ex | jdashton/glowing-succotash | 44580c2d4cb300e33156d42e358e8a055948a079 | [
"MIT"
] | null | null | null | defmodule DungeonCrawl.Enemies do
alias DungeonCrawl.Character
def all,
do: [
%Character{
name: "Ogre",
description: "A large creature. Big muscles. Angry and hungry.",
hit_points: 12,
max_hit_points: 12,
damage_range: 3..5,
attack_description: "a hammer"
},
%Character{
name: "Orc",
description: "A green evil creature. Wears armor and an axe.",
hit_points: 8,
max_hit_points: 8,
damage_range: 2..4,
attack_description: "an axe"
},
%Character{
name: "Goblin",
description: "A small green creature. Wears dirty clothes and a dagger.",
hit_points: 4,
max_hit_points: 4,
damage_range: 1..2,
attack_description: "a dagger"
}
]
end
| 25.65625 | 81 | 0.568819 |
79a9887ca7e07c558498742e50af4c45155ff168 | 750 | ex | Elixir | lib/adify/tool/installation_strategy.ex | ericsullivan/adify | 25b842498ccfbf612e42d8b46530aad1ffb1af5a | [
"MIT"
] | 5 | 2019-07-14T22:24:32.000Z | 2020-11-25T20:36:11.000Z | lib/adify/tool/installation_strategy.ex | ericsullivan/adify | 25b842498ccfbf612e42d8b46530aad1ffb1af5a | [
"MIT"
] | 43 | 2018-01-18T15:16:30.000Z | 2021-01-23T22:12:17.000Z | lib/adify/tool/installation_strategy.ex | ericsullivan/adify | 25b842498ccfbf612e42d8b46530aad1ffb1af5a | [
"MIT"
] | 2 | 2019-05-28T17:50:27.000Z | 2020-03-23T21:00:02.000Z | defmodule Adify.Tool.InstallationStrategy do
@moduledoc """
Represents the set of commands with `up` and `down` with the priority
"""
use Ecto.Schema
import Ecto.Changeset
@primary_key false
embedded_schema do
field(:name, :string)
field(:number, :integer)
field(:description, :string)
field(:default, :boolean, default: false)
embeds_one(:up, Adify.Tool.InstallationStrategy.Workflow)
embeds_one(:down, Adify.Tool.InstallationStrategy.Workflow)
end
def changeset(struct, params) do
struct
|> cast(params, [:name, :number, :description, :default])
|> validate_required([:name, :number, :description])
|> cast_embed(:up, required: true)
|> cast_embed(:down, required: true)
end
end
| 25.862069 | 71 | 0.694667 |
79a9e896d6a716dc0e7570e7e6b96fc95b534f54 | 710 | ex | Elixir | services/fc_inventory/lib/fc_inventory/events/reserved_stock_decreased.ex | fleadope/freshcom | 8d5944befaa6eea8d31e5f5995939be2a1a44262 | [
"BSD-3-Clause"
] | 46 | 2018-10-13T23:18:13.000Z | 2021-08-07T07:46:51.000Z | services/fc_inventory/lib/fc_inventory/events/reserved_stock_decreased.ex | fleadope/freshcom | 8d5944befaa6eea8d31e5f5995939be2a1a44262 | [
"BSD-3-Clause"
] | 25 | 2018-10-14T00:56:07.000Z | 2019-12-23T19:41:02.000Z | services/fc_inventory/lib/fc_inventory/events/reserved_stock_decreased.ex | fleadope/freshcom | 8d5944befaa6eea8d31e5f5995939be2a1a44262 | [
"BSD-3-Clause"
] | 5 | 2018-12-16T04:39:51.000Z | 2020-10-01T12:17:03.000Z | defmodule FCInventory.ReservedStockDecreased do
use FCBase, :event
@version 1
typedstruct do
field :__version__, integer(), default: @version
field :request_id, String.t()
field :requester_id, String.t()
field :requester_type, String.t()
field :requester_role, String.t()
field :client_id, String.t()
field :client_type, String.t()
field :account_id, String.t()
field :stock_id, String.t()
field :transaction_id, String.t()
field :quantity, Decimal.t()
end
end
defimpl Commanded.Serialization.JsonDecoder, for: FCInventory.ReservedStockDecreased do
alias Decimal, as: D
def decode(event) do
%{event | quantity: D.new(event.quantity)}
end
end | 23.666667 | 87 | 0.701408 |
79aa0e699885665cdc54e82db5809c6f1defb487 | 1,152 | ex | Elixir | test/support/message_store_factory.ex | josemrb/ex_message_db | 9defeb9c72bfc47280671d75c82fe33134914fd4 | [
"MIT"
] | null | null | null | test/support/message_store_factory.ex | josemrb/ex_message_db | 9defeb9c72bfc47280671d75c82fe33134914fd4 | [
"MIT"
] | null | null | null | test/support/message_store_factory.ex | josemrb/ex_message_db | 9defeb9c72bfc47280671d75c82fe33134914fd4 | [
"MIT"
] | null | null | null | defmodule ExMessageDB.MessageStoreFactory do
@moduledoc """
MessageStore factory.
"""
use ExMachina
alias Ecto.UUID
alias ExMessageDB.DataGenerator
alias ExMessageDB.TestEvent
def message_factory(attrs) when is_map(attrs) do
category_name = Map.get(attrs, :category_name, "stream")
%{
id: UUID.generate(),
stream_name: sequence(:stream_name, &"#{category_name}-#{&1}"),
embedded_data: build(:event)
}
|> merge_attributes(attrs)
end
def message_data_map_factory(attrs) when is_map(attrs) do
category_name = Map.get(attrs, :category_name, "stream")
%{
id: UUID.generate(),
stream_name: sequence(:stream_name, &"#{category_name}-#{&1}"),
type: sequence("StringType"),
data: %{
name: sequence("map_"),
amount: DataGenerator.random_amount()
}
}
|> merge_attributes(attrs)
end
def event_factory(attrs) when is_map(attrs) do
%{
name: sequence("event_"),
amount: DataGenerator.random_amount(),
enabled: DataGenerator.random_boolean(),
since: DateTime.utc_now()
}
|> TestEvent.create!()
end
end
| 23.510204 | 69 | 0.648438 |
79aa12d5924ad07603098b0209ffbe1ded94c784 | 945 | ex | Elixir | lib/codes/codes_z64.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_z64.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_z64.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_Z64 do
alias IcdCode.ICDCode
def _Z640 do
%ICDCode{full_code: "Z640",
category_code: "Z64",
short_code: "0",
full_name: "Problems related to unwanted pregnancy",
short_name: "Problems related to unwanted pregnancy",
category_name: "Problems related to unwanted pregnancy"
}
end
def _Z641 do
%ICDCode{full_code: "Z641",
category_code: "Z64",
short_code: "1",
full_name: "Problems related to multiparity",
short_name: "Problems related to multiparity",
category_name: "Problems related to multiparity"
}
end
def _Z644 do
%ICDCode{full_code: "Z644",
category_code: "Z64",
short_code: "4",
full_name: "Discord with counselors",
short_name: "Discord with counselors",
category_name: "Discord with counselors"
}
end
end
| 27.794118 | 65 | 0.614815 |
79aa2e955700a460fe2c8017eb3dd83c21731139 | 1,615 | ex | Elixir | clients/people/lib/google_api/people/v1/model/empty.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/people/lib/google_api/people/v1/model/empty.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/people/lib/google_api/people/v1/model/empty.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.People.V1.Model.Empty do
@moduledoc """
A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`.
## Attributes
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{}
end
defimpl Poison.Decoder, for: GoogleApi.People.V1.Model.Empty do
def decode(value, options) do
GoogleApi.People.V1.Model.Empty.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.People.V1.Model.Empty do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.55814 | 381 | 0.745511 |
79aa44acffd559e3a1eb4d8431e6b5d1c29b821a | 362 | ex | Elixir | lib/plain_sitemap/generator.ex | kenta-aktsk/plain_sitemap | 386ea1ca23cc39df943f2a6fcb6136fc54c7a9dc | [
"MIT"
] | 9 | 2016-05-11T04:41:23.000Z | 2019-06-03T14:48:10.000Z | lib/plain_sitemap/generator.ex | kenta-aktsk/plain_sitemap | 386ea1ca23cc39df943f2a6fcb6136fc54c7a9dc | [
"MIT"
] | 7 | 2016-05-06T08:59:37.000Z | 2017-02-26T10:45:32.000Z | lib/plain_sitemap/generator.ex | kenta-aktsk/plain_sitemap | 386ea1ca23cc39df943f2a6fcb6136fc54c7a9dc | [
"MIT"
] | 2 | 2016-09-17T13:48:36.000Z | 2017-02-22T10:33:32.000Z | defmodule PlainSitemap.Generator do
def start_link do
Agent.start_link(fn -> [] end, name: __MODULE__)
end
def add(path, opts) do
entry = {path, opts}
Agent.update(__MODULE__, &([entry | &1]))
end
def flush do
Agent.update(__MODULE__, fn(_) -> [] end)
end
def urlset do
Agent.get(__MODULE__, &(&1 |> Enum.reverse))
end
end
| 19.052632 | 52 | 0.635359 |
79aa75f9fc127cd3b40c50c196035520b4356947 | 713 | ex | Elixir | web/controllers/tp_destination_controller.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | web/controllers/tp_destination_controller.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | web/controllers/tp_destination_controller.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | defmodule CgratesWebJsonapi.TpDestinationController do
use CgratesWebJsonapi.Web, :controller
use JaResource
use CgratesWebJsonapi.TpSubresource
use CgratesWebJsonapi.DefaultSorting
use CgratesWebJsonapi.CsvExport
use CgratesWebJsonapi.DeleteAll
alias CgratesWebJsonapi.TpDestination
plug JaResource
def handle_show(conn, id), do: Repo.get!(TpDestination, id)
def filter(_conn, query, "tag", tag), do: query |> where([r], like(r.tag, ^"%#{tag}%"))
def filter(_conn, query, "prefix", prefix), do: query |> where([r], like(r.prefix, ^"%#{prefix}%"))
defp build_query(conn, params) do
conn
|> handle_index(params)
|> JaResource.Index.filter(conn, __MODULE__)
end
end
| 29.708333 | 101 | 0.7223 |
79aa7c2ea2ba327228d71c20199ef0a256a8c855 | 1,731 | ex | Elixir | clients/document_ai/lib/google_api/document_ai/v1beta3/model/google_cloud_documentai_v1beta3_normalized_vertex.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/document_ai/lib/google_api/document_ai/v1beta3/model/google_cloud_documentai_v1beta3_normalized_vertex.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/document_ai/lib/google_api/document_ai/v1beta3/model/google_cloud_documentai_v1beta3_normalized_vertex.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"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.DocumentAI.V1beta3.Model.GoogleCloudDocumentaiV1beta3NormalizedVertex do
@moduledoc """
A vertex represents a 2D point in the image. NOTE: the normalized vertex coordinates are relative to the original image and range from 0 to 1.
## Attributes
* `x` (*type:* `number()`, *default:* `nil`) - X coordinate.
* `y` (*type:* `number()`, *default:* `nil`) - Y coordinate.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:x => number(),
:y => number()
}
field(:x)
field(:y)
end
defimpl Poison.Decoder,
for: GoogleApi.DocumentAI.V1beta3.Model.GoogleCloudDocumentaiV1beta3NormalizedVertex do
def decode(value, options) do
GoogleApi.DocumentAI.V1beta3.Model.GoogleCloudDocumentaiV1beta3NormalizedVertex.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.DocumentAI.V1beta3.Model.GoogleCloudDocumentaiV1beta3NormalizedVertex do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.472727 | 144 | 0.729058 |
79aaa998b252fce0705c3ecd2d5aaff8c4603ebb | 465 | ex | Elixir | apps/registration_data/lib/registration_data/channel.ex | ndac-todoroki/DiscordSplatoonBot | 6a082b0352684cb64d36fe9116e7f060691cba37 | [
"MIT"
] | 6 | 2017-08-10T13:57:06.000Z | 2019-01-17T08:48:40.000Z | apps/registration_data/lib/registration_data/channel.ex | ndac-todoroki/DiscordSplatoonBot | 6a082b0352684cb64d36fe9116e7f060691cba37 | [
"MIT"
] | 14 | 2017-08-08T13:07:00.000Z | 2019-02-28T15:10:18.000Z | apps/registration_data/lib/registration_data/channel.ex | ndac-todoroki/DiscordSplatoonBot | 6a082b0352684cb64d36fe9116e7f060691cba37 | [
"MIT"
] | null | null | null | defmodule RegistrationData.Channel do
use Ecto.Schema
import Ecto.Changeset
alias RegistrationData.{Schedule, Subscribe}
schema "channels" do
field :identifier, :integer
timestamps()
many_to_many :schedules, Schedule, join_through: Subscribe
end
@doc false
def changeset(%__MODULE__{} = data, attrs) do
data
|> cast(attrs, [:identifier])
|> validate_required([:identifier])
|> unique_constraint(:identifier)
end
end
| 20.217391 | 62 | 0.707527 |
79aaacbde866ca88c218f3af378060720841ecdc | 3,137 | ex | Elixir | lib/ash/dsl/entity.ex | alexfreska/ash | b7ffc5495fd6d956199fb74cfc1f72f58bf8505a | [
"MIT"
] | null | null | null | lib/ash/dsl/entity.ex | alexfreska/ash | b7ffc5495fd6d956199fb74cfc1f72f58bf8505a | [
"MIT"
] | null | null | null | lib/ash/dsl/entity.ex | alexfreska/ash | b7ffc5495fd6d956199fb74cfc1f72f58bf8505a | [
"MIT"
] | null | null | null | defmodule Ash.Dsl.Entity do
@moduledoc """
Declares a DSL entity.
A dsl entity represents a dsl constructor who's resulting value is a struct.
This lets the user create complex objects with arbitrary(mostly) validation rules.
The lifecycle of creating entities is complex, happening as Elixir is compiling
the modules in question. Some of the patterns around validating/transforming entities
have not yet solidified. If you aren't careful and don't follow the guidelines listed
here, you can have subtle and strange bugs during compilation. Anything not isolated to
simple value validations should be done in `transformers`. See `Ash.Dsl.Transformer`.
An entity has a `target` indicating which struct will ultimately be built. An entity
also has a `schema`. This schema is used for documentation, and the options are validated
against it before continuing on with the DSL.
To create positional arguments to the builder, use `args`. The values provided to
`args` need to be in the provided schema as well. They will be positional arguments
in the same order that they are provided in the `args` key.
`auto_set_fields` will set the provided values into the produced struct (they do not need
to be included in the schema).
`transform` is a function that takes a created struct and can alter it. This happens immediately
after handling the DSL options, and can be useful for setting field values on a struct based on
other values in that struct. If you need things that aren't contained in that struct, use an
`Ash.Dsl.Transformer`.
`entities` allows you to specify a keyword list of nested entities. Nested entities are stored
on the struct in the corresponding key, and are used in the same way entities are otherwise.
For a full example, see `Ash.Dsl.Extension`.
"""
defstruct [
:name,
:target,
:transform,
examples: [],
entities: [],
describe: "",
args: [],
modules: [],
schema: [],
auto_set_fields: []
]
@type t :: %__MODULE__{
name: atom,
describe: String.t(),
target: module,
examples: [String.t()],
transform: mfa | nil,
args: [atom],
entities: Keyword.t(),
auto_set_fields: Keyword.t(),
schema: Ash.OptionsHelpers.schema()
}
def build(
%{target: target, schema: schema, auto_set_fields: auto_set_fields, transform: transform},
opts,
nested_entities
) do
{before_validate_auto, after_validate_auto} =
Keyword.split(auto_set_fields || [], Keyword.keys(schema))
with {:ok, opts} <-
Ash.OptionsHelpers.validate(Keyword.merge(opts || [], before_validate_auto), schema),
opts <- Keyword.merge(opts, after_validate_auto),
built <- struct(target, opts),
built <- struct(built, nested_entities),
{:ok, built} <-
transform(transform, built) do
{:ok, built}
end
end
defp transform(nil, built), do: {:ok, built}
defp transform({module, function, args}, built) do
apply(module, function, [built | args])
end
end
| 36.905882 | 98 | 0.684093 |
79aad2cc4e3098ab8e8b7ebcd31c4221831f4d31 | 199 | exs | Elixir | priv/repo/migrations/20190116145140_alter_c11n_theme.exs | coderplanets/coderplanets_server | 3663e56340d6d050e974c91f7e499d8424fc25e9 | [
"Apache-2.0"
] | 240 | 2018-11-06T09:36:54.000Z | 2022-02-20T07:12:36.000Z | priv/repo/migrations/20190116145140_alter_c11n_theme.exs | coderplanets/coderplanets_server | 3663e56340d6d050e974c91f7e499d8424fc25e9 | [
"Apache-2.0"
] | 363 | 2018-07-11T03:38:14.000Z | 2021-12-14T01:42:40.000Z | priv/repo/migrations/20190116145140_alter_c11n_theme.exs | mydearxym/mastani_server | f24034a4a5449200165cf4a547964a0961793eab | [
"Apache-2.0"
] | 22 | 2019-01-27T11:47:56.000Z | 2021-02-28T13:17:52.000Z | defmodule GroupherServer.Repo.Migrations.AlterC11nTheme do
use Ecto.Migration
def change do
alter table(:customizations) do
remove(:theme)
add(:theme, :string)
end
end
end
| 18.090909 | 58 | 0.703518 |
79aae0c2833ad2b61ead0371776f0e328fa67034 | 4,074 | exs | Elixir | test/newslettex_web/controllers/campaign_contact_event_controller_test.exs | silva96/newslettex | 4876392c9900c0ce169dcdcb9ebb01ab3da83d65 | [
"MIT"
] | null | null | null | test/newslettex_web/controllers/campaign_contact_event_controller_test.exs | silva96/newslettex | 4876392c9900c0ce169dcdcb9ebb01ab3da83d65 | [
"MIT"
] | 10 | 2019-07-29T03:03:02.000Z | 2021-05-10T23:59:25.000Z | test/newslettex_web/controllers/campaign_contact_event_controller_test.exs | silva96/newslettex | 4876392c9900c0ce169dcdcb9ebb01ab3da83d65 | [
"MIT"
] | null | null | null | defmodule NewslettexWeb.CampaignContactEventControllerTest do
use NewslettexWeb.ConnCase
alias Newslettex.Newsletter
@create_attrs %{event_type: :send, smtp_message_id: "some smtp_message_id"}
@update_attrs %{event_type: :delivery, smtp_message_id: "some updated smtp_message_id"}
@invalid_attrs %{event_type: nil, smtp_message_id: nil}
def fixture(:campaign_contact_event) do
{:ok, campaign_contact_event} = Newsletter.create_campaign_contact_event(@create_attrs)
campaign_contact_event
end
describe "index" do
test "lists all campaign_contact_events", %{conn: conn} do
conn = get(conn, Routes.campaign_contact_event_path(conn, :index))
assert html_response(conn, 200) =~ "Listing Campaign contact events"
end
end
describe "new campaign_contact_event" do
test "renders form", %{conn: conn} do
conn = get(conn, Routes.campaign_contact_event_path(conn, :new))
assert html_response(conn, 200) =~ "New Campaign contact event"
end
end
describe "create campaign_contact_event" do
test "redirects to show when data is valid", %{conn: conn} do
conn =
post(conn, Routes.campaign_contact_event_path(conn, :create),
campaign_contact_event: @create_attrs
)
assert %{id: id} = redirected_params(conn)
assert redirected_to(conn) == Routes.campaign_contact_event_path(conn, :show, id)
conn = get(conn, Routes.campaign_contact_event_path(conn, :show, id))
assert html_response(conn, 200) =~ "Show Campaign contact event"
end
test "renders errors when data is invalid", %{conn: conn} do
conn =
post(conn, Routes.campaign_contact_event_path(conn, :create),
campaign_contact_event: @invalid_attrs
)
assert html_response(conn, 200) =~ "New Campaign contact event"
end
end
describe "edit campaign_contact_event" do
setup [:create_campaign_contact_event]
test "renders form for editing chosen campaign_contact_event", %{
conn: conn,
campaign_contact_event: campaign_contact_event
} do
conn = get(conn, Routes.campaign_contact_event_path(conn, :edit, campaign_contact_event))
assert html_response(conn, 200) =~ "Edit Campaign contact event"
end
end
describe "update campaign_contact_event" do
setup [:create_campaign_contact_event]
test "redirects when data is valid", %{
conn: conn,
campaign_contact_event: campaign_contact_event
} do
conn =
put(conn, Routes.campaign_contact_event_path(conn, :update, campaign_contact_event),
campaign_contact_event: @update_attrs
)
assert redirected_to(conn) ==
Routes.campaign_contact_event_path(conn, :show, campaign_contact_event)
conn = get(conn, Routes.campaign_contact_event_path(conn, :show, campaign_contact_event))
assert html_response(conn, 200) =~ "some updated smtp_message_id"
end
test "renders errors when data is invalid", %{
conn: conn,
campaign_contact_event: campaign_contact_event
} do
conn =
put(conn, Routes.campaign_contact_event_path(conn, :update, campaign_contact_event),
campaign_contact_event: @invalid_attrs
)
assert html_response(conn, 200) =~ "Edit Campaign contact event"
end
end
describe "delete campaign_contact_event" do
setup [:create_campaign_contact_event]
test "deletes chosen campaign_contact_event", %{
conn: conn,
campaign_contact_event: campaign_contact_event
} do
conn =
delete(conn, Routes.campaign_contact_event_path(conn, :delete, campaign_contact_event))
assert redirected_to(conn) == Routes.campaign_contact_event_path(conn, :index)
assert_error_sent 404, fn ->
get(conn, Routes.campaign_contact_event_path(conn, :show, campaign_contact_event))
end
end
end
defp create_campaign_contact_event(_) do
campaign_contact_event = fixture(:campaign_contact_event)
{:ok, campaign_contact_event: campaign_contact_event}
end
end
| 33.95 | 95 | 0.71404 |
79ab2e9b073f88a445dc26d0e5f52b56d5c3ddd7 | 988 | exs | Elixir | mix.exs | EnaiaInc/live_ex | 43d0d4a8a9d653e5dbadb4fab871641e515ccc68 | [
"MIT"
] | null | null | null | mix.exs | EnaiaInc/live_ex | 43d0d4a8a9d653e5dbadb4fab871641e515ccc68 | [
"MIT"
] | null | null | null | mix.exs | EnaiaInc/live_ex | 43d0d4a8a9d653e5dbadb4fab871641e515ccc68 | [
"MIT"
] | null | null | null | defmodule LiveEx.MixProject do
use Mix.Project
def project do
[
app: :live_ex,
version: "0.3.0",
description: "Flux based State Management for Phoenix LiveView",
source_url: "https://github.com/PJUllrich/live_ex",
package: [
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/PJUllrich/live_ex"}
],
elixir: "~> 1.7",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:jason, ">= 0.0.0"},
{:phoenix_live_view, "~> 0.15"},
# Development and publishing dependencies
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:credo, "~> 1.4", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.0", only: [:dev], runtime: false}
]
end
end
| 24.7 | 70 | 0.566802 |
79ab32513261ed1b8301ee36e6db377b30f98377 | 79 | exs | Elixir | examples/scale_rectangle/test/scale_rectangle_test.exs | shiryel/rayex | 20cbffe788ef9df66d3e8ff918fe16a040aff737 | [
"Apache-2.0"
] | 8 | 2021-08-06T16:12:53.000Z | 2022-02-07T21:23:00.000Z | examples/scale_rectangle/test/scale_rectangle_test.exs | shiryel/rayex | 20cbffe788ef9df66d3e8ff918fe16a040aff737 | [
"Apache-2.0"
] | 3 | 2021-07-31T20:04:29.000Z | 2021-12-17T19:52:41.000Z | examples/scale_rectangle/test/scale_rectangle_test.exs | shiryel/rayex | 20cbffe788ef9df66d3e8ff918fe16a040aff737 | [
"Apache-2.0"
] | 3 | 2021-07-30T06:20:00.000Z | 2022-02-23T22:33:31.000Z | defmodule ScaleRectangleTest do
use ExUnit.Case
doctest ScaleRectangle
end
| 15.8 | 31 | 0.835443 |
79ab4d3467e4d3d105861f1a92eed3b13d2b3c02 | 717 | exs | Elixir | test/vintage_net/technology/null_test.exs | axelson/vintage_net | 68866ff223fa40e7ad6fd4d9fb2f7960cf51b1ca | [
"Apache-2.0"
] | 85 | 2019-05-09T14:54:38.000Z | 2022-02-08T16:52:04.000Z | test/vintage_net/technology/null_test.exs | axelson/vintage_net | 68866ff223fa40e7ad6fd4d9fb2f7960cf51b1ca | [
"Apache-2.0"
] | 132 | 2019-05-09T15:57:59.000Z | 2022-02-28T16:31:22.000Z | test/vintage_net/technology/null_test.exs | axelson/vintage_net | 68866ff223fa40e7ad6fd4d9fb2f7960cf51b1ca | [
"Apache-2.0"
] | 14 | 2019-07-08T19:18:23.000Z | 2022-02-08T16:52:05.000Z | defmodule VintageNet.Technology.NullTest do
use ExUnit.Case
alias VintageNet.Interface.RawConfig
alias VintageNet.Technology.Null
test "normalizing null" do
# Normalizing anything to Null should be Null
assert %{type: VintageNet.Technology.Null} == Null.normalize(%{})
end
test "converting to raw config" do
input = %{
type: VintageNet.Technology.Null
}
# Static IP support is not implemented. This is what is currently produced,
# but it is incomplete.
output = %RawConfig{
type: VintageNet.Technology.Null,
ifname: "eth0",
source_config: input,
required_ifnames: []
}
assert output == Null.to_raw_config("eth0", input, [])
end
end
| 25.607143 | 79 | 0.683403 |
79ab4fe2cbbf1f8243932b775d2710b17b6ae2c4 | 1,628 | ex | Elixir | clients/storage/lib/google_api/storage/v1/model/bucket_access_controls.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/storage/lib/google_api/storage/v1/model/bucket_access_controls.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/storage/lib/google_api/storage/v1/model/bucket_access_controls.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.Storage.V1.Model.BucketAccessControls do
@moduledoc """
An access-control list.
## Attributes
- items ([BucketAccessControl]): The list of items. Defaults to: `null`.
- kind (String.t): The kind of item this is. For lists of bucket access control entries, this is always storage#bucketAccessControls. Defaults to: `null`.
"""
defstruct [
:items,
:kind
]
end
defimpl Poison.Decoder, for: GoogleApi.Storage.V1.Model.BucketAccessControls do
import GoogleApi.Storage.V1.Deserializer
def decode(value, options) do
value
|> deserialize(:items, :list, GoogleApi.Storage.V1.Model.BucketAccessControl, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Storage.V1.Model.BucketAccessControls do
def encode(value, options) do
GoogleApi.Storage.V1.Deserializer.serialize_non_nil(value, options)
end
end
| 33.22449 | 156 | 0.753686 |
79ab9851fde69a6dc1f60d6612dd400d523ada24 | 2,961 | ex | Elixir | lib/desktop/os.ex | watsy0007/desktop | 3ba43a1c16aa39bab3e03c94e56024c66f0b1d96 | [
"MIT"
] | null | null | null | lib/desktop/os.ex | watsy0007/desktop | 3ba43a1c16aa39bab3e03c94e56024c66f0b1d96 | [
"MIT"
] | null | null | null | lib/desktop/os.ex | watsy0007/desktop | 3ba43a1c16aa39bab3e03c94e56024c66f0b1d96 | [
"MIT"
] | null | null | null | defmodule Desktop.OS do
@moduledoc """
The OS module provides shortcuts and helper functions
to access OS specific information.
Most significant one should use OS.type() to differentiate
between the currently supported environments:
- Android
- IOS
- MacOS
- Windows
- Linux
"""
@doc """
Returns the users home directory
"""
@spec home :: binary
def home() do
{:ok, [[home]]} = :init.get_argument(:home)
List.to_string(home)
end
@doc false
def raise_frame(frame) do
if type() == MacOS do
name = System.get_env("EMU", "beam.smp")
fn -> System.cmd("open", ["-a", name], stderr_to_stdout: true) end
|> spawn_link()
else
# Calling this on wxDirDialog segfaults on macos..
:wxTopLevelWindow.setFocus(frame)
:wxWindow.raise(frame)
end
end
@spec type :: Linux | MacOS | Windows | Android | IOS
def type() do
case System.get_env("ELIXIR_DESKTOP_OS", nil) do
"android" ->
Android
"ios" ->
IOS
_ ->
case :os.type() do
{:unix, :darwin} -> MacOS
{:unix, :linux} -> Linux
{:win32, _} -> Windows
end
end
end
def shutdown() do
spawn(&halt/0)
end
@spec halt() :: no_return()
defp halt() do
Process.sleep(300)
# With System.stop(0) shutdown of the WebView takes
# a very long time (10+ seconds), and wxWidgets cleanup
# often crashes on macOS
# System.stop(0)
kill_heart()
System.halt(0)
end
def restart() do
if windows?() or mobile?() do
# on windows reinitializing wx-widgets does work sometimes...
:init.restart()
else
# relying on heart
kill_beam()
end
end
def windows?() do
type() == Windows
end
def mobile?() do
case type() do
Android -> true
IOS -> true
_other -> false
end
end
defp kill_heart() do
heart = Process.whereis(:heart)
if heart != nil do
{:links, links} = Process.info(Process.whereis(:heart), :links)
port = Enum.find(links, fn id -> is_port(id) end)
if port != nil do
{:os_pid, heart_pid} = Port.info(port, :os_pid)
if windows?() do
System.cmd("taskkill", ["/f", "/pid", "#{heart_pid}"], stderr_to_stdout: true)
else
System.cmd("kill", ["-9", "#{heart_pid}"], stderr_to_stdout: true)
end
# kill thyself
kill_beam()
end
end
end
defp kill_beam() do
System.cmd("kill", ["-9", "#{:os.getpid()}"], stderr_to_stdout: true)
end
@doc """
This is a Path.expand variant that normalizes the drive letter
on windows
"""
@spec path_expand(binary) :: binary
def path_expand(path) do
if windows?() do
path = Path.expand(path)
drv = String.first(path)
String.replace_prefix(path, drv <> ":", String.upcase(drv) <> ":")
else
Path.expand(path)
end
end
end
| 21.613139 | 88 | 0.579196 |
79ac08a4e4bf9c7e58bfb9aeed15e915274e3a05 | 1,536 | ex | Elixir | test/support/data_case.ex | gissandrogama/delivery_order | 8642453b03f590fe828225fc13aa58a5f79b2117 | [
"MIT"
] | null | null | null | test/support/data_case.ex | gissandrogama/delivery_order | 8642453b03f590fe828225fc13aa58a5f79b2117 | [
"MIT"
] | 6 | 2021-01-22T15:23:04.000Z | 2021-01-28T07:56:01.000Z | test/support/data_case.ex | gissandrogama/delivery_order | 8642453b03f590fe828225fc13aa58a5f79b2117 | [
"MIT"
] | null | null | null | defmodule OrderApi.DataCase do
@moduledoc """
This module defines the setup for tests requiring
access to the application's data layer.
You may define functions here to be used as helpers in
your tests.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use OrderApi.DataCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
alias Ecto.Adapters.SQL.Sandbox
using do
quote do
alias OrderApi.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import OrderApi.DataCase
end
end
setup tags do
:ok = Sandbox.checkout(OrderApi.Repo)
unless tags[:async] do
Sandbox.mode(OrderApi.Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transforms changeset errors into a map of messages.
assert {:error, changeset} = Accounts.create_user(%{password: "short"})
assert "password is too short" in errors_on(changeset).password
assert %{password: ["password is too short"]} = errors_on(changeset)
"""
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
| 26.947368 | 77 | 0.688802 |
79ac28bc861ad4da21b709fc5d4ed2eff56f4b64 | 1,664 | ex | Elixir | clients/sheets/lib/google_api/sheets/v4/model/delete_developer_metadata_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/sheets/lib/google_api/sheets/v4/model/delete_developer_metadata_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/sheets/lib/google_api/sheets/v4/model/delete_developer_metadata_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.Sheets.V4.Model.DeleteDeveloperMetadataResponse do
@moduledoc """
The response from deleting developer metadata.
## Attributes
* `deletedDeveloperMetadata` (*type:* `list(GoogleApi.Sheets.V4.Model.DeveloperMetadata.t)`, *default:* `nil`) - The metadata that was deleted.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:deletedDeveloperMetadata => list(GoogleApi.Sheets.V4.Model.DeveloperMetadata.t()) | nil
}
field(:deletedDeveloperMetadata, as: GoogleApi.Sheets.V4.Model.DeveloperMetadata, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.DeleteDeveloperMetadataResponse do
def decode(value, options) do
GoogleApi.Sheets.V4.Model.DeleteDeveloperMetadataResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.DeleteDeveloperMetadataResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.404255 | 147 | 0.760817 |
79ac56b278abd957c72a865905b9d64181bbcef6 | 312 | ex | Elixir | lib/colorify_web/plugs/ensure_auth.ex | ashkan18/colorify | e4da2bc54a60199c411afc696086689d825b7a13 | [
"MIT"
] | 1 | 2020-03-12T18:44:10.000Z | 2020-03-12T18:44:10.000Z | lib/colorify_web/plugs/ensure_auth.ex | ashkan18/colorify | e4da2bc54a60199c411afc696086689d825b7a13 | [
"MIT"
] | 1 | 2021-03-10T10:22:38.000Z | 2021-03-10T10:22:38.000Z | lib/colorify_web/plugs/ensure_auth.ex | ashkan18/colorify | e4da2bc54a60199c411afc696086689d825b7a13 | [
"MIT"
] | 1 | 2020-03-12T18:41:42.000Z | 2020-03-12T18:41:42.000Z | defmodule ColorifyWeb.Plugs.EnsureAuth do
import Plug.Conn
import Phoenix.Controller
def init(opts), do: opts
def call(conn, _params) do
case get_session(conn, :access_token) do
nil ->
conn
|> redirect(to: "/auth")
|> halt()
_ ->
conn
end
end
end
| 16.421053 | 44 | 0.586538 |
79ac8d900b1478609f89baf2d94a13731295e827 | 773 | ex | Elixir | lib/redlock/node_chooser/store/hash_ring.ex | voode/redlock | a929fd03f04706dd79b2c2f53c1cda8d86f67d25 | [
"MIT"
] | 21 | 2018-01-10T08:38:31.000Z | 2022-01-30T19:15:25.000Z | lib/redlock/node_chooser/store/hash_ring.ex | voode/redlock | a929fd03f04706dd79b2c2f53c1cda8d86f67d25 | [
"MIT"
] | 16 | 2017-10-09T03:31:25.000Z | 2021-09-01T15:06:49.000Z | lib/redlock/node_chooser/store/hash_ring.ex | voode/redlock | a929fd03f04706dd79b2c2f53c1cda8d86f67d25 | [
"MIT"
] | 17 | 2018-05-17T11:30:14.000Z | 2022-01-28T12:46:28.000Z | defmodule Redlock.NodeChooser.Store.HashRing do
alias ExHashRing.HashRing
@behaviour Redlock.NodeChooser.Store
require Logger
@impl true
def new(pools_list) do
len = length(pools_list)
ring =
idx_list(len)
|> Enum.reduce(HashRing.new(), fn idx, ring ->
{:ok, ring2} = HashRing.add_node(ring, "#{idx}")
ring2
end)
[ring, pools_list]
end
defp idx_list(0) do
raise "must not come here"
end
defp idx_list(1) do
# XXX Shouldn't be come here on production environment
[0]
end
defp idx_list(len) do
0..(len - 1) |> Enum.to_list()
end
@impl true
def choose([ring, pools_list], key) do
idx = HashRing.find_node(ring, key)
Enum.at(pools_list, String.to_integer(idx))
end
end
| 19.325 | 58 | 0.641656 |
79acbf0142503198bc2c2275db87e4dcc80eaf31 | 5,049 | ex | Elixir | web/controllers/console_controller.ex | fangkunping/micro-server-shell | e90a9992bb58d4dbc2661825e6e5bcdce5f40e7d | [
"Apache-2.0"
] | null | null | null | web/controllers/console_controller.ex | fangkunping/micro-server-shell | e90a9992bb58d4dbc2661825e6e5bcdce5f40e7d | [
"Apache-2.0"
] | null | null | null | web/controllers/console_controller.ex | fangkunping/micro-server-shell | e90a9992bb58d4dbc2661825e6e5bcdce5f40e7d | [
"Apache-2.0"
] | null | null | null | defmodule MicroServerShell.ConsoleController do
use MicroServerShell.Web, :controller
def get_token(conn, %{"username" => username, "password" => password}) do
case MicroServerShell.Remoting.User.get_user(conn, username, password) do
nil -> response(conn, "用户名密码错误")
user -> response(conn, %{token: MicroServerShell.ConsoleTokenWorker.gen_token(user)})
end
end
@doc """
更新脚本
"""
def upload_script(
conn,
%{"token" => token, "id" => script_id, "content" => script_content} = params
) do
case MicroServerShell.ConsoleTokenWorker.get_user(token) do
nil ->
response(conn, "token过期")
user ->
update_data =
[
fn
%{"name" => name}, acc -> acc |> Map.put("name", name)
_, acc -> acc
end,
fn
%{"note" => note}, acc -> acc |> Map.put("note", note)
_, acc -> acc
end
]
|> Enum.reduce(
%{
"id" => script_id,
"content" => script_content
},
fn f, acc ->
f.(params, acc)
end
)
MicroServerShell.Remoting.Script.update_script(
user.access_party.vip_type,
user.access_party.id,
update_data
)
response(conn, :ok)
end
end
@doc """
如果脚本存在更新,否则创建
"""
def create_or_update_script(
conn,
%{"token" => token, "content" => script_content, "name" => name, "note" => note}
) do
case MicroServerShell.ConsoleTokenWorker.get_user(token) do
nil ->
response(conn, "token过期")
user ->
update_data = %{
"content" => script_content,
"name" => name,
"note" => note
}
scripts =
MicroServerShell.Remoting.Script.get_script_by_name(
user.access_party.vip_type,
user.access_party.id,
name
)
rt =
case scripts do
# 不存在记录, 则新建记录
[] ->
MicroServerShell.Remoting.Script.create_script(
user.access_party.vip_type,
user.access_party.id,
update_data
)
# 存在记录,则更新;
[script | _] ->
MicroServerShell.Remoting.Script.update_script(
user.access_party.vip_type,
user.access_party.id,
update_data |> Map.put("id", script.id)
)
end
case rt do
{:ok, script} ->
response(conn, %{script_id: script.id})
{:error, err} when is_binary(err) ->
response(conn, "其它错误", err)
_ ->
response(conn, "其它错误", "Database error")
end
end
end
@doc """
删除不符合id的脚本
"""
def delete_script_not_in(conn, %{"token" => token, "script_ids" => script_ids}) do
case MicroServerShell.ConsoleTokenWorker.get_user(token) do
nil ->
response(conn, "token过期")
user ->
script_ids =
script_ids |> String.split(",") |> Enum.map(fn e -> e |> String.to_integer() end)
MicroServerShell.Remoting.Script.get_scripts(
user.access_party.vip_type,
user.access_party.id
)
|> Enum.each(fn script ->
if script.id not in script_ids && script.access_partys_id == user.access_party.id do
MicroServerShell.Remoting.Script.delete_script(
user.access_party.vip_type,
user.access_party.id,
script.id
)
end
end)
response(conn, :ok)
end
end
@doc """
更新 server 信息
"""
def update_server(conn, %{
"token" => token,
"id" => id,
"script_sequence" => script_sequence,
"name" => name,
"note" => note
}) do
case MicroServerShell.ConsoleTokenWorker.get_user(token) do
nil ->
response(conn, "token过期")
user ->
case MicroServerShell.Remoting.Server.update_server(user.access_party.vip_type, user.access_party.id, %{
"id" => id,
"script_sequence" => script_sequence,
"name" => name,
"note" => note
}) do
{:ok, _} ->
response(conn, :ok)
{:error, err} when is_binary(err) ->
response(conn, "其它错误", err)
_ ->
response(conn, "其它错误", "Database error")
end
end
end
defp response(conn, "用户名密码错误") do
conn
|> json(%{
code: 4001
})
end
defp response(conn, "token过期") do
conn
|> json(%{
code: 4002
})
end
defp response(conn, :ok) do
conn
|> json(%{
code: 0
})
end
defp response(conn, data) do
conn
|> json(%{
code: 0,
data: data
})
end
defp response(conn, "其它错误", err_string) do
conn
|> json(%{
code: 4000,
error: err_string
})
end
end
| 23.92891 | 112 | 0.506437 |
79acc2ddabbe4d6a21f27954a063ca381dd45f2c | 3,541 | ex | Elixir | clients/firestore/lib/google_api/firestore/v1/model/write.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/firestore/lib/google_api/firestore/v1/model/write.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/firestore/lib/google_api/firestore/v1/model/write.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Firestore.V1.Model.Write do
@moduledoc """
A write on a document.
## Attributes
* `currentDocument` (*type:* `GoogleApi.Firestore.V1.Model.Precondition.t`, *default:* `nil`) - An optional precondition on the document. The write will fail if this is set and not met by the target document.
* `delete` (*type:* `String.t`, *default:* `nil`) - A document name to delete. In the format: `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* `transform` (*type:* `GoogleApi.Firestore.V1.Model.DocumentTransform.t`, *default:* `nil`) - Applies a transformation to a document.
* `update` (*type:* `GoogleApi.Firestore.V1.Model.Document.t`, *default:* `nil`) - A document to write.
* `updateMask` (*type:* `GoogleApi.Firestore.V1.Model.DocumentMask.t`, *default:* `nil`) - The fields to update in this write. This field can be set only when the operation is `update`. If the mask is not set for an `update` and the document exists, any existing data will be overwritten. If the mask is set and the document on the server has fields not covered by the mask, they are left unchanged. Fields referenced in the mask, but not present in the input document, are deleted from the document on the server. The field paths in this mask must not contain a reserved field name.
* `updateTransforms` (*type:* `list(GoogleApi.Firestore.V1.Model.FieldTransform.t)`, *default:* `nil`) - The transforms to perform after update. This field can be set only when the operation is `update`. If present, this write is equivalent to performing `update` and `transform` to the same document atomically and in order.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:currentDocument => GoogleApi.Firestore.V1.Model.Precondition.t(),
:delete => String.t(),
:transform => GoogleApi.Firestore.V1.Model.DocumentTransform.t(),
:update => GoogleApi.Firestore.V1.Model.Document.t(),
:updateMask => GoogleApi.Firestore.V1.Model.DocumentMask.t(),
:updateTransforms => list(GoogleApi.Firestore.V1.Model.FieldTransform.t())
}
field(:currentDocument, as: GoogleApi.Firestore.V1.Model.Precondition)
field(:delete)
field(:transform, as: GoogleApi.Firestore.V1.Model.DocumentTransform)
field(:update, as: GoogleApi.Firestore.V1.Model.Document)
field(:updateMask, as: GoogleApi.Firestore.V1.Model.DocumentMask)
field(:updateTransforms, as: GoogleApi.Firestore.V1.Model.FieldTransform, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Firestore.V1.Model.Write do
def decode(value, options) do
GoogleApi.Firestore.V1.Model.Write.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Firestore.V1.Model.Write do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 57.112903 | 587 | 0.734821 |
79acca127fb6d45ce18bd7768f2ad7abc9ef86c4 | 2,623 | ex | Elixir | clients/dns/lib/google_api/dns/v1/model/resource_record_sets_list_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dns/lib/google_api/dns/v1/model/resource_record_sets_list_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dns/lib/google_api/dns/v1/model/resource_record_sets_list_response.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.DNS.V1.Model.ResourceRecordSetsListResponse do
@moduledoc """
## Attributes
* `header` (*type:* `GoogleApi.DNS.V1.Model.ResponseHeader.t`, *default:* `nil`) -
* `kind` (*type:* `String.t`, *default:* `dns#resourceRecordSetsListResponse`) - Type of resource.
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The presence of this field indicates that there exist more results following your last page of results in pagination order. To fetch them, make another list request using this value as your pagination token.
In this way you can retrieve the complete contents of even very large collections one page at a time. However, if the contents of the collection change between the first and last paginated list request, the set of all elements returned will be an inconsistent view of the collection. There is no way to retrieve a consistent snapshot of a collection larger than the maximum page size.
* `rrsets` (*type:* `list(GoogleApi.DNS.V1.Model.ResourceRecordSet.t)`, *default:* `nil`) - The resource record set resources.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:header => GoogleApi.DNS.V1.Model.ResponseHeader.t(),
:kind => String.t(),
:nextPageToken => String.t(),
:rrsets => list(GoogleApi.DNS.V1.Model.ResourceRecordSet.t())
}
field(:header, as: GoogleApi.DNS.V1.Model.ResponseHeader)
field(:kind)
field(:nextPageToken)
field(:rrsets, as: GoogleApi.DNS.V1.Model.ResourceRecordSet, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse do
def decode(value, options) do
GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 45.224138 | 390 | 0.736942 |
79acf1efe0a87e3638db5516af4ecd6249f0b9f0 | 4,220 | ex | Elixir | web/controllers/password_controller.ex | remigijusj/coherence | 36fe35b0bfe7ac63b44b4046f3ba62f2fe69603a | [
"MIT"
] | null | null | null | web/controllers/password_controller.ex | remigijusj/coherence | 36fe35b0bfe7ac63b44b4046f3ba62f2fe69603a | [
"MIT"
] | null | null | null | web/controllers/password_controller.ex | remigijusj/coherence | 36fe35b0bfe7ac63b44b4046f3ba62f2fe69603a | [
"MIT"
] | null | null | null | defmodule Coherence.PasswordController do
@moduledoc """
Handle password recovery actions.
Controller that handles the recover password feature.
Actions:
* new - render the recover password form
* create - verify user's email address, generate a token, and send the email
* edit - render the reset password form
* update - verify password, password confirmation, and update the database
"""
use Coherence.Web, :controller
require Logger
use Timex
alias Coherence.ControllerHelpers, as: Helpers
plug :layout_view
plug :redirect_logged_in when action in [:new, :create, :edit, :update]
@doc false
def layout_view(conn, _) do
conn
|> put_layout({Coherence.LayoutView, "app.html"})
|> put_view(Coherence.PasswordView)
end
@doc """
Render the recover password form.
"""
def new(conn, _params) do
user_schema = Config.user_schema
cs = Helpers.changeset :password, user_schema, user_schema.__struct__
conn
|> render(:new, [email: "", changeset: cs])
end
@doc """
Create the recovery token and send the email
"""
def create(conn, %{"password" => password_params} = params) do
user_schema = Config.user_schema
email = password_params["email"]
user = where(user_schema, [u], u.email == ^email)
|> Config.repo.one
case user do
nil ->
changeset = Helpers.changeset :password, user_schema, user_schema.__struct__
conn
|> put_flash(:error, "Could not find that email address")
|> render("new.html", changeset: changeset)
user ->
token = random_string 48
url = router_helpers.password_url(conn, :edit, token)
Logger.debug "reset email url: #{inspect url}"
dt = Ecto.DateTime.utc
cs = Helpers.changeset(:password, user_schema, user,
%{reset_password_token: token, reset_password_sent_at: dt})
Config.repo.update! cs
send_user_email :password, user, url
conn
|> put_flash(:info, "Reset email sent. Check your email for a reset link.")
|> redirect_to(:password_create, params)
end
end
@doc """
Render the password and password confirmation form.
"""
def edit(conn, params) do
user_schema = Config.user_schema
token = params["id"]
user = where(user_schema, [u], u.reset_password_token == ^token)
|> Config.repo.one
case user do
nil ->
conn
|> put_flash(:error, "Invalid reset token.")
|> redirect(to: logged_out_url(conn))
user ->
if expired? user.reset_password_sent_at, days: Config.reset_token_expire_days do
clear_password_params(user, user_schema, %{})
|> Config.repo.update
conn
|> put_flash(:error, "Password reset token expired.")
|> redirect(to: logged_out_url(conn))
else
changeset = Helpers.changeset(:password, user_schema, user)
conn
|> render("edit.html", changeset: changeset)
end
end
end
@doc """
Verify the passwords and update the database
"""
def update(conn, %{"password" => password_params} = params) do
user_schema = Config.user_schema
repo = Config.repo
token = password_params["reset_password_token"]
user = where(user_schema, [u], u.reset_password_token == ^token)
|> repo.one
case user do
nil ->
conn
|> put_flash(:error, "Invalid reset token")
|> redirect(to: logged_out_url(conn))
user ->
cs = Helpers.changeset(:password, user_schema, user, password_params)
case repo.update(cs) do
{:ok, user} ->
clear_password_params(user, user_schema, %{})
|> repo.update
conn
|> put_flash(:info, "Password updated successfully.")
|> redirect_to(:password_update, params)
{:error, changeset} ->
conn
|> render("edit.html", changeset: changeset)
end
end
end
defp clear_password_params(user, user_schema, params) do
params = Map.put(params, "reset_password_token", nil)
|> Map.put("reset_password_sent_at", nil)
Helpers.changeset(:password, user_schema, user, params)
end
end
| 30.57971 | 88 | 0.637204 |
79ad2c4bbd9f12e33cc23538d5b0238dd476df99 | 2,649 | ex | Elixir | lib/codes/codes_n89.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_n89.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_n89.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_N89 do
alias IcdCode.ICDCode
def _N890 do
%ICDCode{full_code: "N890",
category_code: "N89",
short_code: "0",
full_name: "Mild vaginal dysplasia",
short_name: "Mild vaginal dysplasia",
category_name: "Mild vaginal dysplasia"
}
end
def _N891 do
%ICDCode{full_code: "N891",
category_code: "N89",
short_code: "1",
full_name: "Moderate vaginal dysplasia",
short_name: "Moderate vaginal dysplasia",
category_name: "Moderate vaginal dysplasia"
}
end
def _N893 do
%ICDCode{full_code: "N893",
category_code: "N89",
short_code: "3",
full_name: "Dysplasia of vagina, unspecified",
short_name: "Dysplasia of vagina, unspecified",
category_name: "Dysplasia of vagina, unspecified"
}
end
def _N894 do
%ICDCode{full_code: "N894",
category_code: "N89",
short_code: "4",
full_name: "Leukoplakia of vagina",
short_name: "Leukoplakia of vagina",
category_name: "Leukoplakia of vagina"
}
end
def _N895 do
%ICDCode{full_code: "N895",
category_code: "N89",
short_code: "5",
full_name: "Stricture and atresia of vagina",
short_name: "Stricture and atresia of vagina",
category_name: "Stricture and atresia of vagina"
}
end
def _N896 do
%ICDCode{full_code: "N896",
category_code: "N89",
short_code: "6",
full_name: "Tight hymenal ring",
short_name: "Tight hymenal ring",
category_name: "Tight hymenal ring"
}
end
def _N897 do
%ICDCode{full_code: "N897",
category_code: "N89",
short_code: "7",
full_name: "Hematocolpos",
short_name: "Hematocolpos",
category_name: "Hematocolpos"
}
end
def _N898 do
%ICDCode{full_code: "N898",
category_code: "N89",
short_code: "8",
full_name: "Other specified noninflammatory disorders of vagina",
short_name: "Other specified noninflammatory disorders of vagina",
category_name: "Other specified noninflammatory disorders of vagina"
}
end
def _N899 do
%ICDCode{full_code: "N899",
category_code: "N89",
short_code: "9",
full_name: "Noninflammatory disorder of vagina, unspecified",
short_name: "Noninflammatory disorder of vagina, unspecified",
category_name: "Noninflammatory disorder of vagina, unspecified"
}
end
end
| 30.102273 | 78 | 0.598716 |
79ad4037bbc749cea77e171fe339f2141dacbc83 | 1,970 | ex | Elixir | clients/vision/lib/google_api/vision/v1/model/annotate_file_response.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/vision/lib/google_api/vision/v1/model/annotate_file_response.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/vision/lib/google_api/vision/v1/model/annotate_file_response.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Vision.V1.Model.AnnotateFileResponse do
@moduledoc """
Response to a single file annotation request. A file may contain one or more images, which individually have their own responses.
## Attributes
- responses ([AnnotateImageResponse]): Individual responses to images found within the file. Defaults to: `null`.
- inputConfig (InputConfig): Information about the file for which this response is generated. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:responses => list(GoogleApi.Vision.V1.Model.AnnotateImageResponse.t()),
:inputConfig => GoogleApi.Vision.V1.Model.InputConfig.t()
}
field(:responses, as: GoogleApi.Vision.V1.Model.AnnotateImageResponse, type: :list)
field(:inputConfig, as: GoogleApi.Vision.V1.Model.InputConfig)
end
defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.AnnotateFileResponse do
def decode(value, options) do
GoogleApi.Vision.V1.Model.AnnotateFileResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.AnnotateFileResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.627451 | 131 | 0.756345 |
79ad42b6f620b07a811282ea6a05f9d189f457d6 | 169 | exs | Elixir | apps/estuary/test/unit/test_helper.exs | jakeprem/smartcitiesdata | da309ac0d2261527278951cbae88604455207589 | [
"Apache-2.0"
] | null | null | null | apps/estuary/test/unit/test_helper.exs | jakeprem/smartcitiesdata | da309ac0d2261527278951cbae88604455207589 | [
"Apache-2.0"
] | 1 | 2020-01-09T21:00:10.000Z | 2020-01-09T21:00:10.000Z | apps/estuary/test/unit/test_helper.exs | jakeprem/smartcitiesdata | da309ac0d2261527278951cbae88604455207589 | [
"Apache-2.0"
] | null | null | null | Application.ensure_all_started(:mox)
Application.ensure_all_started(:dead_letter)
Application.ensure_all_started(:pipeline)
ExUnit.start(exclude: [:skip])
Faker.start()
| 28.166667 | 44 | 0.83432 |
79ad43b481e2154fb003b7f0c540439092f9c27e | 691 | ex | Elixir | test/support/test_receiver.ex | michael-borisov/membrane_ice_plugin | 5175473dbbca57f389da3ac1447e5fa82bc0e8a5 | [
"Apache-2.0"
] | null | null | null | test/support/test_receiver.ex | michael-borisov/membrane_ice_plugin | 5175473dbbca57f389da3ac1447e5fa82bc0e8a5 | [
"Apache-2.0"
] | null | null | null | test/support/test_receiver.ex | michael-borisov/membrane_ice_plugin | 5175473dbbca57f389da3ac1447e5fa82bc0e8a5 | [
"Apache-2.0"
] | null | null | null | defmodule Membrane.ICE.Support.TestReceiver do
@moduledoc false
use Membrane.Pipeline
alias Membrane.File
require Membrane.Logger
@impl true
def handle_init(opts) do
children = %{
ice: %Membrane.ICE.Bin{
stun_servers: ["64.233.161.127:19302"],
controlling_mode: false,
handshake_module: opts[:handshake_module],
handshake_opts: opts[:handshake_opts]
},
sink: %File.Sink{
location: opts[:file_path]
}
}
pad = Pad.ref(:output, 1)
links = [link(:ice) |> via_out(pad) |> to(:sink)]
spec = %ParentSpec{
children: children,
links: links
}
{{:ok, spec: spec}, %{}}
end
end
| 19.742857 | 53 | 0.600579 |
79ad7ae761ee019d363449bfd324fda6518315c3 | 1,052 | ex | Elixir | lib/advent_of_code/utils.ex | cro/aoc2021 | fbaa92be16b7849b95e1dd39b7d67954e21dc831 | [
"MIT"
] | null | null | null | lib/advent_of_code/utils.ex | cro/aoc2021 | fbaa92be16b7849b95e1dd39b7d67954e21dc831 | [
"MIT"
] | null | null | null | lib/advent_of_code/utils.ex | cro/aoc2021 | fbaa92be16b7849b95e1dd39b7d67954e21dc831 | [
"MIT"
] | null | null | null | defmodule AdventOfCode.Utils do
def get_and_parse_file(fname) do
fname
|> read_file
|> parse_file
end
def read_file(fname) do
{:ok, ftext} = File.read(fname)
ftext
end
def parse_file_to_lines(ftext) do
ftext
|> String.split("\n", trim: true)
end
def parse_file(ftext) do
ftext
|> parse_file_to_lines
|> Enum.map(fn x -> x |> String.to_integer() end)
end
def get_and_parse_directions(fname) do
fname
|> read_file
|> parse_directions
end
def parse_one_directionline(line) do
onedir = line |> String.split()
magnitude = Enum.at(onedir, 1) |> String.to_integer()
{Enum.at(onedir, 0), magnitude}
end
def parse_directions(ftext) do
ftext
|> String.split("\n", trim: true)
|> Enum.map(fn x -> x |> parse_one_directionline end)
end
def parse_bits(line) do
Regex.scan(~r/./, line)
|> Enum.map(fn x -> x |> hd |> String.to_integer() end)
end
def transpose(rows) do
rows
|> List.zip()
|> Enum.map(&Tuple.to_list/1)
end
end
| 19.849057 | 59 | 0.628327 |
79ad810d5275716e6c2baf4275e79c8636bcb2dc | 1,082 | ex | Elixir | lib/ergo_web/channels/user_socket.ex | insprac/ergo | 978970ba7f9639adb7ff8c32fec8cd25f487c656 | [
"MIT"
] | null | null | null | lib/ergo_web/channels/user_socket.ex | insprac/ergo | 978970ba7f9639adb7ff8c32fec8cd25f487c656 | [
"MIT"
] | 2 | 2021-03-10T22:00:43.000Z | 2021-05-11T17:17:30.000Z | lib/ergo_web/channels/user_socket.ex | insprac/ergo | 978970ba7f9639adb7ff8c32fec8cd25f487c656 | [
"MIT"
] | null | null | null | defmodule ErgoWeb.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", ErgoWeb.RoomChannel
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
@impl true
def connect(_params, socket, _connect_info) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# ErgoWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
@impl true
def id(_socket), do: nil
end
| 30.055556 | 83 | 0.692237 |
79adafed4a892fac7c74800826106ec89ef5927d | 17,842 | exs | Elixir | test/eth/transaction_queries_test.exs | grahac/eth | 950eeb89e4059f0e8711ec5c7944732c161a4bef | [
"MIT"
] | 4 | 2021-12-01T17:20:34.000Z | 2021-12-09T23:09:03.000Z | test/eth/transaction_queries_test.exs | grahac/eth | 950eeb89e4059f0e8711ec5c7944732c161a4bef | [
"MIT"
] | null | null | null | test/eth/transaction_queries_test.exs | grahac/eth | 950eeb89e4059f0e8711ec5c7944732c161a4bef | [
"MIT"
] | 4 | 2021-04-29T23:42:55.000Z | 2022-01-30T23:55:58.000Z | defmodule ETH.TransactionQueries.Test do
use ExUnit.Case
setup_all do
ETH.TestClient.start()
on_exit(fn ->
ETH.TestClient.stop()
end)
:ok
end
@first_wallet_in_client %{
eth_address: "0x051D51BA1E1D58DB72EFEA63549A6792C8F5CB13",
mnemonic_phrase:
"pause action enrich describe found panda world tenant one icon arrange balance soccer field hurdle midnight elite ski inquiry exit section globe raise brass",
private_key: "a160512c1dc5c33eff6ef89aae083108dcdcabdbe463481949d327fc2ac6ac48",
public_key:
"04418C292B1E69D5B49A0F2CA082DF83C361401C8A752C62F1081B6E4935948619779105D12AE05BFD1DE368F66133357FC46F2949899E3BD7F90873384C4F3998"
}
@second_wallet_in_client %{
eth_address: "0x1800542A82E6DE47CF4D310305F56EE56F63024A",
mnemonic_phrase:
"dignity adapt fat fury require fury federal crystal hero account art link fancy peace infant endless journey crane prepare topple visual walk owner arrive",
private_key: "3e00614daf3b70bcd519aa6b40303341052f439cd24d78664aa7f29f4fed2788",
public_key:
"048D505C1C871C1A04B8970789CAD4EC70BB302470F3EDE2D32A3D27EE25EB4B827CEE264A268A02D9D6153BFDBCF290DA1C5130523B35BF8D964050688A909770"
}
@third_wallet_in_client %{
eth_address: "0xC8FDF0764E2F783B11B6A2552A78CE14B2CEB484",
mnemonic_phrase:
"loop right hungry only east task humble panel canvas hunt plastic rival page discover omit crisp item when region pencil burden diagram nice nurse",
private_key: "83f739bd4d845bbc1bbcfc21adee985d59ee7de6999d76df46d25151e879e55c",
public_key:
"041D42B37794DA909A9A8C1A2A9EAB6679FE0478383F9FFC212EACDF7B7B844B1E0E7D2F74840DD173141B41AB02B6E01AB0B85D330DBE9D398ECE35C967D230A1"
}
@fourth_wallet_in_client %{
eth_address: "0x8E4E0A1E2D128EE71EFA14000A9D25A0DFD57426",
mnemonic_phrase:
"whisper organ connect honey demise rose gas bronze soul kangaroo word canvas skate arrange cream broccoli pumpkin post mention aware guilt crane idea stand",
private_key: "fa938cbcb693a5781800e5cfaf33f590dca0188cb8e3adb5162c08267a649c1e",
public_key:
"042F65C8522D43CF527A2CFDA9FD15031B835359EB754D32CFCE7447A4FF4928B39B543571E5286FF564D4C8CDD1F8F3D8F928E505CA3D33D02A6917F09A4FC758"
}
@fifth_wallet_in_client %{
eth_address: "0xC2AFEFA6B827CD41AC598086BCF45C5AE7061BFE",
mnemonic_phrase:
"lend network mansion huge october bid sister unlock reform husband offer maze inspire frown bitter escape remember talent goat receive capital they choice century",
private_key: "7ff29a1d3759902c326770b44dfe65c4c754bb05b268b5bbad9059c221c10a09",
public_key:
"04F6851EC9A15E389D4D8632DEC890429B9F50038CBECD6013210DD815220826C95D065083810FFE55A32EAF93E4AD79E485C4B334F065A1C759FB76169CABC238"
}
@sixth_wallet_in_client %{
eth_address: "0xE484D305ED89AAA63FDA68B302547C03F3B479D3",
mnemonic_phrase:
"phrase civil level wine run method tree suspect jeans economy tuition draw safe orchard front message tree cart powder calm term defy fit jazz",
private_key: "a3c53202fdcbd51879fed677a8c7a8a13be13817545fe7e462a4904df67355f3",
public_key:
"04CEA850A30D36321B0F5409219B6D228E98C57297BF8655ADF4AF407D48787224102CE8A4FBD6BA2C6A28E7419158BBCFD5FF1BA8EF05D1FE2B19518F059F3968"
}
# TODO: add some logs in future
test "get_block_transactions(block_no) works" do
{:ok, first_block_transactions_by_number} = ETH.get_block_transactions(1)
assert first_block_transactions_by_number == []
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
assert ETH.get_block_transactions(ETH.block_number!()) ==
{:ok,
[
ETH.get_transaction!(first_tx_hash),
ETH.get_transaction!(second_tx_hash)
]}
end
test "get_block_transactions(block_hash) works" do
{:ok, first_block_transactions_by_number} = ETH.get_block_transactions(ETH.get_block!(1).hash)
assert first_block_transactions_by_number == []
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
target_block = ETH.get_block!(ETH.block_number!())
assert ETH.get_block_transactions(target_block.hash) ==
{:ok,
[
ETH.get_transaction!(first_tx_hash),
ETH.get_transaction!(second_tx_hash)
]}
end
test "get_block_transactions!(block_no) works" do
assert ETH.get_block_transactions!(1) == []
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
assert ETH.get_block_transactions!(ETH.block_number!()) == [
ETH.get_transaction!(first_tx_hash),
ETH.get_transaction!(second_tx_hash)
]
end
test "get_block_transactions!(block_hash) works" do
assert ETH.get_block_transactions!(ETH.get_block!(1).hash) == []
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
target_block = ETH.get_block!(ETH.block_number!())
assert ETH.get_block_transactions!(target_block.hash) == [
ETH.get_transaction!(first_tx_hash),
ETH.get_transaction!(second_tx_hash)
]
end
test "get_block_transaction_count(block_number)" do
assert ETH.get_block_transaction_count(1) == {:ok, 0}
ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
assert ETH.get_block_transaction_count(ETH.block_number!()) == {:ok, 2}
end
test "get_block_transaction_count!(block_number)" do
assert ETH.get_block_transaction_count!(1) == 0
ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
assert ETH.get_block_transaction_count!(ETH.block_number!()) == 2
end
test "get_block_transaction_count(block_hash) works" do
assert ETH.get_block_transaction_count(ETH.get_block!(1).hash) == {:ok, 0}
ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
target_block = ETH.get_block!(ETH.block_number!())
assert ETH.get_block_transaction_count(target_block.hash) == {:ok, 2}
end
test "get_block_transaction_count!(block_hash) works" do
assert ETH.get_block_transaction_count!(ETH.get_block!(1).hash) == 0
ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
target_block = ETH.get_block!(ETH.block_number!())
assert ETH.get_block_transaction_count!(target_block.hash) == 2
end
test "get_transaction_from_block(block_number, index) works" do
assert ETH.get_transaction_from_block(0, 0) |> elem(0) == :error
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
block_no = ETH.block_number!()
assert ETH.get_transaction_from_block(block_no, 0) ==
{:ok, ETH.get_transaction!(first_tx_hash)}
assert ETH.get_transaction_from_block(block_no, 1) ==
{:ok, ETH.get_transaction!(second_tx_hash)}
assert ETH.get_transaction_from_block(block_no, 2) |> elem(0) == :error
end
test "get_transaction_from_block!(block_number, index) works" do
assert_raise MatchError, fn -> ETH.get_transaction_from_block!(0, 0) end
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
block_no = ETH.block_number!()
assert ETH.get_transaction_from_block!(block_no, 0) == ETH.get_transaction!(first_tx_hash)
assert ETH.get_transaction_from_block!(block_no, 1) == ETH.get_transaction!(second_tx_hash)
assert_raise MatchError, fn -> ETH.get_transaction_from_block!(block_no, 2) |> elem(0) end
end
test "get_transaction_from_block(block_hash, index) works" do
first_block_hash = ETH.get_block!(0).hash
assert ETH.get_transaction_from_block(first_block_hash, 0) |> elem(0) == :error
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
block_hash = ETH.get_block!(ETH.block_number!()).hash
assert ETH.get_transaction_from_block(block_hash, 0) ==
{:ok, ETH.get_transaction!(first_tx_hash)}
assert ETH.get_transaction_from_block(block_hash, 1) ==
{:ok, ETH.get_transaction!(second_tx_hash)}
assert ETH.get_transaction_from_block(block_hash, 2) |> elem(0) == :error
end
test "get_transaction_from_block!(block_hash, index) works" do
first_block_hash = ETH.get_block!(0).hash
assert_raise MatchError, fn -> ETH.get_transaction_from_block!(first_block_hash, 0) end
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
block_hash = ETH.get_block!(ETH.block_number!()).hash
assert ETH.get_transaction_from_block!(block_hash, 0) == ETH.get_transaction!(first_tx_hash)
assert ETH.get_transaction_from_block!(block_hash, 1) == ETH.get_transaction!(second_tx_hash)
assert_raise MatchError, fn -> ETH.get_transaction_from_block!(block_hash, 2) |> elem(0) end
end
test "get_transaction(transaction_hash) works" do
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
{:ok, first_transaction} = ETH.get_transaction(first_tx_hash)
{:ok, second_transaction} = ETH.get_transaction(second_tx_hash)
assert Map.keys(first_transaction) == [
:block_hash,
:block_number,
:from,
:gas,
:gas_price,
:hash,
:input,
:nonce,
:r,
:s,
:to,
:transaction_index,
:v,
:value
]
assert first_transaction.hash == first_tx_hash
assert Map.keys(second_transaction) == [
:block_hash,
:block_number,
:from,
:gas,
:gas_price,
:hash,
:input,
:nonce,
:r,
:s,
:to,
:transaction_index,
:v,
:value
]
assert second_transaction.hash == second_tx_hash
end
test "get_transaction!(transaction_hash) works" do
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
first_transaction = ETH.get_transaction!(first_tx_hash)
second_transaction = ETH.get_transaction!(second_tx_hash)
assert Map.keys(first_transaction) == [
:block_hash,
:block_number,
:from,
:gas,
:gas_price,
:hash,
:input,
:nonce,
:r,
:s,
:to,
:transaction_index,
:v,
:value
]
assert first_transaction.hash == first_tx_hash
assert Map.keys(second_transaction) == [
:block_hash,
:block_number,
:from,
:gas,
:gas_price,
:hash,
:input,
:nonce,
:r,
:s,
:to,
:transaction_index,
:v,
:value
]
assert second_transaction.hash == second_tx_hash
end
test "get_transaction_receipt(transaction_hash) works" do
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
{:ok, first_transaction_receipt} = ETH.get_transaction_receipt(first_tx_hash)
{:ok, second_transaction_receipt} = ETH.get_transaction_receipt(second_tx_hash)
assert Map.keys(first_transaction_receipt) == [
:block_hash,
:block_number,
:contract_address,
:cumulative_gas_used,
:from,
:gas_used,
:logs,
:logs_bloom,
:status,
:to,
:transaction_hash,
:transaction_index
]
assert first_transaction_receipt.transaction_hash == first_tx_hash
assert Map.keys(second_transaction_receipt) == [
:block_hash,
:block_number,
:contract_address,
:cumulative_gas_used,
:from,
:gas_used,
:logs,
:logs_bloom,
:status,
:to,
:transaction_hash,
:transaction_index
]
assert second_transaction_receipt.transaction_hash == second_tx_hash
end
test "get_transaction_receipt!(transaction_hash) works" do
first_tx_hash = ETH.send_transaction!(@first_wallet_in_client, @second_wallet_in_client, 500)
second_tx_hash =
ETH.send_transaction!(@second_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
first_transaction_receipt = ETH.get_transaction_receipt!(first_tx_hash)
second_transaction_receipt = ETH.get_transaction_receipt!(second_tx_hash)
assert Map.keys(first_transaction_receipt) == [
:block_hash,
:block_number,
:contract_address,
:cumulative_gas_used,
:from,
:gas_used,
:logs,
:logs_bloom,
:status,
:to,
:transaction_hash,
:transaction_index
]
assert first_transaction_receipt.transaction_hash == first_tx_hash
assert Map.keys(second_transaction_receipt) == [
:block_hash,
:block_number,
:contract_address,
:cumulative_gas_used,
:from,
:gas_used,
:logs,
:logs_bloom,
:status,
:to,
:transaction_hash,
:transaction_index
]
assert second_transaction_receipt.transaction_hash == second_tx_hash
end
test "get_transaction_count(wallet) works" do
assert ETH.get_transaction_count(@third_wallet_in_client) == {:ok, 0}
ETH.send_transaction!(@third_wallet_in_client, @second_wallet_in_client, 500)
ETH.TestClient.advance_block_by(1)
ETH.send_transaction!(@third_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
assert ETH.get_transaction_count(@third_wallet_in_client, "latest") == {:ok, 2}
end
test "get_transaction_count!(wallet) works" do
assert ETH.get_transaction_count!(@fourth_wallet_in_client) == 0
ETH.send_transaction!(@fourth_wallet_in_client, @second_wallet_in_client, 500)
ETH.TestClient.advance_block_by(1)
ETH.send_transaction!(@fourth_wallet_in_client, @first_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
assert ETH.get_transaction_count!(@fourth_wallet_in_client, "latest") == 2
end
test "get_transaction_count(eth_address) works" do
assert ETH.get_transaction_count(@fifth_wallet_in_client.eth_address, "latest") == {:ok, 0}
ETH.send_transaction!(@fifth_wallet_in_client, @second_wallet_in_client, 500)
ETH.TestClient.advance_block_by(1)
ETH.send_transaction!(@fifth_wallet_in_client, @third_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
assert ETH.get_transaction_count(@fifth_wallet_in_client.eth_address) == {:ok, 2}
end
test "get_transaction_count!(eth_address) works" do
assert ETH.get_transaction_count!(@sixth_wallet_in_client.eth_address) == 0
ETH.send_transaction!(@sixth_wallet_in_client, @second_wallet_in_client, 500)
ETH.TestClient.advance_block_by(1)
ETH.send_transaction!(@sixth_wallet_in_client, @third_wallet_in_client, 2000)
ETH.TestClient.advance_block_by(1)
assert ETH.get_transaction_count!(@sixth_wallet_in_client.eth_address) == 2
end
end
| 34.64466 | 171 | 0.701883 |
79adb3151db947c57323a7f7de59581b52f462b0 | 35,027 | ex | Elixir | clients/compute/lib/google_api/compute/v1/api/disks.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/disks.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/disks.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Compute.V1.Api.Disks do
@moduledoc """
API calls for all endpoints tagged `Disks`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Retrieves an aggregated list of persistent disks.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :filter (String.t): A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel Broadwell\") AND (scheduling.automaticRestart = true).
- :maxResults (integer()): The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
- :orderBy (String.t): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy=\"creationTimestamp desc\". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported.
- :pageToken (String.t): Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.DiskAggregatedList{}} on success
{:error, info} on failure
"""
@spec compute_disks_aggregated_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.DiskAggregatedList.t()} | {:error, Tesla.Env.t()}
def compute_disks_aggregated_list(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/aggregated/disks", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.DiskAggregatedList{}])
end
@doc """
Creates a snapshot of a specified persistent disk.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- disk (String.t): Name of the persistent disk to snapshot.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :guestFlush (boolean()):
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (Snapshot):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_disks_create_snapshot(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_disks_create_snapshot(
connection,
project,
zone,
disk,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:guestFlush => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/disks/{disk}/createSnapshot", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"disk" => URI.encode(disk, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Deletes the specified persistent disk. Deleting a disk removes its data permanently and is irreversible. However, deleting a disk does not delete any snapshots previously made from the disk. You must separately delete snapshots.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- disk (String.t): Name of the persistent disk to delete.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_disks_delete(Tesla.Env.client(), String.t(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_disks_delete(connection, project, zone, disk, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/{project}/zones/{zone}/disks/{disk}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"disk" => URI.encode(disk, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Returns a specified persistent disk. Gets a list of available persistent disks by making a list() request.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- disk (String.t): Name of the persistent disk to return.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Disk{}} on success
{:error, info} on failure
"""
@spec compute_disks_get(Tesla.Env.client(), String.t(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Disk.t()} | {:error, Tesla.Env.t()}
def compute_disks_get(connection, project, zone, disk, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/zones/{zone}/disks/{disk}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"disk" => URI.encode(disk, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Disk{}])
end
@doc """
Gets the access control policy for a resource. May be empty if no such policy or resource exists.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- resource (String.t): Name or id of the resource for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Policy{}} on success
{:error, info} on failure
"""
@spec compute_disks_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def compute_disks_get_iam_policy(
connection,
project,
zone,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/zones/{zone}/disks/{resource}/getIamPolicy", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Policy{}])
end
@doc """
Creates a persistent disk in the specified project using the data in the request. You can create a disk with a sourceImage, a sourceSnapshot, or create an empty 500 GB data disk by omitting all properties. You can also create a disk that is larger than the default size by specifying the sizeGb property.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :sourceImage (String.t): Optional. Source image to restore onto a disk.
- :body (Disk):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_disks_insert(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_disks_insert(connection, project, zone, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:sourceImage => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/disks", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Retrieves a list of persistent disks contained within the specified zone.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :filter (String.t): A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel Broadwell\") AND (scheduling.automaticRestart = true).
- :maxResults (integer()): The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
- :orderBy (String.t): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy=\"creationTimestamp desc\". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported.
- :pageToken (String.t): Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.DiskList{}} on success
{:error, info} on failure
"""
@spec compute_disks_list(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.DiskList.t()} | {:error, Tesla.Env.t()}
def compute_disks_list(connection, project, zone, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/zones/{zone}/disks", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.DiskList{}])
end
@doc """
Resizes the specified persistent disk. You can only increase the size of the disk.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- disk (String.t): The name of the persistent disk.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (DisksResizeRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_disks_resize(Tesla.Env.client(), String.t(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_disks_resize(connection, project, zone, disk, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/disks/{disk}/resize", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"disk" => URI.encode(disk, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- resource (String.t): Name or id of the resource for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (ZoneSetPolicyRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Policy{}} on success
{:error, info} on failure
"""
@spec compute_disks_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def compute_disks_set_iam_policy(
connection,
project,
zone,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/disks/{resource}/setIamPolicy", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Policy{}])
end
@doc """
Sets the labels on a disk. To learn more about labels, read the Labeling Resources documentation.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- resource (String.t): Name or id of the resource for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (ZoneSetLabelsRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_disks_set_labels(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_disks_set_labels(
connection,
project,
zone,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/disks/{resource}/setLabels", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Returns permissions that a caller has on the specified resource.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- resource (String.t): Name or id of the resource for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (TestPermissionsRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.TestPermissionsResponse{}} on success
{:error, info} on failure
"""
@spec compute_disks_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.TestPermissionsResponse.t()} | {:error, Tesla.Env.t()}
def compute_disks_test_iam_permissions(
connection,
project,
zone,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/disks/{resource}/testIamPermissions", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.TestPermissionsResponse{}])
end
end
| 51.284041 | 1,213 | 0.685328 |
79add1d0c1d4cfad26e052cfcd486cd567cd20ad | 1,703 | exs | Elixir | elixir/isbn-verifier/isbn_verifier_test.exs | jjdonov/Exercism | 3585420c5b0e74ea51a6fbd60e8263620061a1d9 | [
"MIT"
] | null | null | null | elixir/isbn-verifier/isbn_verifier_test.exs | jjdonov/Exercism | 3585420c5b0e74ea51a6fbd60e8263620061a1d9 | [
"MIT"
] | null | null | null | elixir/isbn-verifier/isbn_verifier_test.exs | jjdonov/Exercism | 3585420c5b0e74ea51a6fbd60e8263620061a1d9 | [
"MIT"
] | null | null | null | if !System.get_env("EXERCISM_TEST_EXAMPLES") do
Code.load_file("isbn_verifier.exs", __DIR__)
end
ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)
defmodule ISBNVerifierTest do
use ExUnit.Case
# @tag :pending
test "valid isbn number" do
assert ISBNVerifier.isbn?("3-598-21508-8")
end
#@tag :pending
test "invalid isbn check digit" do
refute ISBNVerifier.isbn?("3-598-21508-9")
end
#@tag :pending
test "valid isbn number with a check digit of 10" do
assert ISBNVerifier.isbn?("3-598-21507-X")
end
#@tag :pending
test "check digit is a character other than X" do
refute ISBNVerifier.isbn?("3-598-21507-A")
end
#@tag :pending
test "invalid character in isbn" do
refute ISBNVerifier.isbn?("3-598-2K507-0")
end
#@tag :pending
test "X is only valid as a check digit" do
refute ISBNVerifier.isbn?("3-598-2X507-0")
end
#@tag :pending
test "valid isbn without separating dashes" do
assert ISBNVerifier.isbn?("3598215088")
end
#@tag :pending
test "isbn without separating dashes and X as check digit" do
assert ISBNVerifier.isbn?("359821507X")
end
#@tag :pending
test "isbn without check digit and dashes" do
refute ISBNVerifier.isbn?("359821507")
end
#@tag :pending
test "too long isbn and no dashes" do
refute ISBNVerifier.isbn?("3598215078X")
end
#@tag :pending
test "isbn without check digit" do
refute ISBNVerifier.isbn?("3-598-21507")
end
#@tag :pending
test "too long isbn" do
refute ISBNVerifier.isbn?("3-598-21507-XA")
end
#@tag :pending
test "check digit of X should not be used for 0" do
refute ISBNVerifier.isbn?("3-598-21515-X")
end
end
| 22.407895 | 63 | 0.688784 |
79adde88d49a8ed1eb760836eb053eb1c67a50a6 | 2,794 | ex | Elixir | lib/rapid_api.ex | Spyes/RapidAPIConnect_Elixir | 7645f99cb90807d72b97939b13303ac3f6816f32 | [
"Unlicense"
] | 2 | 2017-06-12T20:24:20.000Z | 2017-06-28T05:55:10.000Z | lib/rapid_api.ex | RapidAPI/rapidapi-elixir-sdk | 7645f99cb90807d72b97939b13303ac3f6816f32 | [
"Unlicense"
] | 1 | 2021-01-07T08:53:45.000Z | 2021-01-07T08:53:45.000Z | lib/rapid_api.ex | Spyes/RapidAPIConnect_Elixir | 7645f99cb90807d72b97939b13303ac3f6816f32 | [
"Unlicense"
] | 1 | 2021-12-08T23:46:57.000Z | 2021-12-08T23:46:57.000Z | defmodule RapidApi do
@doc """
Creates a synchronous call to the specified package and base, passing all arguments provided.
Returns {:ok, payload} or {:error, reason}.
"""
@spec call(String.t, String.t, map()) :: map()
def call(pack, base, args \\ %{}) when is_bitstring(pack) and is_bitstring(base) and is_map(args) do
base_url() <> "/connect/#{pack}/#{base}"
|> HTTPoison.post!({:form, Enum.into(args, [])}, headers())
|> Map.get(:body)
|> decode_response
end
@doc """
Creates an asynchronous call to the specified package and base, passing all arguments provided.
When an answer is returned, sends the payload to the specified receiver pid.
Returns :ok
"""
@spec call_async(String.t, String.t, pid(), map()) :: atom()
def call_async(pack, base, receiver_pid, args \\ %{}) when is_bitstring(pack) and is_bitstring(base) and is_pid(receiver_pid) and is_map(args) do
worker = spawn(RapidApi, :async_worker, [receiver_pid])
base_url() <> "/connect/#{pack}/#{base}"
|> HTTPoison.post!({:form, Enum.into(args, [])}, headers(), stream_to: worker)
:ok
end
def async_worker(receiver_pid) when is_pid(receiver_pid) do
receive do
%HTTPoison.AsyncChunk{chunk: data} ->
send(receiver_pid, decode_response(data))
end
end
@doc """
Listens for real-time events by opening a websocket to RapidAPI.
Returns {:ok, socket_pid}
"""
@spec listen(String.t, String.t, pid(), map()) :: atom()
def listen(pack, base, receiver_pid, args \\ %{}) when is_bitstring(pack) and is_bitstring(base) and is_pid(receiver_pid) and is_map(args) do
{token, project} = get_vars()
uid = "#{pack}.#{base}_#{project}:#{token}"
token =
get_token_url(uid)
|> HTTPoison.get!
|> Map.get(:body)
|> Poison.decode!
|> Map.get("token")
{:ok, _socket} = RapidApi.Socket.start_link(token, receiver_pid, args)
end
defp decode_response(data) do
case Poison.decode(data) do
{:ok, decoded} -> {:ok, Map.get(decoded, "payload", "")}
{:error, _} -> {:error, data}
end
end
defp get_vars do
case token = Application.get_env(:rapid_api, :key) do
nil -> raise "No API token defined in config"
token -> token
end
case project = Application.get_env(:rapid_api, :project) do
nil -> raise "No project defined in config"
project -> project
end
{token, project}
end
defp base_url, do: "https://rapidapi.io"
defp get_token_url(user_id), do: "https://webhooks.rapidapi.io/api/get_token?user_id=#{user_id}"
defp headers do
{token, project} = get_vars()
encoded = Base.encode64("#{project}:#{token}")
[
"Authorization": "Basic #{encoded}",
"User-Agent": "RapidAPIConnect_Elixir"
]
end
end
| 31.393258 | 147 | 0.643164 |
79adecd017b0cef49ac892373342609bcf95f013 | 1,191 | ex | Elixir | lib/game/status.ex | tarcisiooliveira/ExMon | 51e59d456c338ac051cd5acd37d02d57f771b251 | [
"MIT"
] | null | null | null | lib/game/status.ex | tarcisiooliveira/ExMon | 51e59d456c338ac051cd5acd37d02d57f771b251 | [
"MIT"
] | null | null | null | lib/game/status.ex | tarcisiooliveira/ExMon | 51e59d456c338ac051cd5acd37d02d57f771b251 | [
"MIT"
] | null | null | null | defmodule ExMon.Game.Status do
def print_status_game(%{status: :started} = info) do
IO.puts("\n===========Jogo Inicializado===================\n")
IO.inspect(info)
IO.puts("------------------------------------------------")
end
def print_status_game(%{status: :continue, turn: player} = info) do
IO.puts("\n===========It's #{player} turn.===================\n")
IO.inspect(info)
IO.puts("------------------------------------------------")
end
def print_status_game(%{status: :game_over} = info) do
IO.puts("\n===========GAME OVER.===================\n")
IO.inspect(info)
IO.puts("------------------------------------------------")
end
def invalid_move(move),
do: IO.puts("\n===========Invalid Move #{move}===================\n")
def print_move_message(:computer, :attack, damage) do
IO.puts("\nThe Player attacked the computer dealing #{damage} damage \n")
end
def print_move_message(:player, :attack, damage) do
IO.puts("\nThe Player attacked the computer dealing #{damage} damage \n")
end
def print_move_message(player, :heal, life) do
IO.puts("\nThe #{player} healled itself to #{life} life \n")
end
end
| 34.028571 | 77 | 0.512175 |
79adefb93002f73e17b686c88998283b4c9b407b | 927 | ex | Elixir | lib/jumubase/foundation/category.ex | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | 2 | 2019-01-20T07:03:30.000Z | 2019-04-11T10:20:14.000Z | lib/jumubase/foundation/category.ex | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | 6 | 2018-09-20T05:52:14.000Z | 2019-04-23T19:27:39.000Z | lib/jumubase/foundation/category.ex | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | null | null | null | defmodule Jumubase.Foundation.Category do
use Jumubase.Schema
import Ecto.Changeset
alias Jumubase.JumuParams
alias Jumubase.Foundation.Category
schema "categories" do
field :name, :string
field :short_name, :string
field :type, :string
field :genre, :string
field :group, :string
field :uses_epochs, :boolean, read_after_writes: true
field :bw_code, :string
field :notes, :string
timestamps()
end
@required_attrs [:name, :short_name, :type, :genre, :group, :uses_epochs]
@optional_attrs [:bw_code, :notes]
@doc false
def changeset(%Category{} = category, attrs) do
category
|> cast(attrs, @required_attrs ++ @optional_attrs)
|> validate_required(@required_attrs)
|> validate_inclusion(:type, JumuParams.category_types())
|> validate_inclusion(:genre, JumuParams.genres())
|> validate_inclusion(:group, JumuParams.category_groups())
end
end
| 28.090909 | 75 | 0.707659 |
79ae0452d271b38a1f168f37c7fe8b40e666d8d7 | 13,697 | exs | Elixir | lib/mix/test/mix/tasks/deps.git_test.exs | xtian/elixir | c680eb1a3992309c272e8f808e15990ea5318d6e | [
"Apache-2.0"
] | null | null | null | lib/mix/test/mix/tasks/deps.git_test.exs | xtian/elixir | c680eb1a3992309c272e8f808e15990ea5318d6e | [
"Apache-2.0"
] | null | null | null | lib/mix/test/mix/tasks/deps.git_test.exs | xtian/elixir | c680eb1a3992309c272e8f808e15990ea5318d6e | [
"Apache-2.0"
] | null | null | null | Code.require_file "../../test_helper.exs", __DIR__
defmodule Mix.Tasks.DepsGitTest do
use MixTest.Case
defmodule DepsOnGitApp do
def project do
[app: :deps_on_git_app,
version: "0.1.0",
deps: [
{:deps_on_git_repo, "0.2.0", git: fixture_path("deps_on_git_repo")}
]]
end
end
defmodule GitApp do
def project do
opts = Process.get(:git_repo_opts) || []
[app: :git_app,
version: "0.1.0",
deps: [
{:git_repo, "0.1.0", [git: fixture_path("git_repo")] ++ opts}
]]
end
end
defmodule GitSubmodulesApp do
def project do
[app: :git_app,
version: "0.1.0",
deps: [
{:git_repo, "0.1.0", git: fixture_path("git_repo"), submodules: true}
]]
end
end
defmodule GitErrorApp do
def project do
[deps: [
{:git_repo, "0.1.0", git: fixture_path("not_git_repo")}
]]
end
end
test "gets and updates Git repos with compilation" do
Mix.Project.push GitApp
in_fixture "no_mixfile", fn ->
Mix.Tasks.Deps.Get.run []
message = "* Getting git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
assert File.read!("mix.lock") =~
~r/"git_repo": {:git, #{inspect fixture_path("git_repo")}, "[a-f0-9]+", \[\]}/
Mix.Tasks.Deps.Update.run ["--all"]
message = "* Updating git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
end
end
test "gets and updates Git repos with submodules" do
Mix.Project.push GitSubmodulesApp
in_fixture "no_mixfile", fn ->
Mix.Tasks.Deps.Get.run []
message = "* Getting git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
assert File.read!("mix.lock") =~ "submodules: true"
end
end
@tag :git_sparse
test "gets and updates Git repos with sparse checkout" do
Process.put(:git_repo_opts, sparse: "sparse_dir")
Mix.Project.push GitApp
in_fixture "no_mixfile", fn ->
Mix.Tasks.Deps.Get.run []
message = "* Getting git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
refute File.exists?("deps/git_repo/mix.exs")
assert File.exists?("deps/git_repo/sparse_dir/mix.exs")
assert File.read!("mix.lock") =~ "sparse: \"sparse_dir\""
end
end
test "handles invalid .git directory" do
Mix.Project.push GitApp
in_fixture "no_mixfile", fn ->
File.mkdir_p!("deps/git_repo/.git")
Mix.Tasks.Deps.Get.run []
message = "* Getting git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
end
end
test "handles missing .git directory" do
Mix.Project.push GitApp
in_fixture "no_mixfile", fn ->
Mix.Tasks.Deps.Get.run []
message = "* Getting git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
File.rm_rf!("deps/git_repo/.git")
assert_raise Mix.Error, "Can't continue due to errors on dependencies", fn ->
Mix.Tasks.Deps.Loadpaths.run ["git_repo"]
end
end
end
test "gets and updates many levels deep dependencies" do
Mix.Project.push DepsOnGitApp
in_fixture "no_mixfile", fn ->
Mix.Tasks.Deps.Get.run []
message = "* Getting git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
message = "* Getting deps_on_git_repo (#{fixture_path("deps_on_git_repo")})"
assert_received {:mix_shell, :info, [^message]}
assert File.exists?("deps/deps_on_git_repo/mix.exs")
assert File.rm("deps/deps_on_git_repo/.fetch") == :ok
assert File.exists?("deps/git_repo/mix.exs")
assert File.rm("deps/git_repo/.fetch") == :ok
# Compile the dependencies
Mix.Tasks.Deps.Compile.run []
# Now update children and make sure it propagates
Mix.Tasks.Deps.Update.run ["git_repo"]
assert File.exists?("deps/deps_on_git_repo/.fetch")
assert File.exists?("deps/git_repo/.fetch")
# Compile Git repo but unload it so...
Mix.Tasks.Deps.Compile.run ["git_repo"]
assert File.exists?("_build/dev/lib/git_repo/ebin")
Code.delete_path("_build/dev/lib/git_repo/ebin")
# Deps on Git repo loads it automatically on compile
Mix.Task.reenable "deps.loadpaths"
Mix.Tasks.Deps.Compile.run ["deps_on_git_repo"]
assert File.exists?("_build/dev/lib/deps_on_git_repo/ebin")
end
after
purge [GitRepo, GitRepo.Mixfile]
end
test "compiles many levels deep dependencies" do
Mix.Project.push DepsOnGitApp
in_fixture "no_mixfile", fn ->
Mix.Tasks.Deps.Get.run []
refute File.exists?("_build/dev/lib/deps_on_git_repo")
refute File.exists?("_build/dev/lib/git_repo")
# Compile the parent with children
Mix.Tasks.Deps.Compile.run ["deps_on_git_repo", "--include-children"]
assert File.exists?("_build/dev/lib/deps_on_git_repo")
assert File.exists?("_build/dev/lib/git_repo")
end
after
purge [GitRepo, GitRepo.Mixfile]
end
test "recompiles the project when a dep is fetched" do
Mix.Project.push GitApp
in_fixture "no_mixfile", fn ->
Mix.Tasks.Deps.Get.run []
assert File.exists?("deps/git_repo/.fetch")
# We can compile just fine
assert Mix.Tasks.Compile.run(["--verbose"]) == :ok
# Clear up to prepare for the update
Mix.Task.clear
Mix.shell.flush
purge [A, B, GitRepo]
# Update will mark the update required
Mix.Tasks.Deps.Update.run ["git_repo"]
assert File.exists?("deps/git_repo/.fetch")
ensure_touched("deps/git_repo/.fetch") # Ensure timestamp differs
# mix deps.compile is required...
Mix.Tasks.Deps.run []
msg = " the dependency build is outdated, please run \"mix deps.compile\""
assert_received {:mix_shell, :info, [^msg]}
# But also ran automatically
Mix.Tasks.Compile.run ["--verbose"]
assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]}
assert File.exists?("_build/dev/lib/git_repo/.compile.fetch")
:ok
end
after
purge [A, B, GitRepo, GitRepo.Mixfile]
end
test "all up to date dependencies" do
Mix.Project.push GitApp
in_fixture "no_mixfile", fn ->
Mix.Tasks.Deps.Get.run []
message = "* Getting git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
Mix.Tasks.Deps.Get.run []
assert_received {:mix_shell, :info, ["All dependencies up to date"]}
end
after
purge [GitRepo, GitRepo.Mixfile]
end
test "updates the lock when the repo updates" do
Mix.Project.push GitApp
# Get Git repo first revision
[last, first | _] = get_git_repo_revs()
in_fixture "no_mixfile", fn ->
Mix.Dep.Lock.write %{git_repo: {:git, fixture_path("git_repo"), first, []}}
Mix.Tasks.Deps.Get.run []
refute File.exists?("deps/git_repo/lib/git_repo.ex")
assert File.read!("mix.lock") =~ first
Mix.Tasks.Deps.Update.run ["git_repo"]
assert File.exists?("deps/git_repo/lib/git_repo.ex")
assert File.read!("mix.lock") =~ last
Mix.Tasks.Deps.Clean.run ["--all"]
refute File.exists?("deps/git_repo/lib/git_repo.ex")
assert File.read!("mix.lock") =~ last
Mix.Tasks.Deps.Clean.run ["--unlock", "--all"]
refute File.read!("mix.lock") =~ last
end
after
purge [GitRepo, GitRepo.Mixfile]
end
test "updates the repo when the lock updates" do
Mix.Project.push GitApp
[last, first | _] = get_git_repo_revs()
in_fixture "no_mixfile", fn ->
Mix.Dep.Lock.write %{git_repo: {:git, fixture_path("git_repo"), first, []}}
Mix.Tasks.Deps.Get.run []
refute File.exists?("deps/git_repo/lib/git_repo.ex")
assert File.read!("mix.lock") =~ first
# Update the lock and now we should get an error
Mix.Dep.Lock.write %{git_repo: {:git, fixture_path("git_repo"), last, []}}
assert_raise Mix.Error, fn ->
Mix.Tasks.Deps.Loadpaths.run []
end
# Flush the errors we got, move to a clean slate
Mix.shell.flush
Mix.Task.clear
# Calling get should update the dependency
Mix.Tasks.Deps.Get.run []
assert File.exists?("deps/git_repo/lib/git_repo.ex")
assert File.read!("mix.lock") =~ last
message = "* Updating git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
# Check we got no error
refute_received {:mix_shell, :error, _}
end
after
purge [GitRepo, GitRepo.Mixfile]
end
@tag :git_sparse
test "updates the repo when sparse is turned off" do
Process.put(:git_repo_opts, sparse: "sparse_dir")
Mix.Project.push GitApp
in_fixture "no_mixfile", fn ->
Mix.Tasks.Deps.Get.run []
refute File.exists?("deps/git_repo/lib/git_repo.ex")
# Flush the errors we got, move to a clean slate
Mix.shell.flush
Mix.Task.clear
Process.delete(:git_repo_opts)
Mix.Project.pop
Mix.Project.push GitApp
# Calling get should update the dependency
Mix.Tasks.Deps.Get.run []
refute File.read!("mix.lock") =~ "sparse_dir"
assert File.exists?("deps/git_repo/lib/git_repo.ex")
message = "* Updating git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
# Check we got no error
refute_received {:mix_shell, :error, _}
end
end
@tag :git_sparse
test "updates the repo when sparse is turned on" do
Mix.Project.push GitApp
in_fixture "no_mixfile", fn ->
Mix.Tasks.Deps.Get.run []
assert File.exists?("deps/git_repo/lib/git_repo.ex")
# Flush the errors we got, move to a clean slate
Mix.shell.flush
Mix.Task.clear
Process.put(:git_repo_opts, sparse: "sparse_dir")
Mix.Project.pop
Mix.Project.push GitApp
# Calling get should update the dependency
Mix.Tasks.Deps.Get.run []
assert File.read!("mix.lock") =~ "sparse_dir"
refute File.exists?("deps/git_repo/lib/git_repo.ex")
message = "* Updating git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
# Check we got no error
refute_received {:mix_shell, :error, _}
end
end
test "updates the repo and the lock when the mixfile updates" do
Mix.Project.push GitApp
[last, first | _] = get_git_repo_revs()
in_fixture "no_mixfile", fn ->
# Move to the first version
Mix.Dep.Lock.write %{git_repo: {:git, fixture_path("git_repo"), first, []}}
Mix.Tasks.Deps.Get.run []
assert File.read!("mix.lock") =~ first
# Update the project configuration. It should force an update.
refresh deps: [{:git_repo, "0.1.0", git: fixture_path("git_repo"), ref: last}]
Mix.Tasks.Deps.run []
msg = " lock outdated: the lock is outdated compared to the options in your mixfile (run \"mix deps.get\" to fetch locked version)"
assert_received {:mix_shell, :info, [^msg]}
# Check an update was triggered
Mix.Tasks.Deps.Get.run []
assert File.read!("mix.lock") =~ last
message = "* Getting git_repo (#{fixture_path("git_repo")})"
assert_received {:mix_shell, :info, [^message]}
# Check we got no error
refute_received {:mix_shell, :error, _}
end
after
purge [GitRepo, GitRepo.Mixfile]
end
test "does not attempt to compile projects that could not be retrieved" do
Mix.Project.push GitErrorApp
in_fixture "no_mixfile", fn ->
exception = assert_raise Mix.Error, fn ->
Mix.Tasks.Deps.Get.run []
end
assert Exception.message(exception) =~ "Command \"git --git-dir=.git fetch"
end
end
test "does not load bad mixfiles on get" do
Mix.Project.push GitApp
[last, _, bad | _] = get_git_repo_revs()
in_fixture "no_mixfile", fn ->
Mix.Dep.Lock.write %{git_repo: {:git, fixture_path("git_repo"), bad, []}}
catch_error(Mix.Tasks.Deps.Get.run [])
Mix.Dep.Lock.write %{git_repo: {:git, fixture_path("git_repo"), last, []}}
Mix.Tasks.Deps.Get.run []
assert File.read!("mix.lock") =~ last
end
after
purge [GitRepo, GitRepo.Mixfile]
end
test "updates on Git opts change" do
Mix.Project.push GitApp
in_fixture "no_mixfile", fn ->
Process.put(:git_repo_opts, tag: "without_module")
refresh([])
Mix.Tasks.Deps.Get.run []
refute File.regular?("deps/git_repo/lib/git_repo.ex")
Process.put(:git_repo_opts, tag: "with_module")
refresh([])
Mix.Tasks.Deps.Get.run []
assert File.regular?("deps/git_repo/lib/git_repo.ex")
end
after
purge [GitRepo, GitRepo.Mixfile]
end
test "does not load bad mixfiles on update" do
Mix.Project.push GitApp
[last, _, bad | _] = get_git_repo_revs()
in_fixture "no_mixfile", fn ->
Mix.Dep.Lock.write %{git_repo: {:git, fixture_path("git_repo"), bad, []}}
catch_error(Mix.Tasks.Deps.Get.run [])
Mix.Tasks.Deps.Update.run ["git_repo"]
Mix.Tasks.Deps.Compile.run ["git_repo"]
assert File.read!("mix.lock") =~ last
end
after
purge [GitRepo, GitRepo.Mixfile]
end
defp refresh(post_config) do
%{name: name, file: file} = Mix.Project.pop
Mix.ProjectStack.post_config(post_config)
Mix.Project.push(name, file)
end
defp get_git_repo_revs() do
File.cd! fixture_path("git_repo"), fn ->
Regex.split ~r(\r?\n), System.cmd("git", ["log", "--format=%H"]) |> elem(0)
end
end
end
| 30.779775 | 138 | 0.636271 |
79ae3569d3ab562d8b81e3916933faa601dfcf31 | 1,058 | exs | Elixir | test/arkecosystem/client/votes_test.exs | ArkEcosystem/ARK-Elixir-Client | a62c0f63c3d490b2d8734384ae354444cc279a9a | [
"MIT"
] | 2 | 2018-07-13T23:05:08.000Z | 2019-02-06T10:27:08.000Z | test/arkecosystem/client/votes_test.exs | ArkEcosystem/ARK-Elixir-Client | a62c0f63c3d490b2d8734384ae354444cc279a9a | [
"MIT"
] | 59 | 2018-06-11T07:59:59.000Z | 2019-11-17T23:30:19.000Z | test/arkecosystem/client/votes_test.exs | ArkEcosystem/ARK-Elixir-Client | a62c0f63c3d490b2d8734384ae354444cc279a9a | [
"MIT"
] | 17 | 2018-07-02T16:10:25.000Z | 2020-11-23T23:43:55.000Z | defmodule ArkEcosystem.Client.API.VotesTest do
use ExUnit.Case
import ArkEcosystem.Client.API.Votes
import Tesla.Mock
@client ArkEcosystem.Client.new(%{
host: "http://127.0.0.1:4003/api",
nethash: "578e820911f24e039733b45e4882b73e301f813a0d2c31330dafda84534ffa23",
version: "1.1.1"
})
setup do
mock(fn
%{method: :get, url: "http://127.0.0.1:4003/api/votes/dummyId"} ->
json(%{"success" => true, "data" => %{id: "dummyId"}})
%{method: :get, url: "http://127.0.0.1:4003/api/votes"} ->
json(%{"success" => true, "data" => [%{id: "dummyId"}]})
end)
:ok
end
test "call ArkEcosystem.Client.API.Votes.list" do
assert {:ok, response} = list(@client)
assert Enum.at(response["data"], 0)["id"] == "dummyId"
assert response["success"] == true
end
test "call ArkEcosystem.Client.API.Votes.show" do
assert {:ok, response} = show(@client, "dummyId")
assert response["data"]["id"] == "dummyId"
assert response["success"] == true
end
end
| 29.388889 | 88 | 0.60586 |
79ae7f2cabc26cd76f2a5a1829791151f6841249 | 3,281 | ex | Elixir | lib/elixir_sense/providers/suggestion/reducers/struct.ex | J3RN/elixir_sense | 0e978dcfbf0a0602743917e3e71dfa40bf7467cf | [
"MIT",
"Unlicense"
] | null | null | null | lib/elixir_sense/providers/suggestion/reducers/struct.ex | J3RN/elixir_sense | 0e978dcfbf0a0602743917e3e71dfa40bf7467cf | [
"MIT",
"Unlicense"
] | null | null | null | lib/elixir_sense/providers/suggestion/reducers/struct.ex | J3RN/elixir_sense | 0e978dcfbf0a0602743917e3e71dfa40bf7467cf | [
"MIT",
"Unlicense"
] | null | null | null | defmodule ElixirSense.Providers.Suggestion.Reducers.Struct do
@moduledoc false
alias ElixirSense.Core.Binding
alias ElixirSense.Core.Introspection
alias ElixirSense.Core.Metadata
alias ElixirSense.Core.Source
alias ElixirSense.Core.State
@type field :: %{
type: :field,
subtype: :struct_field | :map_key,
name: String.t(),
origin: String.t() | nil,
call?: boolean
}
@doc """
A reducer that adds suggestions of struct fields.
"""
def add_fields(hint, env, buffer_metadata, context, acc) do
text_before = context.text_before
case find_struct_fields(hint, text_before, env, buffer_metadata) do
{[], _} ->
{:cont, acc}
{fields, nil} ->
{:halt, %{acc | result: fields}}
{fields, :maybe_struct_update} ->
reducers = [:populate_common, :modules, :functions, :macros, :variables, :attributes]
{:cont, %{acc | result: fields, reducers: reducers}}
end
end
defp find_struct_fields(hint, text_before, env, buffer_metadata) do
%State.Env{
module: module,
vars: vars,
attributes: attributes,
imports: imports,
aliases: aliases
} = env
%Metadata{
structs: structs,
mods_funs_to_positions: mods_funs,
types: metadata_types,
specs: specs
} = buffer_metadata
env = %ElixirSense.Core.Binding{
attributes: attributes,
variables: vars,
structs: structs,
imports: imports,
current_module: module,
specs: specs,
types: metadata_types,
mods_and_funs: mods_funs
}
case Source.which_struct(text_before, module) do
{type, fields_so_far, elixir_prefix, var} ->
type =
case {type, elixir_prefix} do
{{:atom, mod}, false} ->
# which_struct returns not expamded aliases
{:atom, Introspection.expand_alias(mod, aliases)}
_ ->
type
end
type = Binding.expand(env, {:struct, [], type, var})
result = get_fields(type, hint, fields_so_far)
{result, if(fields_so_far == [], do: :maybe_struct_update)}
{:map, fields_so_far, var} ->
var = Binding.expand(env, var)
result = get_fields(var, hint, fields_so_far)
{result, if(fields_so_far == [], do: :maybe_struct_update)}
_ ->
{[], nil}
end
end
defp get_fields({:map, fields, _}, hint, fields_so_far) do
expand_map_field_access(fields, hint, :map, fields_so_far)
end
defp get_fields({:struct, fields, type, _}, hint, fields_so_far) do
expand_map_field_access(fields, hint, {:struct, type}, fields_so_far)
end
defp get_fields(_, _hint, _fields_so_far), do: []
defp expand_map_field_access(fields, hint, type, fields_so_far) do
for {key, _value} when is_atom(key) <- fields,
key not in fields_so_far,
key = Atom.to_string(key),
String.starts_with?(key, hint) do
{subtype, origin} =
case type do
{:struct, mod} -> {:struct_field, if(mod, do: inspect(mod))}
:map -> {:map_key, nil}
end
%{type: :field, name: key, subtype: subtype, origin: origin, call?: false}
end
|> Enum.sort_by(& &1.name)
end
end
| 27.805085 | 93 | 0.612009 |
79aea0e6d850542d434777c7080f1f29b2230caf | 4,858 | ex | Elixir | lib/plug/conn/status.ex | tomciopp/plug | af7fba19e8bce208129d858b924c7a49b93beef1 | [
"Apache-2.0"
] | 1,218 | 2017-07-14T15:13:32.000Z | 2022-03-30T16:42:42.000Z | lib/plug/conn/status.ex | tomciopp/plug | af7fba19e8bce208129d858b924c7a49b93beef1 | [
"Apache-2.0"
] | 502 | 2017-07-19T15:36:44.000Z | 2022-03-31T06:47:36.000Z | deps/plug/lib/plug/conn/status.ex | adrianomota/blog | ef3b2d2ed54f038368ead8234d76c18983caa75b | [
"MIT"
] | 376 | 2017-07-17T15:47:55.000Z | 2022-03-23T19:24:30.000Z | defmodule Plug.Conn.Status do
@moduledoc """
Conveniences for working with status codes.
"""
custom_statuses = Application.get_env(:plug, :statuses, %{})
statuses = %{
100 => "Continue",
101 => "Switching Protocols",
102 => "Processing",
103 => "Early Hints",
200 => "OK",
201 => "Created",
202 => "Accepted",
203 => "Non-Authoritative Information",
204 => "No Content",
205 => "Reset Content",
206 => "Partial Content",
207 => "Multi-Status",
208 => "Already Reported",
226 => "IM Used",
300 => "Multiple Choices",
301 => "Moved Permanently",
302 => "Found",
303 => "See Other",
304 => "Not Modified",
305 => "Use Proxy",
306 => "Switch Proxy",
307 => "Temporary Redirect",
308 => "Permanent Redirect",
400 => "Bad Request",
401 => "Unauthorized",
402 => "Payment Required",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
406 => "Not Acceptable",
407 => "Proxy Authentication Required",
408 => "Request Timeout",
409 => "Conflict",
410 => "Gone",
411 => "Length Required",
412 => "Precondition Failed",
413 => "Request Entity Too Large",
414 => "Request-URI Too Long",
415 => "Unsupported Media Type",
416 => "Requested Range Not Satisfiable",
417 => "Expectation Failed",
418 => "I'm a teapot",
421 => "Misdirected Request",
422 => "Unprocessable Entity",
423 => "Locked",
424 => "Failed Dependency",
425 => "Too Early",
426 => "Upgrade Required",
428 => "Precondition Required",
429 => "Too Many Requests",
431 => "Request Header Fields Too Large",
451 => "Unavailable For Legal Reasons",
500 => "Internal Server Error",
501 => "Not Implemented",
502 => "Bad Gateway",
503 => "Service Unavailable",
504 => "Gateway Timeout",
505 => "HTTP Version Not Supported",
506 => "Variant Also Negotiates",
507 => "Insufficient Storage",
508 => "Loop Detected",
510 => "Not Extended",
511 => "Network Authentication Required"
}
reason_phrase_to_atom = fn reason_phrase ->
reason_phrase
|> String.downcase()
|> String.replace("'", "")
|> String.replace(~r/[^a-z0-9]/, "_")
|> String.to_atom()
end
status_map_to_doc = fn statuses ->
statuses
|> Enum.sort_by(&elem(&1, 0))
|> Enum.map(fn {code, reason_phrase} ->
atom = reason_phrase_to_atom.(reason_phrase)
" * `#{inspect(atom)}` - #{code}\n"
end)
end
custom_status_doc =
if custom_statuses != %{} do
"""
## Custom status codes
#{status_map_to_doc.(custom_statuses)}
"""
end
@doc """
Returns the status code given an integer or a known atom.
## Known status codes
The following status codes can be given as atoms with their
respective value shown next:
#{status_map_to_doc.(statuses)}
#{custom_status_doc}
"""
@spec code(integer | atom) :: integer
def code(integer_or_atom)
def code(integer) when integer in 100..999 do
integer
end
for {code, reason_phrase} <- statuses do
atom = reason_phrase_to_atom.(reason_phrase)
def code(unquote(atom)), do: unquote(code)
end
# This ensures that both the default and custom statuses will work
for {code, reason_phrase} <- custom_statuses do
atom = reason_phrase_to_atom.(reason_phrase)
def code(unquote(atom)), do: unquote(code)
end
@doc """
Returns the atom for given integer.
See `code/1` for the mapping.
"""
@spec reason_atom(integer) :: atom
def reason_atom(code)
for {code, reason_phrase} <- Map.merge(statuses, custom_statuses) do
atom = reason_phrase_to_atom.(reason_phrase)
def reason_atom(unquote(code)), do: unquote(atom)
end
def reason_atom(code) do
raise ArgumentError, "unknown status code #{inspect(code)}"
end
@spec reason_phrase(integer) :: String.t()
def reason_phrase(integer)
for {code, phrase} <- Map.merge(statuses, custom_statuses) do
def reason_phrase(unquote(code)), do: unquote(phrase)
end
def reason_phrase(code) do
raise ArgumentError, """
unknown status code #{inspect(code)}
Custom codes can be defined in the configuration for the :plug application,
under the :statuses key (which contains a map of status codes as keys and
reason phrases as values). For example:
config :plug, :statuses, %{998 => "Not An RFC Status Code"}
After defining the config for custom statuses, Plug must be recompiled for
the changes to take place using:
MIX_ENV=dev mix deps.clean plug --build
Doing this will allow the use of the integer status code 998 as
well as the atom :unavailable_for_legal_reasons in many Plug functions.
For example:
put_status(conn, :not_an_rfc_status_code)
"""
end
end
| 27.602273 | 79 | 0.633388 |
79aea31c20458db09f1dc81379fc8d2cf7804d10 | 9,215 | ex | Elixir | lib/plausible_web/controllers/auth_controller.ex | samuel-p/analytics | 5d35bab9c6c2aafc556659f64e4213848a37ed8a | [
"MIT"
] | 2 | 2020-05-16T13:48:44.000Z | 2020-05-22T09:52:36.000Z | lib/plausible_web/controllers/auth_controller.ex | samuel-p/analytics | 5d35bab9c6c2aafc556659f64e4213848a37ed8a | [
"MIT"
] | null | null | null | lib/plausible_web/controllers/auth_controller.ex | samuel-p/analytics | 5d35bab9c6c2aafc556659f64e4213848a37ed8a | [
"MIT"
] | null | null | null | defmodule PlausibleWeb.AuthController do
use PlausibleWeb, :controller
use Plausible.Repo
alias Plausible.Auth
require Logger
plug PlausibleWeb.RequireLoggedOutPlug
when action in [:register_form, :register, :login_form, :login]
plug PlausibleWeb.RequireAccountPlug
when action in [:user_settings, :save_settings, :delete_me, :password_form, :set_password]
def register_form(conn, _params) do
if Keyword.fetch!(Application.get_env(:plausible, :selfhost), :disable_registration) do
conn
|> redirect(to: "/login")
else
changeset = Plausible.Auth.User.changeset(%Plausible.Auth.User{})
render(conn, "register_form.html",
changeset: changeset,
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
end
end
def register(conn, %{"user" => params}) do
user = Plausible.Auth.User.changeset(%Plausible.Auth.User{}, params)
case Ecto.Changeset.apply_action(user, :insert) do
{:ok, user} ->
token = Auth.Token.sign_activation(user.name, user.email)
url = PlausibleWeb.Endpoint.clean_url() <> "/claim-activation?token=#{token}"
Logger.info(url)
email_template = PlausibleWeb.Email.activation_email(user, url)
Plausible.Mailer.send_email(email_template)
conn
|> render("register_success.html",
email: user.email,
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
{:error, changeset} ->
render(conn, "register_form.html",
changeset: changeset,
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
end
end
def claim_activation_link(conn, %{"token" => token}) do
case Auth.Token.verify_activation(token) do
{:ok, %{name: name, email: email}} ->
case Auth.create_user(name, email) do
{:ok, user} ->
PlausibleWeb.Email.welcome_email(user)
|> Plausible.Mailer.send_email()
conn
|> put_session(:current_user_id, user.id)
|> put_resp_cookie("logged_in", "true", http_only: false)
|> redirect(to: "/password")
{:error, changeset} ->
send_resp(conn, 400, inspect(changeset.errors))
end
{:error, :expired} ->
render_error(conn, 401, "Your token has expired. Please request another activation link.")
{:error, _} ->
render_error(conn, 400, "Your token is invalid. Please request another activation link.")
end
end
def password_reset_request_form(conn, _) do
render(conn, "password_reset_request_form.html",
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
end
def password_reset_request(conn, %{"email" => ""}) do
render(conn, "password_reset_request_form.html",
error: "Please enter an email address",
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
end
def password_reset_request(conn, %{"email" => email}) do
user = Repo.get_by(Plausible.Auth.User, email: email)
if user do
token = Auth.Token.sign_password_reset(email)
url = PlausibleWeb.Endpoint.clean_url() <> "/password/reset?token=#{token}"
Logger.debug("PASSWORD RESET LINK: " <> url)
email_template = PlausibleWeb.Email.password_reset_email(email, url)
Plausible.Mailer.deliver_now(email_template)
render(conn, "password_reset_request_success.html",
email: email,
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
else
render(conn, "password_reset_request_success.html",
email: email,
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
end
end
def password_reset_form(conn, %{"token" => token}) do
case Auth.Token.verify_password_reset(token) do
{:ok, _} ->
render(conn, "password_reset_form.html",
token: token,
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
{:error, :expired} ->
render_error(
conn,
401,
"Your token has expired. Please request another password reset link."
)
{:error, _} ->
render_error(
conn,
401,
"Your token is invalid. Please request another password reset link."
)
end
end
def password_reset(conn, %{"token" => token, "password" => pw}) do
case Auth.Token.verify_password_reset(token) do
{:ok, %{email: email}} ->
user = Repo.get_by(Auth.User, email: email)
changeset = Auth.User.set_password(user, pw)
case Repo.update(changeset) do
{:ok, _updated} ->
conn
|> put_flash(:login_title, "Password updated successfully")
|> put_flash(:login_instructions, "Please log in with your new credentials")
|> put_session(:current_user_id, nil)
|> delete_resp_cookie("logged_in")
|> redirect(to: "/login")
{:error, changeset} ->
render(conn, "password_reset_form.html",
changeset: changeset,
token: token,
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
end
{:error, :expired} ->
render_error(
conn,
401,
"Your token has expired. Please request another password reset link."
)
{:error, _} ->
render_error(
conn,
401,
"Your token is invalid. Please request another password reset link."
)
end
end
def login(conn, %{"email" => email, "password" => password}) do
alias Plausible.Auth.Password
user =
Repo.one(
from u in Plausible.Auth.User,
where: u.email == ^email
)
if user do
if Password.match?(password, user.password_hash || "") do
login_dest = get_session(conn, :login_dest) || "/sites"
conn
|> put_session(:current_user_id, user.id)
|> put_resp_cookie("logged_in", "true", http_only: false)
|> put_session(:login_dest, nil)
|> redirect(to: login_dest)
else
conn
|> render("login_form.html",
error: "Wrong email or password. Please try again.",
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
end
else
Password.dummy_calculation()
conn
|> render("login_form.html",
error: "Wrong email or password. Please try again.",
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
end
end
def login_form(conn, _params) do
render(conn, "login_form.html", layout: {PlausibleWeb.LayoutView, "focus.html"})
end
def password_form(conn, _params) do
render(conn, "password_form.html",
layout: {PlausibleWeb.LayoutView, "focus.html"},
skip_plausible_tracking: true
)
end
def set_password(conn, %{"password" => pw}) do
changeset = Auth.User.set_password(conn.assigns[:current_user], pw)
case Repo.update(changeset) do
{:ok, _user} ->
redirect(conn, to: "/sites/new")
{:error, changeset} ->
render(conn, "password_form.html",
changeset: changeset,
layout: {PlausibleWeb.LayoutView, "focus.html"}
)
end
end
def user_settings(conn, _params) do
changeset = Auth.User.changeset(conn.assigns[:current_user])
render(conn, "user_settings.html",
changeset: changeset,
subscription: conn.assigns[:current_user].subscription
)
end
def save_settings(conn, %{"user" => user_params}) do
changes = Auth.User.changeset(conn.assigns[:current_user], user_params)
case Repo.update(changes) do
{:ok, _user} ->
conn
|> put_flash(:success, "Account settings saved succesfully")
|> redirect(to: "/settings")
{:error, changeset} ->
render(conn, "user_settings.html", changeset: changeset)
end
end
def delete_me(conn, params) do
user =
conn.assigns[:current_user]
|> Repo.preload(:sites)
|> Repo.preload(:subscription)
for site_membership <- user.site_memberships do
Repo.delete!(site_membership)
end
for site <- user.sites do
Repo.delete!(site)
end
if user.subscription, do: Repo.delete!(user.subscription)
Repo.delete!(user)
logout(conn, params)
end
def logout(conn, _params) do
conn
|> configure_session(drop: true)
|> delete_resp_cookie("logged_in")
|> redirect(to: "/")
end
def google_auth_callback(conn, %{"code" => code, "state" => site_id}) do
res = Plausible.Google.Api.fetch_access_token(code)
id_token = res["id_token"]
[_, body, _] = String.split(id_token, ".")
id = body |> Base.decode64!(padding: false) |> Jason.decode!()
Plausible.Site.GoogleAuth.changeset(%Plausible.Site.GoogleAuth{}, %{
email: id["email"],
refresh_token: res["refresh_token"],
access_token: res["access_token"],
expires: NaiveDateTime.utc_now() |> NaiveDateTime.add(res["expires_in"]),
user_id: conn.assigns[:current_user].id,
site_id: site_id
})
|> Repo.insert!()
site = Repo.get(Plausible.Site, site_id)
redirect(conn, to: "/#{URI.encode_www_form(site.domain)}/settings#google-auth")
end
end
| 29.918831 | 98 | 0.617797 |
79aef9eca2ea5fcacf2cd4c4b55f28bd111f5bd8 | 190 | exs | Elixir | test/fixtures/has_hex_dep/mix.exs | hrzndhrn/hex | f74e2ed979e74130bdc4a6974660aa986333f33f | [
"Apache-2.0"
] | 824 | 2015-01-05T09:12:36.000Z | 2022-03-28T12:02:29.000Z | test/fixtures/has_hex_dep/mix.exs | hrzndhrn/hex | f74e2ed979e74130bdc4a6974660aa986333f33f | [
"Apache-2.0"
] | 737 | 2015-01-01T05:48:46.000Z | 2022-03-29T12:56:12.000Z | test/fixtures/has_hex_dep/mix.exs | hrzndhrn/hex | f74e2ed979e74130bdc4a6974660aa986333f33f | [
"Apache-2.0"
] | 220 | 2015-03-14T17:55:11.000Z | 2022-03-23T22:17:07.000Z | defmodule HasHexDep.Fixture.MixProject do
use Mix.Project
def project do
[app: :has_hex_dep, version: "0.0.1", deps: deps()]
end
defp deps do
[{:ecto, "~> 0.1"}]
end
end
| 15.833333 | 55 | 0.626316 |
79af110a8fe91de32813be38a2ce6fda4ce7b00f | 516 | ex | Elixir | robotica_ui/lib/scenes/utils.ex | brianmay/robotica-elixir | 8656510e54b7e32a547e3a54bf946f0e327911c9 | [
"RSA-MD"
] | 1 | 2019-04-23T09:16:44.000Z | 2019-04-23T09:16:44.000Z | robotica_ui/lib/scenes/utils.ex | brianmay/robotica-elixir | 8656510e54b7e32a547e3a54bf946f0e327911c9 | [
"RSA-MD"
] | 107 | 2019-05-26T08:03:26.000Z | 2022-02-03T19:13:56.000Z | robotica_ui/lib/scenes/utils.ex | brianmay/robotica-elixir | 8656510e54b7e32a547e3a54bf946f0e327911c9 | [
"RSA-MD"
] | 1 | 2019-08-10T20:44:24.000Z | 2019-08-10T20:44:24.000Z | defmodule RoboticaUi.Scene.Utils do
@moduledoc """
Helper functions for scenes
"""
import Scenic.Components
import Scenic.Primitives
def add_button(graph, label, id, x, y, opts \\ []) do
x = x * 100 + 120
y = y * 100 + 10
button(graph, label, [id: id, translate: {x, y}, width: 80, height: 80] ++ opts)
end
def add_text(graph, label, x, y, opts \\ []) do
x = x * 100 + 120
y = y * 100 + 60
text(graph, label, [translate: {x, y}, width: 80, height: 80] ++ opts)
end
end
| 22.434783 | 84 | 0.587209 |
79af12aa68aa5654824a0e980a0fe164a40746d3 | 2,952 | ex | Elixir | lib/mailmaid/smtp/uri.ex | tsg-global/mailmaid | 1f76beb4a7fe0f397a239baa189a3dac4d5b5602 | [
"MIT"
] | 6 | 2018-08-05T14:57:46.000Z | 2021-03-19T12:28:43.000Z | lib/mailmaid/smtp/uri.ex | tsg-global/mailmaid | 1f76beb4a7fe0f397a239baa189a3dac4d5b5602 | [
"MIT"
] | 2 | 2018-05-14T00:41:08.000Z | 2018-08-24T19:52:17.000Z | lib/mailmaid/smtp/uri.ex | tsg-global/mailmaid | 1f76beb4a7fe0f397a239baa189a3dac4d5b5602 | [
"MIT"
] | 2 | 2019-11-27T21:04:11.000Z | 2020-07-11T10:50:48.000Z | defmodule Mailmaid.SMTP.URI do
@moduledoc """
Handles special uris in mailer config
"""
@spec user_credentials_from_uri(map) :: {String.t | nil, String.t, String.t | nil}
def user_credentials_from_uri(%{userinfo: u} = _uri) when is_nil(u) or u == "", do: nil
def user_credentials_from_uri(%{userinfo: userinfo} = _uri) when is_binary(userinfo) do
case String.split(userinfo, ":") do
[identity, username, password] ->
{identity, username, password}
[username, password] ->
{nil, username, password}
[username] ->
{nil, username, nil}
end
end
@spec parse_legacy(String.t, Keyword.t) :: Keyword.t
def parse_legacy(uri, config \\ []) do
uri =
uri
|> Elixir.URI.decode()
|> Elixir.URI.parse()
{tls, ssl} = case uri.scheme do
"smtps" -> {:never, true}
"smtp+s" -> {:if_available, false}
"mm4s" -> {:never, true}
"mm4+s" -> {:if_available, false}
_other -> {:never, false}
end
options = [
{:scheme, uri.scheme},
{:relay, uri.host},
{:tls, tls},
{:ssl, ssl}
]
options = if uri.port do
[{:port, uri.port} | options]
else
options
end
options = case user_credentials_from_uri(uri) do
{_, username, password} ->
[
{:username, username},
{:password, password},
{:auth, :always}
| options
]
nil ->
[{:auth, :never} | options]
end
Keyword.merge(options, config)
end
def process_legacy_mailer_config(config) when is_list(config) do
case config[:url] do
nil -> config
url ->
config = Keyword.delete(config, :url)
parse_legacy(url, config)
end
end
@spec parse(String.t, Keyword.t) :: map
def parse(uri_s, config \\ []) do
uri =
uri_s
|> Elixir.URI.decode()
|> Elixir.URI.parse()
options = %{
original_uri: uri_s,
transport: :mm4,
protocol: :tcp,
relay: uri.host,
port: uri.port,
upgrade_to_tls: :never,
use_auth: :never,
identity: nil,
username: nil,
password: nil,
}
options = case uri.scheme do
"mm4" -> %{options | transport: :mm4}
"mm4s" -> %{options | transport: :mm4, protocol: :ssl}
"mm4+s" -> %{options | transport: :mm4, upgrade_to_tls: :if_available}
"smtp" -> %{options | transport: :mm4}
"smtps" -> %{options | transport: :mm4, protocol: :ssl}
"smtp+s" -> %{options | transport: :mm4, upgrade_to_tls: :if_available}
"http" -> %{options | transport: :http}
"https" -> %{options | transport: :http, protocol: :ssl}
end
options = case user_credentials_from_uri(uri) do
{identity, username, password} ->
%{options | use_auth: :always, identity: identity, username: username, password: password}
_ -> options
end
Enum.into(config, options)
end
end
| 25.669565 | 98 | 0.570461 |
79af479bf2b69e6c3fdc09210b1b6bb8b8326332 | 1,554 | exs | Elixir | mix.exs | elixytics/accesslog_parser | d8d565fde15df262ba7725f3f7e0095dc443fdb7 | [
"Apache-2.0"
] | 1 | 2019-06-12T01:22:01.000Z | 2019-06-12T01:22:01.000Z | mix.exs | elixytics/accesslog_parser | d8d565fde15df262ba7725f3f7e0095dc443fdb7 | [
"Apache-2.0"
] | null | null | null | mix.exs | elixytics/accesslog_parser | d8d565fde15df262ba7725f3f7e0095dc443fdb7 | [
"Apache-2.0"
] | null | null | null | defmodule AccessLogParser.MixProject do
use Mix.Project
@url_github "https://github.com/elixytics/accesslog_parser"
def project do
[
app: :accesslog_parser,
version: "0.3.0-dev",
elixir: "~> 1.9",
aliases: aliases(),
deps: deps(),
description: "Access Log Parser",
dialyzer: dialyzer(),
docs: docs(),
package: package(),
preferred_cli_env: [
"bench.parse": :bench,
coveralls: :test,
"coveralls.detail": :test
],
test_coverage: [tool: ExCoveralls]
]
end
defp aliases() do
[
"bench.parse": "run bench/parse.exs"
]
end
defp deps do
[
{:benchee, "~> 1.0", only: :bench, runtime: false},
{:credo, "~> 1.0", only: :dev, runtime: false},
{:dialyxir, "~> 1.0", only: :dev, runtime: false},
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:excoveralls, "~> 0.14.0", only: :test, runtime: false},
{:nimble_parsec, "~> 1.0"}
]
end
defp dialyzer do
[
flags: [
:error_handling,
:race_conditions,
:underspecs,
:unmatched_returns
],
plt_core_path: "plts",
plt_file: {:no_warn, "plts/dialyzer.plt"}
]
end
defp docs do
[
main: "AccessLogParser",
source_ref: "master",
source_url: @url_github
]
end
defp package do
%{
files: ["CHANGELOG.md", "LICENSE", "mix.exs", "README.md", "lib"],
licenses: ["Apache-2.0"],
links: %{"GitHub" => @url_github}
}
end
end
| 21.583333 | 72 | 0.539254 |
79af5ac664013b79373c6f8cf13726d62c0491c6 | 2,960 | ex | Elixir | lib/codes/codes_j38.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_j38.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_j38.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_J38 do
alias IcdCode.ICDCode
def _J3800 do
%ICDCode{full_code: "J3800",
category_code: "J38",
short_code: "00",
full_name: "Paralysis of vocal cords and larynx, unspecified",
short_name: "Paralysis of vocal cords and larynx, unspecified",
category_name: "Paralysis of vocal cords and larynx, unspecified"
}
end
def _J3801 do
%ICDCode{full_code: "J3801",
category_code: "J38",
short_code: "01",
full_name: "Paralysis of vocal cords and larynx, unilateral",
short_name: "Paralysis of vocal cords and larynx, unilateral",
category_name: "Paralysis of vocal cords and larynx, unilateral"
}
end
def _J3802 do
%ICDCode{full_code: "J3802",
category_code: "J38",
short_code: "02",
full_name: "Paralysis of vocal cords and larynx, bilateral",
short_name: "Paralysis of vocal cords and larynx, bilateral",
category_name: "Paralysis of vocal cords and larynx, bilateral"
}
end
def _J381 do
%ICDCode{full_code: "J381",
category_code: "J38",
short_code: "1",
full_name: "Polyp of vocal cord and larynx",
short_name: "Polyp of vocal cord and larynx",
category_name: "Polyp of vocal cord and larynx"
}
end
def _J382 do
%ICDCode{full_code: "J382",
category_code: "J38",
short_code: "2",
full_name: "Nodules of vocal cords",
short_name: "Nodules of vocal cords",
category_name: "Nodules of vocal cords"
}
end
def _J383 do
%ICDCode{full_code: "J383",
category_code: "J38",
short_code: "3",
full_name: "Other diseases of vocal cords",
short_name: "Other diseases of vocal cords",
category_name: "Other diseases of vocal cords"
}
end
def _J384 do
%ICDCode{full_code: "J384",
category_code: "J38",
short_code: "4",
full_name: "Edema of larynx",
short_name: "Edema of larynx",
category_name: "Edema of larynx"
}
end
def _J385 do
%ICDCode{full_code: "J385",
category_code: "J38",
short_code: "5",
full_name: "Laryngeal spasm",
short_name: "Laryngeal spasm",
category_name: "Laryngeal spasm"
}
end
def _J386 do
%ICDCode{full_code: "J386",
category_code: "J38",
short_code: "6",
full_name: "Stenosis of larynx",
short_name: "Stenosis of larynx",
category_name: "Stenosis of larynx"
}
end
def _J387 do
%ICDCode{full_code: "J387",
category_code: "J38",
short_code: "7",
full_name: "Other diseases of larynx",
short_name: "Other diseases of larynx",
category_name: "Other diseases of larynx"
}
end
end
| 30.515464 | 75 | 0.589189 |
79af68d3a0737a4d47f06ddc8928fe407e988ed8 | 3,166 | exs | Elixir | test/liquid_voting_web/absinthe/mutations/create_participant_test.exs | jinjagit/api | c1a176d8c318e05810bc1635706c56395819191e | [
"MIT"
] | null | null | null | test/liquid_voting_web/absinthe/mutations/create_participant_test.exs | jinjagit/api | c1a176d8c318e05810bc1635706c56395819191e | [
"MIT"
] | 10 | 2020-09-28T06:37:48.000Z | 2021-12-22T15:04:38.000Z | test/liquid_voting_web/absinthe/mutations/create_participant_test.exs | jinjagit/api | c1a176d8c318e05810bc1635706c56395819191e | [
"MIT"
] | null | null | null | defmodule LiquidVotingWeb.Absinthe.Mutations.CreateParticipantTest do
use LiquidVotingWeb.ConnCase
alias LiquidVotingWeb.Schema.Schema
describe "create participant" do
@new_participant_email "[email protected]"
@new_participant_name "Noobie"
@another_name "Another Name"
@invalid_email "invalid_email"
@organization_id Ecto.UUID.generate()
test "with a new participant's email and name" do
query = """
mutation {
createParticipant(email: "#{@new_participant_email}", name: "#{@new_participant_name}") {
name
email
}
}
"""
{:ok, %{data: %{"createParticipant" => participant}}} =
Absinthe.run(query, Schema, context: %{organization_id: @organization_id})
assert participant["email"] == @new_participant_email
assert participant["name"] == @new_participant_name
end
test "with an existing participant's email returns error changeset" do
query = """
mutation {
createParticipant(email: "#{@new_participant_email}", name: "#{@new_participant_name}") {
name
email
}
}
"""
{:ok, _} = Absinthe.run(query, Schema, context: %{organization_id: @organization_id})
query = """
mutation {
createParticipant(email: "#{@new_participant_email}", name: "#{@another_name}") {
name
email
}
}
"""
{:ok, %{errors: [%{message: message, details: details}]}} =
Absinthe.run(query, Schema, context: %{organization_id: @organization_id})
assert message == "Could not create participant"
assert details == %{email: ["has already been taken"]}
end
test "with only a new participant's email returns error changeset" do
query = """
mutation {
createParticipant(email: "#{@new_participant_email}") {
name
email
}
}
"""
{:ok, %{errors: [%{message: message}]}} =
Absinthe.run(query, Schema, context: %{organization_id: @organization_id})
assert to_charlist(message) == 'In argument "name": Expected type "String!", found null.'
end
test "with only a new participant's name returns error changeset" do
query = """
mutation {
createParticipant(name: "#{@new_participant_name}") {
name
email
}
}
"""
{:ok, %{errors: [%{message: message}]}} =
Absinthe.run(query, Schema, context: %{organization_id: @organization_id})
assert to_charlist(message) == 'In argument "email": Expected type "String!", found null.'
end
test "with invalid email format returns error changeset" do
query = """
mutation {
createParticipant(email: "#{@invalid_email}", name: "#{@new_participant_name}") {
name
email
}
}
"""
{:ok, %{errors: [%{message: message, details: details}]}} =
Absinthe.run(query, Schema, context: %{organization_id: @organization_id})
assert message == "Could not create participant"
assert details == %{email: ["is invalid"]}
end
end
end
| 29.314815 | 97 | 0.598547 |
79af8a4bd15f0d4821928dcf4088d7bc14a67a4b | 1,179 | ex | Elixir | lib/elasr/endpoint.ex | ench0/ex_elasr | a97e182d13bc5de56c370b687771a485e51fc6ea | [
"MIT"
] | null | null | null | lib/elasr/endpoint.ex | ench0/ex_elasr | a97e182d13bc5de56c370b687771a485e51fc6ea | [
"MIT"
] | null | null | null | lib/elasr/endpoint.ex | ench0/ex_elasr | a97e182d13bc5de56c370b687771a485e51fc6ea | [
"MIT"
] | null | null | null | defmodule Elasr.Endpoint do
use Phoenix.Endpoint, otp_app: :elasr
socket "/socket", Elasr.UserSocket
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phoenix.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/", from: :elasr, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
plug Plug.Session,
store: :cookie,
key: "_elasr_key",
signing_salt: "mtLqs/zj"
plug Elasr.Router
end
| 27.418605 | 69 | 0.710772 |
79af8d74d20876a2c4f0fb31afb12c89ffb184ce | 1,466 | ex | Elixir | lib/gerai.ex | boonious/gerai | 781d486ae2477a37502f03cc4da50ea7c9f01e8b | [
"Apache-2.0"
] | null | null | null | lib/gerai.ex | boonious/gerai | 781d486ae2477a37502f03cc4da50ea7c9f01e8b | [
"Apache-2.0"
] | null | null | null | lib/gerai.ex | boonious/gerai | 781d486ae2477a37502f03cc4da50ea7c9f01e8b | [
"Apache-2.0"
] | null | null | null | defmodule Gerai do
@moduledoc """
Client functions for caching JSON objects.
## Examples
iex> Gerai.put("tt1454468", "{\\\"name\\\":\\\"Gravity\\\",\\\"id\\\":\\\"tt1454468\\\"}")
:ok
iex> Gerai.get("tt1454468")
{:ok, "{\\\"name\\\":\\\"Gravity\\\",\\\"id\\\":\\\"tt1454468\\\"}"}
iex> Gerai.put("tt1316540", "{\\\"name\\\":\\\"The Turin Horse\\\",\\\"id\\\":\\\"tt1316540\\\"}")
:ok
iex> Gerai.get(:all)
{:ok,
["{\\\"name\\\":\\\"The Turin Horse\\\",\\\"id\\\":\\\"tt1316540\\\"}",
"{\\\"name\\\":\\\"Gravity\\\",\\\"id\\\":\\\"tt1454468\\\"}"]}
iex> Gerai.delete("tt1454468")
:ok
"""
@cache_server GeraiJson
@doc """
Retrieve JSON objects from cache by ID or `:all`
"""
@spec get(binary | :all) :: {:ok, binary | list[binary]} | {:error, nil}
def get(id), do: GenServer.call(@cache_server, {:get, id})
@doc """
Cache a serialised JSON by ID
"""
# TODO: perhaps in asyncronuous mode with `cast/handle_cast`
# handles both post and put requests
@spec put(binary, binary) :: :ok | :error
def put("", _), do: :error
def put(nil, _), do: :error
def put(id, json), do: GenServer.call(@cache_server, {:put, id, json})
@doc """
Delete a JSON object from cache by ID
"""
# TODO: perhaps in asyncronuous mode with `cast/handle_cast`
@spec delete(binary) :: :ok | :error
def delete(id), do: GenServer.call(@cache_server, {:delete, id})
end
| 29.32 | 104 | 0.547749 |
79af944fbac4bd8cc903f0b1ece8de6a5fcc41b5 | 935 | exs | Elixir | mix.exs | circles-learning-labs/ex_aws_chime | 5f5ef65a5765f8d6177c0a22c38211d0a0fba9c1 | [
"MIT"
] | 1 | 2020-09-28T19:56:03.000Z | 2020-09-28T19:56:03.000Z | mix.exs | circles-learning-labs/ex_aws_chime | 5f5ef65a5765f8d6177c0a22c38211d0a0fba9c1 | [
"MIT"
] | null | null | null | mix.exs | circles-learning-labs/ex_aws_chime | 5f5ef65a5765f8d6177c0a22c38211d0a0fba9c1 | [
"MIT"
] | 1 | 2020-10-02T22:56:51.000Z | 2020-10-02T22:56:51.000Z | defmodule ExAwsChime.MixProject do
use Mix.Project
def project do
[
app: :ex_aws_chime,
version: "0.1.1",
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
deps: deps(),
package: package()
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:ex_aws, "~> 2.1"},
{:hackney, "~> 1.16"},
{:jason, "~> 1.2"},
{:uuid, "~> 1.1"},
# Non-runtime deps
{:configparser_ex, "~> 4.0", runtime: false},
{:credo, "~> 1.4", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false}
]
end
defp package do
[
description: "Chime support library for ExAws",
licenses: ["MIT"],
files: ["lib", "mix.exs", "README*"],
maintainers: ["Bernard Duggan"],
links: %{github: "https://github.com/circles-learning-labs/ex_aws_chime"}
]
end
end
| 23.375 | 79 | 0.530481 |
79af9e1c01b6db0dfa41dd39fddc41d147553bd2 | 2,180 | ex | Elixir | clients/display_video/lib/google_api/display_video/v1/model/targeting_expansion_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/display_video/lib/google_api/display_video/v1/model/targeting_expansion_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/display_video/lib/google_api/display_video/v1/model/targeting_expansion_config.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.DisplayVideo.V1.Model.TargetingExpansionConfig do
@moduledoc """
Settings that control the targeting expansion of the line item. Targeting expansion allows the line item to reach a larger audience based on the original audience list and the targeting expansion level.
## Attributes
* `excludeFirstPartyAudience` (*type:* `boolean()`, *default:* `nil`) - Required. Whether to exclude first party audiences from targeting. Similar audiences of the excluded first party lists will not be excluded. Only applicable when a first-party audience is positively targeted (directly or included in a combined audience), otherwise this selection will be ignored.
* `targetingExpansionLevel` (*type:* `String.t`, *default:* `nil`) - Required. Magnitude of expansion for applicable targeting under this line item.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:excludeFirstPartyAudience => boolean() | nil,
:targetingExpansionLevel => String.t() | nil
}
field(:excludeFirstPartyAudience)
field(:targetingExpansionLevel)
end
defimpl Poison.Decoder, for: GoogleApi.DisplayVideo.V1.Model.TargetingExpansionConfig do
def decode(value, options) do
GoogleApi.DisplayVideo.V1.Model.TargetingExpansionConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DisplayVideo.V1.Model.TargetingExpansionConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.6 | 372 | 0.763303 |
79afba8ff7cd5eeaa7ea377a59c1fd462e0ad34d | 858 | ex | Elixir | lib/solid/tag/cycle.ex | christopherlai/solid | c7f0553f4ce3c12b68484baff42084bee1aa640b | [
"MIT"
] | 117 | 2016-09-04T03:56:08.000Z | 2022-03-28T18:51:56.000Z | lib/solid/tag/cycle.ex | christopherlai/solid | c7f0553f4ce3c12b68484baff42084bee1aa640b | [
"MIT"
] | 73 | 2017-03-21T09:22:45.000Z | 2022-03-01T20:48:22.000Z | lib/solid/tag/cycle.ex | christopherlai/solid | c7f0553f4ce3c12b68484baff42084bee1aa640b | [
"MIT"
] | 25 | 2017-04-02T02:23:01.000Z | 2022-02-27T20:42:13.000Z | defmodule Solid.Tag.Cycle do
import NimbleParsec
alias Solid.Parser.{BaseTag, Literal}
@behaviour Solid.Tag
@impl true
def spec(_parser) do
space = Literal.whitespace(min: 0)
ignore(BaseTag.opening_tag())
|> ignore(string("cycle"))
|> ignore(space)
|> optional(
Literal.double_quoted_string()
|> ignore(string(":"))
|> ignore(space)
|> unwrap_and_tag(:name)
)
|> concat(
Literal.double_quoted_string()
|> repeat(
ignore(space)
|> ignore(string(","))
|> ignore(space)
|> concat(Literal.double_quoted_string())
)
|> tag(:values)
)
|> ignore(BaseTag.closing_tag())
end
@impl true
def render(cycle, context, _options) do
{context, result} = Solid.Context.run_cycle(context, cycle)
{[text: result], context}
end
end
| 21.45 | 63 | 0.602564 |
79afd888e7606e17454a3832e0dc7f3a160a386a | 6,852 | ex | Elixir | lib/forge_abi/util/bigint.ex | ArcBlock/forge-abi | 918be4d21eba928203a4c0d0ac361ce738bb63da | [
"Apache-2.0"
] | 3 | 2019-05-10T06:13:43.000Z | 2020-09-17T00:12:32.000Z | lib/forge_abi/util/bigint.ex | ArcBlock/forge-abi | 918be4d21eba928203a4c0d0ac361ce738bb63da | [
"Apache-2.0"
] | 3 | 2019-05-23T21:31:34.000Z | 2019-10-04T20:25:50.000Z | lib/forge_abi/util/bigint.ex | ArcBlock/forge-abi | 918be4d21eba928203a4c0d0ac361ce738bb63da | [
"Apache-2.0"
] | null | null | null | defmodule ForgeAbi.Util.BigInt do
@moduledoc """
Big int operators. Note that at the moment we only need `:+` and `:-`.
As for `==`, `!=`, `>`, `>=`, `<`, `<=` the default behavior is as expected so
we won't override them.
"""
import Kernel, except: [+: 2, -: 2, >=: 2, >: 2, <=: 2, <: 2]
alias ForgeAbi.{BigSint, BigUint}
@doc false
defmacro __using__(_opts) do
quote do
import Kernel, except: [+: 2, -: 2, >=: 2, >: 2, <=: 2, <: 2]
import ForgeAbi.Util.BigInt
alias ForgeAbi.{BigSint, BigUint}
end
end
@doc """
Create a `ForgeAbi.BigUint`.
iex> use ForgeAbi.Util.BigInt
iex> biguint(1234)
%ForgeAbi.BigUint{value: <<4, 210>>}
iex> biguint(1111111111111111111111111111111111111111)
%ForgeAbi.BigUint{value: <<3, 67, 232, 55, 78, 152, 132, 21, 75, 248, 55, 181, 113, 199, 28, 113, 199>>}
"""
@spec biguint(integer() | nil) :: BigUint.t()
def biguint(nil), do: nil
def biguint(i) when Kernel.<(i, 0), do: BigUint.new(value: <<0>>)
def biguint(i), do: BigUint.new(value: to_binary(i))
@doc """
Convert BigInt to integer
iex> use ForgeAbi.Util.BigInt
iex> to_int(biguint(1)) === 1
true
iex> to_int(bigsint(1)) === 1
true
iex> to_int(bigsint(-1)) === 1
false
"""
@spec to_int(BigUint.t() | BigSint.t() | integer() | nil) :: integer()
def to_int(nil), do: 0
def to_int(i) when is_integer(i), do: i
def to_int(%BigSint{} = v), do: sign(v.minus) * to_unsigned(v.value)
def to_int(%BigUint{} = v), do: to_unsigned(v.value)
@doc """
Create a `ForgeAbi.BigSint`.
iex> use ForgeAbi.Util.BigInt
iex> bigsint(1234)
%ForgeAbi.BigSint{value: <<4, 210>>, minus: false}
iex> bigsint(-1234)
%ForgeAbi.BigSint{value: <<4, 210>>, minus: true}
iex> bigsint(-1111111111111111111111111111111111111111)
%ForgeAbi.BigSint{value: <<3, 67, 232, 55, 78, 152, 132, 21, 75, 248, 55, 181, 113, 199, 28, 113, 199>>, minus: true}
"""
@spec bigsint(integer()) :: BigSint.t()
def bigsint(i) when Kernel.<(i, 0), do: BigSint.new(value: to_binary(abs(i)), minus: true)
def bigsint(i), do: BigSint.new(value: to_binary(i))
@doc """
Convert a sint to uint
iex> use ForgeAbi.Util.BigInt
iex> to_uint(bigsint(-1234))
%ForgeAbi.BigUint{value: <<4, 210>>}
iex> to_uint(biguint(1234))
%ForgeAbi.BigUint{value: <<4, 210>>}
"""
@spec to_uint(BigUint.t() | BigSint.t() | nil) :: BigUint.t()
def to_uint(nil), do: biguint(0)
def to_uint(v), do: BigUint.new(value: v.value)
@doc """
Convert a uint to sint
iex> use ForgeAbi.Util.BigInt
iex> to_sint(bigsint(-1234))
%ForgeAbi.BigSint{value: <<4, 210>>, minus: true}
iex> to_sint(biguint(1234))
%ForgeAbi.BigSint{value: <<4, 210>>, minus: false}
"""
@spec to_sint(BigUint.t() | BigSint.t()) :: BigSint.t()
def to_sint(%BigSint{} = v), do: v
def to_sint(v), do: BigSint.new(value: v.value)
@doc """
Generate a BigSint with a regular integer
iex> use ForgeAbi.Util.BigInt
iex> to_unit(-1234)
%ForgeAbi.BigSint{minus: true, value: <<171, 64, 124, 158, 176, 82, 0, 0>>}
iex> to_unit(200)
%ForgeAbi.BigSint{minus: false, value: <<27, 193, 109, 103, 78, 200, 0, 0>>}
"""
@spec to_unit(integer(), non_neg_integer()) :: BigSint.t()
def to_unit(v, decimal \\ 0), do: bigsint(v * one_token(decimal))
@spec one_token(non_neg_integer()) :: non_neg_integer()
def one_token(decimal \\ 0), do: decimal_to_int(decimal)
@doc """
Add two big int. Should return a BigUint.
iex> use ForgeAbi.Util.BigInt
iex> biguint(1234) + biguint(1234)
%ForgeAbi.BigUint{value: <<9, 164>>}
"""
@spec (BigUint.t() | BigSint.t() | number() | nil) +
(BigUint.t() | BigSint.t() | number() | nil) :: BigUint.t() | number()
def (%{value: va} = a) + (%{value: vb} = b) when is_binary(va) and is_binary(vb) do
sa = Map.get(a, :minus, false)
sb = Map.get(b, :minus, false)
vc = do_add(sa, sb, va, vb)
biguint(vc)
end
def a + (%{value: vb} = b) when is_binary(vb) and is_integer(a) do
bigsint(a) + b
end
def (%{value: va} = a) + b when is_binary(va) and is_integer(b) do
a + bigsint(b)
end
def nil + nil, do: 0
def nil + b, do: b
def a + nil, do: a
def a + b, do: Kernel.+(a, b)
@doc """
Substract two big int. Should return a BigUint.
iex> use ForgeAbi.Util.BigInt
iex> biguint(1234) - biguint(1233)
%ForgeAbi.BigUint{value: <<1>>}
iex> biguint(1234) - biguint(1235)
%ForgeAbi.BigUint{value: <<0>>}
iex> biguint(1234) - bigsint(-1235)
%ForgeAbi.BigUint{value: <<9, 165>>}
iex> bigsint(-1234) - biguint(1235)
%ForgeAbi.BigUint{value: <<0>>}
"""
@spec (BigUint.t() | number()) - (BigUint.t() | BigSint.t() | number()) ::
BigUint.t() | number()
def %{value: va} - (%{value: vb} = b) when is_binary(va) and is_binary(vb) do
sb = Map.get(b, :minus, false)
vc = do_sub(sb, va, vb)
biguint(vc)
end
def (%{value: va} = a) - b when is_binary(va) and is_integer(b) do
a - bigsint(b)
end
def nil - nil, do: 0
def nil - b, do: Kernel.-(0, b)
def a - nil, do: a
def a - b, do: Kernel.-(a, b)
@doc """
Compare biguint, bigsint(we just use its abs value), and normal integer/float
iex> use ForgeAbi.Util.BigInt
iex> biguint(1234) > biguint(1233)
true
iex> biguint(1234) <= biguint(1235)
true
iex> biguint(1234) > bigsint(-1235)
false
iex> bigsint(-1234) > biguint(100)
true
iex> bigsint(-1234) > 1000
true
iex> bigsint(-1234) > 2000
false
iex> 1000 >= biguint(999)
true
iex> 1000 >= biguint(1001)
false
"""
def a >= b, do: Kernel.>=(to_unsigned(a), to_unsigned(b))
def a > b, do: Kernel.>(to_unsigned(a), to_unsigned(b))
def a <= b, do: Kernel.<=(to_unsigned(a), to_unsigned(b))
def a < b, do: Kernel.<(to_unsigned(a), to_unsigned(b))
# private function
defp sign(false), do: 1
defp sign(true), do: -1
defp to_binary(i), do: :binary.encode_unsigned(i)
defp to_unsigned(nil), do: 0
defp to_unsigned(v) when is_integer(v), do: v
defp to_unsigned(v) when is_float(v), do: v
defp to_unsigned(%{value: a}), do: to_unsigned(a)
defp to_unsigned(v), do: :binary.decode_unsigned(v)
defp do_add(false, false, va, vb), do: to_unsigned(va) + to_unsigned(vb)
defp do_add(false, true, va, vb), do: to_unsigned(va) - to_unsigned(vb)
defp do_add(true, false, va, vb), do: to_unsigned(vb) - to_unsigned(va)
defp do_add(true, true, _va, _vb), do: 0
defp do_sub(false, va, vb), do: to_unsigned(va) - to_unsigned(vb)
defp do_sub(true, va, vb), do: to_unsigned(va) + to_unsigned(vb)
defp decimal_to_int(0) do
decimal = Application.get_env(:forge_abi, :decimal)
round(:math.pow(10, decimal))
end
defp decimal_to_int(d), do: round(:math.pow(10, d))
end
| 31.287671 | 121 | 0.610917 |
79afdc3b3e023192999de2f689ff3add221edb52 | 1,103 | ex | Elixir | deps/mint/lib/mint/core/transport.ex | PrecisionNutrition/frogger | 96374fe0ac0ea616205f6678fe088802572e922e | [
"MIT"
] | null | null | null | deps/mint/lib/mint/core/transport.ex | PrecisionNutrition/frogger | 96374fe0ac0ea616205f6678fe088802572e922e | [
"MIT"
] | null | null | null | deps/mint/lib/mint/core/transport.ex | PrecisionNutrition/frogger | 96374fe0ac0ea616205f6678fe088802572e922e | [
"MIT"
] | null | null | null | defmodule Mint.Core.Transport do
@moduledoc false
@type error() :: {:error, %Mint.TransportError{}}
alias Mint.Types
@callback connect(host :: String.t(), port :: :inet.port_number(), opts :: keyword()) ::
{:ok, Types.socket()} | error()
@callback upgrade(
Types.socket(),
original_scheme :: Types.scheme(),
hostname :: String.t(),
:inet.port_number(),
opts :: keyword()
) :: {:ok, Types.socket()} | error()
@callback negotiated_protocol(Types.socket()) ::
{:ok, protocol :: binary()} | {:error, :protocol_not_negotiated}
@callback send(Types.socket(), payload :: iodata()) :: :ok | error()
@callback close(Types.socket()) :: :ok | error()
@callback recv(Types.socket(), bytes :: non_neg_integer()) :: {:ok, binary()} | error()
@callback setopts(Types.socket(), opts :: keyword()) :: :ok | error()
@callback getopts(Types.socket(), opts :: keyword()) :: {:ok, opts :: keyword()} | error()
@callback wrap_error(reason :: term()) :: %Mint.TransportError{}
end
| 32.441176 | 92 | 0.573889 |
79aff478960641c55129323d6d25ffc2e93e0f5d | 253 | ex | Elixir | lib/gscraper.ex | longnd/elixir-gscraper | 894570afd89e54b80ca591a56a182da55ac6ee61 | [
"MIT"
] | null | null | null | lib/gscraper.ex | longnd/elixir-gscraper | 894570afd89e54b80ca591a56a182da55ac6ee61 | [
"MIT"
] | 25 | 2021-03-23T07:27:21.000Z | 2021-10-31T15:09:52.000Z | lib/gscraper.ex | longnd/elixir-gscraper | 894570afd89e54b80ca591a56a182da55ac6ee61 | [
"MIT"
] | null | null | null | defmodule Gscraper do
@moduledoc """
Gscraper keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end
| 25.3 | 66 | 0.754941 |
79b01376097d19b742b4f463fcba6180e3f58dab | 1,570 | ex | Elixir | lib/console/functions/functions.ex | Oliv4945/console | fd7b85c8ff3b0702c8a524eb888104612946934c | [
"Apache-2.0"
] | null | null | null | lib/console/functions/functions.ex | Oliv4945/console | fd7b85c8ff3b0702c8a524eb888104612946934c | [
"Apache-2.0"
] | null | null | null | lib/console/functions/functions.ex | Oliv4945/console | fd7b85c8ff3b0702c8a524eb888104612946934c | [
"Apache-2.0"
] | null | null | null | defmodule Console.Functions do
import Ecto.Query, warn: false
alias Console.Repo
alias Console.Functions.Function
alias Console.Organizations.Organization
def get_function!(organization, id) do
Repo.get_by!(Function, [id: id, organization_id: organization.id])
end
def get_function(organization, id) do
Repo.get_by(Function, [id: id, organization_id: organization.id])
end
def get_function!(id), do: Repo.get!(Function, id)
def get_function(id), do: Repo.get(Function, id)
def get_function_by_name(name), do: Repo.get_by(Function, %{:name => name})
def get_all_organization_functions(org_id) do
from(f in Function, where: f.organization_id == ^org_id)
|> Repo.all()
end
def fetch_assoc(%Function{} = function, assoc \\ [:labels]) do
Repo.preload(function, assoc)
end
def create_function(attrs \\ %{}, %Organization{} = organization) do
count = get_organization_function_count(organization)
cond do
count > 999 ->
{:error, :forbidden, "Function limit for organization reached"}
true ->
%Function{}
|> Function.changeset(attrs)
|> Repo.insert()
end
end
def update_function(%Function{} = function, attrs) do
function
|> Function.changeset(attrs)
|> Repo.update()
end
def delete_function(%Function{} = function) do
Repo.delete(function)
end
defp get_organization_function_count(organization) do
functions = from(f in Function, where: f.organization_id == ^organization.id) |> Repo.all()
length(functions)
end
end
| 27.068966 | 95 | 0.687898 |
79b01798ecd9b1bacb2c6fc2f40136849ffd9698 | 231 | ex | Elixir | apps/core/lib/core/struct/trade_event.ex | itsemilano/orbex | 301dfaad1369acfd68055f1868d9a1dcd7e51e16 | [
"Apache-2.0"
] | 65 | 2020-07-07T01:51:27.000Z | 2021-09-27T00:13:59.000Z | apps/core/lib/core/struct/trade_event.ex | itsemilano/orbex | 301dfaad1369acfd68055f1868d9a1dcd7e51e16 | [
"Apache-2.0"
] | 5 | 2021-02-12T08:21:15.000Z | 2021-09-01T21:17:27.000Z | apps/core/lib/core/struct/trade_event.ex | itsemilano/orbex | 301dfaad1369acfd68055f1868d9a1dcd7e51e16 | [
"Apache-2.0"
] | 10 | 2020-08-13T13:39:31.000Z | 2021-09-14T12:46:51.000Z | defmodule Core.Struct.TradeEvent do
defstruct [
:event_type,
:event_time,
:symbol,
:trade_id,
:price,
:quantity,
:buyer_order_id,
:seller_order_id,
:trade_time,
:buyer_market_maker
]
end
| 15.4 | 35 | 0.636364 |
79b02006f8c3f3080c4da23235028076e1fc4f4d | 196 | ex | Elixir | lib/canard.ex | Nax/canard | 6db5b1fe98a7c351339047949be0b59fef407e7d | [
"BSD-3-Clause"
] | 1 | 2019-02-16T11:35:37.000Z | 2019-02-16T11:35:37.000Z | lib/canard.ex | Nax/canard | 6db5b1fe98a7c351339047949be0b59fef407e7d | [
"BSD-3-Clause"
] | null | null | null | lib/canard.ex | Nax/canard | 6db5b1fe98a7c351339047949be0b59fef407e7d | [
"BSD-3-Clause"
] | null | null | null | defmodule Canard do
@moduledoc """
Documentation for Canard.
"""
@doc """
Hello world.
## Examples
iex> Canard.hello()
:world
"""
def hello do
:world
end
end
| 10.315789 | 27 | 0.556122 |
79b03800917d7fc2357a1d690a5c5b4e6e34a6c9 | 32,594 | ex | Elixir | lib/elixir/lib/module.ex | hamiltop/elixir | 3b601660d4d4eb0c69f824fcebbbe93a3f2ba463 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/module.ex | hamiltop/elixir | 3b601660d4d4eb0c69f824fcebbbe93a3f2ba463 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/module.ex | hamiltop/elixir | 3b601660d4d4eb0c69f824fcebbbe93a3f2ba463 | [
"Apache-2.0"
] | null | null | null | defmodule Module do
@moduledoc ~S'''
Provides functions to deal with modules during compilation time.
It allows a developer to dynamically add, delete and register
attributes, attach documentation and so forth.
After a module is compiled, using many of the functions in
this module will raise errors, since it is out of their scope
to inspect runtime data. Most of the runtime data can be inspected
via the `__info__(attr)` function attached to each compiled module.
## Module attributes
Each module can be decorated with one or more attributes. The following ones
are currently defined by Elixir:
* `@after_compile`
A hook that will be invoked right after the current module is compiled.
Accepts a module or a tuple `{<module>, <function atom>}`. The function
must take two arguments: the module environment and its bytecode.
When just a module is provided, the function is assumed to be
`__after_compile__/2`.
### Example
defmodule M do
@after_compile __MODULE__
def __after_compile__(env, _bytecode) do
IO.inspect env
end
end
* `@before_compile`
A hook that will be invoked before the module is compiled.
Accepts a module or a tuple `{<module>, <function/macro atom>}`. The
function/macro must take one argument: the module environment. If it's a
macro, its returned value will be injected at the end of the module definition
before the compilation starts.
When just a module is provided, the function/macro is assumed to be
`__before_compile__/1`.
Note: unlike `@after_compile`, the callback function/macro must
be placed in a separate module (because when the callback is invoked,
the current module does not yet exist).
### Example
defmodule A do
defmacro __before_compile__(_env) do
quote do
def hello, do: "world"
end
end
end
defmodule B do
@before_compile A
end
* `@behaviour` (notice the British spelling)
Behaviours can be referenced by modules to ensure they implement
required specific function signatures defined by `@callback`.
For example, you can specify the URI.Parser behaviour as follows:
defmodule URI.Parser do
@doc "Parses the given URL"
@callback parse(uri_info :: URI.t) :: URI.t
@doc "Defines a default port"
@callback default_port() :: integer
end
And then a module may use it as:
defmodule URI.HTTP do
@behaviour URI.Parser
def default_port(), do: 80
def parse(info), do: info
end
If the behaviour changes or URI.HTTP does not implement one of the
callbacks, a warning will be raised.
Specifies an OTP or user-defined behaviour.
### Example
defmodule M do
@behaviour gen_event
# ...
end
* `@compile`
Defines options for module compilation that are passed to the Erlang
compiler.
Accepts an atom, a tuple, or a list of atoms and tuples.
For the list of supported options, see Erlang's
[`:compile` module](http://www.erlang.org/doc/man/compile.html).
Multiple uses of `@compile` will accumulate instead of overriding
previous ones.
### Example
defmodule M do
@compile {:inline, myfun: 1}
def myfun(arg) do
to_string(arg)
end
end
* `@doc`
Provides documentation for the function or macro that follows the
attribute.
Accepts a string (often a heredoc) or `false` where `@doc false` will
make the function/macro invisible to the documentation extraction tools
like ExDoc.
Can be invoked more than once.
### Example
defmodule M do
@doc "Hello world"
def hello do
"world"
end
@doc """
Sums `a` to `b`.
"""
def sum(a, b) do
a + b
end
end
* `@file`
Changes the filename used in stacktraces for the function or macro that
follows the attribute.
Accepts a string. Can be used more than once.
### Example
defmodule M do
@doc "Hello world"
@file "hello.ex"
def hello do
"world"
end
end
* `@moduledoc`
Provides documentation for the current module.
Accepts a string (which is often a heredoc) or `false` where
`@moduledoc false` will make the module invisible to the
documentation extraction tools like ExDoc.
### Example
defmodule M do
@moduledoc """
A very useful module
"""
end
* `@on_definition`
A hook that will be invoked when each function or macro in the current
module is defined. Useful when annotating functions.
Accepts a module or a tuple `{<module>, <function atom>}`. The function
must take 6 arguments:
- the module environment
- kind: `:def`, `:defp`, `:defmacro`, or `:defmacrop`
- function/macro name
- list of quoted arguments
- list of quoted guards
- quoted function body
Note the hook receives the quoted arguments and it is invoked before
the function is stored in the module. So `Module.defines?/2` will return
`false` for the first clause of every function.
If the function/macro being defined has multiple clauses, the hook will
be called for each clause.
Unlike other hooks, `@on_definition` will only invoke functions
and never macros. This is because the hook is invoked inside the context
of the function (and nested function definitions are not allowed in
Elixir).
When just a module is provided, the function is assumed to be
`__on_definition__/6`.
### Example
defmodule H do
def on_def(_env, kind, name, args, guards, body) do
IO.puts "Defining #{kind} named #{name} with args:"
IO.inspect args
IO.puts "and guards"
IO.inspect guards
IO.puts "and body"
IO.puts Macro.to_string(body)
end
end
defmodule M do
@on_definition {H, :on_def}
def hello(arg) when is_binary(arg) or is_list(arg) do
"Hello" <> to_string(arg)
end
def hello(_) do
:ok
end
end
* `@on_load`
A hook that will be invoked whenever the module is loaded.
Accepts a function atom of a function in the current module. The function
must have arity 0 (no arguments) and has to return `:ok`, otherwise the
loading of the module will be aborted.
### Example
defmodule M do
@on_load :load_check
def load_check do
if some_condition() do
:ok
else
nil
end
end
def some_condition do
false
end
end
* `@vsn`
Specify the module version. Accepts any valid Elixir value.
### Example
defmodule M do
@vsn "1.0"
end
* `@external_resource`
Specifies an external resource to the current module.
Many times a module embeds information from an external file. This
attribute allows the module to annotate which external resources
have been used.
Tools like Mix may use this information to ensure the module is
recompiled in case any of the external resources change.
* `@dialyzer`
Defines warnings to request or suppress when using a version of
`:dialyzer` that supports module attributes.
Accepts an atom, a tuple, or a list of atoms and tuples.
For the list of supported warnings, see
[`:dialyzer` module](http://www.erlang.org/doc/man/dialyzer.html).
Multiple uses of `@dialyzer` will accumulate instead of overriding
previous ones.
### Example
defmodule M do
@dialyzer {:nowarn_function, myfun: 1}
def myfun(arg) do
M.not_a_function(arg)
end
end
The following attributes are part of typespecs and are also reserved by
Elixir (see `Kernel.Typespec` for more information about typespecs):
* `@type` - defines a type to be used in `@spec`
* `@typep` - defines a private type to be used in `@spec`
* `@opaque` - defines an opaque type to be used in `@spec`
* `@spec` - provides a specification for a function
* `@callback` - provides a specification for a behaviour callback
* `@macrocallback` - provides a specification for a macro behaviour callback
In addition to the built-in attributes outlined above, custom attributes may
also be added. A custom attribute is any valid identifier prefixed with an
`@` and followed by a valid Elixir value:
defmodule M do
@custom_attr [some: "stuff"]
end
For more advanced options available when defining custom attributes, see
`register_attribute/3`.
## Runtime information about a module
It is possible to query a module at runtime to find out which functions and
macros it defines, extract its docstrings, etc. See `__info__/1`.
'''
@doc """
Provides runtime information about functions and macros defined by the
module, enables docstring extraction, etc.
Each module gets an `__info__/1` function when it's compiled. The function
takes one of the following atoms:
* `:functions` - keyword list of public functions along with their arities
* `:macros` - keyword list of public macros along with their arities
* `:module` - module name (`Module == Module.__info__(:module)`)
In addition to the above, you may also pass to `__info__/1` any atom supported
by `:erlang.module_info/0` which also gets defined for each compiled module.
For a list of supported attributes and more information, see [Modules – Erlang Reference Manual](http://www.erlang.org/doc/reference_manual/modules.html#id77056).
"""
def __info__(kind)
@doc """
Checks if a module is open, i.e. it is currently being defined
and its attributes and functions can be modified.
"""
def open?(module) do
:elixir_module.is_open(module)
end
@doc """
Evaluates the quoted contents in the given module's context.
A list of environment options can also be given as argument.
See `Code.eval_string/3` for more information.
Raises an error if the module was already compiled.
## Examples
defmodule Foo do
contents = quote do: (def sum(a, b), do: a + b)
Module.eval_quoted __MODULE__, contents
end
Foo.sum(1, 2) #=> 3
For convenience, you can pass `__ENV__` as an argument and
all options will be automatically extracted from the environment:
defmodule Foo do
contents = quote do: (def sum(a, b), do: a + b)
Module.eval_quoted __MODULE__, contents, [], __ENV__
end
Foo.sum(1, 2) #=> 3
"""
def eval_quoted(module, quoted, binding \\ [], opts \\ [])
def eval_quoted(%Macro.Env{} = env, quoted, binding, opts) do
eval_quoted(env.module, quoted, binding, Keyword.merge(Map.to_list(env), opts))
end
def eval_quoted(module, quoted, binding, %Macro.Env{} = env) do
eval_quoted(module, quoted, binding, Map.to_list(env))
end
def eval_quoted(module, quoted, binding, opts) do
assert_not_compiled!(:eval_quoted, module)
:elixir_def.reset_last(module)
{value, binding, _env, _scope} =
:elixir.eval_quoted quoted, binding, Keyword.put(opts, :module, module)
{value, binding}
end
@doc """
Creates a module with the given name and defined by
the given quoted expressions.
The line where the module is defined and its file **must**
be passed as options.
## Examples
contents =
quote do
def world, do: true
end
Module.create(Hello, contents, Macro.Env.location(__ENV__))
Hello.world #=> true
## Differences from `defmodule`
`Module.create/3` works similarly to `defmodule` and
return the same results. While one could also use
`defmodule` to define modules dynamically, this
function is preferred when the module body is given
by a quoted expression.
Another important distinction is that `Module.create/3`
allows you to control the environment variables used
when defining the module, while `defmodule` automatically
shares the same environment.
"""
def create(module, quoted, opts)
def create(module, quoted, %Macro.Env{} = env) do
create(module, quoted, Map.to_list(env))
end
def create(module, quoted, opts) when is_atom(module) and is_list(opts) do
unless Keyword.has_key?(opts, :file) do
raise ArgumentError, "expected :file to be given as option"
end
:elixir_module.compile(module, quoted, [], :elixir.env_for_eval(opts))
end
@doc """
Concatenates a list of aliases and returns a new alias.
## Examples
iex> Module.concat([Foo, Bar])
Foo.Bar
iex> Module.concat([Foo, "Bar"])
Foo.Bar
"""
@spec concat([binary | atom]) :: atom
def concat(list) when is_list(list) do
:elixir_aliases.concat(list)
end
@doc """
Concatenates two aliases and returns a new alias.
## Examples
iex> Module.concat(Foo, Bar)
Foo.Bar
iex> Module.concat(Foo, "Bar")
Foo.Bar
"""
@spec concat(binary | atom, binary | atom) :: atom
def concat(left, right) do
:elixir_aliases.concat([left, right])
end
@doc """
Concatenates a list of aliases and returns a new alias only if the alias
was already referenced.
If the alias was not referenced yet, fails with `ArgumentError`.
It handles char lists, binaries and atoms.
## Examples
iex> Module.safe_concat([Module, Unknown])
** (ArgumentError) argument error
iex> Module.safe_concat([List, Chars])
List.Chars
"""
@spec safe_concat([binary | atom]) :: atom | no_return
def safe_concat(list) when is_list(list) do
:elixir_aliases.safe_concat(list)
end
@doc """
Concatenates two aliases and returns a new alias only if the alias was
already referenced.
If the alias was not referenced yet, fails with `ArgumentError`.
It handles char lists, binaries and atoms.
## Examples
iex> Module.safe_concat(Module, Unknown)
** (ArgumentError) argument error
iex> Module.safe_concat(List, Chars)
List.Chars
"""
@spec safe_concat(binary | atom, binary | atom) :: atom | no_return
def safe_concat(left, right) do
:elixir_aliases.safe_concat([left, right])
end
@doc """
Attaches documentation to a given function or type.
It expects the module the function/type belongs to, the line (a non
negative integer), the kind (`def` or `defmacro`), a tuple representing
the function and its arity, the function signature (the signature
should be omitted for types) and the documentation, which should
be either a binary or a boolean.
## Examples
defmodule MyModule do
Module.add_doc(__MODULE__, __ENV__.line + 1, :def, {:version, 0}, [], "Manually added docs")
def version, do: 1
end
"""
def add_doc(module, line, kind, tuple, signature \\ [], doc)
def add_doc(_module, _line, kind, _tuple, _signature, doc) when kind in [:defp, :defmacrop, :typep] do
if doc, do: {:error, :private_doc}, else: :ok
end
def add_doc(module, line, kind, tuple, signature, doc) when
kind in [:def, :defmacro, :type, :opaque] and (is_binary(doc) or is_boolean(doc) or doc == nil) do
assert_not_compiled!(:add_doc, module)
table = data_table_for(module)
signature = simplify_signature(signature)
case :ets.lookup(table, {:doc, tuple}) do
[] ->
:ets.insert(table, {{:doc, tuple}, line, kind, signature, doc})
:ok
[{doc_tuple, line, _old_kind, old_sign, old_doc}] ->
:ets.insert(table, {
doc_tuple,
line,
kind,
merge_signatures(old_sign, signature, 1),
if(is_nil(doc), do: old_doc, else: doc)
})
:ok
end
end
# Simplify signatures to be stored in docs
defp simplify_signature(signature) do
{signature, acc} = :lists.mapfoldl(&simplify_signature/2, [], signature)
{signature, _} = :lists.mapfoldl(&expand_signature/2, {acc, acc}, signature)
signature
end
defp simplify_signature({:\\, _, [left, right ]}, acc) do
{left, acc} = simplify_signature(left, acc)
{{:\\, [], [left, right]}, acc}
end
defp simplify_signature({:=, _, [_, right]}, acc) do
simplify_signature(right, acc)
end
defp simplify_signature({var, _, atom}, acc) when is_atom(atom) do
case Atom.to_string(var) do
"_" <> rest -> {{String.to_atom(rest), [], Elixir}, acc}
_ -> {{var, [], nil}, acc}
end
end
defp simplify_signature({:%, _, [left, _]}, acc) when is_atom(left) do
struct_name = String.to_atom(camelcase_to_underscore(List.last(split(left))))
autogenerated(acc, struct_name)
end
defp simplify_signature({:%{}, _, _}, acc) do
autogenerated(acc, :map)
end
defp simplify_signature(other, acc) when is_integer(other), do: autogenerated(acc, :int)
defp simplify_signature(other, acc) when is_boolean(other), do: autogenerated(acc, :bool)
defp simplify_signature(other, acc) when is_atom(other), do: autogenerated(acc, :atom)
defp simplify_signature(other, acc) when is_list(other), do: autogenerated(acc, :list)
defp simplify_signature(other, acc) when is_float(other), do: autogenerated(acc, :float)
defp simplify_signature(other, acc) when is_binary(other), do: autogenerated(acc, :binary)
defp simplify_signature(_, acc), do: autogenerated(acc, :arg)
defp autogenerated(acc, key) do
{key, [key|acc]}
end
defp expand_signature(key, {all_keys, acc}) when is_atom(key) do
case previous_values(key, all_keys, acc) do
{i, acc} -> {{:"#{key}#{i}", [], Elixir}, {all_keys, acc}}
:none -> {{key, [], Elixir}, {all_keys, acc}}
end
end
defp expand_signature(term, {_, _} = acc) do
{term, acc}
end
defp previous_values(key, all_keys, acc) do
total_occurrences = occurrences(key, all_keys)
if total_occurrences == 1 do
:none
else
index = total_occurrences - occurrences(key, acc) + 1
{index, :lists.delete(key, acc)}
end
end
defp occurrences(key, list) do
length(:lists.filter(fn(el) -> el == key end, list))
end
defp camelcase_to_underscore(<<c::utf8, rest::binary>>) when c >= ?A and c <= ?Z,
do: do_camelcase_to_underscore(rest, <<c + 32::utf8>>)
defp do_camelcase_to_underscore(<<c::utf8, rest::binary>>, acc) when c >= ?A and c <= ?Z,
do: do_camelcase_to_underscore(rest, <<acc::binary, ?_, c + 32::utf8>>)
defp do_camelcase_to_underscore(<<c::utf8, rest::binary>>, acc),
do: do_camelcase_to_underscore(rest, <<acc::binary, c>>)
defp do_camelcase_to_underscore(<<>>, acc),
do: acc
# Merge
defp merge_signatures([h1|t1], [h2|t2], i) do
[merge_signature(h1, h2, i)|merge_signatures(t1, t2, i + 1)]
end
defp merge_signatures([], [], _) do
[]
end
defp merge_signature({:\\, line, [left, right]}, newer, i) do
{:\\, line, [merge_signature(left, newer, i), right]}
end
defp merge_signature(older, {:\\, _, [left, _]}, i) do
merge_signature(older, left, i)
end
# The older signature, when given, always have higher precedence
defp merge_signature({_, _, nil} = older, _newer, _), do: older
defp merge_signature(_older, {_, _, nil} = newer, _), do: newer
# Both are a guess, so check if they are the same guess
defp merge_signature({var, _, _} = older, {var, _, _}, _), do: older
# Otherwise, returns a generic guess
defp merge_signature({_, line, _}, _newer, i), do: {:"arg#{i}", line, Elixir}
@doc """
Checks if the module defines the given function or macro.
Use `defines?/3` to assert for a specific type.
## Examples
defmodule Example do
Module.defines? __MODULE__, {:version, 0} #=> false
def version, do: 1
Module.defines? __MODULE__, {:version, 0} #=> true
end
"""
def defines?(module, tuple) when is_tuple(tuple) do
assert_not_compiled!(:defines?, module)
table = defs_table_for(module)
:ets.lookup(table, tuple) != []
end
@doc """
Checks if the module defines a function or macro of the
given `kind`.
`kind` can be any of `:def`, `:defp`, `:defmacro` or `:defmacrop`.
## Examples
defmodule Example do
Module.defines? __MODULE__, {:version, 0}, :defp #=> false
def version, do: 1
Module.defines? __MODULE__, {:version, 0}, :defp #=> false
end
"""
def defines?(module, tuple, kind) do
assert_not_compiled!(:defines?, module)
table = defs_table_for(module)
case :ets.lookup(table, tuple) do
[{_, ^kind, _, _, _, _, _}] -> true
_ -> false
end
end
@doc """
Returns all functions defined in `module`.
## Examples
defmodule Example do
def version, do: 1
Module.definitions_in __MODULE__ #=> [{:version, 0}]
end
"""
def definitions_in(module) do
assert_not_compiled!(:definitions_in, module)
table = defs_table_for(module)
:lists.concat :ets.match(table, {:'$1', :_, :_, :_, :_, :_, :_})
end
@doc """
Returns all functions defined in `module`, according
to its kind.
## Examples
defmodule Example do
def version, do: 1
Module.definitions_in __MODULE__, :def #=> [{:version, 0}]
Module.definitions_in __MODULE__, :defp #=> []
end
"""
def definitions_in(module, kind) do
assert_not_compiled!(:definitions_in, module)
table = defs_table_for(module)
:lists.concat :ets.match(table, {:'$1', kind, :_, :_, :_, :_, :_})
end
@doc """
Makes the given functions in `module` overridable.
An overridable function is lazily defined, allowing a
developer to customize it. See `Kernel.defoverridable/1` for
more information and documentation.
"""
def make_overridable(module, tuples) do
assert_not_compiled!(:make_overridable, module)
:lists.foreach(fn tuple ->
case :elixir_def.lookup_definition(module, tuple) do
false ->
{name, arity} = tuple
raise "cannot make function #{name}/#{arity} overridable because it was not defined"
clause ->
:elixir_def.delete_definition(module, tuple)
neighbours = if :elixir_compiler.get_opt(:internal) do
[]
else
Module.LocalsTracker.yank(module, tuple)
end
old = :elixir_def_overridable.overridable(module)
count = case :maps.find(tuple, old) do
{:ok, {count, _, _, _}} -> count + 1
:error -> 1
end
new = :maps.put(tuple, {count, clause, neighbours, false}, old)
:elixir_def_overridable.overridable(module, new)
end
end, tuples)
end
@doc """
Returns `true` if `tuple` in `module` is marked as overridable.
"""
def overridable?(module, tuple) do
:maps.is_key(tuple, :elixir_def_overridable.overridable(module))
end
@doc """
Puts an Erlang attribute to the given module with the given
key and value.
The semantics of putting the attribute depends
if the attribute was registered or not via `register_attribute/3`.
## Examples
defmodule MyModule do
Module.put_attribute __MODULE__, :custom_threshold_for_lib, 10
end
"""
def put_attribute(module, key, value) do
put_attribute(module, key, value, nil)
end
@doc false
def put_attribute(module, key, value, stack) when is_atom(key) do
assert_not_compiled!(:put_attribute, module)
table = data_table_for(module)
value = preprocess_attribute(key, value)
acc = :ets.lookup_element(table, {:elixir, :acc_attributes}, 2)
warn_if_redefining_doc_attribute(stack, table, key)
new =
if :lists.member(key, acc) do
case :ets.lookup(table, key) do
[{^key, old}] -> [value|old]
[] -> [value]
end
else
value
end
:ets.insert(table, {key, new})
end
@doc """
Gets the given attribute from a module.
If the attribute was marked with `accumulate` with
`Module.register_attribute/3`, a list is always returned. `nil` is returned
if the attribute has not been marked with `accumulate` and has not been set
to any value.
The `@` macro compiles to a call to this function. For example,
the following code:
@foo
Expands close to:
Module.get_attribute(__MODULE__, :foo)
## Examples
defmodule Foo do
Module.put_attribute __MODULE__, :value, 1
Module.get_attribute __MODULE__, :value #=> 1
Module.register_attribute __MODULE__, :value, accumulate: true
Module.put_attribute __MODULE__, :value, 1
Module.get_attribute __MODULE__, :value #=> [1]
end
"""
@spec get_attribute(atom, atom) :: term
def get_attribute(module, key) do
get_attribute(module, key, nil)
end
@doc """
Deletes all attributes that match the given key.
## Examples
defmodule MyModule do
Module.put_attribute __MODULE__, :custom_threshold_for_lib, 10
Module.delete_attribute __MODULE__, :custom_threshold_for_lib
end
"""
@spec delete_attribute(atom, atom) :: :ok
def delete_attribute(module, key) when is_atom(key) do
assert_not_compiled!(:delete_attribute, module)
table = data_table_for(module)
:ets.delete(table, key)
:ok
end
@doc """
Registers an attribute. By registering an attribute, a developer
is able to customize how Elixir will store and accumulate the
attribute values.
## Options
When registering an attribute, two options can be given:
* `:accumulate` - several calls to the same attribute will
accumulate instead of override the previous one. New attributes
are always added to the top of the accumulated list.
* `:persist` - the attribute will be persisted in the Erlang
Abstract Format. Useful when interfacing with Erlang libraries.
By default, both options are `false`.
## Examples
defmodule MyModule do
Module.register_attribute __MODULE__,
:custom_threshold_for_lib,
accumulate: true, persist: false
@custom_threshold_for_lib 10
@custom_threshold_for_lib 20
@custom_threshold_for_lib #=> [20, 10]
end
"""
def register_attribute(module, new, opts) when is_atom(new) do
assert_not_compiled!(:register_attribute, module)
table = data_table_for(module)
if Keyword.get(opts, :persist) do
old = :ets.lookup_element(table, {:elixir, :persisted_attributes}, 2)
:ets.insert(table, {{:elixir, :persisted_attributes}, [new|old]})
end
if Keyword.get(opts, :accumulate) do
old = :ets.lookup_element(table, {:elixir, :acc_attributes}, 2)
:ets.insert(table, {{:elixir, :acc_attributes}, [new|old]})
end
end
@doc """
Splits the given module name into binary parts.
## Examples
Module.split Very.Long.Module.Name.And.Even.Longer
#=> ["Very", "Long", "Module", "Name", "And", "Even", "Longer"]
"""
def split(module) when is_atom(module) do
split(String.Chars.to_string(module))
end
def split("Elixir." <> name) do
String.split(name, ".")
end
@doc false
# Used internally to compile documentation. This function
# is private and must be used only internally.
def compile_doc(env, kind, name, args, _guards, _body) do
module = env.module
table = data_table_for(module)
arity = length(args)
pair = {name, arity}
{line, doc} = get_doc_info(table, env)
# Arguments are not expanded for the docs, but we make an exception for
# module attributes and for structs (aliases to be precise).
args = Macro.prewalk args, fn
{:@, _, _} = attr ->
Macro.expand_once(attr, env)
{:%, meta, [aliases, fields]} ->
{:%, meta, [Macro.expand_once(aliases, env), fields]}
x ->
x
end
case add_doc(module, line, kind, pair, args, doc) do
:ok ->
:ok
{:error, :private_doc} ->
:elixir_errors.warn line, env.file,
"function #{name}/#{arity} is private, " <>
"@doc's are always discarded for private functions"
end
:ok
end
@doc false
# Used internally to compile types. This function
# is private and must be used only internally.
def store_typespec(module, key, value) when is_atom(key) do
assert_not_compiled!(:put_attribute, module)
table = data_table_for(module)
new =
case :ets.lookup(table, key) do
[{^key, old}] -> [value|old]
[] -> [value]
end
:ets.insert(table, {key, new})
end
@doc false
def get_attribute(module, key, stack) when is_atom(key) and (is_list(stack) or is_nil(stack)) do
assert_not_compiled!(:get_attribute, module)
table = data_table_for(module)
case :ets.lookup(table, key) do
[{^key, val}] ->
postprocess_attribute(key, val)
[] ->
acc = :ets.lookup_element(table, {:elixir, :acc_attributes}, 2)
cond do
:lists.member(key, acc) ->
[]
is_list(stack) ->
:elixir_errors.warn warn_info(stack), "undefined module attribute @#{key}, " <>
"please remove access to @#{key} or explicitly set it before access"
nil
true ->
nil
end
end
end
defp warn_info([entry|_]) do
opts = elem(entry, tuple_size(entry) - 1)
Exception.format_file_line(Keyword.get(opts, :file), Keyword.get(opts, :line)) <> " "
end
defp warn_info([]) do
""
end
## Helpers
defp preprocess_attribute(:on_load, atom) when is_atom(atom) do
{atom, 0}
end
defp preprocess_attribute(:behaviour, atom) when is_atom(atom) do
# Attempt to compile behaviour but ignore failure (will warn later)
_ = Code.ensure_compiled(atom)
atom
end
defp preprocess_attribute(:file, file) when is_binary(file) do
file
end
defp preprocess_attribute(:before_compile, atom) when is_atom(atom),
do: {atom, :__before_compile__}
defp preprocess_attribute(:after_compile, atom) when is_atom(atom),
do: {atom, :__after_compile__}
defp preprocess_attribute(:on_definition, atom) when is_atom(atom),
do: {atom, :__on_definition__}
defp preprocess_attribute(key, _value) when key in [:type, :typep, :export_type, :opaque, :callback, :macrocallback] do
raise ArgumentError, "attributes type, typep, export_type, opaque, callback and macrocallback " <>
"must be set via Kernel.Typespec"
end
defp preprocess_attribute(_key, value) do
value
end
defp postprocess_attribute(:doc, {_line, doc}), do: doc
defp postprocess_attribute(:typedoc, {_line, doc}), do: doc
defp postprocess_attribute(:moduledoc, {_line, doc}), do: doc
defp postprocess_attribute(_, value), do: value
defp get_doc_info(table, env) do
case :ets.take(table, :doc) do
[doc: {_, _} = pair] -> pair
[] -> {env.line, nil}
end
end
defp data_table_for(module) do
:elixir_module.data_table(module)
end
defp defs_table_for(module) do
:elixir_module.defs_table(module)
end
defp assert_not_compiled!(fun, module) do
open?(module) ||
raise ArgumentError,
"could not call #{fun} on module #{inspect module} because it was already compiled"
end
defp warn_if_redefining_doc_attribute(stack, table, key)
when is_list(stack) and key in [:doc, :typedoc, :moduledoc] do
case :ets.lookup(table, key) do
[{_, {line, val}}] when val != false ->
:elixir_errors.warn warn_info(stack),
"redefining @#{key} attribute previously set at line #{line}"
_ ->
false
end
end
defp warn_if_redefining_doc_attribute(nil, _table, _key), do: false
end
| 29.153846 | 164 | 0.638246 |
79b0524a54365b9384009fe8a15bc085f3182603 | 1,532 | ex | Elixir | lib/xdr/transactions/operations/manage_offer.ex | einerzg/stellar_base | 2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f | [
"MIT"
] | 3 | 2021-08-17T20:32:45.000Z | 2022-03-13T20:26:02.000Z | lib/xdr/transactions/operations/manage_offer.ex | einerzg/stellar_base | 2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f | [
"MIT"
] | 45 | 2021-08-12T20:19:41.000Z | 2022-03-27T21:00:10.000Z | lib/xdr/transactions/operations/manage_offer.ex | einerzg/stellar_base | 2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f | [
"MIT"
] | 2 | 2021-09-22T23:11:13.000Z | 2022-01-23T03:19:11.000Z | defmodule StellarBase.XDR.Operations.ManageOffer do
@moduledoc """
Representation of Stellar `ManageOffer` type.
"""
alias StellarBase.XDR.{OfferEntry, Void}
alias StellarBase.XDR.Operations.ManageOfferEffect
@behaviour XDR.Declaration
@arms [
MANAGE_OFFER_CREATED: OfferEntry,
MANAGE_OFFER_UPDATED: OfferEntry,
default: Void
]
@type t :: %__MODULE__{offer: any(), effect: ManageOfferEffect.t()}
defstruct [:offer, :effect]
@spec new(offer :: any(), effect :: ManageOfferEffect.t()) :: t()
def new(offer, %ManageOfferEffect{} = effect),
do: %__MODULE__{offer: offer, effect: effect}
@impl true
def encode_xdr(%__MODULE__{offer: offer, effect: effect}) do
effect
|> XDR.Union.new(@arms, offer)
|> XDR.Union.encode_xdr()
end
@impl true
def encode_xdr!(%__MODULE__{offer: offer, effect: effect}) do
effect
|> XDR.Union.new(@arms, offer)
|> XDR.Union.encode_xdr!()
end
@impl true
def decode_xdr(bytes, spec \\ union_spec())
def decode_xdr(bytes, spec) do
case XDR.Union.decode_xdr(bytes, spec) do
{:ok, {{effect, offer}, rest}} -> {:ok, {new(offer, effect), rest}}
error -> error
end
end
@impl true
def decode_xdr!(bytes, spec \\ union_spec())
def decode_xdr!(bytes, spec) do
{{effect, offer}, rest} = XDR.Union.decode_xdr!(bytes, spec)
{new(offer, effect), rest}
end
@spec union_spec() :: XDR.Union.t()
defp union_spec do
nil
|> ManageOfferEffect.new()
|> XDR.Union.new(@arms)
end
end
| 24.31746 | 73 | 0.658616 |
79b05e263b56d4639b3b7c69b83b4ca0bae0a429 | 718 | ex | Elixir | lib/p7.ex | joekain/ds_p7 | 8ad22fca2d40897314c74b5cc0e3f62e59970000 | [
"MIT"
] | 1 | 2017-06-18T19:06:48.000Z | 2017-06-18T19:06:48.000Z | lib/p7.ex | joekain/ds_p7 | 8ad22fca2d40897314c74b5cc0e3f62e59970000 | [
"MIT"
] | null | null | null | lib/p7.ex | joekain/ds_p7 | 8ad22fca2d40897314c74b5cc0e3f62e59970000 | [
"MIT"
] | null | null | null | defmodule P7 do
use Application
def pool_name, do: :p7_pool
defp poolboy_config do
[
{:name, {:local, pool_name}},
{:worker_module, P7.Worker},
{:size, 5},
{:max_overflow, 10}
]
end
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
:poolboy.child_spec(pool_name(), poolboy_config(), [])
]
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: P7.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 23.933333 | 67 | 0.662953 |
79b065d123c24976c2e50a2639009875cdc058ee | 1,910 | ex | Elixir | lib/docusign/model/document.ex | gaslight/docusign_elixir | d9d88d53dd85d32a39d537bade9db28d779414e6 | [
"MIT"
] | 4 | 2020-12-21T12:50:13.000Z | 2022-01-12T16:50:43.000Z | lib/docusign/model/document.ex | gaslight/docusign_elixir | d9d88d53dd85d32a39d537bade9db28d779414e6 | [
"MIT"
] | 12 | 2018-09-18T15:26:34.000Z | 2019-09-28T15:29:39.000Z | lib/docusign/model/document.ex | gaslight/docusign_elixir | d9d88d53dd85d32a39d537bade9db28d779414e6 | [
"MIT"
] | 15 | 2020-04-29T21:50:16.000Z | 2022-02-11T18:01:51.000Z | # NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule DocuSign.Model.Document do
@moduledoc """
A document object.
"""
@derive [Poison.Encoder]
defstruct [
:applyAnchorTabs,
:authoritativeCopy,
:display,
:documentBase64,
:documentFields,
:documentGroup,
:documentId,
:encryptedWithKeyManager,
:fileExtension,
:fileFormatHint,
:includeInDownload,
:matchBoxes,
:name,
:order,
:pages,
:password,
:remoteUrl,
:signerMustAcknowledge,
:templateLocked,
:templateRequired,
:transformPdfFields,
:uri
]
@type t :: %__MODULE__{
:applyAnchorTabs => String.t(),
:authoritativeCopy => boolean(),
:display => String.t(),
:documentBase64 => String.t(),
:documentFields => [NameValue],
:documentGroup => String.t(),
:documentId => String.t(),
:encryptedWithKeyManager => String.t(),
:fileExtension => String.t(),
:fileFormatHint => String.t(),
:includeInDownload => String.t(),
:matchBoxes => [MatchBox],
:name => String.t(),
:order => String.t(),
:pages => String.t(),
:password => String.t(),
:remoteUrl => String.t(),
:signerMustAcknowledge => String.t(),
:templateLocked => String.t(),
:templateRequired => String.t(),
:transformPdfFields => String.t(),
:uri => String.t()
}
end
defimpl Poison.Decoder, for: DocuSign.Model.Document do
import DocuSign.Deserializer
def decode(value, options) do
value
|> deserialize(:documentFields, :list, DocuSign.Model.NameValue, options)
|> deserialize(:matchBoxes, :list, DocuSign.Model.MatchBox, options)
end
end
| 26.901408 | 77 | 0.597906 |
79b0771d54aacee5b564e532ec6fafb8a182b871 | 1,298 | ex | Elixir | test/support/worker.ex | cdesch/horde | 6a47e90df5755cca51d6a80705b7d49be6bd4ea2 | [
"MIT"
] | 1,026 | 2018-05-15T13:46:58.000Z | 2022-03-24T02:59:54.000Z | test/support/worker.ex | cdesch/horde | 6a47e90df5755cca51d6a80705b7d49be6bd4ea2 | [
"MIT"
] | 191 | 2018-06-04T09:39:37.000Z | 2022-03-30T07:04:31.000Z | test/support/worker.ex | cdesch/horde | 6a47e90df5755cca51d6a80705b7d49be6bd4ea2 | [
"MIT"
] | 109 | 2018-06-07T07:18:26.000Z | 2022-03-21T21:37:21.000Z | defmodule Worker do
require Logger
defstruct name: "",
state: ""
def state(name) do
GenServer.call(via_tuple(name), :state)
end
def set_state(pid, state) when is_pid(pid) do
GenServer.call(pid, {:set_state, state})
end
def set_state(name, state) do
GenServer.call(via_tuple(name), {:set_state, state})
end
def start(name) do
Horde.DynamicSupervisor.start_child(
TestSup,
child_spec(name: name)
)
end
def via_tuple(name) do
{:via, Horde.Registry, {TestReg, name}}
end
def start_link(name) do
GenServer.start_link(__MODULE__, name, name: via_tuple(name))
end
def init(name) do
Logger.info("Starting worker on #{inspect(Node.self())}")
{:ok, %__MODULE__{name: name}, {:continue, :started}}
end
def handle_continue(:started, state) do
Logger.info("Started worker on #{inspect(Node.self())}")
{:noreply, state}
end
def handle_call({:set_state, value}, _from, state) do
{:reply, :ok, %{state | state: value}}
end
def handle_call(:state, _from, state) do
{:reply, {:ok, state.state}, state}
end
defp child_spec(name: name) do
%{
id: String.to_atom("#{__MODULE__}_#{name}"),
start: {__MODULE__, :start_link, [name]},
shutdown: 10_000
}
end
end
| 21.633333 | 65 | 0.637904 |
79b07a0c8233f7954aba74c9f12434a1a9f6870a | 1,876 | exs | Elixir | test/validate_test.exs | nobuyo/json-typedef-elixir | c7bf06063f5f33bb926730cc50d49c67519948bf | [
"MIT"
] | 1 | 2021-04-18T05:05:09.000Z | 2021-04-18T05:05:09.000Z | test/validate_test.exs | nobuyo/json-typedef-elixir | c7bf06063f5f33bb926730cc50d49c67519948bf | [
"MIT"
] | null | null | null | test/validate_test.exs | nobuyo/json-typedef-elixir | c7bf06063f5f33bb926730cc50d49c67519948bf | [
"MIT"
] | null | null | null | defmodule ValidateTest do
use ExUnit.Case
ExUnit.Case.register_attribute(__MODULE__, :fixtures, accumulate: true)
@skipped_tests [
# DateTime.from_iso8601 does not supports this format
"timestamp type schema - 1990-12-31T23:59:60Z",
"timestamp type schema - 1990-12-31T15:59:60-08:00",
# Elixir's Map is supporting no any ordering of keys
"values schema - all values bad"
]
describe "validate" do
test "max depth" do
schema = JTD.Schema.from_map(%{
definitions: %{"loop" => %{ref: "loop"}},
ref: "loop",
})
|> JTD.Schema.verify
assert_raise JTD.MaxDepthExceededError, fn -> JTD.validate(schema, nil, %JTD.ValidationOptions{max_depth: 32}) end
end
test "supports max errors" do
schema = JTD.Schema.from_map(%{
elements: %{ type: "string" }
})
|> JTD.Schema.verify
options = %JTD.ValidationOptions{max_errors: 3}
errors_size = schema|> JTD.validate([nil, nil, nil, nil], options) |> length
assert(errors_size == 3)
end
end
describe "validate: spec tests" do
{:ok, test_cases} = File.read("json-typedef-spec/tests/validation.json")
{:ok, test_cases} = Jason.decode(test_cases)
test_cases
|> Enum.each(fn {name, test_case} ->
@fixtures test_case
unless name in @skipped_tests do
test name, context do
%{ "schema" => case_schema, "instance" => case_instance, "errors" => case_errors } = context.registered.fixtures |> List.first
schema = JTD.Schema.from_map(case_schema) |> JTD.Schema.verify
instance = case_instance
expected_errors = (case_errors || []) |> Enum.map(fn e -> JTD.ValidationError.from_map(e) end)
actual_errors = JTD.validate(schema, instance)
assert(actual_errors == expected_errors)
end
end
end)
end
end
| 31.79661 | 136 | 0.639659 |
79b07e8ee815b142be26d75aabf22e2085b4809f | 53,989 | ex | Elixir | lib/aws/api_gateway.ex | ahsandar/aws-elixir | 25de8b6c3a1401bde737cfc26b0679b14b058f23 | [
"Apache-2.0"
] | null | null | null | lib/aws/api_gateway.ex | ahsandar/aws-elixir | 25de8b6c3a1401bde737cfc26b0679b14b058f23 | [
"Apache-2.0"
] | null | null | null | lib/aws/api_gateway.ex | ahsandar/aws-elixir | 25de8b6c3a1401bde737cfc26b0679b14b058f23 | [
"Apache-2.0"
] | null | null | null | # WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
# See https://github.com/aws-beam/aws-codegen for more details.
defmodule AWS.APIGateway do
@moduledoc """
Amazon API Gateway
Amazon API Gateway helps developers deliver robust, secure, and scalable
mobile and web application back ends. API Gateway allows developers to
securely connect mobile and web applications to APIs that run on AWS
Lambda, Amazon EC2, or other publicly addressable web services that are
hosted outside of AWS.
"""
@doc """
Create an `ApiKey` resource.
<div class="seeAlso">[AWS
CLI](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-api-key.html)</div>
"""
def create_api_key(client, input, options \\ []) do
path_ = "/apikeys"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Adds a new `Authorizer` resource to an existing `RestApi` resource.
<div class="seeAlso">[AWS
CLI](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-authorizer.html)</div>
"""
def create_authorizer(client, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/authorizers"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a new `BasePathMapping` resource.
"""
def create_base_path_mapping(client, domain_name, input, options \\ []) do
path_ = "/domainnames/#{URI.encode(domain_name)}/basepathmappings"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a `Deployment` resource, which makes a specified `RestApi` callable
over the internet.
"""
def create_deployment(client, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/deployments"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
"""
def create_documentation_part(client, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/documentation/parts"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
"""
def create_documentation_version(client, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/documentation/versions"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a new domain name.
"""
def create_domain_name(client, input, options \\ []) do
path_ = "/domainnames"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Adds a new `Model` resource to an existing `RestApi` resource.
"""
def create_model(client, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/models"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a `ReqeustValidator` of a given `RestApi`.
"""
def create_request_validator(client, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/requestvalidators"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a `Resource` resource.
"""
def create_resource(client, parent_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(parent_id)}"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a new `RestApi` resource.
"""
def create_rest_api(client, input, options \\ []) do
path_ = "/restapis"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a new `Stage` resource that references a pre-existing `Deployment`
for the API.
"""
def create_stage(client, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/stages"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a usage plan with the throttle and quota limits, as well as the
associated API stages, specified in the payload.
"""
def create_usage_plan(client, input, options \\ []) do
path_ = "/usageplans"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a usage plan key for adding an existing API key to a usage plan.
"""
def create_usage_plan_key(client, usage_plan_id, input, options \\ []) do
path_ = "/usageplans/#{URI.encode(usage_plan_id)}/keys"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a VPC link, under the caller's account in a selected region, in an
asynchronous operation that typically takes 2-4 minutes to complete and
become operational. The caller must have permissions to create and update
VPC Endpoint services.
"""
def create_vpc_link(client, input, options \\ []) do
path_ = "/vpclinks"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 202)
end
@doc """
Deletes the `ApiKey` resource.
"""
def delete_api_key(client, api_key, input, options \\ []) do
path_ = "/apikeys/#{URI.encode(api_key)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes an existing `Authorizer` resource.
<div class="seeAlso">[AWS
CLI](https://docs.aws.amazon.com/cli/latest/reference/apigateway/delete-authorizer.html)</div>
"""
def delete_authorizer(client, authorizer_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/authorizers/#{URI.encode(authorizer_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes the `BasePathMapping` resource.
"""
def delete_base_path_mapping(client, base_path, domain_name, input, options \\ []) do
path_ = "/domainnames/#{URI.encode(domain_name)}/basepathmappings/#{URI.encode(base_path)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes the `ClientCertificate` resource.
"""
def delete_client_certificate(client, client_certificate_id, input, options \\ []) do
path_ = "/clientcertificates/#{URI.encode(client_certificate_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes a `Deployment` resource. Deleting a deployment will only succeed if
there are no `Stage` resources associated with it.
"""
def delete_deployment(client, deployment_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/deployments/#{URI.encode(deployment_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
"""
def delete_documentation_part(client, documentation_part_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/documentation/parts/#{URI.encode(documentation_part_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
"""
def delete_documentation_version(client, documentation_version, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/documentation/versions/#{URI.encode(documentation_version)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes the `DomainName` resource.
"""
def delete_domain_name(client, domain_name, input, options \\ []) do
path_ = "/domainnames/#{URI.encode(domain_name)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Clears any customization of a `GatewayResponse` of a specified response
type on the given `RestApi` and resets it with the default settings.
"""
def delete_gateway_response(client, response_type, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/gatewayresponses/#{URI.encode(response_type)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Represents a delete integration.
"""
def delete_integration(client, http_method, resource_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/integration"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 204)
end
@doc """
Represents a delete integration response.
"""
def delete_integration_response(client, http_method, resource_id, rest_api_id, status_code, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/integration/responses/#{URI.encode(status_code)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 204)
end
@doc """
Deletes an existing `Method` resource.
"""
def delete_method(client, http_method, resource_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 204)
end
@doc """
Deletes an existing `MethodResponse` resource.
"""
def delete_method_response(client, http_method, resource_id, rest_api_id, status_code, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/responses/#{URI.encode(status_code)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 204)
end
@doc """
Deletes a model.
"""
def delete_model(client, model_name, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/models/#{URI.encode(model_name)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes a `RequestValidator` of a given `RestApi`.
"""
def delete_request_validator(client, request_validator_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/requestvalidators/#{URI.encode(request_validator_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes a `Resource` resource.
"""
def delete_resource(client, resource_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes the specified API.
"""
def delete_rest_api(client, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes a `Stage` resource.
"""
def delete_stage(client, rest_api_id, stage_name, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/stages/#{URI.encode(stage_name)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes a usage plan of a given plan Id.
"""
def delete_usage_plan(client, usage_plan_id, input, options \\ []) do
path_ = "/usageplans/#{URI.encode(usage_plan_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes a usage plan key and remove the underlying API key from the
associated usage plan.
"""
def delete_usage_plan_key(client, key_id, usage_plan_id, input, options \\ []) do
path_ = "/usageplans/#{URI.encode(usage_plan_id)}/keys/#{URI.encode(key_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Deletes an existing `VpcLink` of a specified identifier.
"""
def delete_vpc_link(client, vpc_link_id, input, options \\ []) do
path_ = "/vpclinks/#{URI.encode(vpc_link_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Flushes all authorizer cache entries on a stage.
"""
def flush_stage_authorizers_cache(client, rest_api_id, stage_name, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/stages/#{URI.encode(stage_name)}/cache/authorizers"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Flushes a stage's cache.
"""
def flush_stage_cache(client, rest_api_id, stage_name, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/stages/#{URI.encode(stage_name)}/cache/data"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Generates a `ClientCertificate` resource.
"""
def generate_client_certificate(client, input, options \\ []) do
path_ = "/clientcertificates"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Gets information about the current `Account` resource.
"""
def get_account(client, options \\ []) do
path_ = "/account"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets information about the current `ApiKey` resource.
"""
def get_api_key(client, api_key, include_value \\ nil, options \\ []) do
path_ = "/apikeys/#{URI.encode(api_key)}"
headers = []
query_ = []
query_ = if !is_nil(include_value) do
[{"includeValue", include_value} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets information about the current `ApiKeys` resource.
"""
def get_api_keys(client, customer_id \\ nil, include_values \\ nil, limit \\ nil, name_query \\ nil, position \\ nil, options \\ []) do
path_ = "/apikeys"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(name_query) do
[{"name", name_query} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
query_ = if !is_nil(include_values) do
[{"includeValues", include_values} | query_]
else
query_
end
query_ = if !is_nil(customer_id) do
[{"customerId", customer_id} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Describe an existing `Authorizer` resource.
<div class="seeAlso">[AWS
CLI](https://docs.aws.amazon.com/cli/latest/reference/apigateway/get-authorizer.html)</div>
"""
def get_authorizer(client, authorizer_id, rest_api_id, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/authorizers/#{URI.encode(authorizer_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Describe an existing `Authorizers` resource.
<div class="seeAlso">[AWS
CLI](https://docs.aws.amazon.com/cli/latest/reference/apigateway/get-authorizers.html)</div>
"""
def get_authorizers(client, rest_api_id, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/authorizers"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Describe a `BasePathMapping` resource.
"""
def get_base_path_mapping(client, base_path, domain_name, options \\ []) do
path_ = "/domainnames/#{URI.encode(domain_name)}/basepathmappings/#{URI.encode(base_path)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Represents a collection of `BasePathMapping` resources.
"""
def get_base_path_mappings(client, domain_name, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/domainnames/#{URI.encode(domain_name)}/basepathmappings"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets information about the current `ClientCertificate` resource.
"""
def get_client_certificate(client, client_certificate_id, options \\ []) do
path_ = "/clientcertificates/#{URI.encode(client_certificate_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets a collection of `ClientCertificate` resources.
"""
def get_client_certificates(client, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/clientcertificates"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets information about a `Deployment` resource.
"""
def get_deployment(client, deployment_id, rest_api_id, embed \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/deployments/#{URI.encode(deployment_id)}"
headers = []
query_ = []
query_ = if !is_nil(embed) do
[{"embed", embed} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets information about a `Deployments` collection.
"""
def get_deployments(client, rest_api_id, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/deployments"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
"""
def get_documentation_part(client, documentation_part_id, rest_api_id, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/documentation/parts/#{URI.encode(documentation_part_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
"""
def get_documentation_parts(client, rest_api_id, limit \\ nil, location_status \\ nil, name_query \\ nil, path \\ nil, position \\ nil, type \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/documentation/parts"
headers = []
query_ = []
query_ = if !is_nil(type) do
[{"type", type} | query_]
else
query_
end
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(path) do
[{"path", path} | query_]
else
query_
end
query_ = if !is_nil(name_query) do
[{"name", name_query} | query_]
else
query_
end
query_ = if !is_nil(location_status) do
[{"locationStatus", location_status} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
"""
def get_documentation_version(client, documentation_version, rest_api_id, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/documentation/versions/#{URI.encode(documentation_version)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
"""
def get_documentation_versions(client, rest_api_id, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/documentation/versions"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Represents a domain name that is contained in a simpler, more intuitive URL
that can be called.
"""
def get_domain_name(client, domain_name, options \\ []) do
path_ = "/domainnames/#{URI.encode(domain_name)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Represents a collection of `DomainName` resources.
"""
def get_domain_names(client, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/domainnames"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Exports a deployed version of a `RestApi` in a specified format.
"""
def get_export(client, export_type, rest_api_id, stage_name, parameters \\ nil, accepts \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/stages/#{URI.encode(stage_name)}/exports/#{URI.encode(export_type)}"
headers = []
headers = if !is_nil(accepts) do
[{"Accept", accepts} | headers]
else
headers
end
query_ = []
query_ = if !is_nil(parameters) do
[{"", parameters} | query_]
else
query_
end
case request(client, :get, path_, query_, headers, nil, options, 200) do
{:ok, body, response} ->
body =
[
{"Content-Disposition", "contentDisposition"},
{"Content-Type", "contentType"},
]
|> Enum.reduce(body, fn {header_name, key}, acc ->
case List.keyfind(response.headers, header_name, 0) do
nil -> acc
{_header_name, value} -> Map.put(acc, key, value)
end
end)
{:ok, body, response}
result ->
result
end
end
@doc """
Gets a `GatewayResponse` of a specified response type on the given
`RestApi`.
"""
def get_gateway_response(client, response_type, rest_api_id, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/gatewayresponses/#{URI.encode(response_type)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets the `GatewayResponses` collection on the given `RestApi`. If an API
developer has not added any definitions for gateway responses, the result
will be the API Gateway-generated default `GatewayResponses` collection for
the supported response types.
"""
def get_gateway_responses(client, rest_api_id, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/gatewayresponses"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Get the integration settings.
"""
def get_integration(client, http_method, resource_id, rest_api_id, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/integration"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Represents a get integration response.
"""
def get_integration_response(client, http_method, resource_id, rest_api_id, status_code, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/integration/responses/#{URI.encode(status_code)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Describe an existing `Method` resource.
"""
def get_method(client, http_method, resource_id, rest_api_id, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Describes a `MethodResponse` resource.
"""
def get_method_response(client, http_method, resource_id, rest_api_id, status_code, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/responses/#{URI.encode(status_code)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Describes an existing model defined for a `RestApi` resource.
"""
def get_model(client, model_name, rest_api_id, flatten \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/models/#{URI.encode(model_name)}"
headers = []
query_ = []
query_ = if !is_nil(flatten) do
[{"flatten", flatten} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Generates a sample mapping template that can be used to transform a payload
into the structure of a model.
"""
def get_model_template(client, model_name, rest_api_id, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/models/#{URI.encode(model_name)}/default_template"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Describes existing `Models` defined for a `RestApi` resource.
"""
def get_models(client, rest_api_id, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/models"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets a `RequestValidator` of a given `RestApi`.
"""
def get_request_validator(client, request_validator_id, rest_api_id, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/requestvalidators/#{URI.encode(request_validator_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets the `RequestValidators` collection of a given `RestApi`.
"""
def get_request_validators(client, rest_api_id, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/requestvalidators"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Lists information about a resource.
"""
def get_resource(client, resource_id, rest_api_id, embed \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}"
headers = []
query_ = []
query_ = if !is_nil(embed) do
[{"embed", embed} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Lists information about a collection of `Resource` resources.
"""
def get_resources(client, rest_api_id, embed \\ nil, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
query_ = if !is_nil(embed) do
[{"embed", embed} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Lists the `RestApi` resource in the collection.
"""
def get_rest_api(client, rest_api_id, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Lists the `RestApis` resources for your collection.
"""
def get_rest_apis(client, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/restapis"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Generates a client SDK for a `RestApi` and `Stage`.
"""
def get_sdk(client, rest_api_id, sdk_type, stage_name, parameters \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/stages/#{URI.encode(stage_name)}/sdks/#{URI.encode(sdk_type)}"
headers = []
query_ = []
query_ = if !is_nil(parameters) do
[{"", parameters} | query_]
else
query_
end
case request(client, :get, path_, query_, headers, nil, options, 200) do
{:ok, body, response} ->
body =
[
{"Content-Disposition", "contentDisposition"},
{"Content-Type", "contentType"},
]
|> Enum.reduce(body, fn {header_name, key}, acc ->
case List.keyfind(response.headers, header_name, 0) do
nil -> acc
{_header_name, value} -> Map.put(acc, key, value)
end
end)
{:ok, body, response}
result ->
result
end
end
@doc """
"""
def get_sdk_type(client, id, options \\ []) do
path_ = "/sdktypes/#{URI.encode(id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
"""
def get_sdk_types(client, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/sdktypes"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets information about a `Stage` resource.
"""
def get_stage(client, rest_api_id, stage_name, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/stages/#{URI.encode(stage_name)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets information about one or more `Stage` resources.
"""
def get_stages(client, rest_api_id, deployment_id \\ nil, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/stages"
headers = []
query_ = []
query_ = if !is_nil(deployment_id) do
[{"deploymentId", deployment_id} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets the `Tags` collection for a given resource.
"""
def get_tags(client, resource_arn, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/tags/#{URI.encode(resource_arn)}"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets the usage data of a usage plan in a specified time interval.
"""
def get_usage(client, usage_plan_id, end_date, key_id \\ nil, limit \\ nil, position \\ nil, start_date, options \\ []) do
path_ = "/usageplans/#{URI.encode(usage_plan_id)}/usage"
headers = []
query_ = []
query_ = if !is_nil(start_date) do
[{"startDate", start_date} | query_]
else
query_
end
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
query_ = if !is_nil(key_id) do
[{"keyId", key_id} | query_]
else
query_
end
query_ = if !is_nil(end_date) do
[{"endDate", end_date} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets a usage plan of a given plan identifier.
"""
def get_usage_plan(client, usage_plan_id, options \\ []) do
path_ = "/usageplans/#{URI.encode(usage_plan_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets a usage plan key of a given key identifier.
"""
def get_usage_plan_key(client, key_id, usage_plan_id, options \\ []) do
path_ = "/usageplans/#{URI.encode(usage_plan_id)}/keys/#{URI.encode(key_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Gets all the usage plan keys representing the API keys added to a specified
usage plan.
"""
def get_usage_plan_keys(client, usage_plan_id, limit \\ nil, name_query \\ nil, position \\ nil, options \\ []) do
path_ = "/usageplans/#{URI.encode(usage_plan_id)}/keys"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(name_query) do
[{"name", name_query} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets all the usage plans of the caller's account.
"""
def get_usage_plans(client, key_id \\ nil, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/usageplans"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
query_ = if !is_nil(key_id) do
[{"keyId", key_id} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets a specified VPC link under the caller's account in a region.
"""
def get_vpc_link(client, vpc_link_id, options \\ []) do
path_ = "/vpclinks/#{URI.encode(vpc_link_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Gets the `VpcLinks` collection under the caller's account in a selected
region.
"""
def get_vpc_links(client, limit \\ nil, position \\ nil, options \\ []) do
path_ = "/vpclinks"
headers = []
query_ = []
query_ = if !is_nil(position) do
[{"position", position} | query_]
else
query_
end
query_ = if !is_nil(limit) do
[{"limit", limit} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, nil)
end
@doc """
Import API keys from an external source, such as a CSV-formatted file.
"""
def import_api_keys(client, input, options \\ []) do
path_ = "/apikeys?mode=import"
headers = []
{query_, input} =
[
{"failOnWarnings", "failonwarnings"},
{"format", "format"},
]
|> AWS.Request.build_params(input)
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
"""
def import_documentation_parts(client, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/documentation/parts"
headers = []
{query_, input} =
[
{"failOnWarnings", "failonwarnings"},
{"mode", "mode"},
]
|> AWS.Request.build_params(input)
request(client, :put, path_, query_, headers, input, options, nil)
end
@doc """
A feature of the API Gateway control service for creating a new API from an
external API definition file.
"""
def import_rest_api(client, input, options \\ []) do
path_ = "/restapis?mode=import"
headers = []
{query_, input} =
[
{"failOnWarnings", "failonwarnings"},
{"parameters", ""},
]
|> AWS.Request.build_params(input)
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a customization of a `GatewayResponse` of a specified response type
and status code on the given `RestApi`.
"""
def put_gateway_response(client, response_type, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/gatewayresponses/#{URI.encode(response_type)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 201)
end
@doc """
Sets up a method's integration.
"""
def put_integration(client, http_method, resource_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/integration"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 201)
end
@doc """
Represents a put integration.
"""
def put_integration_response(client, http_method, resource_id, rest_api_id, status_code, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/integration/responses/#{URI.encode(status_code)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 201)
end
@doc """
Add a method to an existing `Resource` resource.
"""
def put_method(client, http_method, resource_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 201)
end
@doc """
Adds a `MethodResponse` to an existing `Method` resource.
"""
def put_method_response(client, http_method, resource_id, rest_api_id, status_code, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/responses/#{URI.encode(status_code)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 201)
end
@doc """
A feature of the API Gateway control service for updating an existing API
with an input of external API definitions. The update can take the form of
merging the supplied definition into the existing API or overwriting the
existing API.
"""
def put_rest_api(client, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}"
headers = []
{query_, input} =
[
{"failOnWarnings", "failonwarnings"},
{"mode", "mode"},
{"parameters", ""},
]
|> AWS.Request.build_params(input)
request(client, :put, path_, query_, headers, input, options, nil)
end
@doc """
Adds or updates a tag on a given resource.
"""
def tag_resource(client, resource_arn, input, options \\ []) do
path_ = "/tags/#{URI.encode(resource_arn)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 204)
end
@doc """
Simulate the execution of an `Authorizer` in your `RestApi` with headers,
parameters, and an incoming request body.
<div class="seeAlso"> [Use Lambda Function as
Authorizer](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html)
[Use Cognito User Pool as
Authorizer](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html)
</div>
"""
def test_invoke_authorizer(client, authorizer_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/authorizers/#{URI.encode(authorizer_id)}"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, nil)
end
@doc """
Simulate the execution of a `Method` in your `RestApi` with headers,
parameters, and an incoming request body.
"""
def test_invoke_method(client, http_method, resource_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, nil)
end
@doc """
Removes a tag from a given resource.
"""
def untag_resource(client, resource_arn, input, options \\ []) do
path_ = "/tags/#{URI.encode(resource_arn)}"
headers = []
{query_, input} =
[
{"tagKeys", "tagKeys"},
]
|> AWS.Request.build_params(input)
request(client, :delete, path_, query_, headers, input, options, 204)
end
@doc """
Changes information about the current `Account` resource.
"""
def update_account(client, input, options \\ []) do
path_ = "/account"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Changes information about an `ApiKey` resource.
"""
def update_api_key(client, api_key, input, options \\ []) do
path_ = "/apikeys/#{URI.encode(api_key)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Updates an existing `Authorizer` resource.
<div class="seeAlso">[AWS
CLI](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-authorizer.html)</div>
"""
def update_authorizer(client, authorizer_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/authorizers/#{URI.encode(authorizer_id)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Changes information about the `BasePathMapping` resource.
"""
def update_base_path_mapping(client, base_path, domain_name, input, options \\ []) do
path_ = "/domainnames/#{URI.encode(domain_name)}/basepathmappings/#{URI.encode(base_path)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Changes information about an `ClientCertificate` resource.
"""
def update_client_certificate(client, client_certificate_id, input, options \\ []) do
path_ = "/clientcertificates/#{URI.encode(client_certificate_id)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Changes information about a `Deployment` resource.
"""
def update_deployment(client, deployment_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/deployments/#{URI.encode(deployment_id)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
"""
def update_documentation_part(client, documentation_part_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/documentation/parts/#{URI.encode(documentation_part_id)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
"""
def update_documentation_version(client, documentation_version, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/documentation/versions/#{URI.encode(documentation_version)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Changes information about the `DomainName` resource.
"""
def update_domain_name(client, domain_name, input, options \\ []) do
path_ = "/domainnames/#{URI.encode(domain_name)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Updates a `GatewayResponse` of a specified response type on the given
`RestApi`.
"""
def update_gateway_response(client, response_type, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/gatewayresponses/#{URI.encode(response_type)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Represents an update integration.
"""
def update_integration(client, http_method, resource_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/integration"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Represents an update integration response.
"""
def update_integration_response(client, http_method, resource_id, rest_api_id, status_code, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/integration/responses/#{URI.encode(status_code)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Updates an existing `Method` resource.
"""
def update_method(client, http_method, resource_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Updates an existing `MethodResponse` resource.
"""
def update_method_response(client, http_method, resource_id, rest_api_id, status_code, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}/methods/#{URI.encode(http_method)}/responses/#{URI.encode(status_code)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, 201)
end
@doc """
Changes information about a model.
"""
def update_model(client, model_name, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/models/#{URI.encode(model_name)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Updates a `RequestValidator` of a given `RestApi`.
"""
def update_request_validator(client, request_validator_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/requestvalidators/#{URI.encode(request_validator_id)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Changes information about a `Resource` resource.
"""
def update_resource(client, resource_id, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/resources/#{URI.encode(resource_id)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Changes information about the specified API.
"""
def update_rest_api(client, rest_api_id, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Changes information about a `Stage` resource.
"""
def update_stage(client, rest_api_id, stage_name, input, options \\ []) do
path_ = "/restapis/#{URI.encode(rest_api_id)}/stages/#{URI.encode(stage_name)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Grants a temporary extension to the remaining quota of a usage plan
associated with a specified API key.
"""
def update_usage(client, key_id, usage_plan_id, input, options \\ []) do
path_ = "/usageplans/#{URI.encode(usage_plan_id)}/keys/#{URI.encode(key_id)}/usage"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Updates a usage plan of a given plan Id.
"""
def update_usage_plan(client, usage_plan_id, input, options \\ []) do
path_ = "/usageplans/#{URI.encode(usage_plan_id)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@doc """
Updates an existing `VpcLink` of a specified identifier.
"""
def update_vpc_link(client, vpc_link_id, input, options \\ []) do
path_ = "/vpclinks/#{URI.encode(vpc_link_id)}"
headers = []
query_ = []
request(client, :patch, path_, query_, headers, input, options, nil)
end
@spec request(AWS.Client.t(), binary(), binary(), list(), list(), map(), list(), pos_integer()) ::
{:ok, Poison.Parser.t(), Poison.Response.t()}
| {:error, Poison.Parser.t()}
| {:error, HTTPoison.Error.t()}
defp request(client, method, path, query, headers, input, options, success_status_code) do
client = %{client | service: "apigateway"}
host = build_host("apigateway", client)
url = host
|> build_url(path, client)
|> add_query(query)
additional_headers = [{"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}]
headers = AWS.Request.add_headers(additional_headers, headers)
payload = encode_payload(input)
headers = AWS.Request.sign_v4(client, method, url, headers, payload)
perform_request(method, url, payload, headers, options, success_status_code)
end
defp perform_request(method, url, payload, headers, options, nil) do
case HTTPoison.request(method, url, payload, headers, options) do
{:ok, %HTTPoison.Response{status_code: 200, body: ""} = response} ->
{:ok, response}
{:ok, %HTTPoison.Response{status_code: status_code, body: body} = response}
when status_code == 200 or status_code == 202 or status_code == 204 ->
{:ok, Poison.Parser.parse!(body, %{}), response}
{:ok, %HTTPoison.Response{body: body}} ->
error = Poison.Parser.parse!(body, %{})
{:error, error}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, %HTTPoison.Error{reason: reason}}
end
end
defp perform_request(method, url, payload, headers, options, success_status_code) do
case HTTPoison.request(method, url, payload, headers, options) do
{:ok, %HTTPoison.Response{status_code: ^success_status_code, body: ""} = response} ->
{:ok, %{}, response}
{:ok, %HTTPoison.Response{status_code: ^success_status_code, body: body} = response} ->
{:ok, Poison.Parser.parse!(body, %{}), response}
{:ok, %HTTPoison.Response{body: body}} ->
error = Poison.Parser.parse!(body, %{})
{:error, error}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, %HTTPoison.Error{reason: reason}}
end
end
defp build_host(_endpoint_prefix, %{region: "local"}) do
"localhost"
end
defp build_host(endpoint_prefix, %{region: region, endpoint: endpoint}) do
"#{endpoint_prefix}.#{region}.#{endpoint}"
end
defp build_url(host, path, %{:proto => proto, :port => port}) do
"#{proto}://#{host}:#{port}#{path}"
end
defp add_query(url, []) do
url
end
defp add_query(url, query) do
querystring = AWS.Util.encode_query(query)
"#{url}?#{querystring}"
end
defp encode_payload(input) do
if input != nil, do: Poison.Encoder.encode(input, %{}), else: ""
end
end
| 31.795642 | 171 | 0.642298 |
79b0a336873583ede7098f725c7e35ea7e789235 | 10,667 | exs | Elixir | test/lib/secretsmanger_test.exs | ex-aws/ex_aws_secretsmanager | cdc528b1eb90ada9aa7268660feb74d1389a6740 | [
"MIT",
"Unlicense"
] | 5 | 2019-05-02T19:10:02.000Z | 2021-07-13T14:58:18.000Z | test/lib/secretsmanger_test.exs | ex-aws/ex_aws_secretsmanager | cdc528b1eb90ada9aa7268660feb74d1389a6740 | [
"MIT",
"Unlicense"
] | 3 | 2018-07-25T14:37:52.000Z | 2019-02-28T16:57:23.000Z | test/lib/secretsmanger_test.exs | ex-aws/ex_aws_secretsmanager | cdc528b1eb90ada9aa7268660feb74d1389a6740 | [
"MIT",
"Unlicense"
] | 5 | 2018-06-21T22:41:55.000Z | 2021-05-26T12:08:40.000Z | defmodule ExAws.SecretsManagerTest do
use ExUnit.Case, async: true
alias ExAws.Operation.JSON
alias ExAws.SecretsManager
test "Cancel Rotating Secret" do
assert %JSON{
before_request: nil,
data: %{"SecretId" => "secret-id"},
headers: [
{"x-amz-target", "secretsmanager.CancelRotateSecret"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} = SecretsManager.cancel_rotate_secret("secret-id")
end
test "Create Secret" do
assert %JSON{
before_request: nil,
data: %{},
headers: [
{"x-amz-target", "secretsmanager.CreateSecret"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} = SecretsManager.create_secret()
end
test "Delete Secret" do
assert %JSON{
before_request: nil,
data: %{"RecoveryWindowInDays" => 5, "SecretId" => "secret-id"},
headers: [
{"x-amz-target", "secretsmanager.DeleteSecret"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} =
SecretsManager.delete_secret("secret-id", [
{:recovery_window_in_days, 5}
])
end
test "Describe Secret" do
assert %JSON{
before_request: nil,
data: %{"SecretId" => "secret-id"},
headers: [
{"x-amz-target", "secretsmanager.DescribeSecret"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} = SecretsManager.describe_secret("secret-id")
end
test "Get Random Password" do
assert %JSON{
before_request: nil,
data: %{},
headers: [
{"x-amz-target", "secretsmanager.GetRandomPassword"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} = SecretsManager.get_random_password()
end
test "Get Secret Value" do
assert %JSON{
before_request: nil,
data: %{
"SecretId" => "secret-id",
"VersionId" => "foo",
"VersionStage" => "bar"
},
headers: [
{"x-amz-target", "secretsmanager.GetSecretValue"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} =
SecretsManager.get_secret_value("secret-id", [
{:version_id, "foo"},
{:version_stage, "bar"}
])
end
test "List Secrets" do
assert %JSON{
before_request: nil,
data: %{"MaxResults" => 5, "NextToken" => "foo"},
headers: [
{"x-amz-target", "secretsmanager.ListSecrets"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} =
SecretsManager.list_secrets([
{:max_results, 5},
{:next_token, "foo"}
])
end
test "List Secret Version Ids" do
assert %JSON{
before_request: nil,
data: %{
"IncludeDeprecated" => true,
"MaxResults" => 5,
"NextToken" => "foo",
"SecretId" => "secret-id"
},
headers: [
{"x-amz-target", "secretsmanager.ListSecretVersionIds"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} =
SecretsManager.list_secret_version_ids("secret-id", [
{:include_deprecated, true},
{:max_results, 5},
{:next_token, "foo"}
])
end
test "Put Secret Value" do
assert %JSON{
before_request: nil,
data: %{
"ClientRequestToken" => "token",
"SecretBinary" => "binary",
"SecretId" => "secret-id",
"SecretString" => "string",
"VersionStages" => ["stage1", "stage2"]
},
headers: [
{"x-amz-target", "secretsmanager.PutSecretValue"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} =
SecretsManager.put_secret_value("secret-id", [
{:client_request_token, "token"},
{:secret_binary, "binary"},
{:secret_string, "string"},
{
:version_stages,
["stage1", "stage2"]
}
])
end
test "Restore Secret" do
assert %JSON{
before_request: nil,
data: %{"SecretId" => "secret-id"},
headers: [
{"x-amz-target", "secretsmanager.RestoreSecret"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} = SecretsManager.restore_secret("secret-id")
end
test "Rotate Secret" do
assert %JSON{
before_request: nil,
data: %{
"ClientRequestToken" => "token",
"RotationLambdaArn" => "rotation lambda",
"RotationRules" => [automatically_after_days: 3],
"SecretId" => "secret-id"
},
headers: [
{"x-amz-target", "secretsmanager.RotateSecret"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} =
SecretsManager.rotate_secret("secret-id", [
{:client_request_token, "token"},
{:rotation_lambda_arn, "rotation lambda"},
{:rotation_rules, [{:automatically_after_days, 3}]}
])
end
test "Tag Resource" do
assert %JSON{
before_request: nil,
data: %{
"SecretId" => "secret-id",
"Tags" => [
%{"Key" => "key1", "Value" => "value1"},
%{"Key" => "key2", "Value" => "value2"}
]
},
headers: [
{"x-amz-target", "secretsmanager.TagResource"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} =
SecretsManager.tag_resource("secret-id", [
[{:key, "key1"}, {:value, "value1"}],
[{:key, "key2"}, {:value, "value2"}]
])
end
test "Untag Resource" do
assert %JSON{
before_request: nil,
data: %{"SecretId" => "secret-id", "TagKeys" => ["key1", "key2"]},
headers: [
{"x-amz-target", "secretsmanager.UntagResource"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} = SecretsManager.untag_resource("secret-id", ["key1", "key2"])
end
test "Update Secret" do
assert %JSON{
before_request: nil,
data: %{
"ClientRequestToken" => "token",
"Description" => "description",
"KmsKeyId" => "kms key",
"SecretBinary" => "binary",
"SecretId" => "secret-id",
"SecretString" => "string"
},
headers: [
{"x-amz-target", "secretsmanager.UpdateSecret"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} =
SecretsManager.update_secret("secret-id", [
{:client_request_token, "token"},
{:description, "description"},
{:kms_key_id, "kms key"},
{:secret_binary, "binary"},
{:secret_string, "string"}
])
end
test "Update Secret Version Stage" do
assert %JSON{
before_request: nil,
data: %{
"MoveToVersionId" => "version",
"RemoveFromVersionId" => "remove",
"SecretId" => "secret-id",
"VersionStage" => "stage"
},
headers: [
{"x-amz-target", "secretsmanager.UpdateSecretVersionStage"},
{"content-type", "application/x-amz-json-1.1"}
],
http_method: :post,
parser: _,
path: "/",
service: :secretsmanager,
stream_builder: nil
} =
SecretsManager.update_secret_version_stage("secret-id", [
{:move_to_version_id, "version"},
{:remove_from_version_id, "remove"},
{:version_stage, "stage"}
])
end
end
| 32.226586 | 79 | 0.45158 |
79b0a9f8466209f89d081db1565c2801d7c54d37 | 283 | exs | Elixir | priv/repo/migrations/20210820084006_add_earned_point_resolution_time_submitted_at_to_answers.exs | nimblehq/codewar-web | 5038bc09d4fc42f6be0737857a4c053ff42463f1 | [
"MIT"
] | 2 | 2021-06-29T02:22:28.000Z | 2022-02-15T06:32:15.000Z | priv/repo/migrations/20210820084006_add_earned_point_resolution_time_submitted_at_to_answers.exs | nimblehq/codewar-web | 5038bc09d4fc42f6be0737857a4c053ff42463f1 | [
"MIT"
] | 14 | 2021-05-06T04:27:19.000Z | 2021-08-24T11:15:33.000Z | priv/repo/migrations/20210820084006_add_earned_point_resolution_time_submitted_at_to_answers.exs | nimblehq/codewar-web | 5038bc09d4fc42f6be0737857a4c053ff42463f1 | [
"MIT"
] | 1 | 2021-08-20T07:50:19.000Z | 2021-08-20T07:50:19.000Z | defmodule Codewar.Repo.Migrations.AddEarnedPointResolutionTimeSubmittedAtToAnswers do
use Ecto.Migration
def change do
alter table(:answers) do
add :earned_point, :integer
add :resolution_time, :integer
add :submitted_at, :naive_datetime
end
end
end
| 23.583333 | 85 | 0.745583 |
79b0c7c1a775e3d3e89f002a3b291117e37a0f2a | 11,124 | ex | Elixir | apps/evm/lib/evm/operation/system.ex | atoulme/mana | cff3fd96c23feaaeb9fe32df3c0d35ee6dc548a5 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | apps/evm/lib/evm/operation/system.ex | atoulme/mana | cff3fd96c23feaaeb9fe32df3c0d35ee6dc548a5 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | apps/evm/lib/evm/operation/system.ex | atoulme/mana | cff3fd96c23feaaeb9fe32df3c0d35ee6dc548a5 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | defmodule EVM.Operation.System do
alias EVM.AccountRepo
alias EVM.BlockHeaderInfo
alias EVM.{
Address,
ExecEnv,
Gas,
MachineState,
Memory,
MessageCall,
Operation,
Stack,
SubState
}
@dialyzer {:no_return, callcode: 2}
@doc """
Create a new account with associated code.
"""
@spec create(Operation.stack_args(), map()) :: Operation.op_result()
def create([value, input_offset, input_size], vm_map = %{exec_env: exec_env}) do
nonce =
AccountRepo.repo(exec_env.account_repo).get_account_nonce(
exec_env.account_repo,
exec_env.address
)
new_account_address = Address.new(exec_env.address, nonce)
create_account([value, input_offset, input_size], vm_map, new_account_address)
end
@spec create2(Operation.stack_args(), map()) :: Operation.op_result()
def create2(
[value, input_offset, input_size, salt],
vm_map = %{
exec_env: exec_env,
machine_state: machine_state
}
) do
{init_code, _machine_state} = EVM.Memory.read(machine_state, input_offset, input_size)
new_account_address = Address.new(exec_env.address, salt, init_code)
create_account([value, input_offset, input_size], vm_map, new_account_address)
end
@doc """
Message-call into an account.
Transfer `value` wei from callers account to callees account then run the code in that account.
"""
@spec call(Operation.stack_args(), Operation.vm_map()) :: Operation.op_result()
def call([call_gas, to, value, in_offset, in_size, out_offset, out_size], %{
exec_env: exec_env,
machine_state: machine_state,
sub_state: sub_state
}) do
to = Address.new(to)
{data, machine_state} = EVM.Memory.read(machine_state, in_offset, in_size)
call_gas = if value != 0, do: call_gas + Gas.callstipend(), else: call_gas
message_call = %MessageCall{
current_exec_env: exec_env,
current_machine_state: machine_state,
current_sub_state: sub_state,
output_params: {out_offset, out_size},
sender: exec_env.address,
originator: exec_env.originator,
recipient: to,
code_owner: to,
gas_price: exec_env.gas_price,
value: value,
execution_value: call_gas,
data: data,
stack_depth: exec_env.stack_depth,
static: exec_env.static,
type: :call
}
MessageCall.call(message_call)
end
@doc """
Message-call into this account with an alternative account’s code, but
persisting the current values for sender and value.
"""
@spec delegatecall(Operation.stack_args(), Operation.vm_map()) :: Operation.op_result()
def delegatecall([call_gas, to, in_offset, in_size, out_offset, out_size], %{
exec_env: exec_env,
machine_state: machine_state,
sub_state: sub_state
}) do
to = Address.new(to)
{data, machine_state} = EVM.Memory.read(machine_state, in_offset, in_size)
message_call = %MessageCall{
current_exec_env: exec_env,
current_machine_state: machine_state,
current_sub_state: sub_state,
output_params: {out_offset, out_size},
sender: exec_env.sender,
originator: exec_env.originator,
recipient: exec_env.address,
code_owner: to,
gas_price: exec_env.gas_price,
value: exec_env.value_in_wei,
execution_value: call_gas,
data: data,
stack_depth: exec_env.stack_depth,
static: exec_env.static,
type: :delegate_call
}
MessageCall.call(message_call)
end
@doc """
Static message-call into an account. Exactly equivalent to CALL except:
The argument μs[2] is replaced with 0.
"""
@spec staticcall(Operation.stack_args(), Operation.vm_map()) :: Operation.op_result()
def staticcall([call_gas, to, in_offset, in_size, out_offset, out_size], %{
exec_env: exec_env,
machine_state: machine_state,
sub_state: sub_state
}) do
to = Address.new(to)
{data, machine_state} = EVM.Memory.read(machine_state, in_offset, in_size)
message_call = %MessageCall{
current_exec_env: exec_env,
current_machine_state: machine_state,
current_sub_state: sub_state,
output_params: {out_offset, out_size},
sender: exec_env.address,
originator: exec_env.originator,
recipient: to,
code_owner: to,
gas_price: exec_env.gas_price,
value: 0,
execution_value: call_gas,
data: data,
stack_depth: exec_env.stack_depth,
static: true,
type: :static_call
}
MessageCall.call(message_call)
end
@doc """
Exactly equivalent to `call` except the recipient is in fact the same account as at present, simply that the code is overwritten.
## Examples
iex> account_repo = EVM.Mock.MockAccountRepo.new(%{})
iex> exec_env = %EVM.ExecEnv{
...> account_repo: account_repo,
...> sender: <<0::160>>,
...> address: <<5::160>>
...> }
iex> machine_state = %EVM.MachineState{gas: 100000}
iex> %{machine_state: machine_state} =
...> EVM.Operation.System.callcode([10, 1, 1, 0, 0, 0, 0],
...> %{exec_env: exec_env, machine_state: machine_state, sub_state: EVM.SubState.empty()})
iex> EVM.Stack.peek(machine_state.stack)
0
"""
@spec callcode(Operation.stack_args(), Operation.vm_map()) :: Operation.op_result()
def callcode(
[call_gas, to, value, in_offset, in_size, out_offset, out_size],
%{exec_env: exec_env, machine_state: machine_state, sub_state: sub_state}
) do
to = Address.new(to)
{data, machine_state} = EVM.Memory.read(machine_state, in_offset, in_size)
call_gas = if value != 0, do: call_gas + Gas.callstipend(), else: call_gas
message_call = %MessageCall{
current_exec_env: exec_env,
current_machine_state: machine_state,
current_sub_state: sub_state,
output_params: {out_offset, out_size},
sender: exec_env.address,
originator: exec_env.originator,
recipient: exec_env.address,
code_owner: to,
gas_price: exec_env.gas_price,
value: value,
execution_value: call_gas,
data: data,
stack_depth: exec_env.stack_depth,
static: exec_env.static,
type: :callcode
}
MessageCall.call(message_call)
end
@doc """
Halt execution returning output data,
## Examples
iex> EVM.Operation.System.return([5, 33], %{machine_state: %EVM.MachineState{active_words: 0}})
%EVM.MachineState{active_words: 2}
iex> EVM.Operation.System.return([5, 33], %{machine_state: %EVM.MachineState{active_words: 5}})
%EVM.MachineState{active_words: 5}
"""
@spec return(Operation.stack_args(), Operation.vm_map()) :: Operation.op_result()
def return([_mem_start, mem_end], %{machine_state: machine_state}) do
words = Memory.get_active_words(mem_end)
MachineState.maybe_set_active_words(machine_state, words)
end
@doc """
We handle revert op code in Functions.is_normal_halting?/2 method. Here it's noop. We only pay for the memory.
"""
@spec revert(Operation.stack_args(), Operation.vm_map()) :: Operation.op_result()
def revert([_mem_start, mem_end], %{machine_state: machine_state}) do
words = Memory.get_active_words(mem_end)
MachineState.maybe_set_active_words(machine_state, words)
end
@doc """
Halt execution and register account for later deletion.
Transfers `value` wei from callers account to the "refund account".
Defined as SELFDESTRUCT in the Yellow Paper.
Note:
There was a consensus issue at some point (see Quirk #2 in
http://martin.swende.se/blog/Ethereum_quirks_and_vulns.html). There is one
test case witnessing the current consensus
`GeneralStateTests/stSystemOperationsTest/suicideSendEtherPostDeath.json`.
"""
@spec selfdestruct(Operation.stack_args(), Operation.vm_map()) :: Operation.op_result()
def selfdestruct([refund_address], %{exec_env: exec_env, sub_state: sub_state}) do
to = Address.new(refund_address)
new_exec_env =
exec_env
|> ExecEnv.transfer_balance_to(to)
|> ExecEnv.clear_account_balance()
new_substate =
sub_state
|> SubState.mark_account_for_destruction(exec_env.address)
|> SubState.add_touched_account(to)
%{exec_env: new_exec_env, sub_state: new_substate}
end
@spec create_account(Operation.stack_args(), map(), Address.t()) :: Operation.op_result()
defp create_account(
[value, input_offset, input_size],
%{
exec_env: exec_env,
machine_state: machine_state,
sub_state: sub_state
},
new_account_address
) do
{data, machine_state} = EVM.Memory.read(machine_state, input_offset, input_size)
account_balance =
AccountRepo.repo(exec_env.account_repo).get_account_balance(
exec_env.account_repo,
exec_env.address
)
block_header = BlockHeaderInfo.block_header(exec_env.block_header_info)
is_allowed =
value <= account_balance and exec_env.stack_depth < EVM.Functions.max_stack_depth()
available_gas =
if exec_env.config.should_fail_nested_operation_lack_of_gas do
machine_state.gas
else
EVM.Helpers.all_but_one_64th(machine_state.gas)
end
remaining_gas = machine_state.gas - available_gas
{status, {updated_account_repo, n_gas, n_sub_state, output}} =
if is_allowed do
account_repo =
AccountRepo.repo(exec_env.account_repo).increment_account_nonce(
exec_env.account_repo,
exec_env.address
)
n_exec_env = %{exec_env | account_repo: account_repo}
AccountRepo.repo(exec_env.account_repo).create_contract(
n_exec_env.account_repo,
# sender
n_exec_env.address,
# originator
n_exec_env.originator,
# available_gas
available_gas,
# gas_price
n_exec_env.gas_price,
# endowment
value,
# init_code
data,
# stack_depth
n_exec_env.stack_depth + 1,
# block_header
block_header,
new_account_address,
exec_env.config
)
else
{:error, {exec_env.account_repo, available_gas, SubState.empty(), <<>>}}
end
# Note if was exception halt or other failure on stack
new_address =
if status == :ok do
new_account_address
else
<<0>>
end
new_address_for_machine_state = :binary.decode_unsigned(new_address)
machine_state = %{
machine_state
| stack: Stack.push(machine_state.stack, new_address_for_machine_state),
gas: n_gas + remaining_gas,
last_return_data: output
}
exec_env = %{exec_env | account_repo: updated_account_repo}
sub_state =
sub_state
|> SubState.merge(n_sub_state)
|> SubState.add_touched_account(new_address)
%{
machine_state: machine_state,
exec_env: exec_env,
sub_state: sub_state
}
end
end
| 31.247191 | 132 | 0.668195 |
79b0e35c63c958e90b4c1c15ecbc0524ae27bde0 | 720 | exs | Elixir | apps/elixir_ls_debugger/mix.exs | E14/elixir-ls | bfa468117d853a30e36e2d3009b7b755e2fca6bf | [
"Apache-2.0"
] | null | null | null | apps/elixir_ls_debugger/mix.exs | E14/elixir-ls | bfa468117d853a30e36e2d3009b7b755e2fca6bf | [
"Apache-2.0"
] | null | null | null | apps/elixir_ls_debugger/mix.exs | E14/elixir-ls | bfa468117d853a30e36e2d3009b7b755e2fca6bf | [
"Apache-2.0"
] | null | null | null | defmodule ElixirLS.Debugger.Mixfile do
use Mix.Project
def project do
[
app: :elixir_ls_debugger,
version: "0.6.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: ">= 1.8.0",
build_embedded: false,
start_permanent: true,
build_per_environment: false,
consolidate_protocols: false,
deps: deps()
]
end
def application do
[mod: {ElixirLS.Debugger, []}, extra_applications: [:mix, :logger, :debugger]]
end
defp deps do
[
{:elixir_sense, github: "elixir-lsp/elixir_sense"},
{:elixir_ls_utils, in_umbrella: true}
]
end
end
| 22.5 | 82 | 0.594444 |
79b0f0ddef9d75ba1f126d3cd384effefaf870f9 | 581 | exs | Elixir | config/config.exs | 0nkery/vigilant-octo-memory | 25d7e7e35ba4c433339d3fb23edf2bef8d471d98 | [
"MIT"
] | null | null | null | config/config.exs | 0nkery/vigilant-octo-memory | 25d7e7e35ba4c433339d3fb23edf2bef8d471d98 | [
"MIT"
] | 5 | 2018-10-29T10:10:15.000Z | 2021-06-25T15:15:48.000Z | config/config.exs | 0nkery/vigilant-octo-memory | 25d7e7e35ba4c433339d3fb23edf2bef8d471d98 | [
"MIT"
] | null | null | null | use Mix.Config
config :twitter_feed, TwitterFeed.Repo,
adapter: Ecto.Adapters.Postgres,
database: "twitter_feed_repo",
username: "postgres",
password: "pass",
hostname: "db",
pool_size: 8
config :twitter_feed,
ecto_repos: [TwitterFeed.Repo],
twitter_client: TwitterFeed.TwitterClient
config :twittex,
consumer_key: System.get_env("TWITTER_CONSUMER_KEY"),
consumer_secret: System.get_env("TWITTER_CONSUMER_SECRET"),
token: System.get_env("TWITTER_OWNER_TOKEN"),
token_secret: System.get_env("TWITTER_OWNER_TOKEN_SECRET")
import_config "#{Mix.env()}.exs"
| 26.409091 | 61 | 0.765921 |
79b105088df3fcf985785b275e0f1ea8b5f0fb39 | 10,032 | exs | Elixir | test/unit/storage_migrator_test.exs | szTheory/ecto_mnesia | 9d1fd3b2845ac3c2c12c669d68198dff9e82a322 | [
"MIT"
] | 245 | 2016-10-22T14:43:36.000Z | 2022-02-28T03:46:27.000Z | test/unit/storage_migrator_test.exs | KushanChamindu/ecto_mnesia | bc0fb46d210eb1be63bcc8f0383212f0633b8c52 | [
"MIT"
] | 80 | 2016-10-22T16:09:19.000Z | 2021-03-03T10:45:01.000Z | test/unit/storage_migrator_test.exs | KushanChamindu/ecto_mnesia | bc0fb46d210eb1be63bcc8f0383212f0633b8c52 | [
"MIT"
] | 53 | 2016-12-03T14:23:05.000Z | 2021-07-01T01:55:22.000Z | defmodule EctoMnesia.Storage.MigratorTest do
use ExUnit.Case, async: true
require Logger
alias :mnesia, as: Mnesia
alias Ecto.Migration.{Table, Index}
alias EctoMnesia.Storage.Migrator
alias EctoMnesia.Table, as: MnesiaTable
@test_table_name :migration_test_table
@test_record_key 1
defp run_migration(migration) do
Migrator.execute(TestRepo, migration, [])
end
defp get_attributes do
@test_table_name |> Mnesia.table_info(:attributes)
end
defp get_indexes do
@test_table_name |> Mnesia.table_info(:index)
end
defp get_record do
@test_table_name |> MnesiaTable.get(@test_record_key)
end
setup do
Mnesia.delete_table(@test_table_name)
:ok
end
describe "create table" do
test "when table does not exist" do
assert :ok ==
run_migration({
:create,
%Table{name: @test_table_name},
[{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]
})
assert [:id, :my_field] == get_attributes()
end
test "when table exists" do
migration =
{:create, %Table{name: @test_table_name}, [{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]}
run_migration(migration)
assert_raise RuntimeError, "Table migration_test_table already exists", fn ->
run_migration(migration)
end
end
end
describe "create table if not exists" do
test "when table does not exist" do
assert :ok ==
run_migration({
:create_if_not_exists,
%Table{name: @test_table_name},
[{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]
})
assert [:id, :my_field] == get_attributes()
end
test "when table exists" do
migration =
{:create_if_not_exists, %Table{name: @test_table_name},
[{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]}
assert :ok == run_migration(migration)
assert :ok == run_migration(migration)
assert [:id, :my_field] == get_attributes()
end
end
describe "alter table" do
test "when table does not exist" do
migration = {:alter, %Table{name: @test_table_name}, [{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]}
assert_raise RuntimeError, "Table migration_test_table does not exists", fn ->
run_migration(migration)
end
end
test "when table exists" do
migration =
{:create, %Table{name: @test_table_name}, [{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]}
run_migration(migration)
assert :ok ==
run_migration({
:alter,
%Table{name: @test_table_name},
[{:add, :new_field, :integer, []}, {:add, :my_second_field, :integer, []}]
})
assert [:id, :my_field, :new_field, :my_second_field] == get_attributes()
end
end
describe "alter table fields" do
setup do
run_migration({
:create,
%Table{name: @test_table_name},
[{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]
})
MnesiaTable.insert(@test_table_name, {@test_table_name, @test_record_key, 123})
:ok
end
test "add field" do
run_migration({
:alter,
%Table{name: @test_table_name},
[{:add, :new_field, :integer, []}]
})
assert [:id, :my_field, :new_field] == get_attributes()
assert {:migration_test_table, 1, 123, nil} == get_record()
end
test "add duplicate field" do
assert_raise RuntimeError, "Duplicate field my_field", fn ->
run_migration({
:alter,
%Table{name: @test_table_name},
[{:add, :my_field, :integer, []}]
})
end
assert [:id, :my_field] == get_attributes()
assert {:migration_test_table, 1, 123} == get_record()
end
test "modify field" do
assert :ok == run_migration({:alter, %Table{name: @test_table_name}, [{:modify, :id, :string, []}]})
assert [:id, :my_field] == get_attributes()
assert {:migration_test_table, 1, 123} == get_record()
end
test "modify not existing field" do
assert_raise RuntimeError, "Field unknown_field not found", fn ->
assert :ok ==
run_migration({
:alter,
%Table{name: @test_table_name},
[{:modify, :unknown_field, :string, []}]
})
end
assert [:id, :my_field] == get_attributes()
assert {:migration_test_table, 1, 123} == get_record()
end
test "rename field" do
assert :ok == run_migration({:rename, %Table{name: @test_table_name}, :id, :new_id})
assert [:new_id, :my_field] == get_attributes()
assert {:migration_test_table, 1, 123} == get_record()
end
test "rename not existing field" do
assert_raise RuntimeError, "Field unknown_field not found", fn ->
assert :ok ==
run_migration({
:alter,
%Table{name: @test_table_name},
[{:modify, :unknown_field, :string, []}]
})
end
assert [:id, :my_field] == get_attributes()
assert {:migration_test_table, 1, 123} == get_record()
end
test "delete field" do
run_migration({:alter, %Table{name: @test_table_name}, [{:add, :new_field, :integer, []}]})
assert {:migration_test_table, 1, 123, nil} == get_record()
assert :ok ==
run_migration({
:alter,
%Table{name: @test_table_name},
[{:remove, :new_field}]
})
assert [:id, :my_field] == get_attributes()
assert {:migration_test_table, 1, 123} == get_record()
end
test "delete not existing field" do
assert_raise RuntimeError, "Field unknown_field not found", fn ->
assert :ok == run_migration({:alter, %Table{name: @test_table_name}, [{:remove, :unknown_field}]})
end
assert [:id, :my_field] == get_attributes()
assert {:migration_test_table, 1, 123} == get_record()
end
end
describe "drop table" do
test "when table does not exist" do
assert_raise RuntimeError, "Table migration_test_table does not exists", fn ->
assert :ok == run_migration({:drop, %Table{name: @test_table_name}})
end
end
test "when table exists" do
migration =
{:create, %Table{name: @test_table_name}, [{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]}
run_migration(migration)
assert :ok == run_migration({:drop, %Table{name: @test_table_name}})
end
end
describe "drop table if exists" do
test "when table does not exist" do
assert :ok == run_migration({:drop_if_exists, %Table{name: @test_table_name}})
end
test "when table exists" do
migration =
{:create, %Table{name: @test_table_name}, [{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]}
run_migration(migration)
assert :ok == run_migration({:drop_if_exists, %Table{name: @test_table_name}})
end
end
describe "create index" do
setup do
run_migration(
{:create, %Table{name: @test_table_name}, [{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]}
)
end
test "when index does not exist" do
assert [:ok] == run_migration({:create, %Index{table: @test_table_name, columns: [:my_field]}})
assert [3] == get_indexes()
end
test "when index exists" do
run_migration({:create, %Index{table: @test_table_name, columns: [:my_field]}})
assert_raise RuntimeError, "Index for field my_field in table migration_test_table already exists", fn ->
run_migration({:create, %Index{table: @test_table_name, columns: [:my_field]}})
end
assert [3] == get_indexes()
end
end
describe "create index if not exists" do
setup do
run_migration(
{:create, %Table{name: @test_table_name}, [{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]}
)
end
test "when index does not exist" do
assert [:ok] == run_migration({:create_if_not_exists, %Index{table: @test_table_name, columns: [:my_field]}})
assert [3] == get_indexes()
end
test "when index exists" do
assert [:ok] == run_migration({:create_if_not_exists, %Index{table: @test_table_name, columns: [:my_field]}})
assert [:ok] == run_migration({:create_if_not_exists, %Index{table: @test_table_name, columns: [:my_field]}})
assert [3] == get_indexes()
end
end
describe "drop index" do
setup do
run_migration(
{:create, %Table{name: @test_table_name}, [{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]}
)
end
test "when index does not exist" do
assert_raise RuntimeError, "Index for field my_field in table migration_test_table does not exists", fn ->
run_migration({:drop, %Index{table: @test_table_name, columns: [:my_field]}})
end
end
test "when index exists" do
run_migration({:create, %Index{table: @test_table_name, columns: [:my_field]}})
assert [:ok] = run_migration({:drop, %Index{table: @test_table_name, columns: [:my_field]}})
assert [] == get_indexes()
end
end
describe "drop index if exists" do
setup do
run_migration(
{:create, %Table{name: @test_table_name}, [{:add, :id, :integer, []}, {:add, :my_field, :integer, []}]}
)
end
test "when index does not exist" do
assert [:ok] = run_migration({:drop_if_exists, %Index{table: @test_table_name, columns: [:my_field]}})
end
test "when index exists" do
run_migration({:create, %Index{table: @test_table_name, columns: [:my_field]}})
assert [:ok] = run_migration({:drop_if_exists, %Index{table: @test_table_name, columns: [:my_field]}})
assert [] == get_indexes()
end
end
end
| 30.962963 | 120 | 0.592703 |
79b11172ec838ed4b58ee772ab3a5d8c797b9c09 | 889 | ex | Elixir | banking_challenge_stone_umbrella/apps/banking_challenge/lib/banking_challenge/transactions/schemas/transaction.ex | douxsalemk/banking_challenge_stone | 59c2790a0f14b68c2b25851c806ebc553227316d | [
"Apache-2.0"
] | null | null | null | banking_challenge_stone_umbrella/apps/banking_challenge/lib/banking_challenge/transactions/schemas/transaction.ex | douxsalemk/banking_challenge_stone | 59c2790a0f14b68c2b25851c806ebc553227316d | [
"Apache-2.0"
] | null | null | null | banking_challenge_stone_umbrella/apps/banking_challenge/lib/banking_challenge/transactions/schemas/transaction.ex | douxsalemk/banking_challenge_stone | 59c2790a0f14b68c2b25851c806ebc553227316d | [
"Apache-2.0"
] | null | null | null | defmodule BankingChallenge.Transactions.Schemas.Transaction do
@moduledoc """
Database schema representation of transaction table
"""
use Ecto.Schema
alias BankingChallenge.Accounts.Schemas.Account
import Ecto.Changeset
@required_fields [:from_account_id, :amount]
@optional_fields [:to_account_id]
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "transaction" do
field :amount, :integer
belongs_to :from_account, Account
belongs_to :to_account, Account
timestamps()
end
@doc """
Generate a changeset for create a new transaction
"""
def changeset(params) when is_map(params) do
%__MODULE__{}
|> cast(params, @required_fields ++ @optional_fields)
|> validate_required(@required_fields)
|> check_constraint(:transaction, name: :amount_must_be_greater_then_or_equal)
end
end
| 22.794872 | 82 | 0.737908 |
79b12977d5f77b0fcb8642c89aaaf8cb66541f89 | 6,710 | exs | Elixir | apps/admin_api/test/admin_api/v1/controllers/balance_controller_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 322 | 2018-02-28T07:38:44.000Z | 2020-05-27T23:09:55.000Z | apps/admin_api/test/admin_api/v1/controllers/balance_controller_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 643 | 2018-02-28T12:05:20.000Z | 2020-05-22T08:34:38.000Z | apps/admin_api/test/admin_api/v1/controllers/balance_controller_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 63 | 2018-02-28T10:57:06.000Z | 2020-05-27T23:10:38.000Z | # Copyright 2018-2019 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule AdminAPI.V1.BalanceControllerTest do
use AdminAPI.ConnCase, async: true
alias EWalletDB.{Account, Token, User}
describe "/wallet.get_balances" do
test_with_auths "returns a list of balances and pagination data when given an existing wallet address" do
user_wallet = prepare_user_wallet()
[omg, btc, _abc] = prepare_balances(user_wallet, [100, 200, 300])
attrs = %{
"sort_by" => "inserted_at",
"sort_dir" => "asc",
"per_page" => 2,
"start_after" => nil,
"start_by" => "id",
"address" => user_wallet.address
}
response = request("/wallet.get_balances", attrs)
token_ids = map_tokens_field(response, "id")
assert response["success"] == true
assert response["data"]["pagination"]["count"] == 2
assert token_ids == [omg.id, btc.id]
end
test_with_auths "returns a list of balances and pagination data after given 'token_id'" do
user_wallet = prepare_user_wallet()
[omg, btc, _abc] = prepare_balances(user_wallet, [100, 200, 300])
attrs = %{
"sort_by" => "inserted_at",
"sort_dir" => "asc",
"per_page" => 1,
"start_after" => omg.id,
"start_by" => "id",
"address" => user_wallet.address
}
response = request("/wallet.get_balances", attrs)
token_ids = map_tokens_field(response, "id")
assert response["success"] == true
assert token_ids == [btc.id]
end
test_with_auths "returns a list of balances with correct amount" do
user_wallet = prepare_user_wallet()
[omg, btc, eth] = prepare_balances(user_wallet, [100, 200, 300])
attrs = %{
"sort_by" => "inserted_at",
"sort_dir" => "asc",
"per_page" => 3,
"start_after" => nil,
"start_by" => "id",
"address" => user_wallet.address
}
response = request("/wallet.get_balances", attrs)
amounts = map_balances_field(response, "amount")
token_ids = map_tokens_field(response, "id")
[omg_subunit, btc_subunit, eth_subunit] = map_tokens_field(response, "subunit_to_unit")
assert response["success"] == true
assert token_ids == [omg.id, btc.id, eth.id]
assert amounts == [100 * omg_subunit, 200 * btc_subunit, 300 * eth_subunit]
end
test_with_auths "returns :error when given non-existing wallet address" do
user_wallet = prepare_user_wallet()
prepare_balances(user_wallet, [100, 200, 300])
attrs = %{
"sort_by" => "inserted_at",
"sort_dir" => "asc",
"start_after" => nil,
"start_by" => "id",
"address" => "qwertyuiop"
}
response = request("/wallet.get_balances", attrs)
assert response["success"] == false
assert response["data"]["code"] == "unauthorized"
assert response["data"]["description"] ==
"You are not allowed to perform the requested operation."
end
test_with_auths "returns :error when missing wallet address" do
attrs = %{
"sort_by" => "inserted_at",
"sort_dir" => "asc",
"start_after" => nil,
"start_by" => "id"
}
response = request("/wallet.get_balances", attrs)
assert response["success"] == false
assert response["data"]["code"] == "client:invalid_parameter"
assert response["data"]["description"] ==
"Invalid parameter provided. `address` is required."
end
test_with_auths "returns :error when querying with a prohibited field" do
user_wallet = prepare_user_wallet()
[_omg, _btc, _eth] = prepare_balances(user_wallet, [100, 200, 300])
attrs = %{
"sort_by" => "inserted_at",
"sort_dir" => "asc",
"start_after" => nil,
"start_by" => "subunit_to_unit",
"address" => user_wallet.address
}
response = request("/wallet.get_balances", attrs)
assert response["success"] == false
assert response["data"]["code"] == "client:invalid_parameter"
assert response["data"]["description"] ==
"start_by: `subunit_to_unit` is not allowed. " <>
"The available fields are: [id, inserted_at, updated_at]"
end
test_with_auths "returns :error when querying with a non-existing field" do
user_wallet = prepare_user_wallet()
[_omg, _btc, _eth] = prepare_balances(user_wallet, [100, 200, 300])
attrs = %{
"sort_by" => "inserted_at",
"sort_dir" => "asc",
"start_after" => nil,
"start_by" => "not_exists",
"address" => user_wallet.address
}
response = request("/wallet.get_balances", attrs)
assert response["success"] == false
assert response["data"]["code"] == "client:invalid_parameter"
assert response["data"]["description"] ==
"start_by: `not_exists` is not allowed. " <>
"The available fields are: [id, inserted_at, updated_at]"
end
end
# number of created tokens == number of given amounts
defp prepare_balances(user_wallet, amounts) do
account = Account.get_master_account()
master_wallet = Account.get_primary_wallet(account)
amounts
|> Enum.reduce([], fn amount, acc ->
[do_prepare_balances(master_wallet, user_wallet, amount) | acc]
end)
|> Enum.reverse()
end
defp do_prepare_balances(master_wallet, user_wallet, amount) do
# Create and mint token
{:ok, token} = :token |> params_for() |> Token.insert()
mint!(token)
# Transfer balance from master_wallet to user_wallet by given amount
transfer!(master_wallet.address, user_wallet.address, token, amount * token.subunit_to_unit)
token
end
defp prepare_user_wallet do
{:ok, user} = :user |> params_for() |> User.insert()
User.get_primary_wallet(user)
end
defp map_tokens_field(response, field) do
Enum.map(response["data"]["data"], fn balance -> balance["token"][field] end)
end
defp map_balances_field(response, field) do
Enum.map(response["data"]["data"], fn balance -> balance[field] end)
end
end
| 31.800948 | 109 | 0.630104 |
79b16847cb43961151c4f7ad20d947842a2e2324 | 11,338 | ex | Elixir | lib/logical_file.ex | mmower/logical_file | 333756092360d36201ceff73df4a94faf5ff3402 | [
"Apache-2.0"
] | null | null | null | lib/logical_file.ex | mmower/logical_file | 333756092360d36201ceff73df4a94faf5ff3402 | [
"Apache-2.0"
] | null | null | null | lib/logical_file.ex | mmower/logical_file | 333756092360d36201ceff73df4a94faf5ff3402 | [
"Apache-2.0"
] | null | null | null | defmodule LogicalFile do
alias LogicalFile.{Macro, Section}
@moduledoc """
## LogicalFile
### One file from many
LogicalFile is a way of creating a logical representation of a unit of lines
of text (e.g. a source code file) supplied by one or more backing files,
presumably separate files on disk. It also provides for a system of macros
that can transform the logical text.
A typical use case for LogicalFile would be to implement a compiler that has
`#include` style functionality. The compiler works on the whole text but
can translate logical line numbers back to specific files and local line
numbers (for example when an error occurs it can pinpoint the specific file
and line the error arose in).
"""
defstruct base_path: nil,
sections: %{}
@type t :: %__MODULE__{
base_path: nil | binary,
sections: map
}
# --- Interface ---
@doc """
`read/3` returns a new `LogicalFile` containing `Section`s that
represent the contents of the file specified by `source_path` relative to
`base_path` and as modified by the macros it is initialised with.
Macros should implement the `LogicalFile.Macro` behaviours and should be
specified as a list of tuples of the form `{module, [options keyword list]}`.
See `LogicalFile.Macro` for further details.
## Examples
iex> file = LogicalFile.read("test/support", "main.source")
iex> assert 11 = LogicalFile.size(file)
"""
def read(base_path, source_path, macros \\ [])
when is_binary(source_path) and is_list(macros) do
base_path = Path.expand(base_path)
file_path = Path.join(base_path, source_path)
section = Section.new(file_path)
%LogicalFile{base_path: base_path, sections: %{section.range => section}}
|> Macro.apply_macros(macros)
end
@doc """
`assemble/2` returns a `LogicalFile` composed of the `Section`s specified in
the second argument. This is mainly intended for internal use when modifying
a `LogicalFile` during macro processing.
"""
def assemble(base_path, sections) when is_list(sections) do
sections
|> Enum.map(fn %Section{range: range} -> range end)
|> check_contiguous()
%LogicalFile{
base_path: base_path,
sections: sections |> Enum.map(fn section -> {section.range, section} end) |> Enum.into(%{})
}
end
defp check_contiguous(range_list) do
pairs = Enum.zip([nil | range_list], range_list ++ [nil])
Enum.each(pairs, fn {r1, r2} ->
case {r1, r2} do
{nil, _} -> nil
{_, nil} -> nil
{_..hi, lo.._} when lo == hi + 1 -> nil
{r1, r2} -> raise "Non-contiguous ranges #{inspect(r1)} & #{inspect(r2)}!"
end
end)
end
@doc """
`line/2` returns the specified logical line number from the `LogicalFile`
at `lno`.
## Example
iex> file = LogicalFile.read("test/support", "main.source")
iex> assert "%(include.source)" = LogicalFile.line(file, 6)
"""
def line(%LogicalFile{} = file, lno) do
with section when not is_nil(section) <- section_including_line(file, lno) do
Section.line(section, lno)
end
end
@doc """
`lines/2` takes a `LogicalFile` and a range of logical line numbers and
returns a list of tuples in the form `{file, line}` for the corresponding
lines.
"""
def lines(%LogicalFile{} = file, logical_line_range)
when is_struct(logical_line_range, Range) do
logical_line_range
|> Enum.reduce([], fn logical_lno, lines ->
[line(file, logical_lno) | lines]
end)
|> Enum.reverse()
end
@doc """
`insert/3` inserts a new `Section` into the `LogicalFile` at the specified
logical line number `at_line` and containing the contents of the `source_path`.
It guarantees that all sections and the logical file remains contiguous.
## Examples
"""
def insert(%LogicalFile{base_path: base_path} = file, source_path, at_line)
when is_binary(source_path) do
insert(file, Section.new(Path.join(base_path, source_path)), at_line)
end
def insert(
%LogicalFile{base_path: base_path, sections: sections},
%Section{} = insert_section,
at_line
) do
sections = Map.values(sections)
{before, target, rest} = partition_sections(sections, at_line)
if is_nil(target) do
raise("Unable to partition: line:#{at_line} is not in any source section.")
else
sections =
case split_strategy(target, at_line) do
:prepend ->
insert_section = Section.shift(insert_section, Section.total_size(before))
rest = [target | rest]
rest =
Enum.map(rest, fn section ->
Section.shift(section, Section.size(insert_section))
end)
before ++ [insert_section] ++ rest
:append ->
before = before ++ [target]
insert_section = Section.shift(insert_section, Section.total_size(before))
rest =
Enum.map(rest, fn section ->
Section.shift(section, Section.size(insert_section))
end)
before ++ [insert_section] ++ rest
:insert ->
{pre, post} = Section.split(target, at_line)
before = before ++ [pre]
insert_section = Section.shift(insert_section, Section.total_size(before))
rest = [post | rest]
rest =
Enum.map(rest, fn section ->
Section.shift(section, Section.size(insert_section))
end)
before ++ [insert_section] ++ rest
end
LogicalFile.assemble(base_path, sections)
end
end
defp split_strategy(%Section{range: lo..lo}, _), do: :append
defp split_strategy(%Section{range: lo.._}, lo), do: :prepend
defp split_strategy(%Section{range: _..hi}, hi), do: :append
defp split_strategy(%Section{}, _), do: :insert
@doc """
`contains_source?/2` returns true if at least one section from the given
`LogicalFile` originates from the specified `source_path`.
## Examples
iex> file = LogicalFile.read("test/support", "main.source")
iex> invalid_path = Path.expand("test/support/player.source")
iex> assert not LogicalFile.contains_source?(file, invalid_path)
iex> valid_path = Path.expand("test/support/main.source")
iex> assert LogicalFile.contains_source?(file, valid_path)
"""
def contains_source?(%LogicalFile{sections: sections}, source_path) do
Enum.any?(sections, fn {_range, section} -> section.source_path == source_path end)
end
@doc """
`lines/1` returns a list of all lines in the `LogicalFile` in line number
order.
"""
def lines(%LogicalFile{} = file) do
file
|> sections_in_order()
|> Enum.reduce([], fn section, lines -> lines ++ section.lines end)
end
@doc """
`size/1` returns the number of lines in the `LogicalFile`.
## Examples
iex> file = LogicalFile.read("test/support", "main.source")
iex> 11 = LogicalFile.size(file)
"""
def size(%LogicalFile{sections: sections}) do
Enum.reduce(sections, 0, fn {_range, section}, size ->
size + Section.size(section)
end)
end
@doc """
`last_line_number/1` returns the line number of the last line in the
specified `LogicalFile`.
## Examples
iex> alias LogicalFile.Section
iex> file = LogicalFile.read("test/support", "main.source")
iex> assert 11 = LogicalFile.last_line_number(file)
"""
def last_line_number(%LogicalFile{} = file) do
file
|> sections_in_order()
|> List.last()
|> then(fn %Section{range: _lo..hi} -> hi end)
end
@doc """
`update_line/3` replaces the content of line `lno` in the specified
`LogicalFile` by passing the current contents of the line to the specified
transformation function. This function is expected to return the new
contents of the line.
## Examples
iex> assert " " =
...> LogicalFile.read("test/support", "main.source")
...> |> LogicalFile.update_line(6, fn line -> String.duplicate(" ", String.length(line)) end)
...> |> LogicalFile.line(6)
"""
def update_line(%LogicalFile{sections: sections} = file, lno, fun) do
updated_section =
file
|> section_including_line(lno)
|> Section.update_line(lno, fun)
%{file | sections: Map.put(sections, updated_section.range, updated_section)}
end
@doc """
`section_including_line/2` returns the `Section` that contains the logical
line `lno`.
## Examples
iex> alias LogicalFile.Section
iex> section1 = Section.new("test/support/main.source")
iex> section2 = Section.new("test/support/include.source") |> Section.shift(Section.size(section1))
iex> map = LogicalFile.assemble("test/support", [section1, section2])
iex> assert ^section1 = LogicalFile.section_including_line(map, section1.range.first)
iex> assert ^section2 = LogicalFile.section_including_line(map, section2.range.first)
"""
def section_including_line(%LogicalFile{} = file, lno) do
file
|> sections_in_order()
|> Enum.find(fn %{range: range} -> lno in range end)
end
@doc """
`resolve_line/2` takes a logical line number `logical_lno` and returns a
tuple `{file, local_line_no}` representing the file and file line number
that logical line represents.
## Examples
iex> alias LogicalFile.Macros.Include
iex> file = LogicalFile.read("test/support", "main.source")
iex> path = Path.expand("test/support/main.source")
iex> assert {^path, 1} = LogicalFile.resolve_line(file, 1)
"""
def resolve_line(%LogicalFile{} = file, logical_lno) do
file
|> section_including_line(logical_lno)
|> Section.resolve_line(logical_lno)
end
# --- Utility functions ---
@doc """
`sections_to_map/1` takes a list of `Section`s and returns a `Map` whose
keys are the logical line number ranges of the sections, mapped to the
corresponding sections.
"""
def sections_to_map(sections) do
Enum.reduce(sections, %{}, fn section, map ->
Map.put(map, section.range, section)
end)
end
@doc """
`sections_in_order/1` takes the `Section`s backing a `LogicalFile` and
returns them as a list, ordered by the range of logical line numbers they
represent.
"""
def sections_in_order(%LogicalFile{sections: sections}) do
sections
|> Map.values()
|> Enum.sort_by(fn %Section{range: range} -> range end)
end
@doc """
`partition_sections/2` accepts a list of `Section`s and a logical
line number `at_line` representing an insertion point. It returns a tuple
`{sections_before, insert_section, sections_after}` by finding the `Section`
containing `at_line` and partitioning the remaining `Section`s around it.
"""
def partition_sections(sections, at_line) when is_list(sections) do
sections
|> Enum.sort_by(fn section -> section.range end)
|> Enum.split_while(fn section -> at_line not in section.range end)
|> then(fn split ->
case split do
{_, []} -> {sections, nil, []}
{before, [target | rest]} -> {before, target, rest}
end
end)
end
end
defimpl String.Chars, for: LogicalFile do
def to_string(%LogicalFile{} = file) do
file
|> LogicalFile.lines()
|> Enum.join("\n")
end
end
| 33.152047 | 105 | 0.656553 |
79b181a317c3eea4e85515ded9a0e5702525f410 | 1,811 | ex | Elixir | clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/segment_definition.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/segment_definition.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/segment_definition.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.AnalyticsReporting.V4.Model.SegmentDefinition do
@moduledoc """
SegmentDefinition defines the segment to be a set of SegmentFilters which
are combined together with a logical `AND` operation.
## Attributes
* `segmentFilters` (*type:* `list(GoogleApi.AnalyticsReporting.V4.Model.SegmentFilter.t)`, *default:* `nil`) - A segment is defined by a set of segment filters which are combined
together with a logical `AND` operation.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:segmentFilters => list(GoogleApi.AnalyticsReporting.V4.Model.SegmentFilter.t())
}
field(:segmentFilters, as: GoogleApi.AnalyticsReporting.V4.Model.SegmentFilter, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.AnalyticsReporting.V4.Model.SegmentDefinition do
def decode(value, options) do
GoogleApi.AnalyticsReporting.V4.Model.SegmentDefinition.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AnalyticsReporting.V4.Model.SegmentDefinition do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.959184 | 182 | 0.760353 |
79b18bd818783763da01268b27350adc39fafdb4 | 1,298 | ex | Elixir | lib/parser/option_struct.ex | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 3 | 2017-11-29T05:07:35.000Z | 2019-12-18T17:16:41.000Z | lib/parser/option_struct.ex | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 1 | 2021-12-02T19:35:28.000Z | 2022-03-29T09:40:52.000Z | lib/parser/option_struct.ex | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 2 | 2017-11-29T05:07:30.000Z | 2020-11-10T07:10:42.000Z | defmodule CWMP.Protocol.Parser.Messages.OptionStruct do
use CWMP.Protocol.ParserHelpers
alias CWMP.Protocol.Messages.OptionStruct
def initial_acc do
%OptionStruct{}
end
def end_element(state, ['OptionName']) do
update_acc(state, fn cur -> %OptionStruct{cur | option_name: state.last_text} end)
end
def end_element(state, ['VoucherSN']) do
update_acc(state, fn cur -> %OptionStruct{cur | voucher_sn: integerValue(state.last_text, fn(x) -> x >= 0 end)} end)
end
def end_element(state, ['State']) do
update_acc(state, fn cur -> %OptionStruct{cur | state: integerValue(state.last_text, fn(x) -> x >= 0 end)} end)
end
def end_element(state, ['Mode']) do
update_acc(state, fn cur -> %OptionStruct{cur | mode: integerValue(state.last_text, fn(x) -> x in 0..2 end)} end)
end
def end_element(state, ['StartDate']) do
update_acc(state, fn cur -> %OptionStruct{cur | start_date: datetimeStructure(state.last_text)} end)
end
def end_element(state, ['ExpirationDate']) do
update_acc(state, fn cur -> %OptionStruct{cur | expiration_date: datetimeStructure(state.last_text)} end)
end
def end_element(state, ['IsTransferable']) do
update_acc(state, fn cur -> %OptionStruct{cur | is_transferable: boolValue(state.last_text)} end)
end
end
| 34.157895 | 120 | 0.709553 |
79b1a53cab600e959d35e2edbcf17fd488c37357 | 2,060 | ex | Elixir | lib/helper/command.ex | n0isiv/fintex | 69607096cc9c216c81e51ca3053ff30fac01964c | [
"MIT"
] | null | null | null | lib/helper/command.ex | n0isiv/fintex | 69607096cc9c216c81e51ca3053ff30fac01964c | [
"MIT"
] | null | null | null | lib/helper/command.ex | n0isiv/fintex | 69607096cc9c216c81e51ca3053ff30fac01964c | [
"MIT"
] | null | null | null | defmodule FinTex.Helper.Command do
@moduledoc false
alias FinTex.Model.Dialog
import Logger
defmacro __using__(_) do
quote do
alias FinTex.Helper.Command
alias FinTex.Model.Dialog
import Command
import Logger
end
end
def validate!(valid_object) do
# if valid_object do
# valid_object
# else
# raise FinTex.Error,
# reason:
# valid_object
# |> Vex.errors()
# |> Enum.at(0)
# |> Tuple.to_list()
# |> Enum.drop(1)
# |> Enum.join(" ")
# end
valid_object
end
def create(module, d = %Dialog{}) do
module.__struct__.new(module, d)
end
# Replace DKKAU by DIKAUS
# Replace HKKAZ by KIKAZS
# Replace HKPIN by HIPINS
# Replace HKSPA by HISPAS
def control_structure_to_bpd(name) when is_binary(name) do
name |> String.upcase() |> String.replace(~r/^(\w)\w(\w{3})$/, "\\1I\\2S")
end
# Replace DIKAUS by DKKAU
# Replace KIKAZS by HKKAZ
# Replace HIPINS by HKPIN
# Replace HISPAS by HKSPA
def bpd_to_control_structure(name) when is_binary(name) do
name |> String.upcase() |> String.replace(~r/^(\w)\w(\w{3}).+$/, "\\1K\\2")
end
def to_messages(feedback_segments) do
feedback_segments
|> Stream.flat_map(&Enum.at(&1, -1))
|> Enum.sort(fn [code1 | _], [code2 | _] -> code1 >= code2 end)
end
def format_messages(feedback_segments) do
feedback_segments
|> to_messages
|> Enum.map(fn
[code, _ref, text] -> "#{code} #{text}"
[code, _ref, text | params] -> "#{code} #{text} #{Enum.join(params, ", ")}"
end)
end
def check_messages_for_errors(feedback_segments) do
strings = feedback_segments |> format_messages
strings |> Enum.each(&warn/1)
case feedback_segments |> to_messages |> Enum.at(0) do
[code | _] when code >= 9000 -> raise FinTex.Error, reason: strings |> Enum.join(" ")
_ -> feedback_segments
end
end
def dialog_id(response) do
response[:HNHBK]
|> Enum.at(0)
|> Enum.at(3)
end
end
| 24.52381 | 91 | 0.61165 |
79b1a5a285613b489cd49d52c6f69cf56df29b4e | 1,131 | exs | Elixir | test/file_store/middleware/errors_test.exs | rzane/file_store | 6ff9e35043d46e655cb532032f4a77a9cd4a3d14 | [
"MIT"
] | 17 | 2019-10-11T05:50:28.000Z | 2022-01-25T23:28:02.000Z | test/file_store/middleware/errors_test.exs | rzane/file_store | 6ff9e35043d46e655cb532032f4a77a9cd4a3d14 | [
"MIT"
] | 8 | 2019-10-25T04:19:42.000Z | 2022-01-27T02:32:47.000Z | test/file_store/middleware/errors_test.exs | rzane/file_store | 6ff9e35043d46e655cb532032f4a77a9cd4a3d14 | [
"MIT"
] | 3 | 2019-10-25T02:30:22.000Z | 2022-01-24T21:24:08.000Z | defmodule FileStore.Middleware.ErrorsTest do
use FileStore.AdapterCase
@config [base_url: "http://localhost:4000"]
setup do
start_supervised!(FileStore.Adapters.Memory)
store = FileStore.Adapters.Memory.new(@config)
store = FileStore.Middleware.Errors.new(store)
{:ok, store: store}
end
test "read/2 is wrapped", %{store: store} do
assert {:error, error} = FileStore.read(store, "invalid")
assert %FileStore.Error{} = error
assert error.key == "invalid"
assert error.action == "read key"
assert error.reason == :enoent
end
test "upload/3 is wrapped", %{store: store} do
assert {:error, error} = FileStore.upload(store, "invalid", "key")
assert %FileStore.UploadError{} = error
assert error.key == "key"
assert error.path == "invalid"
assert error.reason == :enoent
end
test "download/3 is wrapped", %{store: store} do
assert {:error, error} = FileStore.download(store, "invalid", "path")
assert %FileStore.DownloadError{} = error
assert error.key == "invalid"
assert error.path == "path"
assert error.reason == :enoent
end
end
| 28.275 | 73 | 0.668435 |
79b1bc9780495f62f518fda64f2dacc9364f9edb | 955 | ex | Elixir | lib/ecto/query/having_builder.ex | scrogson/ecto | fdcf807901683c73c1117d89751e0d5a7a318154 | [
"Apache-2.0"
] | null | null | null | lib/ecto/query/having_builder.ex | scrogson/ecto | fdcf807901683c73c1117d89751e0d5a7a318154 | [
"Apache-2.0"
] | null | null | null | lib/ecto/query/having_builder.ex | scrogson/ecto | fdcf807901683c73c1117d89751e0d5a7a318154 | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Query.HavingBuilder do
@moduledoc false
alias Ecto.Query.BuilderUtil
@doc """
Builds a quoted expression.
The quoted expression should evaluate to a query at runtime.
If possible, it does all calculations at compile time to avoid
runtime work.
"""
@spec build(Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t
def build(query, binding, expr, env) do
binding = BuilderUtil.escape_binding(binding)
expr = BuilderUtil.escape(expr, binding)
having = quote do: %Ecto.Query.QueryExpr{expr: unquote(expr),
file: unquote(env.file), line: unquote(env.line)}
BuilderUtil.apply_query(query, __MODULE__, [having], env)
end
@doc """
The callback applied by `build/4` to build the query.
"""
@spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t
def apply(query, expr) do
query = Ecto.Queryable.to_query(query)
%{query | havings: query.havings ++ [expr]}
end
end
| 30.806452 | 73 | 0.678534 |
79b203c71e0397a2df9b96d2723bcd4d6d837852 | 148 | ex | Elixir | examples/token_info.ex | ipfinder-io/ip-finder-elixir | 281402fc91f90291a46e0fc4e93620a4390e5c17 | [
"Apache-2.0"
] | null | null | null | examples/token_info.ex | ipfinder-io/ip-finder-elixir | 281402fc91f90291a46e0fc4e93620a4390e5c17 | [
"Apache-2.0"
] | 1 | 2019-08-29T23:23:08.000Z | 2019-08-29T23:23:08.000Z | examples/token_info.ex | ipfinder-io/ip-finder-elixir | 281402fc91f90291a46e0fc4e93620a4390e5c17 | [
"Apache-2.0"
] | 2 | 2019-08-29T23:19:07.000Z | 2022-02-02T03:00:16.000Z | defmodule TokenInfo do
use Ipfinder
def stats do
conf = Ipfinder.new("YOUR_TOKEN_GOES_HERE")
{:ok, status} = Ipfinder.getStatus(conf)
end
end | 21.142857 | 45 | 0.75 |
79b217d396679558794e083bc362e3546e9d41d7 | 859 | ex | Elixir | web/controllers/resource_controller.ex | herald-it/goncord.ex | 2f58706231a28caa067509c5df43f5c915c46320 | [
"MIT"
] | null | null | null | web/controllers/resource_controller.ex | herald-it/goncord.ex | 2f58706231a28caa067509c5df43f5c915c46320 | [
"MIT"
] | 5 | 2017-03-31T06:48:29.000Z | 2018-12-20T03:40:59.000Z | web/controllers/resource_controller.ex | herald-it/goncord.ex | 2f58706231a28caa067509c5df43f5c915c46320 | [
"MIT"
] | 1 | 2019-01-20T10:01:27.000Z | 2019-01-20T10:01:27.000Z | defmodule Goncord.ResourceController do
use Goncord.Web, :controller
def self_update(conn, params) do
user = Guardian.Plug.current_resource conn
resource = conn.assigns[:resource]
Goncord.UserResource.update_payload user, resource, params
conn
|> put_status(:ok)
|> put_view(Goncord.UserView)
|> render("user.json", user: user)
end
def update(conn, params) do
user = Guardian.Plug.current_resource conn
user = extract_apps user, params
conn
|> put_status(:ok)
|> put_view(Goncord.UserView)
|> render("user.json", user: user)
end
defp extract_apps(user, params) do
Enum.each(params, fn {k, v} ->
case Goncord.Repo.get_by Goncord.Resource, url: k do
nil -> nil
resource -> Goncord.UserResource.update_payload user, resource, v
end
end)
user
end
end | 23.861111 | 73 | 0.668219 |
79b2792e90b85cf705ceebdf1fcd11f32a6a91e4 | 963 | exs | Elixir | mix.exs | maltoe/eqrcode | cde803e209eb4840750a24c394a0bb397117f96a | [
"MIT"
] | null | null | null | mix.exs | maltoe/eqrcode | cde803e209eb4840750a24c394a0bb397117f96a | [
"MIT"
] | null | null | null | mix.exs | maltoe/eqrcode | cde803e209eb4840750a24c394a0bb397117f96a | [
"MIT"
] | null | null | null | defmodule EQRCode.MixProject do
use Mix.Project
def project do
[
app: :eqrcode,
version: "0.1.8",
elixir: "~> 1.6",
start_permanent: Mix.env() == :prod,
name: "EQRCode",
description: "Simple QRCode Generator in Elixir",
source_url: "https://github.com/SiliconJungles/eqrcode",
package: package(),
deps: deps(),
docs: docs()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
defp package() do
[
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/SiliconJungles/eqrcode"},
maintainers: ["siliconavengers"]
]
end
defp docs do
[
main: "readme",
extras: [
"README.md"
]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:ex_doc, "~> 0.24", only: :dev, runtime: false}
]
end
end
| 19.26 | 72 | 0.560748 |
79b27f2d0486e30baf561423dfe149e57d20ad9a | 342 | ex | Elixir | genstage_example/lib/genstage_example/producer.ex | gguimond/elixir | 415a7ed10fb44d84089ff89fb651b765b5f5e53f | [
"MIT"
] | 1 | 2019-03-28T09:08:16.000Z | 2019-03-28T09:08:16.000Z | genstage_example/lib/genstage_example/producer.ex | gguimond/elixir | 415a7ed10fb44d84089ff89fb651b765b5f5e53f | [
"MIT"
] | null | null | null | genstage_example/lib/genstage_example/producer.ex | gguimond/elixir | 415a7ed10fb44d84089ff89fb651b765b5f5e53f | [
"MIT"
] | null | null | null | defmodule GenstageExample.Producer do
use GenStage
def start_link(initial \\ 0) do
GenStage.start_link(__MODULE__, initial, name: __MODULE__)
end
def init(counter), do: {:producer, counter}
def handle_demand(demand, state) do
events = Enum.to_list(state..(state + demand - 1))
{:noreply, events, state + demand}
end | 26.307692 | 62 | 0.704678 |
79b29391fca52e70d17e364b3b389b4161111a4b | 1,146 | exs | Elixir | mix.exs | PandemicPlayers/pandemic-server | 39ce8c12b5f08be7dc66623a69423265f01d23e1 | [
"MIT"
] | null | null | null | mix.exs | PandemicPlayers/pandemic-server | 39ce8c12b5f08be7dc66623a69423265f01d23e1 | [
"MIT"
] | null | null | null | mix.exs | PandemicPlayers/pandemic-server | 39ce8c12b5f08be7dc66623a69423265f01d23e1 | [
"MIT"
] | null | null | null | defmodule Pandemic.Mixfile do
use Mix.Project
def project do
[app: :pandemic,
version: "0.0.1",
elixir: "~> 1.2",
elixirc_paths: elixirc_paths(Mix.env),
compilers: [:phoenix, :gettext] ++ Mix.compilers,
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps()]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[mod: {Pandemic, []},
applications: [:phoenix, :phoenix_pubsub, :phoenix_html, :cowboy, :logger, :gettext, :yamerl]]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "web", "test/support"]
defp elixirc_paths(_), do: ["lib", "web"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[{:phoenix, "~> 1.2.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_html, "~> 2.6"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:yamerl, "~> 0.3.2"},
{:yaml_elixir, "~> 1.2.0"},
]
end
end
| 27.285714 | 99 | 0.593368 |
79b295329194537fcbf5d5f6b77402e892b6574d | 5,856 | ex | Elixir | apps/robby_web/web/controllers/name_game_controller.ex | jeffweiss/openrobby | 9fed2024e6ce87a6fe27ef3af85558f3116aca2a | [
"Apache-2.0"
] | null | null | null | apps/robby_web/web/controllers/name_game_controller.ex | jeffweiss/openrobby | 9fed2024e6ce87a6fe27ef3af85558f3116aca2a | [
"Apache-2.0"
] | null | null | null | apps/robby_web/web/controllers/name_game_controller.ex | jeffweiss/openrobby | 9fed2024e6ce87a6fe27ef3af85558f3116aca2a | [
"Apache-2.0"
] | null | null | null | defmodule RobbyWeb.NameGameController do
use RobbyWeb.Web, :controller
alias RobbyWeb.NameGame
alias RobbyWeb.Profile
alias RobbyWeb.LdapRepo
plug :calculate_score when action in [:show]
plug :random_seed when action in [:new]
def new(conn, _) do
game = create_new_game(conn)
redirect(conn, to: name_game_path(conn, :show, game))
end
def show(conn, %{"id" => id}) do
game = Repo.get(NameGame, id)
if game.player_id == conn.assigns.current_user.id do
profile = LdapRepo.get_by(Profile, uid: game.correct_answer_uid)
render(conn, "show.html", game: game, changeset: NameGame.changeset(game), profile: profile)
else
conn
|> put_flash(:error, "That's someone else's game, sorry! Here's a new one for you.")
|> redirect(to: name_game_path(conn, :new))
end
end
def update(conn, %{"id" => id, "name_game" => params}) do
game =
Repo.get(NameGame, id)
|> NameGame.changeset(params)
|> Repo.update!
conn
|> display_answer(game)
|> redirect(to: name_game_path(conn, :new))
end
# catches the case where user doesn't push a button
def update(conn, %{"id" => id}) do
game = Repo.get(NameGame, id)
conn
|> put_flash(:warning, "Please choose a name")
|> redirect(to: name_game_path(conn, :show, game))
end
def display_answer(conn, %NameGame{correct_answer: answer, chosen_answer: answer}) do
conn
|> put_flash(:success, "You are correct.")
end
def display_answer(conn, game) do
conn
|> put_flash(:error, "That's wrong! The correct answer was #{game.correct_answer}.")
end
defp create_new_game(conn) do
answer =
RobbyWeb.NameGame.next_right_answer(conn.assigns.current_user.id)
|> RobbyWeb.LdapRepo.all
|> Enum.random
%NameGame{correct_answer: answer.cn, correct_answer_uid: answer.uid, player_id: conn.assigns.current_user.id}
|> add_randos
|> Ecto.Changeset.apply_changes
|> Repo.insert!
end
defp add_randos(game) do
randos =
NameGame.people_pool(game)
|> LdapRepo.all
|> Enum.take_random(5)
|> Enum.map(fn person -> person.cn end)
NameGame.changeset(game, %{options: randos})
end
defp calculate_score(conn, _) do
{wins, total} =
conn.assigns.current_user.id
|> RobbyWeb.NameGame.all_time_plays_for_user
|> Ecto.Query.where([turn], not is_nil(turn.chosen_answer))
|> Ecto.Query.select([turn], {sum(fragment("case when chosen_answer = correct_answer then 1 else 0 end")), count(turn.id)})
|> RobbyWeb.Repo.one
if total == 0 do
assign(conn, :score, nil)
else
assign(conn, :score, Float.round(wins / total * 100, 2))
end
end
def leaderboard(conn, _) do
top_10_ref = Task.async(fn -> get_leaderboard_stat(:top_10_most_correct) end)
most_accurate_ref = Task.async(fn -> get_leaderboard_stat(:top_10_most_accurate) end)
most_correctly_guessed_ref = Task.async(fn -> get_leaderboard_stat(:most_recognizable) end)
top_10 = Task.await(top_10_ref)
most_accurate = Task.await(most_accurate_ref)
most_correctly_guessed = Task.await(most_correctly_guessed_ref)
render(conn, "leaderboard.html", top: top_10, recognizable: most_correctly_guessed, accurate: most_accurate)
end
def get_leaderboard_stat(atom) when is_atom(atom) do
unprocessed = apply(__MODULE__, atom, [])
map = retrieve_uid_and_cn(unprocessed)
Enum.map(unprocessed, &sub_with_map_value(&1, map))
end
def sub_with_map_value({a, b, c}, map), do: {a, b, Map.get(map, c)}
def sub_with_map_value({a, b}, map), do: {a, Map.get(map, b)}
def retrieve_uid_and_cn([tuple|_] = list) do
query_params =
list
|> Enum.map(&elem(&1, tuple_size(tuple) - 1))
ldap_uid_name_query(query_params, tuple_size(tuple))
|> RobbyWeb.LdapRepo.all
|> Enum.into(%{})
end
def ldap_uid_name_query(params, 3) do
Ecto.Query.from(u in RobbyWeb.Profile,
where: u.mail in ^params,
select: {u.mail, {u.uid, u.cn}})
end
def ldap_uid_name_query(params, 2) do
Ecto.Query.from(u in RobbyWeb.Profile,
where: u.uid in ^params,
select: {u.uid, {u.uid, u.cn}})
end
def top_10_most_correct do
Ecto.Query.from(RobbyWeb.NameGame)
|> Ecto.Query.where([turn], not is_nil(turn.chosen_answer))
|> Ecto.Query.join(:inner, [turn], user in RobbyWeb.User, turn.player_id == user.id)
|> Ecto.Query.select([turn, user], {sum(fragment("case when chosen_answer = correct_answer then 1 else 0 end")), count(turn.id), user.username})
|> Ecto.Query.group_by([turn, user], user.username)
|> Ecto.Query.order_by([turn, user], [desc: sum(fragment("case when chosen_answer = correct_answer then 1 else 0 end")), asc: count(turn.id)])
|> Ecto.Query.limit(10)
|> RobbyWeb.Repo.all
end
def most_recognizable do
Ecto.Query.from(n in RobbyWeb.NameGame,
where: n.chosen_answer == n.correct_answer,
group_by: n.correct_answer_uid,
order_by: [desc: count(n.id)],
select: {count(n.id), n.correct_answer_uid},
limit: 10)
|> RobbyWeb.Repo.all
end
def top_10_most_accurate do
Ecto.Query.from(RobbyWeb.NameGame)
|> Ecto.Query.where([turn], not is_nil(turn.chosen_answer))
|> Ecto.Query.join(:inner, [turn], user in RobbyWeb.User, turn.player_id == user.id)
|> Ecto.Query.select([turn, user], {fragment("round(sum(case when correct_answer=chosen_answer then 1 else 0 end) * 100.0 / count(*), 2) as percent"), count(turn.id), user.username})
|> Ecto.Query.group_by([turn, user], user.username)
|> Ecto.Query.order_by([turn, user], [desc: fragment("percent"), desc: count(turn.id)])
|> Ecto.Query.limit(10)
|> RobbyWeb.Repo.all
end
def random_seed(conn, _) do
:rand.normal()
conn
end
end
| 34.650888 | 186 | 0.667179 |
79b2993d843ed41eb9dcac35ecbb77eca5e8962c | 56,035 | ex | Elixir | clients/cloud_iot/lib/google_api/cloud_iot/v1/api/projects.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/cloud_iot/lib/google_api/cloud_iot/v1/api/projects.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/cloud_iot/lib/google_api/cloud_iot/v1/api/projects.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.CloudIot.V1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.CloudIot.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Creates a device registry that contains devices.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `parent`. The project and cloud region where this device registry must be created. For example, `projects/example-project/locations/us-central1`.
- locations_id (String.t): Part of `parent`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (DeviceRegistry):
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.DeviceRegistry{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.DeviceRegistry.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_create(
connection,
projects_id,
locations_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/projects/{projectsId}/locations/{locationsId}/registries", %{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.DeviceRegistry{})
end
@doc """
Deletes a device registry configuration.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `name`. The name of the device registry. For example, `projects/example-project/locations/us-central1/registries/my-registry`.
- locations_id (String.t): Part of `name`. See documentation of `projectsId`.
- registries_id (String.t): Part of `name`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_delete(
connection,
projects_id,
locations_id,
registries_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.Empty{})
end
@doc """
Lists the last few versions of the device configuration in descending order (i.e.: newest first).
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `name`. The name of the device. For example, `projects/p0/locations/us-central1/registries/registry0/devices/device0` or `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
- locations_id (String.t): Part of `name`. See documentation of `projectsId`.
- registries_id (String.t): Part of `name`. See documentation of `projectsId`.
- devices_id (String.t): Part of `name`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :numVersions (integer()): The number of versions to list. Versions are listed in decreasing order of the version number. The maximum number of versions retained is 10. If this value is zero, it will return all the versions available.
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.ListDeviceConfigVersionsResponse{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_devices_config_versions_list(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.CloudIot.V1.Model.ListDeviceConfigVersionsResponse.t()}
| {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_devices_config_versions_list(
connection,
projects_id,
locations_id,
registries_id,
devices_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:numVersions => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}/devices/{devicesId}/configVersions",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id),
"devicesId" => URI.encode_www_form(devices_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.ListDeviceConfigVersionsResponse{})
end
@doc """
Creates a device in a device registry.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `parent`. The name of the device registry where this device should be created. For example, `projects/example-project/locations/us-central1/registries/my-registry`.
- locations_id (String.t): Part of `parent`. See documentation of `projectsId`.
- registries_id (String.t): Part of `parent`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (Device):
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.Device{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_devices_create(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.Device.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_devices_create(
connection,
projects_id,
locations_id,
registries_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}/devices",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.Device{})
end
@doc """
Deletes a device.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `name`. The name of the device. For example, `projects/p0/locations/us-central1/registries/registry0/devices/device0` or `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
- locations_id (String.t): Part of `name`. See documentation of `projectsId`.
- registries_id (String.t): Part of `name`. See documentation of `projectsId`.
- devices_id (String.t): Part of `name`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_devices_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_devices_delete(
connection,
projects_id,
locations_id,
registries_id,
devices_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}/devices/{devicesId}",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id),
"devicesId" => URI.encode_www_form(devices_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.Empty{})
end
@doc """
Gets details about a device.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `name`. The name of the device. For example, `projects/p0/locations/us-central1/registries/registry0/devices/device0` or `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
- locations_id (String.t): Part of `name`. See documentation of `projectsId`.
- registries_id (String.t): Part of `name`. See documentation of `projectsId`.
- devices_id (String.t): Part of `name`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :fieldMask (String.t): The fields of the `Device` resource to be returned in the response. If the field mask is unset or empty, all fields are returned.
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.Device{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_devices_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.Device.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_devices_get(
connection,
projects_id,
locations_id,
registries_id,
devices_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:fieldMask => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}/devices/{devicesId}",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id),
"devicesId" => URI.encode_www_form(devices_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.Device{})
end
@doc """
List devices in a device registry.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `parent`. The device registry path. Required. For example, `projects/my-project/locations/us-central1/registries/my-registry`.
- locations_id (String.t): Part of `parent`. See documentation of `projectsId`.
- registries_id (String.t): Part of `parent`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :pageToken (String.t): The value returned by the last `ListDevicesResponse`; indicates that this is a continuation of a prior `ListDevices` call, and that the system should return the next page of data.
- :fieldMask (String.t): The fields of the `Device` resource to be returned in the response. The fields `id`, and `num_id` are always returned by default, along with any other fields specified.
- :pageSize (integer()): The maximum number of devices to return in the response. If this value is zero, the service will select a default size. A call may return fewer objects than requested, but if there is a non-empty `page_token`, it indicates that more entries are available.
- :deviceIds ([String.t]): A list of device string identifiers. If empty, it will ignore this field. For example, `['device0', 'device12']`. This field cannot hold more than 10,000 entries.
- :deviceNumIds ([String.t]): A list of device numerical ids. If empty, it will ignore this field. This field cannot hold more than 10,000 entries.
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.ListDevicesResponse{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_devices_list(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.ListDevicesResponse.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_devices_list(
connection,
projects_id,
locations_id,
registries_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:pageToken => :query,
:fieldMask => :query,
:pageSize => :query,
:deviceIds => :query,
:deviceNumIds => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}/devices",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.ListDevicesResponse{})
end
@doc """
Modifies the configuration for the device, which is eventually sent from the Cloud IoT Core servers. Returns the modified configuration version and its metadata.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `name`. The name of the device. For example, `projects/p0/locations/us-central1/registries/registry0/devices/device0` or `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
- locations_id (String.t): Part of `name`. See documentation of `projectsId`.
- registries_id (String.t): Part of `name`. See documentation of `projectsId`.
- devices_id (String.t): Part of `name`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (ModifyCloudToDeviceConfigRequest):
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.DeviceConfig{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_devices_modify_cloud_to_device_config(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.DeviceConfig.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_devices_modify_cloud_to_device_config(
connection,
projects_id,
locations_id,
registries_id,
devices_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}/devices/{devicesId}:modifyCloudToDeviceConfig",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id),
"devicesId" => URI.encode_www_form(devices_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.DeviceConfig{})
end
@doc """
Updates a device.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `device.name`. The resource path name. For example, `projects/p1/locations/us-central1/registries/registry0/devices/dev0` or `projects/p1/locations/us-central1/registries/registry0/devices/{num_id}`. When `name` is populated as a response from the service, it always ends in the device numeric ID.
- locations_id (String.t): Part of `device.name`. See documentation of `projectsId`.
- registries_id (String.t): Part of `device.name`. See documentation of `projectsId`.
- devices_id (String.t): Part of `device.name`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :updateMask (String.t): Only updates the `device` fields indicated by this mask. The field mask must not be empty, and it must not contain fields that are immutable or only set by the server. Mutable top-level fields: `credentials`, `blocked`, and `metadata`
- :body (Device):
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.Device{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_devices_patch(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.Device.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_devices_patch(
connection,
projects_id,
locations_id,
registries_id,
devices_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}/devices/{devicesId}",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id),
"devicesId" => URI.encode_www_form(devices_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.Device{})
end
@doc """
Lists the last few versions of the device state in descending order (i.e.: newest first).
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `name`. The name of the device. For example, `projects/p0/locations/us-central1/registries/registry0/devices/device0` or `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
- locations_id (String.t): Part of `name`. See documentation of `projectsId`.
- registries_id (String.t): Part of `name`. See documentation of `projectsId`.
- devices_id (String.t): Part of `name`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :numStates (integer()): The number of states to list. States are listed in descending order of update time. The maximum number of states retained is 10. If this value is zero, it will return all the states available.
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.ListDeviceStatesResponse{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_devices_states_list(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.CloudIot.V1.Model.ListDeviceStatesResponse.t()}
| {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_devices_states_list(
connection,
projects_id,
locations_id,
registries_id,
devices_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:numStates => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}/devices/{devicesId}/states",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id),
"devicesId" => URI.encode_www_form(devices_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.ListDeviceStatesResponse{})
end
@doc """
Gets a device registry configuration.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `name`. The name of the device registry. For example, `projects/example-project/locations/us-central1/registries/my-registry`.
- locations_id (String.t): Part of `name`. See documentation of `projectsId`.
- registries_id (String.t): Part of `name`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.DeviceRegistry{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.DeviceRegistry.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_get(
connection,
projects_id,
locations_id,
registries_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.DeviceRegistry{})
end
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `resource`. REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
- locations_id (String.t): Part of `resource`. See documentation of `projectsId`.
- registries_id (String.t): Part of `resource`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (GetIamPolicyRequest):
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.Policy{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_get_iam_policy(
connection,
projects_id,
locations_id,
registries_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}:getIamPolicy",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.Policy{})
end
@doc """
Lists device registries.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `parent`. The project and cloud region path. For example, `projects/example-project/locations/us-central1`.
- locations_id (String.t): Part of `parent`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :pageToken (String.t): The value returned by the last `ListDeviceRegistriesResponse`; indicates that this is a continuation of a prior `ListDeviceRegistries` call, and that the system should return the next page of data.
- :pageSize (integer()): The maximum number of registries to return in the response. If this value is zero, the service will select a default size. A call may return fewer objects than requested, but if there is a non-empty `page_token`, it indicates that more entries are available.
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.ListDeviceRegistriesResponse{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.CloudIot.V1.Model.ListDeviceRegistriesResponse.t()}
| {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_list(
connection,
projects_id,
locations_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:pageToken => :query,
:pageSize => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/projects/{projectsId}/locations/{locationsId}/registries", %{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.ListDeviceRegistriesResponse{})
end
@doc """
Updates a device registry configuration.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `deviceRegistry.name`. The resource path name. For example, `projects/example-project/locations/us-central1/registries/my-registry`.
- locations_id (String.t): Part of `deviceRegistry.name`. See documentation of `projectsId`.
- registries_id (String.t): Part of `deviceRegistry.name`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :updateMask (String.t): Only updates the `device_registry` fields indicated by this mask. The field mask must not be empty, and it must not contain fields that are immutable or only set by the server. Mutable top-level fields: `event_notification_config`, `http_config`, `mqtt_config`, and `state_notification_config`.
- :body (DeviceRegistry):
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.DeviceRegistry{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_patch(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.DeviceRegistry.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_patch(
connection,
projects_id,
locations_id,
registries_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.DeviceRegistry{})
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `resource`. REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
- locations_id (String.t): Part of `resource`. See documentation of `projectsId`.
- registries_id (String.t): Part of `resource`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (SetIamPolicyRequest):
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.Policy{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.CloudIot.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_set_iam_policy(
connection,
projects_id,
locations_id,
registries_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}:setIamPolicy",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.Policy{})
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error.
## Parameters
- connection (GoogleApi.CloudIot.V1.Connection): Connection to server
- projects_id (String.t): Part of `resource`. REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
- locations_id (String.t): Part of `resource`. See documentation of `projectsId`.
- registries_id (String.t): Part of `resource`. See documentation of `projectsId`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (TestIamPermissionsRequest):
## Returns
{:ok, %GoogleApi.CloudIot.V1.Model.TestIamPermissionsResponse{}} on success
{:error, info} on failure
"""
@spec cloudiot_projects_locations_registries_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.CloudIot.V1.Model.TestIamPermissionsResponse.t()}
| {:error, Tesla.Env.t()}
def cloudiot_projects_locations_registries_test_iam_permissions(
connection,
projects_id,
locations_id,
registries_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:quotaUser => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/registries/{registriesId}:testIamPermissions",
%{
"projectsId" => URI.encode_www_form(projects_id),
"locationsId" => URI.encode_www_form(locations_id),
"registriesId" => URI.encode_www_form(registries_id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudIot.V1.Model.TestIamPermissionsResponse{})
end
end
| 44.72067 | 374 | 0.657732 |
79b2c4fa93fe6728befee0eb8680273f3dd2b63b | 2,243 | ex | Elixir | lib/rediscovery/pub_sub.ex | RyanWillDev/rediscovery | ec3af767431a4cc304d9a537cfd16907c04d584f | [
"MIT"
] | 2 | 2020-10-29T08:56:48.000Z | 2020-11-02T16:12:34.000Z | lib/rediscovery/pub_sub.ex | RyanWillDev/rediscovery | ec3af767431a4cc304d9a537cfd16907c04d584f | [
"MIT"
] | null | null | null | lib/rediscovery/pub_sub.ex | RyanWillDev/rediscovery | ec3af767431a4cc304d9a537cfd16907c04d584f | [
"MIT"
] | 1 | 2021-06-15T17:03:22.000Z | 2021-06-15T17:03:22.000Z | defmodule Rediscovery.PubSub do
use GenServer
import Rediscovery.Logger
alias Rediscovery.State
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
@impl true
def init(%{pubsub: pubsub, redix: redix, prefix: prefix} = opts) do
debug("PubSub: Starting")
{:ok, ref} = Redix.PubSub.psubscribe(pubsub, "__keyspace@0__:#{prefix}:*", self())
{:ok, "OK"} = Redix.command(redix, ["CONFIG", "SET", "notify-keyspace-events", "K$gx"])
debug("PubSub: Connected")
{:ok, Map.put(opts, :ref, ref)}
end
@impl true
def handle_info({:redix_pubsub, _pubsub, ref, :psubscribed, _message}, %{ref: ref} = opts) do
debug("PubSub: Subscribed")
{:noreply, opts}
end
@impl true
def handle_info(
{:redix_pubsub, _pubsub, ref, :pmessage, %{channel: "__keyspace@0__:" <> key, payload: "set"}},
%{redix: redix, prefix: prefix, ref: ref} = opts
) do
node = String.trim_leading(key, prefix <> ":")
{:ok, data} = Redix.command(redix, ["GET", prefix <> ":" <> node])
if data do
:ok = State.add(String.to_atom(node), :erlang.binary_to_term(data))
end
{:noreply, opts}
end
@impl true
def handle_info(
{:redix_pubsub, _pubsub, ref, :pmessage, %{channel: "__keyspace@0__:" <> key, payload: "expired"}},
%{prefix: prefix, ref: ref} = opts
) do
node = String.trim_leading(key, prefix <> ":")
:ok = State.remove(node)
{:noreply, opts}
end
def handle_info(
{:redix_pubsub, _pubsub, ref, :pmessage, %{channel: "__keyspace@0__:" <> key, payload: "del"}},
%{prefix: prefix, ref: ref} = opts
) do
node = String.trim_leading(key, prefix <> ":")
:ok = State.remove(node)
{:noreply, opts}
end
@impl true
def handle_info(
{:redix_pubsub, _pubsub, ref, :pmessage, %{channel: "__keyspace@0__:" <> _key, payload: "expire"}},
%{ref: ref} = opts
) do
{:noreply, opts}
end
@impl true
def handle_info(
{:redix_pubsub, _pubsub, ref, :pmessage, %{channel: "__keyspace@0__:" <> _key} = msg},
%{ref: ref} = opts
) do
debug("PubSub: unknown pubsub message: #{inspect(msg)}")
{:noreply, opts}
end
end
| 26.702381 | 107 | 0.601872 |
79b2d3d22518943d3ed9026ffef9da18f2bc691a | 157 | ex | Elixir | lib/apoc/hazmat/hash/sha384.ex | auxesis/apoc | e650c21767f508a2720dad1bb3d14439bdcf39c4 | [
"Apache-2.0"
] | 6 | 2018-10-04T14:18:35.000Z | 2020-05-15T08:43:31.000Z | lib/apoc/hazmat/hash/sha384.ex | auxesis/apoc | e650c21767f508a2720dad1bb3d14439bdcf39c4 | [
"Apache-2.0"
] | 3 | 2018-10-23T12:20:45.000Z | 2021-01-27T10:41:14.000Z | lib/apoc/hazmat/hash/sha384.ex | auxesis/apoc | e650c21767f508a2720dad1bb3d14439bdcf39c4 | [
"Apache-2.0"
] | 2 | 2020-02-19T00:43:37.000Z | 2021-08-19T04:04:25.000Z | defmodule Apoc.Hazmat.Hash.SHA384 do
use Apoc.Adapter.Hash
@impl Apoc.Adapter.Hash
def hash!(message) do
:crypto.hash(:sha384, message)
end
end
| 17.444444 | 36 | 0.719745 |
79b2f735c853465b28ff7bf0177302d71de107ba | 698 | ex | Elixir | log-level/lib/log_level.ex | okaram/exercism-elixir | 66429a50738a16da5d352ad4455a483622625949 | [
"Unlicense"
] | null | null | null | log-level/lib/log_level.ex | okaram/exercism-elixir | 66429a50738a16da5d352ad4455a483622625949 | [
"Unlicense"
] | null | null | null | log-level/lib/log_level.ex | okaram/exercism-elixir | 66429a50738a16da5d352ad4455a483622625949 | [
"Unlicense"
] | null | null | null | defmodule LogLevel do
def to_label(level, legacy?) do
if legacy? do
case level do
0 -> :unknown
1 -> :debug
2 -> :info
3 -> :warning
4 -> :error
5 -> :unknown
level -> :unknown
end
else
case level do
0 -> :trace
1 -> :debug
2 -> :info
3 -> :warning
4 -> :error
5 -> :fatal
level -> :unknown
end
end
end
def alert_recipient(level, legacy?) do
label=to_label(level,legacy?)
cond do
label==:error or label==:fatal -> :ops
label==:unknown and legacy? -> :dev1
label==:unknown -> :dev2
true -> nil
end
end
end
| 19.388889 | 44 | 0.481375 |
79b31045db36a32d00339f99d206886075790429 | 119 | exs | Elixir | apps/elixir_security_advisory_api_v1/.formatter.exs | ex-security-advisory/api | 75674d42efd3b9f2406233e36244d5cb5f174971 | [
"MIT"
] | 5 | 2019-01-03T18:33:40.000Z | 2021-01-25T10:15:06.000Z | apps/elixir_security_advisory_api_v1/.formatter.exs | ex-security-advisory/api | 75674d42efd3b9f2406233e36244d5cb5f174971 | [
"MIT"
] | 15 | 2018-12-27T16:59:06.000Z | 2019-01-04T17:34:38.000Z | apps/elixir_security_advisory_api_v1/.formatter.exs | ex-security-advisory/api | 75674d42efd3b9f2406233e36244d5cb5f174971 | [
"MIT"
] | null | null | null | [
import_deps: [:phoenix, :absinthe, :absinthe_relay],
inputs: ["*.{ex,exs}", "{config,lib,test}/**/*.{ex,exs}"]
]
| 23.8 | 59 | 0.579832 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.