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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f771a6e886e8626ab091e3624908a69fb03a46f7 | 1,732 | ex | Elixir | apps/ello_auth/lib/ello_auth/public_token.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 16 | 2017-06-21T21:31:20.000Z | 2021-05-09T03:23:26.000Z | apps/ello_auth/lib/ello_auth/public_token.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 25 | 2017-06-07T12:18:28.000Z | 2018-06-08T13:27:43.000Z | apps/ello_auth/lib/ello_auth/public_token.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 3 | 2018-06-14T15:34:07.000Z | 2022-02-28T21:06:13.000Z | defmodule Ello.Auth.PublicToken do
@moduledoc """
Retreives and manages public tokens.
"""
use GenServer
alias __MODULE__.Client
@table :public_token_bucket
## Client
def start_link do
GenServer.start_link(__MODULE__, [], name: __MODULE__)
end
@doc """
Fetch a token given the client id and secret.
Returns from ETS immediately if present and unexpired.
If expired or missing the singleton gen server will be called to
request a new token.
"""
def fetch(client_id, client_secret) do
case fetch_from_ets(client_id, client_secret) do
{:ok, token} -> token
_ -> fetch_from_server(client_id, client_secret)
end
end
defp fetch_from_server(id, secret) do
GenServer.call(__MODULE__, {:fetch_from_server, id, secret})
end
defp fetch_from_ets(id, secret) do
with [{_, token}] <- :ets.lookup(@table, {id, secret}),
false <- expired?(token) do
{:ok, token}
else
[] -> :token_not_found
true -> :expired_token
end
end
defp expired?(%{"expires_in" => expires_in, "created_at" => created_at}) do
(created_at + expires_in) <= DateTime.to_unix(DateTime.utc_now)
end
## Server
def init(_) do
:ets.new(@table, [:named_table])
{:ok, %{}}
end
def handle_call({:fetch_from_server, id, secret}, _from, state) do
# check ETS again - make sure token hasn't been updated
case fetch_from_ets(id, secret) do
{:ok, token} -> {:reply, token, state}
_ ->
{:ok, token} = client().fetch_token(id, secret)
:ets.insert(@table, {{id, secret}, token})
{:reply, token, state}
end
end
defp client() do
Application.get_env(:ello_auth, :http_client, Client)
end
end
| 24.055556 | 77 | 0.649538 |
f771bd7a26158bcaa02a9d902ce16fb07780ee86 | 12,101 | ex | Elixir | clients/content/lib/google_api/content/v2/api/products.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/api/products.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/api/products.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.Content.V2.Api.Products do
@moduledoc """
API calls for all endpoints tagged `Products`.
"""
alias GoogleApi.Content.V2.Connection
import GoogleApi.Content.V2.RequestBuilder
@doc """
Retrieves, inserts, and deletes multiple products in a single request. This method can only be called for non-multi-client accounts.
## Parameters
- connection (GoogleApi.Content.V2.Connection): Connection to server
- opts (KeywordList): [optional] Optional parameters
- :alt (String): Data format for the response.
- :fields (String): Selector specifying which fields to include in a partial response.
- :key (String): 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): OAuth 2.0 token for the current user.
- :pretty_print (Boolean): Returns response with indentations and line breaks.
- :quota_user (String): 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. Overrides userIp if both are provided.
- :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits.
- :dry_run (Boolean): Flag to run the request in dry-run mode.
- :body (ProductsCustomBatchRequest):
## Returns
{:ok, %GoogleApi.Content.V2.Model.ProductsCustomBatchResponse{}} on success
{:error, info} on failure
"""
@spec content_products_custombatch(Tesla.Env.client, keyword()) :: {:ok, GoogleApi.Content.V2.Model.ProductsCustomBatchResponse.t} | {:error, Tesla.Env.t}
def content_products_custombatch(connection, opts \\ []) do
optional_params = %{
:"alt" => :query,
:"fields" => :query,
:"key" => :query,
:"oauth_token" => :query,
:"prettyPrint" => :query,
:"quotaUser" => :query,
:"userIp" => :query,
:"dryRun" => :query,
:"body" => :body
}
%{}
|> method(:post)
|> url("/products/batch")
|> add_optional_params(optional_params, opts)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> decode(%GoogleApi.Content.V2.Model.ProductsCustomBatchResponse{})
end
@doc """
Deletes a product from your Merchant Center account. This method can only be called for non-multi-client accounts.
## Parameters
- connection (GoogleApi.Content.V2.Connection): Connection to server
- merchant_id (String): The ID of the managing account.
- product_id (String): The ID of the product.
- opts (KeywordList): [optional] Optional parameters
- :alt (String): Data format for the response.
- :fields (String): Selector specifying which fields to include in a partial response.
- :key (String): 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): OAuth 2.0 token for the current user.
- :pretty_print (Boolean): Returns response with indentations and line breaks.
- :quota_user (String): 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. Overrides userIp if both are provided.
- :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits.
- :dry_run (Boolean): Flag to run the request in dry-run mode.
## Returns
{:ok, %{}} on success
{:error, info} on failure
"""
@spec content_products_delete(Tesla.Env.client, String.t, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t}
def content_products_delete(connection, merchant_id, product_id, opts \\ []) do
optional_params = %{
:"alt" => :query,
:"fields" => :query,
:"key" => :query,
:"oauth_token" => :query,
:"prettyPrint" => :query,
:"quotaUser" => :query,
:"userIp" => :query,
:"dryRun" => :query
}
%{}
|> method(:delete)
|> url("/{merchantId}/products/{productId}", %{
"merchantId" => URI.encode_www_form(merchant_id),
"productId" => URI.encode_www_form(product_id)
})
|> add_optional_params(optional_params, opts)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> decode(false)
end
@doc """
Retrieves a product from your Merchant Center account. This method can only be called for non-multi-client accounts.
## Parameters
- connection (GoogleApi.Content.V2.Connection): Connection to server
- merchant_id (String): The ID of the managing account.
- product_id (String): The ID of the product.
- opts (KeywordList): [optional] Optional parameters
- :alt (String): Data format for the response.
- :fields (String): Selector specifying which fields to include in a partial response.
- :key (String): 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): OAuth 2.0 token for the current user.
- :pretty_print (Boolean): Returns response with indentations and line breaks.
- :quota_user (String): 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. Overrides userIp if both are provided.
- :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits.
## Returns
{:ok, %GoogleApi.Content.V2.Model.Product{}} on success
{:error, info} on failure
"""
@spec content_products_get(Tesla.Env.client, String.t, String.t, keyword()) :: {:ok, GoogleApi.Content.V2.Model.Product.t} | {:error, Tesla.Env.t}
def content_products_get(connection, merchant_id, product_id, opts \\ []) do
optional_params = %{
:"alt" => :query,
:"fields" => :query,
:"key" => :query,
:"oauth_token" => :query,
:"prettyPrint" => :query,
:"quotaUser" => :query,
:"userIp" => :query
}
%{}
|> method(:get)
|> url("/{merchantId}/products/{productId}", %{
"merchantId" => URI.encode_www_form(merchant_id),
"productId" => URI.encode_www_form(product_id)
})
|> add_optional_params(optional_params, opts)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> decode(%GoogleApi.Content.V2.Model.Product{})
end
@doc """
Uploads a product to your Merchant Center account. If an item with the same channel, contentLanguage, offerId, and targetCountry already exists, this method updates that entry. This method can only be called for non-multi-client accounts.
## Parameters
- connection (GoogleApi.Content.V2.Connection): Connection to server
- merchant_id (String): The ID of the managing account.
- opts (KeywordList): [optional] Optional parameters
- :alt (String): Data format for the response.
- :fields (String): Selector specifying which fields to include in a partial response.
- :key (String): 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): OAuth 2.0 token for the current user.
- :pretty_print (Boolean): Returns response with indentations and line breaks.
- :quota_user (String): 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. Overrides userIp if both are provided.
- :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits.
- :dry_run (Boolean): Flag to run the request in dry-run mode.
- :body (Product):
## Returns
{:ok, %GoogleApi.Content.V2.Model.Product{}} on success
{:error, info} on failure
"""
@spec content_products_insert(Tesla.Env.client, String.t, keyword()) :: {:ok, GoogleApi.Content.V2.Model.Product.t} | {:error, Tesla.Env.t}
def content_products_insert(connection, merchant_id, opts \\ []) do
optional_params = %{
:"alt" => :query,
:"fields" => :query,
:"key" => :query,
:"oauth_token" => :query,
:"prettyPrint" => :query,
:"quotaUser" => :query,
:"userIp" => :query,
:"dryRun" => :query,
:"body" => :body
}
%{}
|> method(:post)
|> url("/{merchantId}/products", %{
"merchantId" => URI.encode_www_form(merchant_id)
})
|> add_optional_params(optional_params, opts)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> decode(%GoogleApi.Content.V2.Model.Product{})
end
@doc """
Lists the products in your Merchant Center account. This method can only be called for non-multi-client accounts.
## Parameters
- connection (GoogleApi.Content.V2.Connection): Connection to server
- merchant_id (String): The ID of the managing account.
- opts (KeywordList): [optional] Optional parameters
- :alt (String): Data format for the response.
- :fields (String): Selector specifying which fields to include in a partial response.
- :key (String): 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): OAuth 2.0 token for the current user.
- :pretty_print (Boolean): Returns response with indentations and line breaks.
- :quota_user (String): 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. Overrides userIp if both are provided.
- :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits.
- :include_invalid_inserted_items (Boolean): Flag to include the invalid inserted items in the result of the list request. By default the invalid items are not shown (the default value is false).
- :max_results (Integer): The maximum number of products to return in the response, used for paging.
- :page_token (String): The token returned by the previous request.
## Returns
{:ok, %GoogleApi.Content.V2.Model.ProductsListResponse{}} on success
{:error, info} on failure
"""
@spec content_products_list(Tesla.Env.client, String.t, keyword()) :: {:ok, GoogleApi.Content.V2.Model.ProductsListResponse.t} | {:error, Tesla.Env.t}
def content_products_list(connection, merchant_id, opts \\ []) do
optional_params = %{
:"alt" => :query,
:"fields" => :query,
:"key" => :query,
:"oauth_token" => :query,
:"prettyPrint" => :query,
:"quotaUser" => :query,
:"userIp" => :query,
:"includeInvalidInsertedItems" => :query,
:"maxResults" => :query,
:"pageToken" => :query
}
%{}
|> method(:get)
|> url("/{merchantId}/products", %{
"merchantId" => URI.encode_www_form(merchant_id)
})
|> add_optional_params(optional_params, opts)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> decode(%GoogleApi.Content.V2.Model.ProductsListResponse{})
end
end
| 46.363985 | 240 | 0.684489 |
f771c534e6af223b4af95da3d5d4e7f394cf0ef6 | 20 | ex | Elixir | testData/org/elixir_lang/parser_definition/matched_when_operation_parsing_test_case/Sigil.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 1,668 | 2015-01-03T05:54:27.000Z | 2022-03-25T08:01:20.000Z | testData/org/elixir_lang/parser_definition/matched_when_operation_parsing_test_case/Sigil.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 2,018 | 2015-01-01T22:43:39.000Z | 2022-03-31T20:13:08.000Z | testData/org/elixir_lang/parser_definition/matched_when_operation_parsing_test_case/Sigil.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | ~c{one} when ~s{two} | 20 | 20 | 0.6 |
f771e85d23f03aed0b09a3c8cb15fe42a355db03 | 1,113 | exs | Elixir | day21/config/config.exs | jwarwick/aoc_2016 | 62a1d975835570f3fa7b60d32aa2e84da706be53 | [
"MIT"
] | null | null | null | day21/config/config.exs | jwarwick/aoc_2016 | 62a1d975835570f3fa7b60d32aa2e84da706be53 | [
"MIT"
] | null | null | null | day21/config/config.exs | jwarwick/aoc_2016 | 62a1d975835570f3fa7b60d32aa2e84da706be53 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :day21, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:day21, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 35.903226 | 73 | 0.750225 |
f771eb987048c1abd3aa85f10574e3331ab683a1 | 347 | ex | Elixir | alcarin_api/apps/alcarin/lib/alcarin/game_events/args/speak_event_args.ex | alcarin-org/alcarin-elixir | a04d4e043790a7773745e0fba7098e1c06362896 | [
"MIT"
] | null | null | null | alcarin_api/apps/alcarin/lib/alcarin/game_events/args/speak_event_args.ex | alcarin-org/alcarin-elixir | a04d4e043790a7773745e0fba7098e1c06362896 | [
"MIT"
] | 3 | 2018-05-26T10:36:22.000Z | 2018-05-26T13:48:36.000Z | alcarin_api/apps/alcarin/lib/alcarin/game_events/args/speak_event_args.ex | alcarin-org/alcarin-elixir | a04d4e043790a7773745e0fba7098e1c06362896 | [
"MIT"
] | null | null | null | defmodule Alcarin.GameEvents.Args.SpeakEventArgs do
use Ecto.Schema
import Ecto.Changeset
embedded_schema do
field(:content, :string)
end
@doc false
def changeset(game_event_args, attrs) do
game_event_args
|> cast(attrs, [:content])
|> validate_required([:content])
|> validate_length(:content, min: 1)
end
end
| 20.411765 | 51 | 0.706052 |
f772065e66fbbe64e75a087974bd6b4896988b17 | 4,425 | ex | Elixir | apps/state_mediator/lib/state_mediator/mediator.ex | mbta/automatic-fiesta | de9eb43e4fc7c47aa069f5ded8497ddd39ff74c5 | [
"MIT"
] | 62 | 2019-01-17T12:34:39.000Z | 2022-03-20T21:49:47.000Z | apps/state_mediator/lib/state_mediator/mediator.ex | mbta/automatic-fiesta | de9eb43e4fc7c47aa069f5ded8497ddd39ff74c5 | [
"MIT"
] | 375 | 2019-02-13T15:30:50.000Z | 2022-03-30T18:50:41.000Z | apps/state_mediator/lib/state_mediator/mediator.ex | mbta/automatic-fiesta | de9eb43e4fc7c47aa069f5ded8497ddd39ff74c5 | [
"MIT"
] | 14 | 2019-01-16T19:35:57.000Z | 2022-02-26T18:55:54.000Z | defmodule StateMediator.Mediator do
@moduledoc """
Mediator is responsible for periodically fetching a URL and passing it to
another module for handling.
"""
defstruct [
:module,
:url,
{:fetch_opts, []},
:sync_timeout,
:interval,
{:retries, 0}
]
@opaque t :: %__MODULE__{
module: module,
url: String.t() | {module(), atom(), [any()]},
fetch_opts: Keyword.t(),
sync_timeout: pos_integer,
interval: pos_integer | nil,
retries: non_neg_integer
}
# 5 minutes
@max_retry_duration 60 * 5
use GenServer
require Logger
def child_spec(opts) do
{spec_id, opts} = Keyword.pop!(opts, :spec_id)
%{
id: spec_id,
start: {__MODULE__, :start_link, [opts]}
}
end
@spec start_link(Keyword.t()) :: {:ok, pid}
def start_link(options) do
GenServer.start_link(__MODULE__, options)
end
@spec stop(pid) :: :ok
def stop(pid) do
GenServer.stop(pid)
end
@spec init(Keyword.t()) :: {:ok, __MODULE__.t()} | no_return
def init(options) do
state_module = Keyword.fetch!(options, :state)
url = Keyword.fetch!(options, :url)
fetch_opts = Keyword.get(options, :opts, [])
sync_timeout = options |> Keyword.get(:sync_timeout, 5000)
interval = options |> Keyword.get(:interval)
if url == "" do
:ignore
else
send(self(), :initial)
{:ok,
%__MODULE__{
module: state_module,
url: url,
fetch_opts: fetch_opts,
sync_timeout: sync_timeout,
interval: interval
}}
end
end
@spec handle_info(:initial | :timeout, t) :: {:noreply, t} | {:noreply, t, :hibernate}
def handle_info(:initial, %{module: state_module} = state) do
_ = Logger.debug(fn -> "#{__MODULE__} #{state_module} initial sync starting" end)
require_body? = state_module.size == 0
fetch(state, require_body: require_body?)
end
def handle_info(:timeout, %{module: state_module} = state) do
_ = Logger.debug(fn -> "#{__MODULE__} #{state_module} timeout sync starting" end)
fetch(state)
end
defp fetch(%{url: url, fetch_opts: fetch_opts} = state, opts \\ []) do
url = expand_url(url)
data =
debug_time("fetching #{url}", fn ->
Fetch.fetch_url(url, Keyword.merge(opts, fetch_opts))
end)
data
|> handle_response(state)
end
def handle_response({:ok, body}, %{module: state_module, sync_timeout: sync_timeout} = state) do
_ =
Logger.debug(fn ->
"#{__MODULE__} #{state_module} received body of length #{byte_size(body)}"
end)
debug_time("#{state_module} new state", fn -> state_module.new_state(body, sync_timeout) end)
state
|> reset_retries
|> schedule_update
end
def handle_response(:unmodified, %{module: state_module} = state) do
_ = Logger.debug(fn -> "#{__MODULE__} #{state_module} received unmodified" end)
state
|> reset_retries
|> schedule_update
end
def handle_response({:error, error}, %{module: state_module, retries: retries} = state) do
max_seconds = min(trunc(:math.pow(2, retries + 1)) + 1, @max_retry_duration)
timeout = :rand.uniform(max_seconds)
logger = logger_with_level_for_error(error)
_ =
logger.(fn ->
Enum.join(
[
__MODULE__,
state_module,
"received error:",
inspect(error),
"retrying after #{timeout} (#{retries})"
],
" "
)
end)
state = reset_retries(state, retries + 1)
{:noreply, state, :timer.seconds(timeout)}
end
defp reset_retries(state, value \\ 0) do
%{state | retries: value}
end
defp schedule_update(%{interval: interval} = state) when interval != nil do
{:noreply, state, interval}
end
defp schedule_update(state) do
{:noreply, state}
end
defp debug_time(description, func) do
State.Logger.debug_time(func, fn milliseconds ->
"#{__MODULE__} #{description} took #{milliseconds}ms"
end)
end
defp logger_with_level_for_error(%HTTPoison.Error{reason: :timeout}), do: &Logger.warn/1
defp logger_with_level_for_error(_), do: &Logger.error/1
@spec expand_url(String.t() | {module(), atom(), [any()]}) :: String.t()
defp expand_url(url) when is_binary(url), do: url
defp expand_url({mod, func, args}), do: apply(mod, func, args)
end
| 26.183432 | 98 | 0.617853 |
f7724e16d7e8f295666001a545340a0ccbfa82dc | 2,935 | ex | Elixir | lib/sanbase_web/graphql/resolvers/historical_balance_resolver.ex | santiment/sanbase2 | 9ef6e2dd1e377744a6d2bba570ea6bd477a1db31 | [
"MIT"
] | 81 | 2017-11-20T01:20:22.000Z | 2022-03-05T12:04:25.000Z | lib/sanbase_web/graphql/resolvers/historical_balance_resolver.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 359 | 2017-10-15T14:40:53.000Z | 2022-01-25T13:34:20.000Z | lib/sanbase_web/graphql/resolvers/historical_balance_resolver.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 16 | 2017-11-19T13:57:40.000Z | 2022-02-07T08:13:02.000Z | defmodule SanbaseWeb.Graphql.Resolvers.HistoricalBalanceResolver do
import Absinthe.Resolution.Helpers
import Sanbase.Utils.ErrorHandling,
only: [maybe_handle_graphql_error: 2, handle_graphql_error: 4]
alias Sanbase.Clickhouse.HistoricalBalance
alias SanbaseWeb.Graphql.Resolvers.MetricResolver
alias SanbaseWeb.Graphql.SanbaseDataloader
def assets_held_by_address(_root, args, _resolution) do
selector =
case Map.get(args, :selector) do
nil -> %{infrastructure: "ETH", address: Map.fetch!(args, :address)}
selector -> selector
end
HistoricalBalance.assets_held_by_address(selector)
|> case do
{:ok, result} ->
# We do this, because many contracts emit a transfer
# event when minting new tokens by setting 0x00...000
# as the from address, hence 0x00...000 is "sending"
# tokens it does not have which leads to "negative" balance
result =
result
|> Enum.reject(fn %{balance: balance} -> balance < 0 end)
{:ok, result}
{:error, error} ->
{:error,
handle_graphql_error("Assets held by address", selector.address, error,
description: "address"
)}
end
end
def historical_balance(
_root,
%{from: from, to: to, interval: interval, address: address} = args,
_resolution
) do
selector =
case args do
%{selector: selector} -> selector
%{slug: slug} -> %{slug: slug}
end
HistoricalBalance.historical_balance(
selector,
address,
from,
to,
interval
)
|> maybe_handle_graphql_error(fn error ->
handle_graphql_error(
"Historical Balances",
inspect(selector),
error,
description: "selector"
)
end)
end
def address_historical_balance_change(
_root,
%{selector: selector, from: from, to: to, addresses: addresses},
_resolution
) do
HistoricalBalance.balance_change(selector, addresses, from, to)
|> maybe_handle_graphql_error(fn error ->
handle_graphql_error(
"Historical Balance Change per Address",
inspect(selector),
error,
description: "selector"
)
end)
end
def miners_balance(root, %{} = args, resolution) do
MetricResolver.timeseries_data(
root,
args,
Map.put(resolution, :source, %{metric: "miners_balance"})
)
|> Sanbase.Utils.Transform.rename_map_keys(
old_key: :value,
new_key: :balance
)
end
def balance_usd(%{slug: slug, balance: balance}, _args, %{
context: %{loader: loader}
}) do
loader
|> Dataloader.load(SanbaseDataloader, :last_price_usd, slug)
|> on_load(fn loader ->
price_usd = Dataloader.get(loader, SanbaseDataloader, :last_price_usd, slug)
{:ok, price_usd && balance * price_usd}
end)
end
end
| 27.175926 | 82 | 0.629302 |
f7727702b1a555d28a0a9a847b024fb6e17142d7 | 3,669 | ex | Elixir | lib/cldr/ddl.ex | kianmeng/cldr_units_sql | 7ea5c9673b4986c21baf035eaf07451f9ad37d1c | [
"Apache-2.0"
] | null | null | null | lib/cldr/ddl.ex | kianmeng/cldr_units_sql | 7ea5c9673b4986c21baf035eaf07451f9ad37d1c | [
"Apache-2.0"
] | 2 | 2021-07-08T21:14:50.000Z | 2022-03-07T20:43:44.000Z | lib/cldr/ddl.ex | kianmeng/cldr_units_sql | 7ea5c9673b4986c21baf035eaf07451f9ad37d1c | [
"Apache-2.0"
] | 2 | 2021-07-08T20:24:57.000Z | 2022-03-06T13:54:41.000Z | defmodule Cldr.Unit.DDL do
@moduledoc """
Functions to return SQL DDL commands that support the
creation and deletion of the `cldr_unit` database
type and associated aggregate functions.
"""
# @doc since: "2.7.0"
@default_db :postgres
@supported_db_types :code.priv_dir(:ex_cldr_units_sql)
|> Path.join("SQL")
|> File.ls!()
|> Enum.map(&String.to_atom/1)
@doc """
Returns the SQL string which when executed will
define the `money_with_currency` data type.
## Arguments
* `db_type`: the type of the database for which the SQL
string should be returned. Defaults to `:postgres` which
is currently the only supported database type.
"""
def create_cldr_unit(db_type \\ @default_db) do
read_sql_file(db_type, "create_cldr_unit.sql")
end
@doc """
Returns the SQL string which when executed will
drop the `money_with_currency` data type.
## Arguments
* `db_type`: the type of the database for which the SQL
string should be returned. Defaults to `:postgres` which
is currently the only supported database type.
"""
def drop_cldr_unit(db_type \\ @default_db) do
read_sql_file(db_type, "drop_cldr_unit.sql")
end
@doc """
Returns the SQL string which when executed will
define aggregate functions for the `money_with_currency`
data type.
## Arguments
* `db_type`: the type of the database for which the SQL
string should be returned. Defaults to `:postgres` which
is currently the only supported database type.
"""
def define_aggregate_functions(db_type \\ @default_db) do
read_sql_file(db_type, "define_aggregate_functions.sql")
end
@doc """
Returns the SQL string which when executed will
drop the aggregate functions for the `money_with_currency`
data type.
## Arguments
* `db_type`: the type of the database for which the SQL
string should be returned. Defaults to `:postgres` which
is currently the only supported database type.
"""
def drop_aggregate_functions(db_type \\ @default_db) do
read_sql_file(db_type, "drop_aggregate_functions.sql")
end
@doc """
Returns a string that will Ecto `execute` each SQL
command.
## Arguments
* `sql` is a string of SQL commands that are
separated by three newlines ("\\n"),
that is to say two blank lines between commands
in the file.
## Example
iex> Money.DDL.execute "SELECT name FROM customers;\n\n\nSELECT id FROM orders;"
"execute \"\"\"\nSELECT name FROM customers;\n\n\nSELECT id FROM orders;\n\"\"\""
"""
def execute_each(sql) do
sql
|> String.split("\n\n\n")
|> Enum.map(&execute/1)
|> Enum.join("\n")
end
@doc """
Returns a string that will Ecto `execute` a single SQL
command.
## Arguments
* `sql` is a single SQL command
## Example
iex> Money.DDL.execute "SELECT name FROM customers;"
"execute \"SELECT name FROM customers;\""
"""
def execute(sql) do
sql = String.trim_trailing(sql, "\n")
if String.contains?(sql, "\n") do
"execute \"\"\"\n" <> sql <> "\n\"\"\""
else
"execute " <> inspect(sql)
end
end
defp read_sql_file(db_type, file_name) when db_type in @supported_db_types do
base_dir(db_type)
|> Path.join(file_name)
|> File.read!()
end
defp read_sql_file(db_type, file_name) do
raise ArgumentError,
"Database type #{db_type} does not have a SQL definition " <> "file #{inspect(file_name)}"
end
@app Mix.Project.config[:app]
defp base_dir(db_type) do
:code.priv_dir(@app)
|> Path.join(["SQL", "/#{db_type}"])
end
end
| 25.479167 | 100 | 0.663941 |
f77298de31fd7ac2f8c890d3063e6aeafd3f7a99 | 982 | exs | Elixir | machine_translation/MorpHIN/Learned/Resources/Set5/TrainingInstances/59.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | machine_translation/MorpHIN/Learned/Resources/Set5/TrainingInstances/59.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | machine_translation/MorpHIN/Learned/Resources/Set5/TrainingInstances/59.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | **EXAMPLE FILE**
noun cardinal cm particle cardinal;
adjective cardinal cardinal verb cardinal;
noun cm noun noun cardinal;
cm cardinal noun cm cardinal;
verb conj noun noun cardinal;
noun cm noun cm cardinal;
cm cardinal cm quantifier noun;
cm cardinal particle quantifier cardinal;
pnoun cm cm noun noun;
verb particle pnoun noun cardinal;
verb cardinal cm quantifier noun;
SYM cardinal cm verb noun;
pn cardinal cm particle cardinal;
verb_aux SYM noun nst cardinal;
pn cardinal noun particle cardinal;
cm cardinal cm quantifier cardinal;
pn cardinal noun verb cardinal;
cm nst pnoun SYM cardinal;
demonstrative noun pnoun cm cardinal;
cm cm noun nst cardinal;
pn cm noun adjective cardinal;
conj cardinal noun noun noun;
pnoun cm pnoun SYM cardinal;
particle quantifier noun pnoun cardinal;
quantifier cardinal pnoun SYM noun;
verb conj particle noun cardinal;
cm cm noun pnoun cardinal;
verb_aux SYM noun cm cardinal;
adverb cardinal noun cm noun;
| 30.6875 | 43 | 0.786151 |
f772c8224c2d20b5fee1bddd6b1fd2524c4b1669 | 459 | ex | Elixir | lib/hangman/player_action.ex | brpandey/elixir-hangman | 458502af766b42e492ebb9ca543fc8b855687b09 | [
"MIT"
] | 1 | 2016-12-19T00:10:34.000Z | 2016-12-19T00:10:34.000Z | lib/hangman/player_action.ex | brpandey/elixir-hangman | 458502af766b42e492ebb9ca543fc8b855687b09 | [
"MIT"
] | null | null | null | lib/hangman/player_action.ex | brpandey/elixir-hangman | 458502af766b42e492ebb9ca543fc8b855687b09 | [
"MIT"
] | null | null | null | defprotocol Hangman.Player.Action do
@moduledoc """
Typeclass for specific player functionality
The Player Action protocol is implemented for the Human and Robot types, with
the generic Player handling all overlaps in functionality.
Enables custom player implementations
Function names are `setup/1`, `guess/2`
"""
@doc "Sets up each action state"
def setup(player)
@doc "Returns player guess"
def guess(player, guess \\ nil)
end
| 24.157895 | 79 | 0.740741 |
f772ccc8a7cef2d594153a3d93ed7960fac20db6 | 316 | ex | Elixir | lib/hangman.ex | slaily/hangman | 6964f2641dfa71923735043e4521db02ca9bf269 | [
"MIT"
] | null | null | null | lib/hangman.ex | slaily/hangman | 6964f2641dfa71923735043e4521db02ca9bf269 | [
"MIT"
] | null | null | null | lib/hangman.ex | slaily/hangman | 6964f2641dfa71923735043e4521db02ca9bf269 | [
"MIT"
] | null | null | null | defmodule Hangman do
alias Hangman.Game
def new_game() do
{ :ok, pid } = Supervisor.start_child(Hangman.Supervisor, [])
pid
end
def tally(game_pid) do
GenServer.call(game_pid, { :tally })
end
def make_move(game_pid, guess) do
GenServer.call(game_pid, { :make_move, guess })
end
end
| 17.555556 | 65 | 0.667722 |
f772d0fb333c1ec0c841a151976a1161b1b1d61c | 677 | exs | Elixir | config/config.exs | astery/instream | 91d031d4cdc1091314451279ce43651d8fd7ec89 | [
"Apache-2.0"
] | null | null | null | config/config.exs | astery/instream | 91d031d4cdc1091314451279ce43651d8fd7ec89 | [
"Apache-2.0"
] | null | null | null | config/config.exs | astery/instream | 91d031d4cdc1091314451279ce43651d8fd7ec89 | [
"Apache-2.0"
] | null | null | null | use Mix.Config
if Mix.env() == :test do
alias Instream.TestHelpers.Connections.DefaultConnection
config :logger, :console,
format: "\n$time $metadata[$level] $levelpad$message\n",
metadata: [:query_time, :response_status]
case System.get_env("INFLUXDB_TOKEN") do
nil ->
config :instream, DefaultConnection,
auth: [username: "instream_test", password: "instream_test"],
database: "test_database",
loggers: []
token ->
config :instream, DefaultConnection,
auth: [method: :token, token: token],
bucket: "test_database",
org: "instream_test",
loggers: [],
version: :v2
end
end
| 26.038462 | 69 | 0.633678 |
f772eb43e690fda67a472171e744b86659da3816 | 3,504 | ex | Elixir | lib/unicode/sentence_break.ex | kianmeng/unicode | 85702a499c155cfe8aecefde937f9cfc1d67b26c | [
"Apache-2.0"
] | null | null | null | lib/unicode/sentence_break.ex | kianmeng/unicode | 85702a499c155cfe8aecefde937f9cfc1d67b26c | [
"Apache-2.0"
] | null | null | null | lib/unicode/sentence_break.ex | kianmeng/unicode | 85702a499c155cfe8aecefde937f9cfc1d67b26c | [
"Apache-2.0"
] | null | null | null | defmodule Unicode.SentenceBreak do
@moduledoc """
Functions to introspect Unicode
sentence breaks for binaries
(Strings) and codepoints.
"""
@behaviour Unicode.Property.Behaviour
alias Unicode.Utils
@sentence_breaks Utils.sentence_breaks()
|> Utils.remove_annotations()
@doc """
Returns the map of Unicode
sentence breaks.
The sentence break name is the map
key and a list of codepoint
ranges as tuples as the value.
"""
def sentence_breaks do
@sentence_breaks
end
@doc """
Returns a list of known Unicode
sentence break names.
This function does not return the
names of any sentence break aliases.
"""
@known_sentence_breaks Map.keys(@sentence_breaks)
def known_sentence_breaks do
@known_sentence_breaks
end
@sentence_break_alias Utils.property_value_alias()
|> Map.get("sb")
|> Utils.invert_map
|> Utils.atomize_values()
|> Utils.downcase_keys_and_remove_whitespace()
|> Utils.add_canonical_alias()
@doc """
Returns a map of aliases for
Unicode sentence breaks.
An alias is an alternative name
for referring to a sentence break. Aliases
are resolved by the `fetch/1` and
`get/1` functions.
"""
@impl Unicode.Property.Behaviour
def aliases do
@sentence_break_alias
end
@doc """
Returns the Unicode ranges for
a given sentence break as a list of
ranges as 2-tuples.
Aliases are resolved by this function.
Returns either `{:ok, range_list}` or
`:error`.
"""
@impl Unicode.Property.Behaviour
def fetch(sentence_break) when is_atom(sentence_break) do
Map.fetch(sentence_breaks(), sentence_break)
end
def fetch(sentence_break) do
sentence_break = Utils.downcase_and_remove_whitespace(sentence_break)
sentence_break = Map.get(aliases(), sentence_break, sentence_break)
Map.fetch(sentence_breaks(), sentence_break)
end
@doc """
Returns the Unicode ranges for
a given sentence break as a list of
ranges as 2-tuples.
Aliases are resolved by this function.
Returns either `range_list` or
`nil`.
"""
@impl Unicode.Property.Behaviour
def get(sentence_break) do
case fetch(sentence_break) do
{:ok, sentence_break} -> sentence_break
_ -> nil
end
end
@doc """
Returns the count of the number of characters
for a given sentence break.
## Example
iex> Unicode.SentenceBreak.count(:extend)
2395
"""
@impl Unicode.Property.Behaviour
def count(sentence_break) do
with {:ok, sentence_break} <- fetch(sentence_break) do
Enum.reduce(sentence_break, 0, fn {from, to}, acc -> acc + to - from + 1 end)
end
end
@doc """
Returns the sentence break name(s) for the
given binary or codepoint.
In the case of a codepoint, a single
sentence break name is returned.
For a binary a list of distinct sentence break
names represented by the graphemes in
the binary is returned.
"""
def sentence_break(string) when is_binary(string) do
string
|> String.to_charlist()
|> Enum.map(&sentence_break/1)
|> Enum.uniq()
end
for {sentence_break, ranges} <- @sentence_breaks do
def sentence_break(codepoint) when unquote(Utils.ranges_to_guard_clause(ranges)) do
unquote(sentence_break)
end
end
def sentence_break(codepoint) when is_integer(codepoint) and codepoint in 0..0x10FFFF do
:other
end
end
| 23.052632 | 90 | 0.683505 |
f772f261e465ccf4e05a8351ec35731511596b8b | 1,598 | ex | Elixir | lib/donatebox_web/endpoint.ex | Adnatull/donatebox | 47e07e7831c223265a465425520313da5370f149 | [
"Apache-2.0"
] | null | null | null | lib/donatebox_web/endpoint.ex | Adnatull/donatebox | 47e07e7831c223265a465425520313da5370f149 | [
"Apache-2.0"
] | null | null | null | lib/donatebox_web/endpoint.ex | Adnatull/donatebox | 47e07e7831c223265a465425520313da5370f149 | [
"Apache-2.0"
] | null | null | null | defmodule DonateboxWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :donatebox
socket "/socket", DonateboxWeb.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: :donatebox, gzip: false
# 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.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: "_donatebox_key",
signing_salt: "ATw4zIJ8"
plug DonateboxWeb.Router
@doc """
Callback invoked for dynamically configuring the endpoint.
It receives the endpoint configuration and checks if
configuration should be loaded from the system environment.
"""
def init(_key, config) do
if config[:load_from_system_env] do
port = System.get_env("PORT") || raise "expected the PORT environment variable to be set"
{:ok, Keyword.put(config, :http, [:inet6, port: port])}
else
{:ok, config}
end
end
end
| 28.535714 | 95 | 0.709637 |
f77312de3bd3218083217a3df453d486558c178e | 1,663 | ex | Elixir | test/support/integration_testing/test_generator.ex | fimassuda/web_driver_client | 09d373c9a8a923c5e2860f107f84b16565e338f7 | [
"MIT"
] | 8 | 2019-11-24T18:33:12.000Z | 2020-12-09T10:20:09.000Z | test/support/integration_testing/test_generator.ex | fimassuda/web_driver_client | 09d373c9a8a923c5e2860f107f84b16565e338f7 | [
"MIT"
] | 67 | 2019-12-20T16:33:30.000Z | 2021-09-14T03:50:10.000Z | test/support/integration_testing/test_generator.ex | fimassuda/web_driver_client | 09d373c9a8a923c5e2860f107f84b16565e338f7 | [
"MIT"
] | 10 | 2020-06-19T16:15:03.000Z | 2021-09-13T17:56:25.000Z | defmodule WebDriverClient.IntegrationTesting.TestGenerator do
@moduledoc false
alias WebDriverClient.IntegrationTesting.Scenarios
alias WebDriverClient.IntegrationTesting.Scenarios.Scenario
defmacro generate_describe_per_scenario(opts \\ [], do: block) when is_list(opts) do
default_scenarios = Scenarios.all()
quote do
unquote(opts)
|> Keyword.get(:scenarios, unquote(Macro.escape(default_scenarios)))
|> Enum.each(fn scenario ->
%Scenario{
driver: driver,
browser: browser,
session_configuration_name: configuration_name
} = scenario
describe_name =
unquote(__MODULE__).__scenario_description__(scenario, unquote(__CALLER__.line))
integration_test_driver_configuration_name = "#{driver}-#{configuration_name}"
integration_test_driver_browser = "#{driver}-#{browser}"
describe describe_name do
@describetag scenario: scenario
@describetag integration_test_driver: to_string(driver)
@describetag integration_test_driver_browser: integration_test_driver_browser
@describetag integration_test_driver_configuration_name:
integration_test_driver_configuration_name
unquote(block)
end
end)
end
end
@doc false
def __scenario_description__(scenario, line_number) do
%Scenario{
browser: browser,
driver: driver,
protocol: protocol,
session_configuration_name: session_configuration_name
} = scenario
"Scenario(#{browser}/#{driver}/#{protocol}/#{session_configuration_name}/line=#{line_number})"
end
end
| 32.607843 | 98 | 0.703548 |
f77315129b378f36c3a6d8e627c7a9dcf6f0901e | 617 | exs | Elixir | test/loki_logger_test.exs | lauriannala/LokiLogger | f203fbf59a780ece826bedf385a5d84ceea17128 | [
"Apache-2.0"
] | 5 | 2020-02-26T12:35:32.000Z | 2022-03-30T13:47:35.000Z | test/loki_logger_test.exs | lauriannala/LokiLogger | f203fbf59a780ece826bedf385a5d84ceea17128 | [
"Apache-2.0"
] | 3 | 2020-10-22T10:14:29.000Z | 2022-01-11T10:42:44.000Z | test/loki_logger_test.exs | lauriannala/LokiLogger | f203fbf59a780ece826bedf385a5d84ceea17128 | [
"Apache-2.0"
] | 5 | 2020-03-24T10:13:03.000Z | 2022-03-31T11:10:09.000Z | defmodule LokiLoggerTest do
use ExUnit.Case
doctest LokiLogger
require Logger
test "greets the world" do
Logger.info("Sample message")
Logger.debug("Sample message")
Logger.error("Sample message")
Logger.info("Sample message")
Logger.debug("Sample message")
Logger.error("Sample message")
Logger.info("Sample message")
Logger.debug("Sample message")
Logger.warn("Sample message")
Logger.flush()
end
test "benchmark" do
Benchee.run(
%{
"debug" => fn -> Logger.debug("Sample message") end
},
time: 4,
parallel: 2
)
end
end
| 21.275862 | 59 | 0.636953 |
f773250410b4fe42bae1887244541cf94a704860 | 617 | exs | Elixir | daniel/pragstudio/servy/mix.exs | jdashton/glowing-succotash | 44580c2d4cb300e33156d42e358e8a055948a079 | [
"MIT"
] | null | null | null | daniel/pragstudio/servy/mix.exs | jdashton/glowing-succotash | 44580c2d4cb300e33156d42e358e8a055948a079 | [
"MIT"
] | 1 | 2020-02-26T14:55:23.000Z | 2020-02-26T14:55:23.000Z | daniel/pragstudio/servy/mix.exs | jdashton/glowing-succotash | 44580c2d4cb300e33156d42e358e8a055948a079 | [
"MIT"
] | null | null | null | defmodule Servy.MixProject do
use Mix.Project
def project do
[
app: :servy,
description: "A humble HTTP server",
version: "0.1.0",
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {Servy, []},
env: [port: 3000]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:poison, "~> 4.0"},
{:earmark, "~> 1.4"},
{:httpoison, "~> 1.7"}
]
end
end
| 18.69697 | 59 | 0.534846 |
f7733cd5c3f9b95059dadb5e340223d79410da10 | 9,853 | ex | Elixir | clients/content/lib/google_api/content/v2/api/productstatuses.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/api/productstatuses.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/api/productstatuses.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.Content.V2.Api.Productstatuses do
@moduledoc """
API calls for all endpoints tagged `Productstatuses`.
"""
alias GoogleApi.Content.V2.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets the statuses of multiple products in a single request.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:includeAttributes` (*type:* `boolean()`) - Flag to include full product data in the results of this request. The default value is false.
* `:body` (*type:* `GoogleApi.Content.V2.Model.ProductstatusesCustomBatchRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.ProductstatusesCustomBatchResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_productstatuses_custombatch(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.ProductstatusesCustomBatchResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def content_productstatuses_custombatch(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:includeAttributes => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/productstatuses/batch", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.ProductstatusesCustomBatchResponse{}]
)
end
@doc """
Gets the status of a product from your Merchant Center account.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that contains the product. This account cannot be a multi-client account.
* `product_id` (*type:* `String.t`) - The REST ID of the product.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:destinations` (*type:* `list(String.t)`) - If set, only issues for the specified destinations are returned, otherwise only issues for the Shopping destination.
* `:includeAttributes` (*type:* `boolean()`) - Flag to include full product data in the result of this get request. The default value is false.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.ProductStatus{}}` on success
* `{:error, info}` on failure
"""
@spec content_productstatuses_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.ProductStatus.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def content_productstatuses_get(
connection,
merchant_id,
product_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:destinations => :query,
:includeAttributes => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{merchantId}/productstatuses/{productId}", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"productId" => URI.encode(product_id, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.ProductStatus{}])
end
@doc """
Lists the statuses of the products in your Merchant Center account.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that contains the products. This account cannot be a multi-client account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:destinations` (*type:* `list(String.t)`) - If set, only issues for the specified destinations are returned, otherwise only issues for the Shopping destination.
* `:includeAttributes` (*type:* `boolean()`) - Flag to include full product data in the results of the list request. The default value is false.
* `:includeInvalidInsertedItems` (*type:* `boolean()`) - Flag to include the invalid inserted items in the result of the list request. By default the invalid items are not shown (the default value is false).
* `:maxResults` (*type:* `integer()`) - The maximum number of product statuses to return in the response, used for paging.
* `:pageToken` (*type:* `String.t`) - The token returned by the previous request.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.ProductstatusesListResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_productstatuses_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.ProductstatusesListResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def content_productstatuses_list(connection, merchant_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:destinations => :query,
:includeAttributes => :query,
:includeInvalidInsertedItems => :query,
:maxResults => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{merchantId}/productstatuses", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.ProductstatusesListResponse{}]
)
end
end
| 46.042056 | 215 | 0.646504 |
f7736b024e4ab6416ecf04902cc689d706a7edb1 | 4,092 | ex | Elixir | core/core.ex | ikeyasu/antikythera | 544fdd22e46b1f34177053d87d9e2a9708c74113 | [
"Apache-2.0"
] | null | null | null | core/core.ex | ikeyasu/antikythera | 544fdd22e46b1f34177053d87d9e2a9708c74113 | [
"Apache-2.0"
] | null | null | null | core/core.ex | ikeyasu/antikythera | 544fdd22e46b1f34177053d87d9e2a9708c74113 | [
"Apache-2.0"
] | null | null | null | # Copyright(c) 2015-2018 ACCESS CO., LTD. All rights reserved.
use Croma
defmodule AntikytheraCore do
use Application
@impl true
def start(_type, _args) do
add_gears_dir_to_erl_libs()
AntikytheraCore.FileSetup.setup_files_and_ets_tables()
AntikytheraCore.Config.Core.load()
if not Antikythera.Env.no_listen?() do # Just to suppress log messages by :syn.init()
establish_connections_to_other_nodes()
:syn.init()
end
activate_raft_fleet(fn ->
if not Antikythera.Env.no_listen?() do
start_cowboy_http()
end
{:ok, pid} = start_sup()
AntikytheraCore.Config.Gear.load_all(0) # `GearManager` and `StartupManager` must be up and running here
{:ok, pid}
end)
end
defp add_gears_dir_to_erl_libs() do
# Set ERL_LIBS environment variable in order to load gear's code appropriately.
# See also: http://www.erlang.org/doc/man/code.html#lib_dir-1
dirs = (System.get_env("ERL_LIBS") || "") |> String.split(":")
new_value = [AntikytheraCore.Version.Artifact.gears_dir() | dirs] |> Enum.join(":")
System.put_env("ERL_LIBS", new_value)
end
defp establish_connections_to_other_nodes(tries_remaining \\ 3) do
if tries_remaining == 0 do
raise "cannot establish connections to other nodes!"
else
case AntikytheraCore.Cluster.connect_to_other_nodes_on_start() do
{:ok, true} -> :ok
_otherwise -> establish_connections_to_other_nodes(tries_remaining - 1)
end
end
end
defp activate_raft_fleet(f) do
:ok = RaftFleet.activate(AntikytheraEal.ClusterConfiguration.zone_of_this_host())
try do
f.()
catch
type, reason ->
# When an error occurred in the core part of `start/2`, try to cleanup this node so that
# existing consensus groups (especially `RaftFleet.Cluster`) are not disturbed by the failing node.
RaftFleet.deactivate()
:timer.sleep(10_000) # wait for a moment in the hope that deactivation succeeds...
{:error, {type, reason}}
end
end
defp start_cowboy_http() do
dispatch_rules = AntikytheraCore.Handler.CowboyRouting.compiled_routes([], false)
ranch_transport_opts = [
port: Antikythera.Env.port_to_listen(),
max_connections: :infinity, # limit is imposed on a per-executor pool basis
]
cowboy_proto_opts = %{
idle_timeout: 120_000, # increase idle timeout of keepalive connections; this should be longer than LB's idle timeout
request_timeout: 30_000, # timeout must be sufficiently longer than the gear action timeout (10_000)
env: %{dispatch: dispatch_rules},
stream_handlers: [:cowboy_compress_h, :cowboy_stream_h],
}
{:ok, _} = :cowboy.start_clear(:antikythera_http_listener, ranch_transport_opts, cowboy_proto_opts)
end
defp start_sup() do
children = [
AntikytheraCore.ErrorCountsAccumulator ,
{AntikytheraCore.Alert.Manager , [:antikythera, AntikytheraCore.Alert.Manager]},
AntikytheraCore.GearManager ,
AntikytheraCore.ClusterHostsPoller ,
AntikytheraCore.ClusterNodesConnector ,
AntikytheraCore.MnesiaNodesCleaner ,
AntikytheraCore.StartupManager ,
AntikytheraCore.TerminationManager ,
AntikytheraCore.CoreConfigPoller ,
AntikytheraCore.GearConfigPoller ,
AntikytheraCore.VersionUpgradeTaskQueue ,
AntikytheraCore.VersionSynchronizer ,
AntikytheraCore.StaleGearArtifactCleaner ,
{AntikytheraCore.MetricsUploader , [:antikythera, AntikytheraCore.MetricsUploader]},
{AntikytheraCore.SystemMetricsReporter , [AntikytheraCore.MetricsUploader]},
AntikytheraCore.ExecutorPool.Sup ,
AntikytheraCore.GearExecutorPoolsManager ,
AntikytheraCore.TenantExecutorPoolsManager,
AntikytheraCore.TmpdirTracker ,
]
opts = [strategy: :one_for_one, name: AntikytheraCore.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 40.514851 | 126 | 0.690127 |
f773872784e7b1acdb9ee22ddbeca0e52e500d47 | 29,642 | ex | Elixir | lib/jamdb_oracle_query.ex | isaacsanders/jamdb_oracle | 895e0d3e8232df5057e467a4c5cdbac6da852cab | [
"MIT"
] | null | null | null | lib/jamdb_oracle_query.ex | isaacsanders/jamdb_oracle | 895e0d3e8232df5057e467a4c5cdbac6da852cab | [
"MIT"
] | null | null | null | lib/jamdb_oracle_query.ex | isaacsanders/jamdb_oracle | 895e0d3e8232df5057e467a4c5cdbac6da852cab | [
"MIT"
] | null | null | null | defmodule Jamdb.Oracle.Query do
@moduledoc """
Adapter module for Oracle. `DBConnection.Query` protocol implementation.
See `DBConnection.prepare_execute/4`.
"""
defstruct [:statement, :name]
alias Ecto.Query.{BooleanExpr, JoinExpr, QueryExpr}
@doc false
def all(query) do
sources = create_names(query)
from = from(query, sources)
select = select(query, sources)
window = window(query, sources)
join = join(query, sources)
where = where(query, sources)
group_by = group_by(query, sources)
having = having(query, sources)
combinations = combinations(query)
order_by = order_by(query, sources)
limit = limit(query, sources)
offset = offset(query, sources)
lock = lock(query.lock)
[select, window, from, join, where, group_by, having, combinations, order_by, offset, limit | lock]
end
@doc false
def update_all(%{from: %{source: source}} = query, prefix \\ nil) do
sources = create_names(query)
{from, name} = get_source(query, sources, 0, source)
prefix = prefix || ["UPDATE ", from, ?\s, name | " SET "]
fields = update_fields(query, sources)
where = where(%{query | wheres: query.wheres}, sources)
[prefix, fields, where | returning(query, sources)]
end
@doc false
def delete_all(%{from: from} = query) do
sources = create_names(query)
{from, name} = get_source(query, sources, 0, from)
where = where(%{query | wheres: query.wheres}, sources)
["DELETE FROM ", from, ?\s, name, where | returning(query, sources)]
end
@doc false
def insert(prefix, table, header, rows, _on_conflict, returning) do
values =
if header == [] do
[" VALUES " | intersperse_map(rows, ?,, fn _ -> "(DEFAULT)" end)]
else
[?\s, ?(, intersperse_map(header, ?,, "e_name/1), ") VALUES " | insert_all([header], 1)]
end
["INSERT INTO ", quote_table(prefix, table), values | returning(returning)]
end
defp insert_all(rows, counter) do
intersperse_reduce(rows, ?,, counter, fn row, counter ->
{row, counter} = insert_each(row, counter)
{[?(, row, ?)], counter}
end)
|> elem(0)
end
defp insert_each(values, counter) do
intersperse_reduce(values, ?,, counter, fn
nil, counter ->
{"DEFAULT", counter}
_, counter ->
{[?: | Integer.to_string(counter)], counter + 1}
end)
end
@doc false
def update(prefix, table, fields, filters, returning) do
{fields, count} = intersperse_reduce(fields, ", ", 1, fn field, acc ->
{[quote_name(field), " = :" | Integer.to_string(acc)], acc + 1}
end)
{filters, _count} = intersperse_reduce(filters, " AND ", count, fn
{field, nil}, acc ->
{[quote_name(field), " IS NULL"], acc}
{field, _value}, acc ->
{[quote_name(field), " = :" | Integer.to_string(acc)], acc + 1}
end)
["UPDATE ", quote_table(prefix, table), " SET ",
fields, " WHERE ", filters | returning(returning)]
end
@doc false
def delete(prefix, table, filters, returning) do
{filters, _} = intersperse_reduce(filters, " AND ", 1, fn
{field, nil}, acc ->
{[quote_name(field), " IS NULL"], acc}
{field, _value}, acc ->
{[quote_name(field), " = :" | Integer.to_string(acc)], acc + 1}
end)
["DELETE FROM ", quote_table(prefix, table), " WHERE ", filters | returning(returning)]
end
@doc false
def table_exists_query(table) do
{"SELECT count(*) FROM user_tables WHERE table_name = :1 ", [table]}
end
## Query generation
binary_ops =
[==: " = ", !=: " != ", <=: " <= ", >=: " >= ", <: " < ", >: " > ",
+: " + ", -: " - ", *: " * ", /: " / ",
and: " AND ", or: " OR ", like: " LIKE "]
@binary_ops Keyword.keys(binary_ops)
Enum.map(binary_ops, fn {op, str} ->
defp handle_call(unquote(op), 2), do: {:binary_op, unquote(str)}
end)
defp handle_call(fun, _arity), do: {:fun, Atom.to_string(fun)}
defp select(%{select: %{fields: fields}, distinct: distinct} = query, sources) do
["SELECT ", distinct(distinct, sources, query) | select_fields(fields, sources, query)]
end
defp select_fields([], _sources, _query),
do: "NULL"
defp select_fields(fields, sources, query) do
intersperse_map(fields, ", ", fn
{key, value} ->
[expr(value, sources, query), ?\s | quote_name(key)]
value ->
expr(value, sources, query)
end)
end
defp distinct(nil, _, _), do: []
defp distinct(%QueryExpr{expr: []}, _, _), do: {[], []}
defp distinct(%QueryExpr{expr: true}, _, _), do: "DISTINCT "
defp distinct(%QueryExpr{expr: false}, _, _), do: []
defp distinct(%QueryExpr{expr: exprs}, _, _) when is_list(exprs), do: "DISTINCT "
defp from(%{from: %{hints: [_ | _]}} = query, _sources) do
error!(query, "table hints are not supported")
end
defp from(%{from: %{source: source}} = query, sources) do
{from, name} = get_source(query, sources, 0, source)
[" FROM ", from, ?\s | name]
end
defp update_fields(%{updates: updates} = query, sources) do
for(%{expr: expr} <- updates,
{op, kw} <- expr,
{key, value} <- kw,
do: update_op(op, key, value, sources, query)) |> Enum.intersperse(", ")
end
defp update_op(:set, key, value, sources, query) do
[quote_name(key), " = " | expr(value, sources, query)]
end
defp update_op(:inc, key, value, sources, query) do
[quote_name(key), " = ", quote_qualified_name(key, sources, 0), " + " |
expr(value, sources, query)]
end
defp update_op(command, _key, _value, _sources, query) do
error!(query, "unknown update operation #{inspect command}")
end
defp join(%{joins: []}, _sources), do: []
defp join(%{joins: joins} = query, sources) do
[?\s | intersperse_map(joins, ?\s, fn
%JoinExpr{on: %QueryExpr{expr: expr}, qual: qual, ix: ix, source: source, hints: hints} ->
if hints != [] do
error!(query, "table hints are not supported")
end
{join, name} = get_source(query, sources, ix, source)
[join_qual(qual), join, " ", name | join_on(qual, expr, sources, query)]
end)]
end
defp join_on(:cross, true, _sources, _query), do: []
defp join_on(_qual, expr, sources, query), do: [" ON " | expr(expr, sources, query)]
defp join_qual(:inner), do: "INNER JOIN "
defp join_qual(:left), do: "LEFT OUTER JOIN "
defp join_qual(:left_lateral), do: "LATERAL "
defp join_qual(:right), do: "RIGHT OUTER JOIN "
defp join_qual(:full), do: "FULL OUTER JOIN "
defp join_qual(:cross), do: "CROSS JOIN "
defp where(%{wheres: wheres} = query, sources) do
boolean(" WHERE ", wheres, sources, query)
end
defp having(%{havings: havings} = query, sources) do
boolean(" HAVING ", havings, sources, query)
end
defp group_by(%{group_bys: []}, _sources), do: []
defp group_by(%{group_bys: group_bys} = query, sources) do
[" GROUP BY " |
intersperse_map(group_bys, ", ", fn
%QueryExpr{expr: expr} ->
intersperse_map(expr, ", ", &expr(&1, sources, query))
end)]
end
defp window(%{windows: []}, _sources), do: []
defp window(%{windows: windows} = query, sources) do
intersperse_map(windows, ", ", fn
{_, %{expr: kw}} ->
window_exprs(kw, sources, query)
end)
end
defp window_exprs(kw, sources, query) do
[?(, intersperse_map(kw, ?\s, &window_expr(&1, sources, query)), ?)]
end
defp window_expr({:partition_by, fields}, sources, query) do
["PARTITION BY " | intersperse_map(fields, ", ", &expr(&1, sources, query))]
end
defp window_expr({:order_by, fields}, sources, query) do
["ORDER BY " | intersperse_map(fields, ", ", &order_by_expr(&1, sources, query))]
end
defp window_expr({:frame, {:fragment, _, _} = fragment}, sources, query) do
expr(fragment, sources, query)
end
defp order_by(%{order_bys: []}, _sources), do: []
defp order_by(%{order_bys: order_bys} = query, sources) do
[" ORDER BY " |
intersperse_map(order_bys, ", ", fn
%QueryExpr{expr: expr} ->
intersperse_map(expr, ", ", &order_by_expr(&1, sources, query))
end)]
end
defp order_by_expr({dir, expr}, sources, query) do
str = expr(expr, sources, query)
case dir do
:asc -> str
:asc_nulls_last -> [str | " ASC NULLS LAST"]
:asc_nulls_first -> [str | " ASC NULLS FIRST"]
:desc -> [str | " DESC"]
:desc_nulls_last -> [str | " DESC NULLS LAST"]
:desc_nulls_first -> [str | " DESC NULLS FIRST"]
end
end
defp limit(%{limit: nil}, _sources), do: []
defp limit(%{limit: %QueryExpr{expr: expr}} = query, sources) do
[" FETCH NEXT ", expr(expr, sources, query), " ROWS ONLY"]
end
defp offset(%{offset: nil}, _sources), do: []
defp offset(%{offset: %QueryExpr{expr: expr}} = query, sources) do
[" OFFSET ", expr(expr, sources, query), " ROWS"]
end
defp combinations(%{combinations: combinations}) do
Enum.map(combinations, fn
{:union, query} -> [" UNION (", all(query), ")"]
{:union_all, query} -> [" UNION ALL (", all(query), ")"]
{:except, query} -> [" MINUS (", all(query), ")"]
{:intersect, query} -> [" INTERSECT (", all(query), ")"]
end)
end
defp lock(nil), do: []
defp lock(lock_clause), do: [?\s | lock_clause]
defp boolean(_name, [], _sources, _query), do: []
defp boolean(name, [%{expr: expr, op: op} | query_exprs], sources, query) do
[name |
Enum.reduce(query_exprs, {op, paren_expr(expr, sources, query)}, fn
%BooleanExpr{expr: expr, op: op}, {op, acc} ->
{op, [acc, operator_to_boolean(op), paren_expr(expr, sources, query)]}
%BooleanExpr{expr: expr, op: op}, {_, acc} ->
{op, [?(, acc, ?), operator_to_boolean(op), paren_expr(expr, sources, query)]}
end) |> elem(1)]
end
defp operator_to_boolean(:and), do: " AND "
defp operator_to_boolean(:or), do: " OR "
defp parens_for_select([first_expr | _] = expr) do
if is_binary(first_expr) and String.starts_with?(first_expr, ["SELECT", "select"]) do
[?(, expr, ?)]
else
expr
end
end
defp paren_expr(expr, sources, query) do
[?(, expr(expr, sources, query), ?)]
end
defp expr({:^, [], [ix]}, _sources, _query) do
[?: | Integer.to_string(ix + 1)]
end
defp expr({{:., _, [{:&, _, [idx]}, field]}, _, []}, sources, _query) when is_atom(field) do
quote_qualified_name(field, sources, idx)
end
defp expr({:&, _, [idx]}, sources, _query) do
{_, source, _} = elem(sources, idx)
source
end
defp expr({:in, _, [_left, []]}, _sources, _query) do
"false"
end
defp expr({:in, _, [left, right]}, sources, query) when is_list(right) do
args =
intersperse_map(right, ?,, fn
elem when is_list(elem) -> [?(, intersperse_map(elem, ?,, &expr(&1, sources, query)), ?)]
elem -> expr(elem, sources, query)
end)
[expr(left, sources, query), " IN (", args, ?)]
end
defp expr({:in, _, [left, {:^, _, [_, length]}]}, sources, query) do
right = for ix <- 1..length, do: {:^, [], [ix]}
expr({:in, [], [left, right]}, sources, query)
end
defp expr({:in, _, [left, right]}, sources, query) do
[expr(left, sources, query), " = ANY(", expr(right, sources, query), ?)]
end
defp expr({:is_nil, _, [arg]}, sources, query) do
[expr(arg, sources, query) | " IS NULL"]
end
defp expr({:not, _, [expr]}, sources, query) do
["NOT (", expr(expr, sources, query), ?)]
end
defp expr(%Ecto.SubQuery{query: query}, _sources, _query) do
[?(, all(query), ?)]
end
defp expr({:fragment, _, [kw]}, _sources, query) when is_list(kw) or tuple_size(kw) == 3 do
error!(query, "keyword or interpolated fragments are not supported")
end
defp expr({:fragment, _, parts}, sources, query) do
Enum.map(parts, fn
{:raw, part} -> part
{:expr, expr} -> expr(expr, sources, query)
end)
|> parens_for_select
end
defp expr({:date_add, _, [date, count, interval]}, sources, query) do
interval(date, " + ", count, interval, sources, query)
end
defp expr({:datetime_add, _, [datetime, count, interval]}, sources, query) do
interval(datetime, " + ", count, interval, sources, query)
end
defp expr({:from_now, _, [count, interval]}, sources, query) do
interval(DateTime.utc_now, " + ", count, interval, sources, query)
end
defp expr({:ago, _, [count, interval]}, sources, query) do
interval(DateTime.utc_now, " - ", count, interval, sources, query)
end
defp expr({:over, _, [agg, name]}, sources, query) when is_atom(name) do
aggregate = expr(agg, sources, query)
[aggregate, " OVER "]
end
defp expr({:over, _, [agg, kw]}, sources, query) do
aggregate = expr(agg, sources, query)
[aggregate, " OVER ", window_exprs(kw, sources, query)]
end
defp expr({:{}, _, elems}, sources, query) do
[?(, intersperse_map(elems, ?,, &expr(&1, sources, query)), ?)]
end
defp expr({:count, _, []}, _sources, _query), do: "count(*)"
defp expr({fun, _, args}, sources, query) when is_atom(fun) and is_list(args) do
case handle_call(fun, length(args)) do
{:binary_op, op} ->
[left, right] = args
[op_to_binary(left, sources, query), op | op_to_binary(right, sources, query)]
{:fun, fun} ->
[fun, ?(, [], intersperse_map(args, ", ", &expr(&1, sources, query)), ?)]
end
end
defp expr(%Ecto.Query.Tagged{value: literal}, sources, query) do
expr(literal, sources, query)
end
defp expr(nil, _sources, _query), do: "NULL"
defp expr(true, _sources, _query), do: "TRUE"
defp expr(false, _sources, _query), do: "FALSE"
defp expr(literal, _sources, _query) when is_binary(literal) or is_list(literal) do
["'", escape_string(literal), "'"]
end
defp expr(literal, _sources, _query) when is_integer(literal) do
Integer.to_string(literal)
end
defp expr(literal, _sources, _query) when is_float(literal) do
Float.to_string(literal)
end
defp interval(datetime, literal, count, interval, sources, query) do
[?(, expr(datetime, sources, query), literal, " INTERVAL '",
expr(count, sources, query), "' ", interval, ?)]
end
defp op_to_binary({op, _, [_, _]} = expr, sources, query) when op in @binary_ops do
paren_expr(expr, sources, query)
end
defp op_to_binary(expr, sources, query) do
expr(expr, sources, query)
end
defp returning(%{select: nil}, _sources),
do: []
defp returning(%{select: %{fields: fields}} = query, sources) do
[{:&, _, [_idx, returning, _counter]}] = fields
[" RETURN ", select_fields(fields, sources, query),
" INTO ", intersperse_map(returning, ", ", &[?: | quote_name(&1)])]
end
defp returning([]),
do: []
defp returning(fields) do
returning = fields |> Enum.filter(& is_tuple(&1) == false)
[" RETURN ", intersperse_map(returning, ", ", "e_name/1),
" INTO ", intersperse_map(returning, ", ", &[?: | quote_name(&1)])]
end
defp create_names(%{sources: sources}) do
create_names(sources, 0, tuple_size(sources)) |> List.to_tuple()
end
defp create_names(sources, pos, limit) when pos < limit do
[create_name(sources, pos) | create_names(sources, pos + 1, limit)]
end
defp create_names(_sources, pos, pos) do
[]
end
defp create_name(sources, pos) do
case elem(sources, pos) do
{:fragment, _, _} ->
{nil, [?f | Integer.to_string(pos)], nil}
{table, schema, prefix} ->
name = [create_alias(table) | Integer.to_string(pos)]
{quote_table(prefix, table), name, schema}
%Ecto.SubQuery{} ->
{nil, [?s | Integer.to_string(pos)], nil}
end
end
defp create_alias(<<first, _rest::binary>>) when first in ?a..?z when first in ?A..?Z do
<<first>>
end
defp create_alias(_) do
"t"
end
# DDL
alias Ecto.Migration.{Table, Index, Reference, Constraint}
def execute_ddl({command, %Table{} = table, columns}) when command in [:create, :create_if_not_exists] do
table_name = quote_table(table.prefix, table.name)
query = [if_do(command == :create_if_not_exists, :begin),
"CREATE TABLE ",
table_name, ?\s, ?(,
column_definitions(table, columns), pk_definition(columns, ", "), ?),
options_expr(table.options),
if_do(command == :create_if_not_exists, :end)]
[query] ++
comments_on("TABLE", table_name, table.comment) ++
comments_for_columns(table_name, columns)
end
def execute_ddl({command, %Table{} = table}) when command in [:drop, :drop_if_exists] do
[[if_do(command == :drop_if_exists, :begin),
"DROP TABLE ", quote_table(table.prefix, table.name),
if_do(command == :drop_if_exists, :end)]]
end
def execute_ddl({:alter, %Table{} = table, changes}) do
table_name = quote_table(table.prefix, table.name)
query = ["ALTER TABLE ", table_name, ?\s,
column_changes(table, changes), pk_definition(changes, ", ADD ")]
[query] ++
comments_on("TABLE", table_name, table.comment) ++
comments_for_columns(table_name, changes)
end
def execute_ddl({command, %Index{} = index}) when command in [:create, :create_if_not_exists] do
[[if_do(command == :create_if_not_exists, :begin),
"CREATE", if_do(index.unique, " UNIQUE"), " INDEX ",
quote_name(index.name),
" ON ",
quote_table(index.prefix, index.table), ?\s,
?(, intersperse_map(index.columns, ", ", &index_expr/1), ?),
if_do(command == :create_if_not_exists, :end)]]
end
def execute_ddl({command, %Index{} = index}) when command in [:drop, :drop_if_exists] do
[[if_do(command == :drop_if_exists, :begin),
"DROP INDEX ", quote_table(index.prefix, index.name),
if_do(command == :drop_if_exists, :end)]]
end
def execute_ddl({:rename, %Table{} = current_table, %Table{} = new_table}) do
[["RENAME ", quote_table(current_table.prefix, current_table.name),
" TO ", quote_table(nil, new_table.name)]]
end
def execute_ddl({:rename, %Table{} = table, current_column, new_column}) do
[["ALTER TABLE ", quote_table(table.prefix, table.name), " RENAME COLUMN ",
quote_name(current_column), " TO ", quote_name(new_column)]]
end
def execute_ddl({command, %Constraint{} = constraint}) when command in [:create, :create_if_not_exists] do
[[if_do(command == :create_if_not_exists, :begin),
"ALTER TABLE ", quote_table(constraint.prefix, constraint.table),
" ADD CONSTRAINT ", quote_name(constraint.name), constraint_expr(constraint),
if_do(command == :create_if_not_exists, :end)]]
end
def execute_ddl({command, %Constraint{} = constraint}) when command in [:drop, :drop_if_exists] do
[[if_do(command == :drop_if_exists, :begin),
"ALTER TABLE ", quote_table(constraint.prefix, constraint.table),
" DROP CONSTRAINT ", quote_name(constraint.name),
if_do(command == :drop_if_exists, :end)]]
end
def execute_ddl(string) when is_binary(string), do: [string]
def execute_ddl(keyword) when is_list(keyword),
do: error!(nil, "keyword lists in execute are not supported")
defp pk_definition(columns, prefix) do
pks =
for {_, name, _, opts} <- columns,
opts[:primary_key],
do: name
case pks do
[] -> []
_ -> [prefix, "PRIMARY KEY (", intersperse_map(pks, ", ", "e_name/1), ")"]
end
end
defp comments_on(_object, _name, nil), do: []
defp comments_on(object, name, comment) do
[["COMMENT ON ", object, ?\s, name, " IS ", single_quote(comment)]]
end
defp comments_for_columns(table_name, columns) do
Enum.flat_map(columns, fn
{_operation, column_name, _column_type, opts} ->
column_name = [table_name, ?. | quote_name(column_name)]
comments_on("COLUMN", column_name, opts[:comment])
_ -> []
end)
end
defp column_definitions(table, columns) do
intersperse_map(columns, ", ", &column_definition(table, &1))
end
defp column_definition(table, {:add, name, %Reference{} = ref, opts}) do
[quote_name(name), ?\s, column_type(ref.type, opts),
column_options(ref.type, opts), reference_expr(ref, table, name)]
end
defp column_definition(_table, {:add, name, type, opts}) do
[quote_name(name), ?\s, column_type(type, opts), column_options(type, opts)]
end
defp column_changes(table, columns) do
intersperse_map(columns, ", ", &column_change(table, &1))
end
defp column_change(table, {:add, name, %Reference{} = ref, opts}) do
["ADD COLUMN ", quote_name(name), ?\s, column_type(ref.type, opts),
column_options(ref.type, opts), reference_expr(ref, table, name)]
end
defp column_change(_table, {:add, name, type, opts}) do
["ADD COLUMN ", quote_name(name), ?\s, column_type(type, opts),
column_options(type, opts)]
end
defp column_change(table, {:modify, name, %Reference{} = ref, opts}) do
[drop_constraint_expr(opts[:from], table, name), "ALTER COLUMN ", quote_name(name), " TYPE ", column_type(ref.type, opts),
constraint_expr(ref, table, name), modify_null(name, opts), modify_default(name, ref.type, opts)]
end
defp column_change(table, {:modify, name, type, opts}) do
[drop_constraint_expr(opts[:from], table, name), "ALTER COLUMN ", quote_name(name), " TYPE ",
column_type(type, opts), modify_null(name, opts), modify_default(name, type, opts)]
end
defp column_change(_table, {:remove, name}), do: ["DROP COLUMN ", quote_name(name)]
defp column_change(table, {:remove, name, %Reference{} = ref, _opts}) do
[drop_constraint_expr(ref, table, name), "DROP COLUMN ", quote_name(name)]
end
defp column_change(_table, {:remove, name, _type, _opts}), do: ["DROP COLUMN ", quote_name(name)]
defp modify_null(name, opts) do
case Keyword.get(opts, :null) do
true -> [", ALTER COLUMN ", quote_name(name), " DROP NOT NULL"]
false -> [", ALTER COLUMN ", quote_name(name), " SET NOT NULL"]
nil -> []
end
end
defp modify_default(name, _type, opts) do
case Keyword.fetch(opts, :default) do
{:ok, val} -> [", ALTER COLUMN ", quote_name(name), " SET", default_expr({:ok, val})]
:error -> []
end
end
defp column_options(_type, opts) do
default = Keyword.fetch(opts, :default)
null = Keyword.get(opts, :null)
[default_expr(default), null_expr(null)]
end
defp null_expr(false), do: " NOT NULL"
defp null_expr(true), do: " NULL"
defp null_expr(_), do: []
defp default_expr({:ok, nil}),
do: " DEFAULT NULL"
defp default_expr({:ok, literal}) when is_binary(literal),
do: [" DEFAULT '", escape_string(literal), ?']
defp default_expr({:ok, literal}) when is_number(literal) or is_boolean(literal),
do: [" DEFAULT ", to_string(literal)]
defp default_expr({:ok, {:fragment, expr}}),
do: [" DEFAULT ", expr]
defp default_expr({:ok, value}) when is_map(value),
do: error!(nil, "json defaults are not supported")
defp default_expr(:error),
do: []
defp index_expr(literal) when is_binary(literal),
do: literal
defp index_expr(literal),
do: quote_name(literal)
defp options_expr(nil),
do: []
defp options_expr(keyword) when is_list(keyword),
do: error!(nil, "keyword lists in :options are not supported")
defp options_expr(options),
do: [?\s, options]
defp column_type({:array, type}, opts),
do: [column_type(type, opts), "[]"]
defp column_type(type, _opts) when type in ~w(utc_datetime naive_datetime)a,
do: [ecto_to_db(type), "(0)"]
defp column_type(type, opts) when type in ~w(utc_datetime_usec naive_datetime_usec)a do
precision = Keyword.get(opts, :precision)
type_name = ecto_to_db(type)
if precision do
[type_name, ?(, to_string(precision), ?)]
else
type_name
end
end
defp column_type(type, opts) do
size = Keyword.get(opts, :size)
precision = Keyword.get(opts, :precision)
scale = Keyword.get(opts, :scale)
national = Keyword.get(opts, :national, false)
type_name = [if_do(national and type in [:string, :binary], "n"), ecto_to_db(type)]
cond do
size -> [type_name, ?(, to_string(size), ?)]
precision -> [type_name, ?(, to_string(precision), ?,, to_string(scale || 0), ?)]
type == :string -> [type_name, "(255)"]
true -> type_name
end
end
defp reference_expr(%Reference{} = ref, table, name),
do: [" CONSTRAINT ", reference_name(ref, table, name), " REFERENCES ",
quote_table(ref.prefix || table.prefix, ref.table), ?(, quote_name(ref.column), ?),
reference_on_delete(ref.on_delete)]
defp constraint_expr(%Reference{} = ref, table, name),
do: [", ADD CONSTRAINT ", reference_name(ref, table, name), ?\s,
"FOREIGN KEY (", quote_name(name), ") REFERENCES ",
quote_table(ref.prefix || table.prefix, ref.table), ?(, quote_name(ref.column), ?),
reference_on_delete(ref.on_delete)]
defp drop_constraint_expr(%Reference{} = ref, table, name),
do: ["DROP CONSTRAINT ", reference_name(ref, table, name), ", "]
defp drop_constraint_expr(_, _, _),
do: []
defp reference_name(%Reference{name: nil}, table, column),
do: quote_name("#{table.name}_#{column}_fkey")
defp reference_name(%Reference{name: name}, _table, _column),
do: quote_name(name)
defp constraint_expr(%Constraint{check: check}) when is_binary(check),
do: [" CHECK ", ?(, check, ?)]
defp constraint_expr(_),
do: []
defp reference_on_delete(:nilify_all), do: " ON DELETE SET NULL"
defp reference_on_delete(:delete_all), do: " ON DELETE CASCADE"
defp reference_on_delete(_), do: []
defp ecto_to_db(:id), do: "integer"
defp ecto_to_db(:binary_id), do: "raw(16)"
defp ecto_to_db(:uuid), do: "raw(16)"
defp ecto_to_db(:bigint), do: "integer"
defp ecto_to_db(:bigserial), do: "integer"
defp ecto_to_db(:integer), do: "integer"
defp ecto_to_db(:float), do: "number"
defp ecto_to_db(:boolean), do: "char(1)"
defp ecto_to_db(:string), do: "varchar2"
defp ecto_to_db(:binary), do: "clob"
defp ecto_to_db({:array, _}), do: "blob"
defp ecto_to_db(:map), do: "clob"
defp ecto_to_db({:map, _}), do: "clob"
defp ecto_to_db(:decimal), do: "decimal"
defp ecto_to_db(:naive_datetime), do: "timestamp"
defp ecto_to_db(:naive_datetime_usec), do: "timestamp"
defp ecto_to_db(:utc_datetime), do: "timestamp with time zone"
defp ecto_to_db(:utc_datetime_usec), do: "timestamp with time zone"
defp ecto_to_db(other), do: Atom.to_string(other)
defp single_quote(value), do: [?', escape_string(value), ?']
defp if_do(condition, :begin) do
if condition, do: "BEGIN EXECUTE IMMEDIATE '", else: []
end
defp if_do(condition, :end) do
if condition, do: "'; EXCEPTION WHEN OTHERS THEN NULL; END;", else: []
end
defp if_do(condition, value) do
if condition, do: value, else: []
end
## Helpers
defp get_source(query, sources, ix, source) do
{expr, name, _schema} = elem(sources, ix)
{expr || paren_expr(source, sources, query), name}
end
defp quote_qualified_name(name, sources, ix) do
{_, source, _} = elem(sources, ix)
[source, ?. | quote_name(name)]
end
defp quote_name(name) when is_atom(name) do
quote_name(Atom.to_string(name))
end
defp quote_name(name) do
if String.contains?(name, "\"") do
error!(nil, "bad field name #{inspect name}")
end
[name] # identifiers are not case sensitive
end
defp quote_table(nil, name), do: quote_table(name)
defp quote_table(prefix, name), do: [quote_table(prefix), ?., quote_table(name)]
defp quote_table(name) when is_atom(name),
do: quote_table(Atom.to_string(name))
defp quote_table(name) do
if String.contains?(name, "\"") do
error!(nil, "bad table name #{inspect name}")
end
[name] # identifiers are not case sensitive
end
defp intersperse_map(list, separator, mapper, acc \\ [])
defp intersperse_map([], _separator, _mapper, acc),
do: acc
defp intersperse_map([elem], _separator, mapper, acc),
do: [acc | mapper.(elem)]
defp intersperse_map([elem | rest], separator, mapper, acc),
do: intersperse_map(rest, separator, mapper, [acc, mapper.(elem), separator])
defp intersperse_reduce(list, separator, user_acc, reducer, acc \\ [])
defp intersperse_reduce([], _separator, user_acc, _reducer, acc),
do: {acc, user_acc}
defp intersperse_reduce([elem], _separator, user_acc, reducer, acc) do
{elem, user_acc} = reducer.(elem, user_acc)
{[acc | elem], user_acc}
end
defp intersperse_reduce([elem | rest], separator, user_acc, reducer, acc) do
{elem, user_acc} = reducer.(elem, user_acc)
intersperse_reduce(rest, separator, user_acc, reducer, [acc, elem, separator])
end
defp escape_string(value) when is_list(value) do
escape_string(:binary.list_to_bin(value))
end
defp escape_string(value) when is_binary(value) do
:binary.replace(value, "'", "''", [:global])
end
defp error!(nil, msg) do
raise ArgumentError, msg
end
defp error!(query, msg) do
raise Ecto.QueryError, query: query, message: msg
end
end
defimpl String.Chars, for: Jamdb.Oracle.Query do
def to_string(%Jamdb.Oracle.Query{statement: statement}) do
IO.iodata_to_binary(statement)
end
end
| 34.14977 | 126 | 0.624452 |
f773acedda83108d029e5691de5e82b7760b8778 | 4,244 | ex | Elixir | clients/apps_activity/lib/google_api/apps_activity/v1/api/activities.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/apps_activity/lib/google_api/apps_activity/v1/api/activities.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/apps_activity/lib/google_api/apps_activity/v1/api/activities.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.AppsActivity.V1.Api.Activities do
@moduledoc """
API calls for all endpoints tagged `Activities`.
"""
alias GoogleApi.AppsActivity.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Returns a list of activities visible to the current logged in user. Visible activities are determined by the visibility settings of the object that was acted on, e.g. Drive files a user can see. An activity is a record of past events. Multiple events may be merged if they are similar. A request is scoped to activities from a given Google service using the source parameter.
## Parameters
- connection (GoogleApi.AppsActivity.V1.Connection): Connection to server
- 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.
- :drive.ancestorId (String.t): Identifies the Drive folder containing the items for which to return activities.
- :drive.fileId (String.t): Identifies the Drive item to return activities for.
- :groupingStrategy (String.t): Indicates the strategy to use when grouping singleEvents items in the associated combinedEvent object.
- :pageSize (integer()): The maximum number of events to return on a page. The response includes a continuation token if there are more events.
- :pageToken (String.t): A token to retrieve a specific page of results.
- :source (String.t): The Google service from which to return activities. Possible values of source are: - drive.google.com
- :userId (String.t): The ID used for ACL checks (does not filter the resulting event list by the assigned value). Use the special value me to indicate the currently authenticated user.
## Returns
{:ok, %GoogleApi.AppsActivity.V1.Model.ListActivitiesResponse{}} on success
{:error, info} on failure
"""
@spec appsactivity_activities_list(Tesla.Env.client(), keyword()) ::
{:ok, GoogleApi.AppsActivity.V1.Model.ListActivitiesResponse.t()}
| {:error, Tesla.Env.t()}
def appsactivity_activities_list(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:"drive.ancestorId" => :query,
:"drive.fileId" => :query,
:groupingStrategy => :query,
:pageSize => :query,
:pageToken => :query,
:source => :query,
:userId => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/activities")
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.AppsActivity.V1.Model.ListActivitiesResponse{}]
)
end
end
| 48.227273 | 377 | 0.713242 |
f773bc32a662fdd82668c897bfbaed7684800786 | 1,818 | ex | Elixir | clients/tpu/lib/google_api/tpu/v1/model/list_nodes_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/tpu/lib/google_api/tpu/v1/model/list_nodes_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/tpu/lib/google_api/tpu/v1/model/list_nodes_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.TPU.V1.Model.ListNodesResponse do
@moduledoc """
Response for ListNodes.
## Attributes
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The next page token or empty if none.
* `nodes` (*type:* `list(GoogleApi.TPU.V1.Model.Node.t)`, *default:* `nil`) - The listed nodes.
* `unreachable` (*type:* `list(String.t)`, *default:* `nil`) - Locations that could not be reached.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:nextPageToken => String.t(),
:nodes => list(GoogleApi.TPU.V1.Model.Node.t()),
:unreachable => list(String.t())
}
field(:nextPageToken)
field(:nodes, as: GoogleApi.TPU.V1.Model.Node, type: :list)
field(:unreachable, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.TPU.V1.Model.ListNodesResponse do
def decode(value, options) do
GoogleApi.TPU.V1.Model.ListNodesResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.TPU.V1.Model.ListNodesResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.301887 | 103 | 0.709021 |
f773bdeeb9442c7d14c79a235cdccb3e47a02075 | 1,330 | exs | Elixir | test/game/session/gmcp_test.exs | nomicflux/ex_venture | 3e87dc8802c24067256d99856198c814d0bae4d6 | [
"MIT"
] | null | null | null | test/game/session/gmcp_test.exs | nomicflux/ex_venture | 3e87dc8802c24067256d99856198c814d0bae4d6 | [
"MIT"
] | null | null | null | test/game/session/gmcp_test.exs | nomicflux/ex_venture | 3e87dc8802c24067256d99856198c814d0bae4d6 | [
"MIT"
] | null | null | null | defmodule Game.Session.GMCPTest do
use ExVenture.SessionCase
alias Game.Session.GMCP
alias Game.Session.State
setup do
state = %State{
socket: :socket,
state: "active",
mode: "commands",
}
%{state: state}
end
test "character enters - player", %{state: state} do
GMCP.character_enter(state, {:player, %{id: 10, name: "user"}})
assert_socket_gmcp {"Room.Character.Enter", json}
assert Poison.decode!(json) == %{"type" => "player", "id" => 10, "name" => "user"}
end
test "character enters - npc", %{state: state} do
GMCP.character_enter(state, {:npc, %{id: 10, name: "Bandit"}})
assert_socket_gmcp {"Room.Character.Enter", json}
assert Poison.decode!(json) == %{"type" => "npc", "id" => 10, "name" => "Bandit"}
end
test "character leaves - player", %{state: state} do
GMCP.character_leave(state, {:player, %{id: 10, name: "user"}})
assert_socket_gmcp {"Room.Character.Leave", json}
assert Poison.decode!(json) == %{"type" => "player", "id" => 10, "name" => "user"}
end
test "character leaves - npc", %{state: state} do
GMCP.character_leave(state, {:npc, %{id: 10, name: "user"}})
assert_socket_gmcp {"Room.Character.Leave", json}
assert Poison.decode!(json) == %{"type" => "npc", "id" => 10, "name" => "user"}
end
end
| 29.555556 | 86 | 0.610526 |
f773d8d811f4b3b73e672169eb3ff3c3afbe2277 | 3,293 | ex | Elixir | Getting_Started_Elixir/binaries_strings_charlists.ex | spenserhuang/elixir-learning | c272038f4063038248285fb51f62ec6c0e429f2f | [
"MIT"
] | null | null | null | Getting_Started_Elixir/binaries_strings_charlists.ex | spenserhuang/elixir-learning | c272038f4063038248285fb51f62ec6c0e429f2f | [
"MIT"
] | null | null | null | Getting_Started_Elixir/binaries_strings_charlists.ex | spenserhuang/elixir-learning | c272038f4063038248285fb51f62ec6c0e429f2f | [
"MIT"
] | null | null | null | # This document showcases binaries, strings, and char lists
# UTF-8 and UNICODE
# Strings are UTF-8 encoded binaries. Strings are a bunch of bytes organized in a way to represent certain code points
# The Unicode standard assigns code points to many characters we know
# Characters of code points above 255 need more than one byte to represent them Ex. ł has a code point of 322 and requires 2 bytes to represent it as shown through byte_size/1 and String.length/1 as byte_size/1 counts the underlying raw bytes and String.length/1 counts characters
string = "hełło"
# => "hełło"
byte_size(string)
# => 7
String.length(string)
# => 5
# You can get a character's code point by using ?
?a
# => 97
?ł
# => 322
# You can split a string into individual characters each as a string with length 1
String.codepoints("hełło")
# => ["h", "e", "ł", "ł", "o"]
# BINARIES & BITSTRINGS
# You can define a binary using <<>>
<<0, 1, 2, 3>>
# => <<0, 1, 2, 3>>
byte_size(<<0, 1, 2, 3>>)
# => 4
# Binaries are sequences of bytes and can be organized in any way
String.valid?(<<239, 191, 191>>)
# => false
# String concatenation is actually a binary concatenation operator
<<0, 1>> <> <<2, 3>>
# => <<0, 1, 2, 3>>
"hełło" <> <<0>>
<<104, 101, 197, 130, 197, 130, 111, 0>>
# A common trick is to concatenate the null byte <<0>> to a string to see its inner binary representations
# Each num given to a binary is meant to represent a byte and must go up to 255. We can convert a code point to UTF-8 representation though
<<255>>
# => <<255>>
<<256>>
# => <<0>>
<<256 :: size(16)>>
# => <<1, 0>>
# Use 16 bits (2 bytes) to store the number
<<256 :: utf8>>
# => À
# Number is a code point
<<256 :: utf8, 0>>
# => <<196, 128, 0>>
<<1 :: size(1)>>
# => <<1::size(1)>>
<2 :: size(1)>>
# => <<0::size(1)>>
# Truncated because we only pass a size of 1 bit
is_binary(<<1 :: size(1)>>)
# => false
is_bitstring(<<1 :: size(1)>>)
# => true
bit_size(<<1 :: size(1)>>)
# => 1
# The value is no longer a binary, but a bitstring.
# A binary is a bitstring where the number of bits is divisible by 8
is_binary(<<1 :: size(16)>>)
# => true
is_binary(<<1 :: size(15)>>)
# => false
# We can also pattern match on binaries and bitstrings
<<0, 1, x>> = <<0, 1, 2>>
# => <<0, 1, 2>>
x
# => 2
<<0, 1, x>> = <<0, 1, 2, 3>>
# => **(MatchError) no match of right hand side value: <<0, 1, 2, 3>>
<<0 , 1, x :: binary>> = <<0, 1, 2, 3>>
# => <<0, 1, 2, 3>>
x
# => <<2, 3>>
# Binary pattern is expected to match exactly 8 bits. If we want to match on a binary of unknown size, it is possible by using the binary modifier at the end of the pattern
"he" <> rest = "hello"
# => "hello"
rest
# => "llo"
# Similar results can be done with the string concatenation operator <>
# A string is a UTF-8 encoded binary and a binary is a bitstring where the number of bits is divisible by 8
# CHAR LISTS
# A char list is nothing more than a list of code points
# Char lists may be created with single-quoted literals
'hełło'
# => [104, 101, 322, 322, 111]
is_list('hełło')
# => true
'hello'
# => 'hello'
List.first('hello')
104
# Instaed of containing bytes, char lists contain code points of each character
to_charlist "hełło"
# => [104, 101, 322, 322, 111]
to_string 'hełło'
# => "hełło"
to_string :hello
# => "hello"
to_string 1
# => 1 | 27.672269 | 280 | 0.643486 |
f773f2d9b761cedccf676de8b64ecde919091d05 | 401 | exs | Elixir | hls/test/hls_web/views/error_view_test.exs | Papillon6814/hls_example | f113ecaadabe013a4a5b3a3166d16befb07123c5 | [
"MIT"
] | null | null | null | hls/test/hls_web/views/error_view_test.exs | Papillon6814/hls_example | f113ecaadabe013a4a5b3a3166d16befb07123c5 | [
"MIT"
] | null | null | null | hls/test/hls_web/views/error_view_test.exs | Papillon6814/hls_example | f113ecaadabe013a4a5b3a3166d16befb07123c5 | [
"MIT"
] | null | null | null | defmodule HlsWeb.ErrorViewTest do
use HlsWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(HlsWeb.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(HlsWeb.ErrorView, "500.html", []) == "Internal Server Error"
end
end
| 26.733333 | 88 | 0.723192 |
f7741a47584e195dd38b07b60b774d31ecabad77 | 671 | ex | Elixir | web/models/move.ex | whenther/chopsticks | ec8d9f90cb4e9afc9e80322c734d9c6bfe5e14e1 | [
"MIT"
] | 2 | 2016-11-08T18:17:41.000Z | 2017-02-23T06:51:56.000Z | web/models/move.ex | will-wow/chopsticks | ec8d9f90cb4e9afc9e80322c734d9c6bfe5e14e1 | [
"MIT"
] | null | null | null | web/models/move.ex | will-wow/chopsticks | ec8d9f90cb4e9afc9e80322c734d9c6bfe5e14e1 | [
"MIT"
] | null | null | null | defmodule Chopsticks.Move do
def decode(move) do
type = convert_type_string(move["type"])
data =
case type do
:touch -> convert_touch_data(move["data"])
_ -> nil
end
{type, data}
end
defp convert_type_string("touch"), do: :touch
defp convert_type_string("split"), do: :split
defp convert_type_string("quit"), do: :quit
defp convert_type_string(type), do: type
defp convert_touch_data([player_direction, opponent_direction]) do
{convert_direction(player_direction),
convert_direction(opponent_direction)}
end
defp convert_direction("left"), do: :left
defp convert_direction("right"), do: :right
end
| 25.807692 | 68 | 0.694486 |
f77421d13a9f3ecd882296a5f2ab8c0a9ce3b734 | 65,051 | ex | Elixir | utils/lib/feedback.ex | auranykh/beta_curriculum | b41af67343f13b2c411956ab4789b2a952a4e682 | [
"MIT"
] | null | null | null | utils/lib/feedback.ex | auranykh/beta_curriculum | b41af67343f13b2c411956ab4789b2a952a4e682 | [
"MIT"
] | null | null | null | utils/lib/feedback.ex | auranykh/beta_curriculum | b41af67343f13b2c411956ab4789b2a952a4e682 | [
"MIT"
] | null | null | null | defmodule Utils.Feedback do
@moduledoc """
Utils.Feedback defines tests using the `feedback` macro.
Each `feedback` macro creates an associated Utils.feedback function and
ensures that each has a corresponding solution in Utils.Solutions.
## Examples
```elixir
feedback :example do
answer = get_answers()
assert answer == 5
end
```
Creates a a Utils.feedback(:example, answers) function clause.
"""
Module.register_attribute(Utils.Feedback, :test_names, accumulate: true)
require Utils.Macros
import Utils.Macros
import ExUnit.CaptureLog
require Logger
feedback :card_count_four do
next_count = get_answers()
assert next_count == 1
end
feedback :card_count_king do
next_count = get_answers()
assert next_count === 4
end
feedback :card_count_random do
[card, next_count] = get_answers()
cond do
card in 2..6 ->
assert next_count === 1
card in 7..9 ->
assert next_count === 0
card in 10..14 ->
assert next_count === -1
true ->
raise "Something went wrong. Please reset the exercise."
end
end
feedback :habit_tracker_definition do
[small, medium, large] = get_answers()
assert small == 5
assert medium == 20
assert large == 30
end
feedback :habit_tracker_add do
total_points = get_answers()
assert total_points == 20 + 5
end
feedback :habit_tracker_percentage do
percentage = get_answers()
assert percentage == (5 + 20) / 40 * 100
end
feedback :habit_tracker_penalties_1 do
total_points = get_answers()
assert total_points == 5 + 20 + 30 * 0.5
end
feedback :habit_tracker_penalties_2 do
total_points = get_answers()
assert total_points == 5 / 2 * 3 + 20 / 2 * 3
end
feedback :habit_tracker_rewards do
total_points = get_answers()
assert total_points == 20 * 1.6 + 5 * 1.6 + 30 * 0.5
end
feedback :percentage do
[completed_items, total_items, percentage] = get_answers()
assert completed_items == 10,
"completed_items should always be 10. Please reset the exercise."
assert total_items == 100, "total_items should always be 100. Please reset the exercise."
assert percentage == completed_items / total_items * 100
end
feedback :pythagorean_c_square do
c_square = get_answers()
assert c_square == 10 ** 2 + 10 ** 2
end
feedback :pythagorean_c do
c = get_answers()
assert c == :math.sqrt(200)
end
feedback :string_concatenation do
answer = get_answers()
assert is_binary(answer), "the answer should be a string."
assert "Hi, " <> _name = answer, "the answer should be in the format: Hi, name."
assert Regex.match?(~r/Hi, \w+\./, answer), "the answer should end in a period."
end
feedback :string_interpolation do
answer = get_answers()
assert is_binary(answer), "the answer should be a string."
assert Regex.match?(~r/I have/, answer),
"the answer should be in the format: I have 10 classmates"
assert Regex.match?(~r/I have \d+/, answer),
"the answer should contain an integer for classmates."
assert Regex.match?(~r/I have \d+ classmates\./, answer) ||
answer === "I have 1 classmate.",
"the answer should end in a period."
end
feedback :tip_amount do
[cost_of_the_meal, tip_rate, tip_amount] = get_answers()
assert tip_rate == 0.20, "tip rate should be 0.2."
assert cost_of_the_meal == 55.5, "cost_of_the_meal should be 55.5."
assert tip_amount === cost_of_the_meal * tip_rate,
"tip_amount should be cost_of_the_meal * tip_rate."
end
feedback :rock_paper_scissors_ai do
[player_choice, ai_choice] = get_answers()
case player_choice do
:rock ->
assert ai_choice === :paper,
"when player_choice is :rock, ai_choice should be :paper."
:paper ->
assert ai_choice === :scissors,
"when player_choice is :paper, ai_choice should be :scissors."
:scissors ->
assert ai_choice === :rock,
"when player_choice is :scissors, ai_choice should be :rock."
end
end
feedback :rock_paper_scissors_two_player do
[player1_choice, player2_choice, winner] = get_answers()
case {player1_choice, player2_choice} do
{:rock, :scissors} -> assert winner == :player1
{:paper, :rock} -> assert winner == :player1
{:scissors, :paper} -> assert winner == :player1
{:scissors, :rock} -> assert winner == :player2
{:rock, :paper} -> assert winner == :player2
{:paper, :scissors} -> assert winner == :player2
_ -> assert winner == :draw
end
end
feedback :rock_paper_scissors_pattern_matching do
rock_paper_scissors = get_answers()
assert rock_paper_scissors.play(:rock, :rock) == "draw",
"Ensure you implement the RockPaperScissors.play/2 function."
assert rock_paper_scissors.play(:paper, :paper) == "draw"
assert rock_paper_scissors.play(:scissors, :scissors) == "draw"
assert rock_paper_scissors.play(:rock, :scissors) == ":rock beats :scissors!"
assert rock_paper_scissors.play(:scissors, :paper) == ":scissors beats :paper!"
assert rock_paper_scissors.play(:paper, :rock) == ":paper beats :rock!"
assert rock_paper_scissors.play(:rock, :paper) == ":paper beats :rock!"
assert rock_paper_scissors.play(:scissors, :rock) == ":rock beats :scissors!"
assert rock_paper_scissors.play(:paper, :scissors) == ":scissors beats :rock!"
end
feedback :rocket_ship do
force = get_answers()
assert force == 20
end
feedback :startup_madlib do
[
madlib,
name_of_company,
a_defined_offering,
a_defined_audience,
solve_a_problem,
secret_sauce
] = answers = get_answers()
assert Enum.all?(answers, fn each -> is_binary(each) and String.length(each) > 0 end),
"each variable should be bound to a non-empty string"
assert madlib ==
"My company, #{name_of_company} is developing #{a_defined_offering} to help #{a_defined_audience} #{solve_a_problem} with #{secret_sauce}."
end
feedback :nature_show_madlib do
[
animal,
country,
plural_noun,
a_food,
type_of_screen_device,
noun,
verb1,
verb2,
adjective,
madlib
] = answers = get_answers()
assert Enum.all?(answers, fn each -> is_binary(each) and String.length(each) > 0 end),
"each variable should be bound to a non-empty string"
assert madlib ==
"The majestic #{animal} has roamed the forests of #{country} for thousands of years. Today she wanders in search of #{plural_noun}. She must find food to survive. While hunting for #{a_food}, she found a/an #{type_of_screen_device} hidden behind a #{noun}. She has never seen anything like this before. What will she do? With the device in her teeth, she tries to #{verb1}, but nothing happens. She takes it back to her family. When her family sees it, they quickly #{verb2}. Soon, the device becomes #{adjective}, and the family decides to put it back where they found it."
end
feedback :boolean_diagram1 do
answer = get_answers()
assert answer == false
end
feedback :boolean_diagram2 do
answer = get_answers()
assert answer == true
end
feedback :boolean_diagram3 do
answer = get_answers()
assert answer == false
end
feedback :boolean_diagram4 do
answer = get_answers()
assert answer == false
end
feedback :boolean_diagram5 do
answer = get_answers()
assert answer == true
end
feedback :boolean_diagram6 do
answer = get_answers()
assert answer == true
end
feedback :guess_the_word do
[guess, answer, correct] = answers = get_answers()
assert Enum.all?(answers, &is_binary/1),
"Ensure `guess`, `answer`, and `correct` are all strings"
if guess == answer do
assert correct == "Correct!"
else
assert correct == "Incorrect."
end
end
feedback :guess_the_number do
[guess, answer, correct] = get_answers()
assert is_integer(guess), "Ensure `guess` is an integer"
assert is_integer(answer), "Ensure `answer` is an integer"
assert is_binary(correct), "Ensure `correct` is a string"
cond do
guess == answer -> assert correct == "Correct!"
guess < answer -> assert correct == "Too low!"
guess > answer -> assert correct == "Too high!"
end
end
feedback :copy_file do
file_name = get_answers()
assert {:ok, "Copy me!"} = File.read("../data/#{file_name}")
end
feedback :shopping_list do
shopping_list = get_answers()
list = [] ++ ["grapes", "walnuts", "apples"]
list = list ++ ["blueberries", "chocolate", "pizza"]
list = list -- ["grapes", "walnuts"]
list = list ++ ["banana", "banana", "banana"]
assert is_list(shopping_list), "Ensure shopping_list is still a list."
assert Enum.sort(list) == Enum.sort(shopping_list),
"Ensure your shopping list has all of the expected items"
assert shopping_list == list, "Ensure you add and remove items in the expected order"
end
feedback :shopping_list_with_quantities do
shopping_list = get_answers()
list = [] ++ [milk: 1, eggs: 12]
list = list ++ [bars_of_butter: 2, candies: 10]
list = list -- [bars_of_butter: 2]
list = list -- [candies: 10]
list = list ++ [candies: 5]
assert is_list(shopping_list), "Ensure shopping_list is still a list."
assert Enum.sort(shopping_list) == Enum.sort(shopping_list),
"Ensure your shopping list has all of the expected items"
assert shopping_list == list, "Ensure you add and remove items in the expected order"
end
feedback :family_tree do
family_tree = get_answers()
assert is_map(family_tree), "Ensure `family_tree` is a map."
assert %{name: "Arthur"} = family_tree, "Ensure `family_tree` starts with Arthur."
assert %{name: "Arthur", parents: _list} = family_tree,
"Ensure Arthur in `family_tree` has a list of parents."
assert family_tree == Utils.Solutions.family_tree()
end
feedback :naming_numbers do
naming_numbers = get_answers()
assert is_function(naming_numbers),
"Ensure you bind `naming_numbers` to an anonymous function."
list = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
Enum.each(1..9, fn integer ->
assert naming_numbers.(integer) == Enum.at(list, integer)
end)
end
feedback :numbering_names do
numbering_names = get_answers()
list = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
capital_list = Enum.map(list, &String.capitalize/1)
assert is_function(numbering_names),
"Ensure you bind `naming_numbers` to an anonymous function."
Enum.each(list, fn name ->
assert numbering_names.(name) ==
Enum.find_index(list, fn each -> each == String.downcase(name) end)
end)
Enum.each(capital_list, fn name ->
assert numbering_names.(name) ==
Enum.find_index(list, fn each -> each == String.downcase(name) end)
end)
end
feedback :define_character_struct do
character_module = get_answers()
assert Keyword.get(character_module.__info__(:functions), :__struct__),
"Ensure you use `defstruct`"
assert match?(%{name: nil, class: nil, weapon: nil}, struct(character_module)),
"Ensure you use `defstruct` with :name, :class, and :weapon"
assert_raise ArgumentError, fn ->
struct!(character_module, %{weapon: "", class: ""})
end
end
feedback :character_structs do
[arthur, gandalf, jarlaxle] = get_answers()
assert is_struct(arthur), "Ensure `arthur` is a struct."
assert is_struct(gandalf), "Ensure `gandalf` is a struct."
assert is_struct(jarlaxle), "Ensure `jarlaxle` is a struct."
assert %{name: "Arthur", weapon: "sword", class: "warrior"} = arthur
assert %{name: "Gandalf", weapon: "staff", class: "wizard"} = gandalf
assert %{name: "Jarlaxle", weapon: "daggers", class: "rogue"} = jarlaxle
end
feedback :character_dialogue do
dialogue_module = get_answers()
character_permutations =
for class <- ["wizard", "rogue", "warrior", nil],
weapon <- ["daggers", "sword", "staff", nil],
name <- [Utils.Factory.name(), nil] do
%{class: class, weapon: weapon, name: name}
end
enemy = Utils.Factory.name()
Enum.each(character_permutations, fn character ->
assert dialogue_module.greet(character) == "Hello, my name is #{character.name}."
assert dialogue_module.attack(character, enemy) ==
"#{character.name} attacks #{enemy} with a #{character.weapon}."
relinquish_weapon_dialogue =
case character.class do
"rogue" -> "Fine, have my #{character.weapon}. I have more hidden anyway."
"wizard" -> "You would not part an old man from his walking stick?"
"warrior" -> "Have my #{character.weapon} then!"
_ -> "My precious!"
end
assert dialogue_module.relinquish_weapon(character) == relinquish_weapon_dialogue
matching_weapon_dialogue =
case {character.class, character.weapon} do
{"wizard", "staff"} -> "My lovely magical staff"
{"rogue", "daggers"} -> "Hidden and deadly."
{"warrior", "sword"} -> "My noble sword!"
{_, nil} -> "I'm unarmed!"
{_, _} -> "I'm not sure a #{character.weapon} suits a #{character.class}."
end
assert dialogue_module.matching_weapon(character) == matching_weapon_dialogue
end)
end
feedback :define_pokemon_struct do
pokemon_module = get_answers()
assert Keyword.get(pokemon_module.__info__(:functions), :__struct__),
"Ensure you use `defstruct`."
assert match?(%{name: nil, type: nil, speed: nil}, struct(pokemon_module)),
"Ensure you use `defstruct` with :name, :type, :health, :attack, and :speed."
assert match?(%{health: 20, attack: 5}, struct(pokemon_module)),
"Ensure :health has a default value of 20 and :attack has a default value of 5."
end
feedback :pokemon_structs do
[charmander, bulbasaur, squirtle] = get_answers()
assert is_struct(charmander), "Ensure `charmander` is a struct."
assert is_struct(squirtle), "Ensure `squirtle` is a struct."
assert is_struct(bulbasaur), "Ensure `bulbasaur` is a struct."
assert %{name: "Charmander", type: :fire, attack: 5, health: 20, speed: 20} = charmander
assert %{name: "Bulbasaur", type: :grass, attack: 5, health: 20, speed: 15} = bulbasaur
assert %{name: "Squirtle", type: :water, attack: 5, health: 20, speed: 10} = squirtle
end
feedback :pokemon_battle do
[pokemon_battle_module, pokemon_module] = get_answers()
assert Keyword.get(pokemon_module.__info__(:functions), :__struct__),
"Ensure you complete the `Pokemon` module above first."
assert match?(
%{name: nil, type: nil, speed: nil, health: 20, attack: 5},
struct(pokemon_module)
),
"Ensure you complete the `Pokemon` module above first."
pokemon_types =
for speed <- 10..30//5,
type <- [:water, :fire, :grass],
attack <- 5..40//5,
health <- 5..20//5 do
struct(pokemon_module, %{
name: "#{Atom.to_string(type)} pokemon",
speed: speed,
attack: attack,
health: health
})
end
pokemon_types
|> Enum.shuffle()
|> Enum.take(2)
|> Enum.chunk_every(2)
|> Enum.each(fn [pokemon1, pokemon2] ->
attacked_pokemon = pokemon_battle_module.attack(pokemon1, pokemon2)
multiplier = Utils.Solutions.PokemonBattle.multiplier(pokemon1, pokemon2)
assert attacked_pokemon == %{
pokemon2
| health: pokemon2.health - pokemon2.attack * multiplier
}
assert {battled_pokemon1, battled_pokemon2} =
pokemon_battle_module.battle(pokemon1, pokemon2)
{expected_battled_pokemon1, expected_battled_pokemon2} =
Utils.Solutions.PokemonBattle.battle(pokemon1, pokemon2)
assert battled_pokemon1 == expected_battled_pokemon1
assert battled_pokemon2 == expected_battled_pokemon2
end)
end
feedback :rock_paper_scissors_lizard_spock do
module = get_answers()
assert Keyword.has_key?(module.__info__(:functions), :play),
"Ensure you define the `play/2` function"
game_permutations =
for player1 <- [:rock, :paper, :scissors, :lizard, :spock],
player2 <- [:rock, :paper, :scissors, :lizard, :spock] do
{player1, player2}
end
beats? = fn player1, player2 ->
{player1, player2} in [
{:rock, :paper},
{:paper, :rock},
{:scissors, :paper},
{:rock, :lizard},
{:lizard, :spock},
{:scissors, :lizard},
{:lizard, :paper},
{:paper, :spock},
{:spock, :rock}
]
end
Enum.each(game_permutations, fn {p1, p2} ->
expected_result =
cond do
beats?.(p1, p2) -> "#{p1} beats #{p2}."
beats?.(p2, p1) -> "#{p2} beats #{p1}."
true -> "tie game, play again?"
end
actual = module.play(p1, p2)
assert actual == expected_result,
"Failed on RockPaperScissorsLizardSpock.play(:#{p1}, :#{p2})."
end)
end
feedback :custom_rps do
custom_game_module = get_answers()
assert 3 == Keyword.get(custom_game_module.__info__(:functions), :new),
"Ensure you define the `new/3` function"
assert Keyword.get(custom_game_module.__info__(:functions), :__struct__),
"Ensure you use `defstruct`."
assert match?(%{rock: _, paper: _, scissors: _}, struct(custom_game_module)),
"Ensure you use `defstruct` with :rock, :paper, and :scissors."
assert %{rock: :custom_rock, paper: :custom_paper, scissors: :custom_scissors} =
custom_game_module.new(:custom_rock, :custom_paper, :custom_scissors)
assert 3 == Keyword.get(custom_game_module.__info__(:functions), :play),
"Ensure you define the `play/3` function"
game = custom_game_module.new(:custom_rock, :custom_paper, :custom_scissors)
beats? = fn p1, p2 ->
{p1, p2} in [
{:custom_rock, :custom_scissors},
{:custom_paper, :custom_rock},
{:custom_scissors, :custom_paper}
]
end
for player1 <- [:custom_rock, :custom_paper, :custom_scissors],
player2 <- [:custom_rock, :custom_paper, :custom_scissors] do
result = custom_game_module.play(game, player1, player2)
expected_result =
cond do
beats?.(player1, player2) -> "#{player1} beats #{player2}"
beats?.(player2, player1) -> "#{player2} beats #{player1}"
true -> "draw"
end
assert result == expected_result
end
end
feedback :fizzbuzz do
fizz_buzz_module = get_answers()
assert fizz_buzz_module.run(1..15) == [
1,
2,
"fizz",
4,
"buzz",
"fizz",
7,
8,
"fizz",
"buzz",
11,
"fizz",
13,
14,
"fizzbuzz"
]
assert fizz_buzz_module.run(1..100) == Utils.Solutions.FizzBuzz.run(1..100)
end
feedback :voter_count do
voter_count = get_answers()
assert voter_count.count([], :test), "Implement the `count` function."
assert voter_count.count([:dogs, :dogs, :dogs, :cats], :dogs) == 3,
"failed on ([:dogs, :dogs, :dogs, :cats], :dogs)"
assert voter_count.count([:dogs, :dogs, :dogs, :cats], :cats) == 1,
"Failed on ([:dogs, :dogs, :dogs, :cats], :cats)"
assert voter_count.count([:apples, :oranges, :apples, :cats], :birds) == 0,
"Failed on ([:apples, :oranges, :apples, :cats], :birds)"
list = Enum.map(1..10, fn _ -> Enum.random([:cat, :dog, :bird, :apple, :orange]) end)
choice = Enum.random([:cat, :dog, :bird, :apple, :orange])
assert voter_count.count(list, choice) == Enum.count(list, fn each -> each == choice end)
end
feedback :is_anagram do
anagram_module = get_answers()
assert anagram_module.is_anagram?("stop", "pots") == true
refute anagram_module.is_anagram?("example", "nonanagram") == true
word = Utils.Factory.string()
generate_non_anagram = fn word ->
word <> Enum.random(["a", "b", "c"])
end
generate_anagram = fn word ->
String.split(word, "", trim: true) |> Enum.shuffle() |> Enum.join("")
end
assert anagram_module.is_anagram?(word, generate_anagram.(word)),
"`is_anagram?/1` failed to identify anagram."
refute anagram_module.is_anagram?(word, generate_non_anagram.(word)),
"`is_anagram?/1` failed to identify non-anagram."
non_anagrams = Enum.map(1..5, fn _ -> generate_non_anagram.(word) end)
anagrams = Enum.map(1..5, fn _ -> generate_anagram.(word) end)
result = anagram_module.filter_anagrams(word, anagrams ++ non_anagrams)
assert is_list(result), "filter_anagrams/2 should return a list"
assert Enum.sort(result) == Enum.sort(anagrams), "filter_anagrams/2 failed to filter anagrams"
end
feedback :bottles_of_soda do
bottles_of_soda = get_answers()
result = bottles_of_soda.on_the_wall()
assert result, "Implement the `on_the_wall/0` function."
assert is_list(result), "`on_the_wall/0` should return a list."
assert Enum.at(result, 0) ==
"99 bottles of soda on the wall.\n99 bottles of soda.\nTake one down, pass it around.\n98 bottles of soda on the wall."
assert length(result) == 100, "There should be 100 total verses."
assert Enum.at(result, 97) ==
"2 bottles of soda on the wall.\n2 bottles of soda.\nTake one down, pass it around.\n1 bottle of soda on the wall."
assert Enum.at(result, 98) ==
"1 bottle of soda on the wall.\n1 bottle of soda.\nTake one down, pass it around.\n0 bottles of soda on the wall."
assert Enum.at(result, 99) ==
"No more bottles of soda on the wall, no more bottles of soda.\nGo to the store and buy some more, 99 bottles of soda on the wall."
assert result == Utils.Solutions.BottlesOfSoda.on_the_wall()
end
feedback :bottles_of_blank do
bottles_of_soda = get_answers()
result = bottles_of_soda.on_the_wall(50..0, "pop", "cans")
assert result, "Implement the `on_the_wall/3` function."
assert is_list(result), "`on_the_wall/3` should return a list."
assert Enum.at(result, 0) ==
"50 cans of pop on the wall.\n50 cans of pop.\nTake one down, pass it around.\n49 cans of pop on the wall."
assert length(result) == 51, "There should be 51 total verses."
assert Enum.at(result, 48) ==
"2 cans of pop on the wall.\n2 cans of pop.\nTake one down, pass it around.\n1 can of pop on the wall."
assert Enum.at(result, 49) ==
"1 can of pop on the wall.\n1 can of pop.\nTake one down, pass it around.\n0 cans of pop on the wall."
assert Enum.at(result, 50) ==
"No more cans of pop on the wall, no more cans of pop.\nGo to the store and buy some more, 99 cans of pop on the wall."
end
feedback :item_generator_item do
item = get_answers()
assert Keyword.get(item.__info__(:functions), :__struct__),
"Ensure you use `defstruct`."
assert match?(%{type: nil, effect: nil, level: nil, size: nil, style: nil}, struct(item)),
"Ensure you use `defstruct` with :type, :effect, :level, :size, and :style."
end
feedback :item_generator do
items = get_answers()
assert is_list(items), "`items` should be a list."
expected_items = Utils.Solutions.item_generator()
expected_length = length(expected_items)
assert length(items) == expected_length,
"There should be #{expected_length} permutations of items."
Enum.each(items, fn item ->
assert is_struct(item), "Each item should be an `Item` struct."
assert match?(%{type: _, effect: _, style: _, size: _, level: _, __struct__: _}, item)
end)
end
feedback :item_generator_search do
search = get_answers()
items = [Utils.Factory.item(%{}), Utils.Factory.item()]
result = search.all_items(items, [])
assert result, "Implement the `all_items/2` function."
assert is_list(result), "`all_items/2` should return a list."
assert length(result) == 2,
"`all_items/2` should return all items when no filters are provided."
assert length(result) == 2,
"`all_items/2` should return all items when no filters are provided."
assert Enum.sort(items) == Enum.sort(result),
"`all_items/2` should return all items when no filters are provided."
[item1, _] = items = [Utils.Factory.item(%{type: "a"}), Utils.Factory.item(%{type: "b"})]
result = search.all_items(items, type: "a")
assert result == [item1], "`all_items/2` should filter by type."
[item1, _] = items = [Utils.Factory.item(%{effect: "a"}), Utils.Factory.item(%{effect: "b"})]
result = search.all_items(items, effect: "a")
assert result == [item1], "`all_items/2` should filter by type."
[item1, _] = items = [Utils.Factory.item(%{style: "a"}), Utils.Factory.item(%{style: "b"})]
result = search.all_items(items, style: "a")
assert result == [item1], "`all_items/2` should filter by style."
[item1, _] = items = [Utils.Factory.item(%{size: 1}), Utils.Factory.item(%{size: 2})]
result = search.all_items(items, size: 1)
assert result == [item1], "`all_items/2` should filter by size."
[item1, _] = items = [Utils.Factory.item(%{level: 1}), Utils.Factory.item(%{level: 2})]
result = search.all_items(items, level: 1)
assert result == [item1], "`all_items/2` should filter by level."
[item1, item2] = items = [Utils.Factory.item(), Utils.Factory.item(%{level: 2})]
result =
search.all_items(items,
type: item1.type,
effect: item1.effect,
style: item1.style,
size: item1.size,
level: item1.level
)
assert result == [item1], "`all_items/2` should work with multiple filters."
result =
search.all_items(items,
type: item1.type,
effect: item1.effect,
style: item1.style,
size: item1.size,
level: item2.level,
inclusive: true
)
assert Enum.sort(result) == Enum.sort([item1, item2]),
"`all_items/2` should work with multiple inclusive filters."
end
feedback :custom_enum do
list = Enum.to_list(1..10)
custom_enum = get_answers()
assert custom_enum.map(list, & &1), "Implement the `map/2` funtion."
assert is_list(custom_enum.map(list, & &1)), "`map/2` should return a list."
assert custom_enum.map(list, &(&1 * 2)) == Enum.map(list, &(&1 * 2)),
"`map/2` should call the function on each element and return a new list."
assert custom_enum.each(list, & &1), "Implement the `each/2` funtion."
assert custom_enum.each(list, & &1) == :ok, "`each/2` should return :ok."
assert custom_enum.filter(list, & &1), "Implement the `filter/2` funtion."
assert is_list(custom_enum.filter(list, & &1)), "`each/2` should return a list."
assert custom_enum.filter(list, &(&1 < 5)) == Enum.filter(list, &(&1 < 5))
assert custom_enum.sum(list), "Implement the `sum/1` funtion."
assert is_integer(custom_enum.sum(list)), "`sum/1` should return an integer."
assert custom_enum.sum(list) == Enum.sum(list)
end
feedback :voter_tally do
voter_tally = get_answers()
assert voter_tally.tally([]), "Implement the `tally/1` function."
assert is_map(voter_tally.tally([])), "`tally/1` should return a map."
assert voter_tally.tally([:dogs, :cats]) == %{dogs: 1, cats: 1}
assert voter_tally.tally([:dogs, :dogs, :cats]) == %{dogs: 2, cats: 1}
votes = Enum.map(1..10, fn _ -> Enum.random([:cats, :dogs, :birds]) end)
expected_result =
Enum.reduce(votes, %{}, fn each, acc ->
Map.update(acc, each, 1, fn existing_value -> existing_value + 1 end)
end)
assert voter_tally.tally(votes) == expected_result
end
feedback :voter_power do
voter_tally = get_answers()
assert voter_tally.tally([]), "Implement the `tally/1` function."
assert is_map(voter_tally.tally([])), "`tally/1` should return a map."
assert voter_tally.tally(dogs: 2) == %{dogs: 2}
assert voter_tally.tally(dogs: 2, cats: 1) == %{dogs: 2, cats: 1}
assert voter_tally.tally([:cats, dogs: 2]) == %{dogs: 2, cats: 1}
assert voter_tally.tally([:dogs, :cats, birds: 3, dogs: 10]) == %{dogs: 11, cats: 1, birds: 3}
end
feedback :measurements do
measurements = get_answers()
list = Utils.Factory.integers()
assert measurements.increased([1, 1]), "Implement the `increased` function."
assert measurements.increased([1, 2, 1]) == 1
assert measurements.increased([1, 1, 2, 3, 1]) == 2
assert measurements.increased(list) == Utils.Solutions.Measurements.increased(list)
assert measurements.increased_by([1, 1]), "Implement the `increased_by` function."
assert measurements.increased_by([100, 150, 120, 130]) == 60
assert measurements.increased_by([10, 20, 10, 40]) == 40
assert measurements.increased_by(list) == Utils.Solutions.Measurements.increased_by(list)
assert measurements.increments([1, 2]), "Implement the `increments` function."
assert measurements.increments([100, 150, 120, 130]) == [50, -30, 10]
assert measurements.increments([10, 20, 10, 40]) == [10, -10, 30]
assert measurements.increments(list) == Utils.Solutions.Measurements.increments(list)
assert measurements.average([1, 1]), "Implement the `average` function."
assert measurements.average([4, 5, 6]) == 5
assert measurements.average([2, 10]) == 6
assert measurements.average(list) == Utils.Solutions.Measurements.average(list)
end
feedback :keyword_list_hero do
hero = get_answers()
assert [name: _, secret_identity: _] = hero,
"Ensure hero is a keyword list with :name and :secret_identity."
end
feedback :string_key_map do
map = get_answers()
assert is_map(map), "Ensure you use %{} to create a map."
assert map_size(map) > 0, "Ensure your map is not empty."
assert Enum.all?(Map.keys(map), &is_binary/1), "Ensure your map contains only string keys."
end
feedback :atom_key_map do
map = get_answers()
assert is_map(map), "Ensure you use %{} to create a map."
assert map_size(map) > 0, "Ensure your map is not empty."
assert Enum.all?(Map.keys(map), &is_atom/1), "Ensure your map contains only atom keys."
end
feedback :non_standard_key_map do
map = get_answers()
assert is_map(map), "Ensure you use %{} to create a map."
assert map_size(map) > 0, "Ensure your map is not empty."
assert Enum.all?(Map.keys(map), fn key -> !is_atom(key) and !is_binary(key) end),
"Ensure your map contains only non-atom and non-string keys."
end
feedback :access_map do
value = get_answers()
assert value == "world"
end
feedback :update_map do
updated_map = get_answers()
assert is_map(updated_map), "Ensure `updated_map` is a map."
assert Map.has_key?(updated_map, :example_key),
"Ensure `updated_map` still has the `:example_key`"
assert %{example_key: _} = updated_map
assert updated_map.example_key !== "value",
"Ensure you update the :example_key with a changed value."
end
feedback :remainder do
remainder = get_answers()
assert remainder == rem(10, 3)
end
feedback :exponents do
result = get_answers()
assert result == 10 ** 214
end
feedback :bedmas do
answer = get_answers()
assert answer == (20 + 20) * 20
end
feedback :gcd do
gcd = get_answers()
assert gcd == Integer.gcd(10, 15)
end
feedback :string_at do
answer = get_answers()
assert answer == "l"
end
feedback :merged_map do
merged_map = get_answers()
assert merged_map == %{one: 1, two: 2}
end
feedback :bingo_winner do
bingo_winner = get_answers()
row_win = ["X", "X", "X"]
row_lose = [nil, nil, nil]
# full board
assert bingo_winner.is_winner?([row_win, row_win, row_win])
# empty (losing) board
refute bingo_winner.is_winner?([row_lose, row_lose, row_lose])
# rows
assert bingo_winner.is_winner?([row_win, row_lose, row_lose])
assert bingo_winner.is_winner?([row_lose, row_win, row_lose])
assert bingo_winner.is_winner?([row_lose, row_lose, row_win])
# colums
assert bingo_winner.is_winner?([["X", nil, nil], ["X", nil, nil], ["X", nil, nil]])
assert bingo_winner.is_winner?([[nil, "X", nil], [nil, "X", nil], [nil, "X", nil]])
assert bingo_winner.is_winner?([[nil, nil, "X"], [nil, nil, "X"], [nil, nil, "X"]])
# diagonals
assert bingo_winner.is_winner?([["X", nil, nil], [nil, "X", nil], [nil, nil, "X"]])
assert bingo_winner.is_winner?([[nil, nil, "X"], [nil, "X", nil], ["X", nil, nil]])
# losing boards (not fully comprehensive)
losing_board =
["X", "X", nil, nil, nil, nil, nil, nil, nil] |> Enum.shuffle() |> Enum.chunk_every(3)
refute bingo_winner.is_winner?(losing_board)
end
feedback :bingo do
bingo = get_answers()
numbers = Enum.to_list(1..9)
[row1, row2, row3] = board = Enum.chunk_every(numbers, 3)
[r1c1, r1c2, r1c3] = row1
[r2c1, r2c2, r2c3] = row2
[r3c1, r3c2, r3c3] = row3
# rows
assert bingo.is_winner?(board, row1)
assert bingo.is_winner?(board, row2)
assert bingo.is_winner?(board, row3)
# columns
assert bingo.is_winner?(board, [r1c1, r2c1, r3c1])
assert bingo.is_winner?(board, [r1c2, r2c2, r3c2])
assert bingo.is_winner?(board, [r1c3, r2c3, r3c3])
# diagonals
assert bingo.is_winner?(board, [r1c1, r2c2, r3c3])
assert bingo.is_winner?(board, [r3c1, r2c2, r1c3])
# losing (not fully comprehensive)
refute bingo.is_winner?(board, numbers |> Enum.shuffle() |> Enum.take(2))
end
feedback :is_type do
[
is_a_map,
is_a_bitstring,
is_a_integer,
is_a_float,
is_a_boolean,
is_a_list,
is_a_tuple
] = get_answers()
assert is_a_map, "Use the Kernel.is_map/1 function on `map`"
assert is_a_bitstring, "Use the Kernel.is_binary/1 function on `bitstring`"
assert is_a_integer, "Use the Kernel.is_integer/1 function on `integer`"
assert is_a_float, "Use the Kernel.is_float/1 function on `float`"
assert is_a_boolean, "Use the Kernel.is_boolean/1 function on `boolean`"
assert is_a_list, "Use the Kernel.is_list/1 function on `list`"
assert is_a_tuple, "Use the Kernel.is_tuple/1 function on `tuple`"
end
feedback :pipe_operator do
answer = get_answers()
assert answer
assert is_integer(answer), "answer should be an integer"
assert answer == 56
end
feedback :filter_by_type do
filter = get_answers()
input = [1, 2, 1.0, 2.0, :one, :two, [], [1], [1, 2], %{}, %{one: 1}, [one: 1], [two: 2]]
assert filter.integers(input) == [1, 2]
assert filter.floats(input) == [1.0, 2.0]
assert filter.numbers(input) == [1, 2, 1.0, 2.0]
assert filter.atoms(input) == [:one, :two]
assert filter.lists(input) == [[], [1], [1, 2], [one: 1], [two: 2]]
assert filter.maps(input) == [%{}, %{one: 1}]
assert filter.keyword_lists(input) == [[], [one: 1], [two: 2]]
end
feedback :tic_tak_toe do
tic_tak_toe = get_answers()
board = [
[nil, nil, nil],
[nil, nil, nil],
[nil, nil, nil]
]
assert tic_tak_toe.play(board, {0, 0}, "X"), "Ensure you implement the `play/3` function."
assert tic_tak_toe.play(board, {0, 0}, "X") == [
["X", nil, nil],
[nil, nil, nil],
[nil, nil, nil]
]
assert tic_tak_toe.play(board, {0, 2}, "X") == [
[nil, nil, "X"],
[nil, nil, nil],
[nil, nil, nil]
]
assert tic_tak_toe.play(board, {1, 1}, "X") == [
[nil, nil, nil],
[nil, "X", nil],
[nil, nil, nil]
]
assert tic_tak_toe.play(board, {2, 2}, "X") == [
[nil, nil, nil],
[nil, nil, nil],
[nil, nil, "X"]
]
assert board
|> tic_tak_toe.play({0, 0}, "X")
|> tic_tak_toe.play({1, 1}, "O")
|> tic_tak_toe.play({2, 2}, "X")
|> tic_tak_toe.play({2, 1}, "O") ==
[
["X", nil, nil],
[nil, "O", nil],
[nil, "O", "X"]
]
end
feedback :datetime_new do
date = get_answers()
assert date == DateTime.new!(~D[1938-04-18], ~T[12:00:00])
end
feedback :datetime_today do
today = get_answers()
now = DateTime.utc_now()
assert today.year == now.year
assert today.month == now.month
assert today.day == now.day
assert today.hour == now.hour
assert today.minute == now.minute
assert today.second == now.second
end
feedback :datetime_tomorrow do
today = get_answers()
now = DateTime.utc_now()
assert today.year == now.year
assert today.month == now.month
assert today.day == now.day + 1
assert today.hour == now.hour
assert today.minute == now.minute
assert today.second == now.second
end
feedback :datetime_compare do
comparison = get_answers()
assert comparison == :gt
end
feedback :datetime_diff do
difference = get_answers()
assert is_integer(difference), "`difference` should be a positive integer."
assert difference != -318_384_000, "Ensure your arguments are in the correct order."
assert difference == 318_384_000
end
feedback :itinerary do
itinerary = get_answers()
start = DateTime.utc_now()
# four hours
finish = DateTime.add(start, 60 * 60 * 4)
assert itinerary.has_time?(start, finish, [])
assert itinerary.has_time?(start, finish, hour: 0)
assert itinerary.has_time?(start, finish, hour: 0, minute: 0)
assert itinerary.has_time?(start, finish, hour: 3, minute: 59)
assert itinerary.has_time?(start, finish, hour: 4)
refute itinerary.has_time?(start, finish, hour: 5)
refute itinerary.has_time?(start, finish, hour: 4, minute: 1)
end
feedback :timeline do
timeline = get_answers()
assert timeline.generate(["2022-04-24", "2022-04-24"]) == [0]
assert timeline.generate(["2022-04-24", "2022-04-25"]) == [1]
assert timeline.generate(["2022-04-24", "2022-05-24"]) == [30]
assert timeline.generate(["2022-04-24", "2023-04-24"]) == [365]
assert timeline.generate(["2022-04-24", "2023-05-24"]) == [395]
end
feedback :school_must_register do
school_grades = get_answers()
name = Faker.Person.first_name()
assert school_grades.must_register([], 2022) == []
assert school_grades.must_register([%{name: name, birthday: Date.new!(2017, 12, 31)}], 2022) ==
[%{name: name, birthday: Date.new!(2017, 12, 31)}]
assert school_grades.must_register([%{name: name, birthday: Date.new!(2018, 1, 1)}], 2022) ==
[]
assert school_grades.must_register([%{name: name, birthday: Date.new!(2005, 12, 31)}], 2022) ==
[]
assert school_grades.must_register([%{name: name, birthday: Date.new!(2006, 1, 1)}], 2022) ==
[
%{name: name, birthday: Date.new!(2006, 1, 1)}
]
end
feedback :school_grades do
school = get_answers()
name = Faker.Person.first_name()
assert school.grades([], 2022), "Implement the `grades/2` function."
assert school.grades([], 2022) == %{}
assert school.grades([%{name: name, birthday: ~D[2016-01-01]}], 2022) == %{
grade1: [%{name: name, birthday: ~D[2016-01-01]}]
}
assert school.grades([%{name: name, birthday: ~D[2015-01-01]}], 2022) == %{
grade2: [%{name: name, birthday: ~D[2015-01-01]}]
}
assert school.grades([%{name: name, birthday: ~D[2014-01-01]}], 2022) == %{
grade3: [%{name: name, birthday: ~D[2014-01-01]}]
}
assert school.grades([%{name: name, birthday: ~D[2013-01-01]}], 2022) == %{
grade4: [%{name: name, birthday: ~D[2013-01-01]}]
}
assert school.grades([%{name: name, birthday: ~D[2012-01-01]}], 2022) == %{
grade5: [%{name: name, birthday: ~D[2012-01-01]}]
}
students = [
%{name: "Name1", birthday: ~D[2016-01-01]},
%{name: "Name2", birthday: ~D[2016-12-31]},
%{name: "Name3", birthday: ~D[2015-01-01]},
%{name: "Name4", birthday: ~D[2015-12-31]},
%{name: "Name5", birthday: ~D[2014-01-01]},
%{name: "Name6", birthday: ~D[2014-12-31]},
%{name: "Name7", birthday: ~D[2013-01-01]},
%{name: "Name8", birthday: ~D[2013-12-31]},
%{name: "Name9", birthday: ~D[2012-01-01]},
%{name: "Name10", birthday: ~D[2012-12-31]}
]
assert school.grades(students, 2022) ==
%{
grade1: [
%{name: "Name1", birthday: ~D[2016-01-01]},
%{name: "Name2", birthday: ~D[2016-12-31]}
],
grade2: [
%{name: "Name3", birthday: ~D[2015-01-01]},
%{name: "Name4", birthday: ~D[2015-12-31]}
],
grade3: [
%{name: "Name5", birthday: ~D[2014-01-01]},
%{name: "Name6", birthday: ~D[2014-12-31]}
],
grade4: [
%{name: "Name7", birthday: ~D[2013-01-01]},
%{name: "Name8", birthday: ~D[2013-12-31]}
],
grade5: [
%{name: "Name9", birthday: ~D[2012-01-01]},
%{name: "Name10", birthday: ~D[2012-12-31]}
]
}
assert school.grades(Enum.take(students, 8), 2023) == %{
grade2: [
%{name: "Name1", birthday: ~D[2016-01-01]},
%{name: "Name2", birthday: ~D[2016-12-31]}
],
grade3: [
%{name: "Name3", birthday: ~D[2015-01-01]},
%{name: "Name4", birthday: ~D[2015-12-31]}
],
grade4: [
%{name: "Name5", birthday: ~D[2014-01-01]},
%{name: "Name6", birthday: ~D[2014-12-31]}
],
grade5: [
%{name: "Name7", birthday: ~D[2013-01-01]},
%{name: "Name8", birthday: ~D[2013-12-31]}
]
}
end
feedback :say_guards do
say = get_answers()
name = Faker.Person.first_name()
assert say.hello(name), "Ensure you implement the `hello/1` function"
assert say.hello(name) == "Hello, #{name}."
assert_raise FunctionClauseError, fn ->
say.hello(1) && flunk("Ensure you guard against non string values.")
end
end
feedback :percent do
percent = get_answers()
assert percent.display(1), "Ensure you implement the `display/1` function"
assert percent.display(0.1) == "0.1%"
assert percent.display(100) == "100%"
assert_raise FunctionClauseError, fn ->
percent.display(0) && flunk("Ensure you guard against 0.")
end
assert_raise FunctionClauseError, fn ->
percent.display(-1) && flunk("Ensure you guard negative numbers.")
end
assert_raise FunctionClauseError, fn ->
percent.display(101) && flunk("Ensure you guard against numbers greater than 100.")
end
end
feedback :case_match do
case_match = get_answers()
assert case_match != "default", "Ensure you replace `nil` with a value that matches [_, 2, 3]"
assert case_match == "A"
end
feedback :hello_match do
hello = get_answers()
assert_raise FunctionClauseError, fn ->
hello.everyone(nil) && flunk("Replace `nil` with your answer.")
end
assert hello.everyone(["name", "name", "name"]) == "Hello, everyone!"
assert hello.everyone(["name", "name", "name", "name"]) == "Hello, everyone!",
"list with 4 elements should match."
assert_raise FunctionClauseError, fn ->
hello.everyone([]) && flunk("Empty list should not match.")
end
assert_raise FunctionClauseError, fn ->
hello.everyone(["name"]) && flunk("list with one element should not match.")
end
assert_raise FunctionClauseError, fn ->
hello.everyone(["name", "name"]) && flunk("list with two elements should not match.")
end
end
feedback :with_points do
points = get_answers()
assert points.tally([10, 20]) == 30
assert points.tally([20, 20]) == 40
assert points.tally(10) == {:error, :invalid}
assert points.tally([]) == {:error, :invalid}
assert points.tally([10]) == {:error, :invalid}
assert points.tally([10, 20, 30]) == {:error, :invalid}
assert points.tally([10, ""]) == {:error, :invalid}
assert points.tally([1, 10]) == {:error, :invalid}
end
feedback :money do
money = get_answers()
assert Keyword.get(money.__info__(:functions), :__struct__),
"Ensure you use `defstruct`"
assert match?(%{amount: nil, currency: nil}, struct(money)),
"Ensure you use `defstruct` with :amount and :currency without enforcing keys."
assert money.new(500, :CAD), "Ensure you implement the `new/1` function"
assert is_struct(money.new(500, :CAD)), "Money.new/2 should return a `Money` struct"
assert %{amount: 500, currency: :CAD} = money.new(500, :CAD),
"Money.new(500, :CAD) should create a %Money{amount: 500, currency: :CAD} struct"
assert %{amount: 500, currency: :EUR} = money.new(500, :EUR),
"Money.new(500, :EUR) should create a %Money{amount: 500, currency: :EUR} struct"
assert %{amount: 500, currency: :US} = money.new(500, :US),
"Money.new(500, :US) should create a %Money{amount: 500, currency: :US} struct"
assert money.convert(money.new(500, :CAD), :EUR) == money.new(round(500 * 1.39), :EUR)
assert %{amount: 10000, currency: :CAD} =
money.add(money.new(500, :CAD), money.new(500, :CAD))
assert money.subtract(money.new(10000, :US), 100) == money.new(9900, :US)
assert = money.multiply(money.new(100, :CAD), 10) == money.new(1000, :CAD)
assert_raise FunctionClauseError, fn ->
money.add(money.new(500, :CAD), money.new(100, :US)) &&
flunk(
"Money.add/2 should only accept the same currency type or throw a FunctionClauseError."
)
end
end
feedback :metric_measurements do
measurement = get_answers()
conversion = [
millimeter: 0.1,
meter: 100,
kilometer: 100_000,
inch: 2.54,
feet: 30,
yard: 91,
mile: 160_000
]
assert measurement.convert({:milimeter, 1}, :centimeter),
"Ensure you implement the `convert/2` function."
assert measurement.convert({:milimeter, 1}, :centimeter) == {:centimeter, 0.1}
# from centimeter
Enum.each(conversion, fn {measure, amount} ->
assert measurement.convert({:centimeter, 1}, measure) == {measure, 1 / amount}
end)
# to centimeter
Enum.each(conversion, fn {measure, amount} ->
assert measurement.convert({measure, 1}, :centimeter) == {:centimeter, amount}
end)
# from anything to anything
Enum.each(conversion, fn {measure1, amount1} ->
Enum.each(conversion, fn {measure2, amount2} ->
assert measurement.convert({measure1, 1}, measure2) == {measure2, amount1 / amount2}
end)
end)
end
feedback :cypher do
cypher = get_answers()
assert cypher.shift("a"), "Ensure you implement the `shift/1` function."
assert cypher.shift("a") == "b"
assert cypher.shift("b") == "c"
assert cypher.shift("abc") == "bcd"
assert cypher.shift("z") == "a",
"Ensure you handle the z special case. It should wrap around to a."
assert cypher.shift("abcdefghijklmnopqrstuvwxyz") == "bcdefghijklmnopqrstuvwxyza"
end
feedback :email_validation do
email = get_answers()
assert email.validate("[email protected]"), "Ensure you implement the `validate/1` function."
assert email.validate("[email protected]")
assert email.validate("[email protected]")
assert email.validate("***@#@$.!@#")
assert email.validate("[email protected]")
refute email.validate("")
refute email.validate("recipient")
refute email.validate("123")
refute email.validate("@.")
refute email.validate("@domain.")
refute email.validate("name@domain")
refute email.validate("name@domain.")
refute email.validate("domain.com")
refute email.validate("@domain.com")
end
feedback :obfuscate_phone do
obfuscate = get_answers()
assert is_function(obfuscate), "Ensure obfuscate is a function."
assert obfuscate.(""), "Ensure you implement the obfuscate function."
assert obfuscate.("111-111-1111") == "XXX-111-XXXX"
assert obfuscate.("123-111-1234") == "XXX-111-XXXX"
assert obfuscate.("123-123-1234") == "XXX-123-XXXX"
assert obfuscate.("123-123-1234 123-123-1234") == "XXX-123-XXXX XXX-123-XXXX"
end
feedback :convert_phone do
convert = get_answers()
assert convert.("#1231231234"), "Ensure you implement the `convert/1` function."
assert convert.("#1231231234") == "#123-123-1234"
assert convert.("#1231231234 #1231231234") == "#123-123-1234 #123-123-1234"
assert convert.("#1231231234 1231231234") == "#123-123-1234 1231231234"
assert convert.("#999-999-9999 #9999999999") == "#999-999-9999 #999-999-9999"
end
feedback :phone_number_parsing do
phone_number = get_answers()
assert phone_number.parse("1231231234"), "Ensure you implement the `parse/1` function."
assert phone_number.parse("1231231234") == "123-123-1234"
assert phone_number.parse("123 123 1234") == "123-123-1234"
assert phone_number.parse("(123)-123-1234") == "123-123-1234"
assert phone_number.parse("(123) 123 1234") == "123-123-1234"
assert phone_number.parse("(123)123-1234") == "123-123-1234"
text = "
1231231234
123 123 1234
(123)-123-1234
(123) 123 1234
(123)123-1234
"
assert phone_number.parse(text) == "
123-123-1234
123-123-1234
123-123-1234
123-123-1234
123-123-1234
"
end
feedback :classified do
classified = get_answers()
assert classified.redact(""), "Ensure you implement the `redact/1` function."
assert classified.redact("Peter Parker") == "REDACTED"
assert classified.redact("Bruce Wayne") == "REDACTED"
assert classified.redact("Clark Kent") == "REDACTED"
assert classified.redact("1234") == "REDACTED"
assert classified.redact("111-111-1111") == "REDACTED"
assert classified.redact("[email protected]") == "REDACTED"
assert classified.redact("1234 123-123-1234") == "REDACTED REDACTED"
assert classified.redact("@mail.com") == "@mail.com"
assert classified.redact("12345") == "12345"
assert classified.redact(".com") == ".com"
assert classified.redact("12341234") == "12341234"
assert classified.redact("-1234-") == "-REDACTED-"
text = "
Peter Parker
Bruce Wayne
Clark Kent
1234
4567
9999
123-123-1234
456-456-4567
999-999-9999
[email protected]
[email protected]
"
assert classified.redact(text) == "
REDACTED
REDACTED
REDACTED
REDACTED
REDACTED
REDACTED
REDACTED
REDACTED
REDACTED
REDACTED
REDACTED
"
end
feedback :caesar_cypher do
caesar_cypher = get_answers()
assert caesar_cypher.encode("", 1), "Ensure you implement the `encode/2` function."
assert caesar_cypher.encode("", 1) == ""
assert caesar_cypher.encode("a", 1) == "b"
assert caesar_cypher.encode("a", 14) == "o"
assert caesar_cypher.encode("a", 25) == "z"
assert caesar_cypher.encode("z", 1) == "a"
assert caesar_cypher.encode("z", 14) == "n"
assert caesar_cypher.encode("z", 25) == "y"
assert caesar_cypher.encode("abcdefghijklmnopqrstuvwxyz", 1) == "bcdefghijklmnopqrstuvwxyza"
assert caesar_cypher.encode("abcdefghijklmnopqrstuvwxyz", 14) == "opqrstuvwxyzabcdefghijklmn"
assert caesar_cypher.encode("abcdefghijklmnopqrstuvwxyz", 25) == "zabcdefghijklmnopqrstuvwxy"
assert caesar_cypher.encode("Et tu, Brute?", 2) == "Gv vw, Dtwvg?"
assert caesar_cypher.decode("", 1), "Ensure you implement the `decode/2` function."
assert caesar_cypher.decode("", 1) == ""
assert caesar_cypher.decode("b", 1) == "a"
assert caesar_cypher.decode("o", 14) == "a"
assert caesar_cypher.decode("z", 14) == "a"
assert caesar_cypher.decode("a", 1) == "z"
assert caesar_cypher.decode("n", 14) == "z"
assert caesar_cypher.decode("y", 25) == "z"
assert caesar_cypher.encode("bcdefghijklmnopqrstuvwxyza", 1) == "abcdefghijklmnopqrstuvwxyz"
assert caesar_cypher.encode("opqrstuvwxyzabcdefghijklmn", 14) == "abcdefghijklmnopqrstuvwxyz"
assert caesar_cypher.encode("zabcdefghijklmnopqrstuvwxy", 25) == "abcdefghijklmnopqrstuvwxyz"
assert caesar_cypher.encode("Gv vw, Dtwvg?", 2) == "Et tu, Brute?"
end
feedback :rollable_expressions do
rollable = get_answers()
assert rollable.replace(""), "Ensure you implement the `replace/1` function."
assert rollable.replace("") == ""
assert rollable.replace("1d4") == "[1d4](https://www.google.com/search?q=roll+1d4)"
assert rollable.replace("1d6") == "[1d6](https://www.google.com/search?q=roll+1d6)"
assert rollable.replace("1d8") == "[1d8](https://www.google.com/search?q=roll+1d8)"
assert rollable.replace("1d12") == "[1d12](https://www.google.com/search?q=roll+1d12)"
assert rollable.replace("1d20") == "[1d20](https://www.google.com/search?q=roll+1d20)"
assert rollable.replace("2d4") == "[2d4](https://www.google.com/search?q=roll+2d4)"
assert rollable.replace("10d4") == "[10d4](https://www.google.com/search?q=roll+10d4)"
assert rollable.replace("99d4") == "[99d4](https://www.google.com/search?q=roll+99d4)"
assert rollable.replace("10d20") == "[10d20](https://www.google.com/search?q=roll+10d20)"
assert rollable.replace("99d20") == "[99d20](https://www.google.com/search?q=roll+99d20)"
for sides <- ["4", "6", "8", "12", "20"], dice <- 1..99 do
assert rollable.replace("Fireball: deal #{sides}d#{dice} fire damage.") ==
"Fireball: deal [#{sides}d#{dice}](https://www.google.com/search?q=roll+#{sides}d#{dice}) fire damage."
end
rollable.replace("Click the following to test your solution: 1d4")
|> Kino.Markdown.new()
|> Kino.render()
end
feedback :custom_enum_map do
custom_enum = get_answers()
assert custom_enum.map(1..10, fn each -> each end),
"Ensure you implement the `map/2` function"
assert custom_enum.map(1..5, fn each -> each end) == [1, 2, 3, 4, 5]
assert custom_enum.map(1..10, fn each -> each * 2 end) ==
Enum.map(1..10, fn each -> each * 2 end)
assert custom_enum.map(1..10, fn each -> each + 2 end) ==
Enum.map(1..10, fn each -> each + 2 end)
assert custom_enum.map(1..10, fn each -> each - 2 end) ==
Enum.map(1..10, fn each -> each - 2 end)
end
feedback :enum_recursion do
custom_enum = get_answers()
assert custom_enum.map(1..10), "Ensure you implement the `map/2` function."
assert custom_enum.map(1..10, fn each -> each end) == Enum.to_list(1..10)
assert custom_enum.map(1..10, fn each -> each * 2 end) == Enum.to_list(2..20//2)
assert custom_enum.reverse(1..10), "Ensure you implement the `reverse/2` function."
assert custom_enum.map(1..10) == Enum.to_list(10..1)
assert custom_enum.map(4..20) == Enum.to_list(20..4)
assert custom_enum.reduce(1..5, 0, fn each, acc -> each end),
"Ensure you implement the `reduce/3` function."
assert custom_enum.reduce(1..5, 0, fn each, acc -> acc + each end) == 15
assert custom_enum.each(1..5, fn _ -> nil end), "Ensure you implement the `each/2` function."
assert custom_enum.each(1..5, fn _ -> nil end) == :ok,
"The `each/2` function should return :ok"
assert capture_log(fn ->
custom_enum.each(["log message"], fn each -> Logger.error(each) end)
end) =~ "log message"
assert custom_enum.filter([], fn _ -> true end) == [],
"Ensure you implement the `filter/2` function."
assert custom_enum.filter(1..5, fn _ -> true end) == [1, 2, 3, 4, 5]
assert custom_enum.filter(1..5, fn _ -> false end) == []
assert custom_enum.filter([true, false, true], fn each -> each end) == [true, true]
assert custom_enum.filter([1..5], fn each -> each >= 3 end) == [1, 2, 3]
end
feedback :pascal do
pascal = get_answers()
assert pascal.of(1), "Ensure you implement the `pascal/1` function."
assert pascal.of(1) == [[1]]
assert pascal.of(2) == [[1], [1, 2]]
assert pascal.of(5) == [
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 3, 6, 3, 1]
]
assert pascal.of(8) == [
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 3, 6, 3, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
[1, 7, 21, 35, 35, 21, 7, 1]
]
assert length(pascal.of(50)) == 50
end
# test_names must be after tests that require a solution.
def test_names, do: @test_names
feedback :timer_tc do
result = get_answers()
assert {_time, _result} = result, "Ensure you use `:timer.tc/1` with `slow_function/0`"
assert {time, :ok} = result, "The result of `slow_function/0` should be :ok."
assert time > 900_000,
"It's possible that your computer hardware causes :timer.tc/1 to deviate significantly."
assert time < 1_100_000,
"It's possible that your computer hardware causes :timer.tc/1 to deviate significantly."
end
feedback :binary_150 do
binary = get_answers()
assert binary == 10_010_110
end
feedback :graphemes do
graphemes = get_answers()
assert graphemes == String.graphemes("hello")
end
feedback :hexadecimal_4096 do
hexadecimal = get_answers()
assert hexadecimal == 0x1000
end
feedback :hexadecimal_a do
hexadecimal = get_answers()
assert hexadecimal == "\u0061"
end
feedback :codepoint_z do
z = get_answers()
assert z == ?z
end
feedback :jewel do
jewel = get_answers()
assert jewel == "jewel"
end
feedback :hello do
hello = get_answers()
assert hello == "world"
end
feedback :jewel do
jewel = get_answers()
assert jewel != [1, 2, "jewel"], "Ensure you use pattern matching to bind `jewel`"
assert jewel == "jewel"
end
feedback :number_wordle do
number_wordle = get_answers()
assert number_wordle.feedback(1111, 9999), "Ensure you implement the feedback/2 function."
assert number_wordle.feedback(1111, 1111) == [:green, :green, :green, :green]
assert number_wordle.feedback(1111, 2222) == [:gray, :gray, :gray, :gray]
assert number_wordle.feedback(1111, 1122) == [:green, :green, :gray, :gray]
assert number_wordle.feedback(1112, 2333) == [:gray, :gray, :gray, :yellow]
assert number_wordle.feedback(2221, 1222) == [:yellow, :green, :green, :yellow]
end
feedback :keyword_get do
color = get_answers()
options = [color: "red"]
assert color == Keyword.get(options, :color)
end
feedback :keyword_keys do
options = [one: 1, two: 2, three: 3]
keys = get_answers()
assert keys == Keyword.keys(options)
end
feedback :keyword_keyword? do
is_keyword_list = get_answers()
keyword_list = [key: "value"]
assert is_keyword_list == Keyword.keyword?(keyword_list)
end
feedback :integer_parse do
parsed = get_answers()
assert parsed == Integer.parse("2")
end
feedback :integer_digits do
digits = get_answers()
assert digits == Integer.digits(123_456_789)
end
feedback :string_contains do
answer = get_answers()
assert answer == String.contains?("Hello", "lo")
end
feedback :string_capitalize do
answer = get_answers()
assert answer == String.capitalize("hello")
end
feedback :string_split do
words = get_answers()
string = "have,a,great,day"
assert words == String.split(string, ",")
end
feedback :string_trim do
trimmed_string = get_answers()
string = " hello! "
assert trimmed_string == String.trim(string)
end
feedback :string_upcase do
uppercase_string = get_answers()
string = "hello"
assert uppercase_string == String.upcase(string)
end
feedback :map_get do
retrieved_value = get_answers()
map = %{hello: "world"}
assert retrieved_value == Map.get(map, :hello)
end
feedback :map_put do
new_map = get_answers()
map = %{one: 1}
assert new_map == Map.put(map, :two, 2)
end
feedback :map_keys do
keys = get_answers()
map = %{key1: 1, key2: 2, key3: 3}
assert keys == Map.keys(map)
end
feedback :map_delete do
new_map = get_answers()
map = %{key1: 1, key2: 2, key3: 3}
assert new_map == Map.delete(map, :key1)
end
feedback :map_values do
values = get_answers()
map = %{key1: 1, key2: 2, key3: 3}
assert values == Map.values(map)
end
feedback :date_compare do
[today, tomorrow, comparison] = get_answers()
assert today, "Ensure today is defined"
assert today == Date.utc_today()
assert tomorrow, "Ensure tomorrow is defined"
assert tomorrow == Date.add(today, 1)
assert comparison, "Ensure comparison is defined"
assert comparison == Date.compare(today, tomorrow)
end
feedback :date_sigil do
today = get_answers()
assert today == Date.utc_today()
end
feedback :date_difference do
[date1, date2, difference] = get_answers()
assert is_struct(date1), "date1 should be a `Date` struct."
assert date1.__struct__ == Date, "date1 should be a `Date` struct."
assert date1 == %Date{year: 1995, month: 4, day: 28}
assert is_struct(date2), "date2 should be a `Date` struct."
assert date2.__struct__ == Date, "date2 should be a `Date` struct."
assert date2 == %Date{year: 1915, month: 4, day: 17}
assert difference == Date.diff(date2, date1)
end
feedback :calculate_force do
calculate_force = get_answers()
assert calculate_force
assert is_function(calculate_force), "calculate_force should be a function."
assert is_function(calculate_force, 2),
"calculate_force should be a function with arity of 2."
assert calculate_force.(10, 5), "calculate_force should return a value."
assert is_integer(calculate_force.(10, 5)), "calculate_force should return an integer."
assert calculate_force.(10, 5) == 10 * 5, "calculate_force should return mass * acceleration"
end
feedback :is_even? do
is_even? = get_answers()
assert is_even?
assert is_function(is_even?), "is_even? should be a function."
assert is_function(is_even?, 1), "is_even? should be a function with a single parameter."
even_number = Enum.random(2..10//2)
odd_number = Enum.random(1..9//2)
refute is_even?.(odd_number), "is_even? should return false for odd numbers."
assert is_even?.(even_number), "is_even? should return true for even numbers."
end
feedback :call_with_20 do
call_with_20 = get_answers()
assert call_with_20
assert is_function(call_with_20), "call_with_20 should be a function."
assert is_function(call_with_20, 1),
"call_with_20 should be a function with a single parameter."
assert call_with_20.(fn int -> int * 2 end) == 20 * 2
assert call_with_20.(fn int -> int * 10 end) == 20 * 10
end
feedback :created_project do
path = get_answers()
assert File.dir?("../projects/#{path}"),
"Ensure you create a mix project `#{path}` in the `projects` folder."
end
# Allows for tests that don't require input
def test(test_name), do: test(test_name, "")
def test(test_name, answers) do
cond do
test_name not in @test_names ->
"Something went wrong, feedback does not exist for #{test_name}."
Mix.env() == :test ->
ExUnit.start(auto_run: false)
test_module(test_name, answers)
ExUnit.run()
is_nil(answers) ->
"Please enter your answer above."
is_list(answers) and not Enum.any?(answers) ->
"Please enter an answer above."
true ->
ExUnit.start(auto_run: false)
test_module(test_name, answers)
ExUnit.run()
end
end
end
| 33.087996 | 587 | 0.625832 |
f7744021473077cc146f53fc8a73d27f1abe41f7 | 161 | exs | Elixir | apps/data/priv/repo/migrations/20170821043909_add_projects_timestamps.exs | elixirschool/extracurricular | eb8b725fa49ca91b1c6b7e610a8522bc81a80de1 | [
"MIT"
] | 48 | 2017-08-21T02:08:16.000Z | 2022-01-05T14:02:56.000Z | apps/data/priv/repo/migrations/20170821043909_add_projects_timestamps.exs | elixirschool/extracurricular | eb8b725fa49ca91b1c6b7e610a8522bc81a80de1 | [
"MIT"
] | 68 | 2017-08-21T02:17:32.000Z | 2017-11-09T15:56:27.000Z | apps/data/priv/repo/migrations/20170821043909_add_projects_timestamps.exs | elixirschool/extracurricular | eb8b725fa49ca91b1c6b7e610a8522bc81a80de1 | [
"MIT"
] | 26 | 2017-08-21T04:28:22.000Z | 2018-12-09T14:20:29.000Z | defmodule Data.Repo.Migrations.AddProjectsTimestamps do
use Ecto.Migration
def change do
alter table(:projects) do
timestamps()
end
end
end
| 16.1 | 55 | 0.720497 |
f77456d1663b8454b581d1dc27d3e910f96e1ccb | 171 | exs | Elixir | config/runtime.exs | jhg/BorsNgBot | 1e56b06fe088e01505ffa4a175ec775920862607 | [
"Unlicense"
] | null | null | null | config/runtime.exs | jhg/BorsNgBot | 1e56b06fe088e01505ffa4a175ec775920862607 | [
"Unlicense"
] | null | null | null | config/runtime.exs | jhg/BorsNgBot | 1e56b06fe088e01505ffa4a175ec775920862607 | [
"Unlicense"
] | null | null | null | import Config
config :bors_ng_bot,
telegram_bot_token: System.get_env("TELEGRAM_BOT_TOKEN")
config :bors_ng_bot, BorsNgBot.Repo,
url: System.get_env("DATABASE_URL")
| 21.375 | 58 | 0.795322 |
f7746c080dd59dd9b1e8906fdd005588c47fefd2 | 266 | ex | Elixir | lib/slax/projects/project_channel.ex | HoffsMH/slax | b91ee30b9fd71a4cb7826f50b605ce580b7c1651 | [
"MIT"
] | null | null | null | lib/slax/projects/project_channel.ex | HoffsMH/slax | b91ee30b9fd71a4cb7826f50b605ce580b7c1651 | [
"MIT"
] | null | null | null | lib/slax/projects/project_channel.ex | HoffsMH/slax | b91ee30b9fd71a4cb7826f50b605ce580b7c1651 | [
"MIT"
] | null | null | null | defmodule Slax.ProjectChannel do
@moduledoc false
use Slax.Schema
@type t :: %__MODULE__{}
schema "project_channels" do
belongs_to(:project, Slax.Project)
field(:channel_name, :string)
field(:webhook_token, :string)
timestamps()
end
end
| 17.733333 | 38 | 0.699248 |
f774829ff7a97031b06f846c0aaa0964cad2bbe2 | 3,462 | ex | Elixir | lib/rank.ex | pkhodakovsky/elixir-poker-game | 4191283f31b236d311e412c37045ad5d4fdc4f9e | [
"MIT"
] | null | null | null | lib/rank.ex | pkhodakovsky/elixir-poker-game | 4191283f31b236d311e412c37045ad5d4fdc4f9e | [
"MIT"
] | null | null | null | lib/rank.ex | pkhodakovsky/elixir-poker-game | 4191283f31b236d311e412c37045ad5d4fdc4f9e | [
"MIT"
] | null | null | null | # Rank Encoding
#
# Rank for Hands
# 9 - straight flush + highest card
# 8 - four of a kind + card value
# 7 - full house + 3 card value
# 6 - flush + highest cards
# 5 - straight (can be ace high) + highest card
# 4 - three of a kind + 3 card value
# 3 - two pair + highest pairs + remaining card
# 2 - pair + 2 card value + highest cards
# 1 - high card + highest cards
#
# Face Value Rank
# ace - 14
# king - 13
# queen - 12
# jack - 11
# ten - 10
# 9 - 09
# ...
# 2 - 02
# ace - 01 <<< ace as a low card
#
# Rank Code
# [ rank code, sorted faces ]
# e.g.
# - 1, 0504030201
# - 1, 0605040302 WINNER
# - 4, 0404040201
# - 4, 0505050201 WINNER
defmodule Rank do
@moduledoc "Rank a poker hand"
def rank(hand) do
cond do
# Rank 9
Hand.is_straight_flush_ace_high(hand) -> format_straight_flush_ace_high(hand)
# Rank 9
Hand.is_straight_flush_ace_low(hand) -> format_straight_flush_ace_low(hand)
# Rank 8
Hand.is_four_of_a_kind(hand) -> format_four_of_a_kind(hand)
# Rank 7
Hand.is_full_house(hand) -> format_full_house(hand)
# Rank 6
Hand.is_flush(hand) -> format_flush(hand)
# Rank 5
Hand.is_straight_ace_high(hand) -> format_straight_ace_high(hand)
# Rank 5
Hand.is_straight_ace_low(hand) -> format_straight_ace_low(hand)
# Rank 4
Hand.is_three_of_a_kind(hand) -> format_three_of_a_kind(hand)
# Rank 3
Hand.is_two_pair(hand) -> format_two_pair(hand)
# Rank 2
Hand.is_pair(hand) -> format_pair(hand)
# Rank 1
Hand.is_high_card(hand) -> format_high_card(hand)
end
end
@doc """
Format methods:
Input: [[:heart, :seven], [:club, :seven], [:diamond, :two], [:spade, :seven], [:diamond, :three]]
Output: "4,0707070302"
"""
def format_high_card(hand) do
sort_by_face(hand, "1", :ace)
end
def format_pair(hand) do
sort_by_count_and_face(hand, "2", :ace)
end
def format_two_pair(hand) do
sort_by_count_and_face(hand, "3", :ace)
end
def format_three_of_a_kind(hand) do
sort_by_count_and_face(hand, "4", :ace)
end
def format_straight_ace_high(hand) do
sort_by_face(hand, "5", :ace)
end
def format_straight_ace_low(hand) do
sort_by_face(hand, "5", :ace_low)
end
def format_flush(hand) do
sort_by_face(hand, "6", :ace)
end
def format_full_house(hand) do
sort_by_count_and_face(hand, "7", :ace)
end
def format_four_of_a_kind(hand) do
sort_by_count_and_face(hand, "8", :ace)
end
def format_straight_flush_ace_high(hand) do
sort_by_count_and_face(hand, "9", :ace)
end
def format_straight_flush_ace_low(hand) do
sort_by_count_and_face(hand, "9", :ace_low)
end
defp sort_by_face(hand, rank_code, ace) do
Enum.map(hand, fn card -> Card.rank(card, ace) end)
|> Enum.sort(fn face_rank1, face_rank2 -> face_rank1 > face_rank2 end)
|> format_rank(rank_code)
end
defp sort_by_count_and_face(hand, rank_code, ace) do
Enum.group_by(hand, fn [_, face] -> face end)
|> Enum.sort(fn {face1, cards1}, {face2, cards2} ->
"#{length(cards1)}|#{Card.rank(face1, ace)}" > "#{length(cards2)}|#{Card.rank(face2, ace)}"
end)
|> Enum.map(fn {_, cards} -> cards end)
|> Enum.concat()
|> Enum.map(fn card -> Card.rank(card, ace) end)
|> format_rank(rank_code)
end
defp format_rank(hand, rank_code) do
Enum.into(hand, ["#{rank_code},"])
|> Enum.join()
end
end
| 25.835821 | 101 | 0.647603 |
f774a997e8557a2f7d1fd0d1ef0641a5913147d7 | 1,024 | ex | Elixir | config/dispatcher/dispatcher.ex | lblod/app-klachtenformulier | 367d5effce932843f1a6a6ce819e731499011b2e | [
"MIT"
] | null | null | null | config/dispatcher/dispatcher.ex | lblod/app-klachtenformulier | 367d5effce932843f1a6a6ce819e731499011b2e | [
"MIT"
] | null | null | null | config/dispatcher/dispatcher.ex | lblod/app-klachtenformulier | 367d5effce932843f1a6a6ce819e731499011b2e | [
"MIT"
] | null | null | null | defmodule Dispatcher do
use Matcher
define_accept_types [
any: [ "*/*" ]
]
@any %{ accept: %{ any: true } }
# Users only create complaint forms.
post "/complaint-forms/*path", @any do
forward conn, path, "http://resource/complaint-forms/"
end
# This will be protected by basic-auth, so file content will never be public.
get "/files/:id/download", @any do
forward conn, [], "http://file/files/" <> id <> "/download"
end
# Returns meta data of the uploaded file.
get "/files/*path", @any do
forward conn, path, "http://resource/files/"
end
# Endpoint required to upload file content.
post "/file-service/files/*path", @any do
forward conn, path, "http://file/files/"
end
# User must be able to delete file.
delete "/files/*path", @any do
forward conn, path, "http://file/files/"
end
get "/*_", %{ last_call: true } do
send_resp( conn, 404, "{ \"error\": { \"code\": 404, \"message\": \"Route not found. See config/dispatcher.ex\" } }" )
end
end
| 25.6 | 123 | 0.624023 |
f774bb1d1229d72e9c1fc660e4d5b8a8d3750291 | 2,913 | ex | Elixir | backend/lib/edgehog/tenants.ex | szakhlypa/edgehog | b1193c26f403132dead6964c1c052e5dcae533af | [
"Apache-2.0"
] | 14 | 2021-12-02T16:31:16.000Z | 2022-03-18T17:40:44.000Z | backend/lib/edgehog/tenants.ex | szakhlypa/edgehog | b1193c26f403132dead6964c1c052e5dcae533af | [
"Apache-2.0"
] | 77 | 2021-11-03T15:14:41.000Z | 2022-03-30T14:13:32.000Z | backend/lib/edgehog/tenants.ex | szakhlypa/edgehog | b1193c26f403132dead6964c1c052e5dcae533af | [
"Apache-2.0"
] | 7 | 2021-11-03T10:58:37.000Z | 2022-02-28T14:00:03.000Z | #
# This file is part of Edgehog.
#
# Copyright 2021 SECO Mind Srl
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
#
defmodule Edgehog.Tenants do
@moduledoc """
The Tenants context.
"""
import Ecto.Query, warn: false
alias Edgehog.Repo
alias Edgehog.Tenants.Tenant
@doc """
Returns the list of tenants.
## Examples
iex> list_tenants()
[%Tenant{}, ...]
"""
def list_tenants do
Repo.all(Tenant, skip_tenant_id: true)
end
@doc """
Gets a single tenant.
Raises `Ecto.NoResultsError` if the Tenant does not exist.
## Examples
iex> get_tenant!(123)
%Tenant{}
iex> get_tenant!(456)
** (Ecto.NoResultsError)
"""
def get_tenant!(id), do: Repo.get!(Tenant, id, skip_tenant_id: true)
@doc """
Fetches a single tenant by its slug.
Returns `{:ok, tenant}` or `{:error, :not_found}`.
## Examples
iex> fetch_tenant_by_slug("test")
{:ok, %Tenant{}}
iex> fetch_tenant_by_slug("unknown")
{:error, :not_found}
"""
def fetch_tenant_by_slug(slug) do
case Repo.get_by(Tenant, [slug: slug], skip_tenant_id: true) do
%Tenant{} = tenant -> {:ok, tenant}
nil -> {:error, :not_found}
end
end
@doc """
Creates a tenant.
## Examples
iex> create_tenant(%{field: value})
{:ok, %Tenant{}}
iex> create_tenant(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_tenant(attrs \\ %{}) do
%Tenant{}
|> Tenant.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a tenant.
## Examples
iex> update_tenant(tenant, %{field: new_value})
{:ok, %Tenant{}}
iex> update_tenant(tenant, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_tenant(%Tenant{} = tenant, attrs) do
tenant
|> Tenant.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a tenant.
## Examples
iex> delete_tenant(tenant)
{:ok, %Tenant{}}
iex> delete_tenant(tenant)
{:error, %Ecto.Changeset{}}
"""
def delete_tenant(%Tenant{} = tenant) do
Repo.delete(tenant)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking tenant changes.
## Examples
iex> change_tenant(tenant)
%Ecto.Changeset{data: %Tenant{}}
"""
def change_tenant(%Tenant{} = tenant, attrs \\ %{}) do
Tenant.changeset(tenant, attrs)
end
end
| 19.952055 | 74 | 0.633024 |
f774d7c96b59fdfabb6395ce9d5b160cd9895a3f | 810 | ex | Elixir | bliss_01/lib/bliss.ex | kallisto/bliss | fb0db73784ad01fb3bcc495afcbd75110f62599c | [
"MIT"
] | null | null | null | bliss_01/lib/bliss.ex | kallisto/bliss | fb0db73784ad01fb3bcc495afcbd75110f62599c | [
"MIT"
] | null | null | null | bliss_01/lib/bliss.ex | kallisto/bliss | fb0db73784ad01fb3bcc495afcbd75110f62599c | [
"MIT"
] | null | null | null | defmodule Bliss do
@moduledoc false
import Bliss.Interpreter
@kernel_file "priv/kernel.bls"
@external_resource @kernel_file
@kernel (
File.read!(@kernel_file)
|> String.to_charlist
|> :lexer.string
|> elem(1)
|> :parser.parse
|> elem(1)
|> (&(interpret(new_opts(), &1, %{}, []))).())
@doc "Entry point for the CLI"
def main(_args) do
{opts, dict, stack} = @kernel
loop(opts, dict, stack)
end
def usage, do: "Usage: bliss (no args)"
def loop(opts \\ new_opts(), dict \\ %{}, stack \\ []) do
IO.write("> ")
line =
IO.read(:line)
|> String.to_charlist
|> :lexer.string
|> elem(1)
|> :parser.parse
|> elem(1)
{opts, dict, stack} = interpret(opts, line, dict, stack)
loop(opts, dict, stack)
end
end
| 20.769231 | 60 | 0.566667 |
f774d7f8fc73109430a30bca585c3a1df95c382c | 2,522 | ex | Elixir | clients/games/lib/google_api/games/v1/model/instance_ios_details.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/instance_ios_details.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/instance_ios_details.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"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.Games.V1.Model.InstanceIosDetails do
@moduledoc """
This is a JSON template for the iOS details resource.
## Attributes
- bundleIdentifier (String.t): Bundle identifier. Defaults to: `null`.
- itunesAppId (String.t): iTunes App ID. Defaults to: `null`.
- kind (String.t): Uniquely identifies the type of this resource. Value is always the fixed string games#instanceIosDetails. Defaults to: `null`.
- preferredForIpad (boolean()): Indicates that this instance is the default for new installations on iPad devices. Defaults to: `null`.
- preferredForIphone (boolean()): Indicates that this instance is the default for new installations on iPhone devices. Defaults to: `null`.
- supportIpad (boolean()): Flag to indicate if this instance supports iPad. Defaults to: `null`.
- supportIphone (boolean()): Flag to indicate if this instance supports iPhone. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:bundleIdentifier => any(),
:itunesAppId => any(),
:kind => any(),
:preferredForIpad => any(),
:preferredForIphone => any(),
:supportIpad => any(),
:supportIphone => any()
}
field(:bundleIdentifier)
field(:itunesAppId)
field(:kind)
field(:preferredForIpad)
field(:preferredForIphone)
field(:supportIpad)
field(:supportIphone)
end
defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.InstanceIosDetails do
def decode(value, options) do
GoogleApi.Games.V1.Model.InstanceIosDetails.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.InstanceIosDetails do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.212121 | 147 | 0.723236 |
f7752189abc24768b218f1e39fb2ad919d3ae086 | 304 | ex | Elixir | elixir/src/example/lib/example.ex | nbari/docker | 4fc653fcff08c58d0f4d1837c45beda291795afe | [
"BSD-3-Clause"
] | null | null | null | elixir/src/example/lib/example.ex | nbari/docker | 4fc653fcff08c58d0f4d1837c45beda291795afe | [
"BSD-3-Clause"
] | null | null | null | elixir/src/example/lib/example.ex | nbari/docker | 4fc653fcff08c58d0f4d1837c45beda291795afe | [
"BSD-3-Clause"
] | 1 | 2021-05-21T14:00:00.000Z | 2021-05-21T14:00:00.000Z | defmodule Example do
use Application
require Logger
def start(_type, _args) do
children = [
Plug.Adapters.Cowboy.child_spec(:http, Example.HelloWorldPlug, [], port: 8080)
]
Logger.info "Started application"
Supervisor.start_link(children, strategy: :one_for_one)
end
end
| 20.266667 | 84 | 0.707237 |
f7753288911fd5ed90ea09525c41f0dfe4cf7003 | 41 | exs | Elixir | test/test_helper.exs | CaptChrisD/logger_error_counter_backend | f268972244430b8bdfe685446eeb317bbc961ca2 | [
"MIT"
] | null | null | null | test/test_helper.exs | CaptChrisD/logger_error_counter_backend | f268972244430b8bdfe685446eeb317bbc961ca2 | [
"MIT"
] | null | null | null | test/test_helper.exs | CaptChrisD/logger_error_counter_backend | f268972244430b8bdfe685446eeb317bbc961ca2 | [
"MIT"
] | null | null | null | :application.start :logger
ExUnit.start() | 20.5 | 26 | 0.804878 |
f77534f9135009a17dac90ba12c2d703d9da5b6d | 253 | ex | Elixir | lib/party_hub.ex | AminArria/party_hub | aef6d17500856789c115e1c68fc95b853b220e1f | [
"MIT"
] | 2 | 2020-05-22T15:45:53.000Z | 2020-06-07T21:07:03.000Z | lib/party_hub.ex | AminArria/party_hub | aef6d17500856789c115e1c68fc95b853b220e1f | [
"MIT"
] | 1 | 2021-03-10T16:36:46.000Z | 2021-03-10T16:36:46.000Z | lib/party_hub.ex | AminArria/party_hub | aef6d17500856789c115e1c68fc95b853b220e1f | [
"MIT"
] | null | null | null | defmodule PartyHub do
@moduledoc """
PartyHub 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 |
f7755b64e63063067454c9a8fbbe7dd1a6b0981f | 3,012 | ex | Elixir | clients/file/lib/google_api/file/v1/model/google_cloud_saasaccelerator_management_providers_v1_slo_metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/file/lib/google_api/file/v1/model/google_cloud_saasaccelerator_management_providers_v1_slo_metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/file/lib/google_api/file/v1/model/google_cloud_saasaccelerator_management_providers_v1_slo_metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.File.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata do
@moduledoc """
SloMetadata contains resources required for proper SLO classification of the instance.
## Attributes
* `nodes` (*type:* `list(GoogleApi.File.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata.t)`, *default:* `nil`) - Optional. List of nodes. Some producers need to use per-node metadata to calculate SLO. This field allows such producers to publish per-node SLO meta data, which will be consumed by SSA Eligibility Exporter and published in the form of per node metric to Monarch.
* `perSliEligibility` (*type:* `GoogleApi.File.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility.t`, *default:* `nil`) - Optional. Multiple per-instance SLI eligibilities which apply for individual SLIs.
* `tier` (*type:* `String.t`, *default:* `nil`) - Name of the SLO tier the Instance belongs to. This name will be expected to match the tiers specified in the service SLO configuration. Field is mandatory and must not be empty.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:nodes =>
list(
GoogleApi.File.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata.t()
)
| nil,
:perSliEligibility =>
GoogleApi.File.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility.t()
| nil,
:tier => String.t() | nil
}
field(:nodes,
as: GoogleApi.File.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata,
type: :list
)
field(:perSliEligibility,
as:
GoogleApi.File.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
)
field(:tier)
end
defimpl Poison.Decoder,
for: GoogleApi.File.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata do
def decode(value, options) do
GoogleApi.File.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.File.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.833333 | 404 | 0.750332 |
f77567db38a872b6932e257c46c24b0a8a463938 | 1,266 | ex | Elixir | apps/admin_api/lib/admin_api/v1/channels/transaction_request_channel.ex | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | apps/admin_api/lib/admin_api/v1/channels/transaction_request_channel.ex | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | apps/admin_api/lib/admin_api/v1/channels/transaction_request_channel.ex | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# credo:disable-for-this-file
defmodule AdminAPI.V1.TransactionRequestChannel do
@moduledoc """
Represents the transaction request channel.
"""
use Phoenix.Channel, async: false
alias EWalletDB.TransactionRequest
alias EWallet.TransactionRequestPolicy
def join("transaction_request:" <> request_id, _params, %{assigns: %{auth: auth}} = socket) do
with %TransactionRequest{} = request <- TransactionRequest.get(request_id, preload: :wallet),
:ok <- Bodyguard.permit(TransactionRequestPolicy, :join, auth, request) do
{:ok, socket}
else
_ -> {:error, :forbidden_channel}
end
end
def join(_, _, _), do: {:error, :invalid_parameter}
end
| 36.171429 | 97 | 0.733017 |
f77598480176b7f639dc472c52edf612411e5eea | 11,026 | exs | Elixir | test/duration_test.exs | kianmeng/cldr_calendars | af1ffe1b40100792e8e643ce09cc7db7224060b6 | [
"Apache-2.0"
] | 6 | 2019-08-29T12:31:03.000Z | 2021-08-28T23:15:39.000Z | test/duration_test.exs | kianmeng/cldr_calendars | af1ffe1b40100792e8e643ce09cc7db7224060b6 | [
"Apache-2.0"
] | 8 | 2019-11-08T09:13:00.000Z | 2021-12-26T05:34:28.000Z | test/duration_test.exs | kianmeng/cldr_calendars | af1ffe1b40100792e8e643ce09cc7db7224060b6 | [
"Apache-2.0"
] | 2 | 2020-05-08T12:19:01.000Z | 2022-03-03T14:53:06.000Z | defmodule Cldr.Calendar.Duration.Test do
use ExUnit.Case, async: true
alias Cldr.Calendar.Duration
import Cldr.Calendar.Helper
test "date durations" do
assert Cldr.Calendar.Duration.date_duration(~D[1999-02-03], ~D[2000-12-01]) ==
%Cldr.Calendar.Duration{
day: 26,
hour: 0,
microsecond: 0,
minute: 0,
month: 9,
second: 0,
year: 1
}
assert Cldr.Calendar.plus(~D[1999-02-03], %Cldr.Calendar.Duration{
day: 26,
hour: 0,
microsecond: 0,
minute: 0,
month: 9,
second: 0,
year: 1
}) == ~D[2000-12-01]
assert Cldr.Calendar.Duration.date_duration(~D"1984-02-14", ~D"2008-08-20") ==
%Cldr.Calendar.Duration{
day: 6,
hour: 0,
microsecond: 0,
minute: 0,
month: 6,
second: 0,
year: 24
}
assert Cldr.Calendar.plus(~D"1984-02-14", %Cldr.Calendar.Duration{
day: 6,
hour: 0,
microsecond: 0,
minute: 0,
month: 6,
second: 0,
year: 24
}) == ~D"2008-08-20"
assert Cldr.Calendar.Duration.date_duration(~D"1960-06-14", ~D"2008-07-14") ==
%Cldr.Calendar.Duration{
day: 0,
hour: 0,
microsecond: 0,
minute: 0,
month: 1,
second: 0,
year: 48
}
assert Cldr.Calendar.plus(~D"1960-06-14", %Cldr.Calendar.Duration{
day: 0,
hour: 0,
microsecond: 0,
minute: 0,
month: 1,
second: 0,
year: 48
}) == ~D"2008-07-14"
assert Cldr.Calendar.Duration.date_duration(~D"1960-05-05", ~D"2008-07-13") ==
%Cldr.Calendar.Duration{
day: 8,
hour: 0,
microsecond: 0,
minute: 0,
month: 2,
second: 0,
year: 48
}
assert Cldr.Calendar.plus(~D"1960-05-05", %Cldr.Calendar.Duration{
day: 8,
hour: 0,
microsecond: 0,
minute: 0,
month: 2,
second: 0,
year: 48
}) == ~D"2008-07-13"
end
test "datetime duration full year" do
assert Duration.new(~D[2019-01-01], ~D[2019-12-31]) ==
{:ok,
%Duration{
year: 0,
month: 11,
day: 30,
hour: 0,
microsecond: 0,
minute: 0,
second: 0
}}
end
test "datetime duration one day crossing month boundary" do
assert Duration.new(~D[2019-01-31], ~D[2019-02-01]) ==
{:ok,
%Duration{year: 0, month: 0, day: 1, hour: 0, microsecond: 0, minute: 0, second: 0}}
end
test "datetime one day crossing year bounday" do
assert Duration.new(~D[2019-12-31], ~D[2020-01-01]) ==
{:ok,
%Duration{year: 0, month: 0, day: 1, hour: 0, microsecond: 0, minute: 0, second: 0}}
end
test "datetime duration month and day incremented" do
assert Duration.new(~D[2019-05-27], ~D[2019-08-30]) ==
{:ok,
%Duration{year: 0, month: 3, day: 3, hour: 0, microsecond: 0, minute: 0, second: 0}}
end
test "datetime duration month and day also incremented to last day of year" do
assert Duration.new(~D[2000-05-01], ~D[2019-12-31]) ==
{:ok,
%Duration{
year: 19,
month: 7,
day: 30,
hour: 0,
microsecond: 0,
minute: 0,
second: 0
}}
end
test "datetime duration of two months across a year bounday" do
assert Duration.new(~D[2000-12-01], ~D[2019-01-31]) ==
{:ok,
%Duration{
year: 18,
month: 1,
day: 30,
hour: 0,
microsecond: 0,
minute: 0,
second: 0
}}
end
test "datetime duration 19 years less one day" do
assert Duration.new(
date(2000, 12, 01, Cldr.Calendar.Gregorian),
date(2019, 01, 31, Cldr.Calendar.Gregorian)
) ==
{:ok,
%Duration{
year: 18,
month: 1,
day: 30,
hour: 0,
microsecond: 0,
minute: 0,
second: 0
}}
end
test "datetiem duration of week-based calendar" do
assert Duration.new(
date(2000, 12, 01, Cldr.Calendar.CSCO),
date(2019, 01, 07, Cldr.Calendar.CSCO)
) ==
{:ok,
%Duration{year: 18, month: 1, day: 6, hour: 0, microsecond: 0, minute: 0, second: 0}}
end
test "duration with the same month and day 2 later than day 1" do
assert Duration.new(
date(2020, 01, 01, Cldr.Calendar.Gregorian),
date(2020, 01, 03, Cldr.Calendar.Gregorian)
) ==
{:ok,
%Duration{
year: 0,
month: 0,
day: 2,
hour: 0,
microsecond: 0,
minute: 0,
second: 0
}}
end
if Code.ensure_loaded?(Cldr.List) do
test "duration to_string" do
{:ok, duration} = Duration.new(~D[2019-01-01], ~D[2019-12-31])
assert to_string(duration) ==
"11 months and 30 days"
assert Cldr.Calendar.Duration.to_string(duration, style: :narrow) ==
{:ok, "11m and 30d"}
assert Cldr.Calendar.Duration.to_string(duration,
style: :narrow,
list_options: [style: :unit_narrow]
) ==
{:ok, "11m 30d"}
end
else
test "duration to_string" do
{:ok, duration} = Duration.new(~D[2019-01-01], ~D[2019-12-31])
assert to_string(duration) ==
"11 months, 30 days"
assert Cldr.Calendar.Duration.to_string(duration, style: :narrow) ==
{:ok, "11 months, 30 days"}
assert Cldr.Calendar.Duration.to_string(duration,
style: :narrow,
list_options: [style: :unit_narrow]
) ==
{:ok, "11 months, 30 days"}
end
end
test "incompatible calendars" do
from = ~D[2019-01-01]
to = ~D[2019-12-31] |> Map.put(:calendar, Cldr.Calendar.Gregorian)
assert Duration.new(from, to) ==
{:error,
{Cldr.IncompatibleCalendarError,
"The two dates must be in the same calendar. Found #{inspect(from)} and #{
inspect(to)
}"}}
end
test "incompatible time zones" do
{:ok, from} = ~U[2020-01-01 00:00:00.0Z] |> DateTime.from_naive("Etc/UTC")
{:ok, to} = ~U[2020-01-01 00:00:00.0Z] |> DateTime.from_naive("Australia/Sydney")
assert Duration.new(from, to) == {:error, {Cldr.IncompatibleTimeZone,
"`from` and `to` must be in the same time zone. " <>
"Found ~U[2020-01-01 00:00:00.0Z] and #DateTime<2020-01-01 00:00:00.0+11:00 AEDT Australia/Sydney>"
}}
end
test "duration with positive time difference no date difference" do
assert Cldr.Calendar.Duration.new(~U[2020-01-01 00:00:00.0Z], ~U[2020-01-01 01:00:00.0Z]) ==
{:ok,
%Cldr.Calendar.Duration{
day: 0,
hour: 1,
microsecond: 0,
minute: 0,
month: 0,
second: 0,
year: 0
}}
assert Cldr.Calendar.Duration.new(~U[2020-01-01 00:00:00.0Z], ~U[2020-01-01 01:02:00.0Z]) ==
{:ok,
%Cldr.Calendar.Duration{
day: 0,
hour: 1,
microsecond: 0,
minute: 2,
month: 0,
second: 0,
year: 0
}}
assert Cldr.Calendar.Duration.new(~U[2020-01-01 00:00:00.0Z], ~U[2020-01-01 01:02:03.0Z]) ==
{:ok,
%Cldr.Calendar.Duration{
day: 0,
hour: 1,
microsecond: 0,
minute: 2,
month: 0,
second: 3,
year: 0
}}
assert Cldr.Calendar.Duration.new(~U[2020-01-01 00:00:00.0Z], ~U[2020-01-01 01:02:03.4Z])
{:ok,
%Cldr.Calendar.Duration{
day: 0,
hour: 1,
microsecond: 400000,
minute: 2,
month: 0,
second: 3,
year: 0
}}
end
test "duration with negative time difference" do
assert Cldr.Calendar.Duration.new(~U[2020-01-01 02:00:00.0Z], ~U[2020-01-02 01:00:00.0Z]) ==
{:ok,
%Cldr.Calendar.Duration{
day: 0,
hour: 23,
microsecond: 0,
minute: 0,
month: 0,
second: 0,
year: 0
}}
assert Cldr.Calendar.Duration.new(~U[2020-01-01 02:02:00.0Z], ~U[2020-01-02 01:00:00.0Z]) ==
{:ok,
%Cldr.Calendar.Duration{
day: 0,
hour: 22,
microsecond: 0,
minute: 58,
month: 0,
second: 0,
year: 0
}}
assert Cldr.Calendar.Duration.new(~U[2020-01-01 02:02:02.0Z], ~U[2020-01-02 01:00:00.0Z]) ==
{:ok,
%Cldr.Calendar.Duration{
day: 0,
hour: 22,
microsecond: 0,
minute: 57,
month: 0,
second: 58,
year: 0
}}
assert Cldr.Calendar.Duration.new(~U[2020-01-01 02:03:04.0Z], ~U[2020-01-02 01:00:00.0Z]) ==
{:ok,
%Cldr.Calendar.Duration{
day: 0,
hour: 22,
microsecond: 0,
minute: 56,
month: 0,
second: 56,
year: 0
}}
end
test "duration from date range" do
assert Cldr.Calendar.Duration.new(Date.range(~D[2020-01-01], ~D[2020-12-31])) ==
{:ok,
%Cldr.Calendar.Duration{
day: 30,
hour: 0,
microsecond: 0,
minute: 0,
month: 11,
second: 0,
year: 0
}}
end
test "duration from CalendarInterval" do
use CalendarInterval
assert Cldr.Calendar.Duration.new(~I"2020-01/12") ==
{:ok,
%Cldr.Calendar.Duration{
day: 30,
hour: 0,
microsecond: 0,
minute: 0,
month: 11,
second: 0,
year: 0
}}
end
test "time duration" do
assert Cldr.Calendar.Duration.new(~T[00:00:59], ~T[00:01:23]) ==
{:ok,
%Cldr.Calendar.Duration{
day: 0,
hour: 0,
microsecond: 0,
minute: 0,
month: 0,
second: 24,
year: 0
}}
end
test "creating a negative time duration" do
assert Cldr.Calendar.Duration.new(~T[10:00:00.0], ~T[09:00:00.0]) ==
{:ok,
%Cldr.Calendar.Duration{
day: 0,
hour: -1,
microsecond: 0,
minute: 0,
month: 0,
second: 0,
year: 0
}}
end
end
| 26.958435 | 105 | 0.478687 |
f7759c53951579d16b218d359f945c31cdd681af | 1,732 | ex | Elixir | lib/smwc/accounts/user_notifier.ex | druu/smwcbot | 0c9e3530c470028c767b6a77be8a939481756438 | [
"MIT"
] | 2 | 2022-03-09T18:04:42.000Z | 2022-03-11T22:24:25.000Z | lib/smwc/accounts/user_notifier.ex | druu/smwcbot | 0c9e3530c470028c767b6a77be8a939481756438 | [
"MIT"
] | null | null | null | lib/smwc/accounts/user_notifier.ex | druu/smwcbot | 0c9e3530c470028c767b6a77be8a939481756438 | [
"MIT"
] | 2 | 2022-02-27T22:00:17.000Z | 2022-02-28T02:20:21.000Z | defmodule SMWC.Accounts.UserNotifier do
@moduledoc """
The User Notifier context.
"""
import Swoosh.Email
alias SMWC.Mailer
# Delivers the email using the application mailer.
defp deliver(recipient, subject, body) do
email =
new()
|> to(recipient)
|> from({"MyApp", "[email protected]"})
|> subject(subject)
|> text_body(body)
with {:ok, _metadata} <- Mailer.deliver(email) do
{:ok, email}
end
end
@doc """
Deliver instructions to confirm account.
"""
def deliver_confirmation_instructions(user, url) do
deliver(user.email, "Confirmation instructions", """
==============================
Hi #{user.email},
You can confirm your account by visiting the URL below:
#{url}
If you didn't create an account with us, please ignore this.
==============================
""")
end
@doc """
Deliver instructions to reset a user password.
"""
def deliver_reset_password_instructions(user, url) do
deliver(user.email, "Reset password instructions", """
==============================
Hi #{user.email},
You can reset your password by visiting the URL below:
#{url}
If you didn't request this change, please ignore this.
==============================
""")
end
@doc """
Deliver instructions to update a user email.
"""
def deliver_update_email_instructions(user, url) do
deliver(user.email, "Update email instructions", """
==============================
Hi #{user.email},
You can change your email by visiting the URL below:
#{url}
If you didn't request this change, please ignore this.
==============================
""")
end
end
| 20.86747 | 64 | 0.569861 |
f775b70357b2ad32daa6a27c86e77f0fe228f920 | 743 | ex | Elixir | lib/day_01_tyranny_of_the_rocket.ex | scmx/advent-of-code-2019-elixir | f3022efb422e15abead6b882c78855b26b138443 | [
"MIT"
] | 1 | 2019-12-02T16:27:06.000Z | 2019-12-02T16:27:06.000Z | lib/day_01_tyranny_of_the_rocket.ex | scmx/advent-of-code-2019-elixir | f3022efb422e15abead6b882c78855b26b138443 | [
"MIT"
] | null | null | null | lib/day_01_tyranny_of_the_rocket.ex | scmx/advent-of-code-2019-elixir | f3022efb422e15abead6b882c78855b26b138443 | [
"MIT"
] | 1 | 2020-12-10T10:47:21.000Z | 2020-12-10T10:47:21.000Z | defmodule Adventofcode.Day01TyrannyOfTheRocket do
use Adventofcode
def fuel_requirements_sum(input) do
input
|> parse()
|> Enum.map(&calculate_fuel/1)
|> Enum.sum()
end
def fuel_requirements_recursive_sum(input) do
input
|> parse()
|> Enum.map(&calculate_fuel/1)
|> Enum.map(&break_down_fuel/1)
|> Enum.sum()
end
defp parse(input) do
input
|> String.split("\n")
|> Enum.map(&String.to_integer/1)
end
def calculate_fuel(input) do
div(input, 3) - 2
end
def break_down_fuel(input, acc \\ 0)
def break_down_fuel(input, acc) when input <= 0, do: acc
def break_down_fuel(input, acc) do
input
|> calculate_fuel()
|> break_down_fuel(input + acc)
end
end
| 19.051282 | 58 | 0.647376 |
f775c7269d59eff78bcc032295d8a78ee738f018 | 3,087 | ex | Elixir | lib/glimesh_web/live/user_live/components/streamer_title.ex | wolfcomp/glimesh.tv | 3953e07946aabe85fe90d9d0f36df833b22d262a | [
"MIT"
] | null | null | null | lib/glimesh_web/live/user_live/components/streamer_title.ex | wolfcomp/glimesh.tv | 3953e07946aabe85fe90d9d0f36df833b22d262a | [
"MIT"
] | null | null | null | lib/glimesh_web/live/user_live/components/streamer_title.ex | wolfcomp/glimesh.tv | 3953e07946aabe85fe90d9d0f36df833b22d262a | [
"MIT"
] | null | null | null | defmodule GlimeshWeb.UserLive.Components.StreamerTitle do
use GlimeshWeb, :live_view
alias Glimesh.Presence
alias Glimesh.Streams
alias Glimesh.Streams.StreamMetadata
@impl true
def render(assigns) do
~L"""
<%= if @user && @is_streamer do %>
<%= if !@editing do %>
<h5 class=""><span class="badge badge-danger">Live!</span> <%= @title %> <a class="fas fa-edit" phx-click="toggle-edit" href="#"></a></h5>
<% else %>
<h5 class="">
<div class="form-group">
<%= f = form_for @changeset, "#", [phx_submit: :save] %>
<%= text_input f, :stream_title, [class: "form-control"] %>
<%= submit dgettext("streams", "Update Title"), class: "btn btn-primary mt-1" %>
<i class="far fa-edit" phx-click="toggle-edit" style="color: red"></i>
</div>
</h5>
<% end %>
<% else %>
<h5 class=""><span class="badge badge-danger">Live!</span> <%= @title %></h5>
<% end %>
"""
end
@impl true
def mount(_params, %{"streamer" => streamer, "user" => nil}, socket) do
if connected?(socket), do: Streams.subscribe_metadata(streamer.id)
{:ok,
socket
|> assign(:streamer, streamer)
|> assign(:user, nil)
|> assign(:title, Streams.get_metadata_from_streamer(streamer).stream_title)
|> assign(:editing, false)
|> assign(:is_streamer, false)}
end
@impl true
def mount(_params, %{"streamer" => streamer, "user" => user}, socket) do
if connected?(socket), do: Streams.subscribe_metadata(streamer.id)
title_changeset =
if streamer.username == user.username do
Streams.StreamMetadata.changeset(
Streams.get_metadata_from_streamer(streamer)
|> Map.merge(%{streamer: streamer})
)
else
nil
end
{:ok,
socket
|> assign(:streamer, streamer)
|> assign(:user, user)
|> assign(:title, Streams.get_metadata_from_streamer(streamer).stream_title)
|> assign(:changeset, title_changeset)
|> assign(:is_streamer, if(user.username == streamer.username, do: true, else: false))
|> assign(:editing, false)}
end
@impl true
def handle_event("toggle-edit", _value, socket) do
{:noreply, socket |> assign(:editing, socket.assigns.editing |> Kernel.not())}
end
@impl true
def handle_event("save", %{"stream_metadata" => %{"stream_title" => new_title}}, socket) do
case Streams.update_title(socket.assigns.streamer, new_title) do
{:ok, changetitle} ->
{:noreply,
socket
|> assign(:editing, false)
|> assign(:title, new_title)
|> assign(
:changeset,
Streams.StreamMetadata.changeset(
changetitle
|> Map.merge(%{streamer: socket.assigns.streamer})
)
)}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
@impl true
def handle_info({:update_title, data}, socket) do
{:noreply, assign(socket, title: data.title)}
end
end
| 31.5 | 147 | 0.594428 |
f7762febea9fc0e4eb8f7296ed4d2ce4ed818f74 | 488 | ex | Elixir | web/models/post.ex | mogetutu/didactic-invention | be25678ba30ca5b9efc1b27e9f7c79350f53ab95 | [
"MIT"
] | null | null | null | web/models/post.ex | mogetutu/didactic-invention | be25678ba30ca5b9efc1b27e9f7c79350f53ab95 | [
"MIT"
] | null | null | null | web/models/post.ex | mogetutu/didactic-invention | be25678ba30ca5b9efc1b27e9f7c79350f53ab95 | [
"MIT"
] | null | null | null | defmodule ElixirApp.Post do
use ElixirApp.Web, :model
schema "posts" do
field :title, :string
field :body, :string
belongs_to :user, ElixirApp.User
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
@required_fields ~w(title)a
@optional_fields ~w(body)a
def changeset(struct, params \\ %{}) do
struct
|> cast(params, @required_fields ++ @optional_fields)
|> validate_required(@required_fields)
end
end
| 20.333333 | 57 | 0.665984 |
f7765a3a3d2f0bf75e11198a81cb38f19c31134d | 1,143 | exs | Elixir | test/schema/transfer_transaction_test.exs | SimplicityMatters/exnem | 05b77fc0ffd98321701eaba974ec2fd1def39fe2 | [
"Apache-2.0"
] | 1 | 2018-10-01T23:57:04.000Z | 2018-10-01T23:57:04.000Z | test/schema/transfer_transaction_test.exs | SimplicityMatters/exnem | 05b77fc0ffd98321701eaba974ec2fd1def39fe2 | [
"Apache-2.0"
] | null | null | null | test/schema/transfer_transaction_test.exs | SimplicityMatters/exnem | 05b77fc0ffd98321701eaba974ec2fd1def39fe2 | [
"Apache-2.0"
] | null | null | null | defmodule Exnem.Schema.TransferTransactionTest do
use Exnem.Case
import Exnem.Transaction, only: [transfer: 3, mosaic: 2, pack: 1]
alias Exnem.Crypto.KeyPair
describe "Transfer Transaction" do
test "it should create a transfer transaction", %{test_keypair: keypair} do
recipient = "SDUP5PLHDXKBX3UU5Q52LAY4WYEKGEWC6IB3VBFM"
mosaics =
with {:ok, mosaic1} <- mosaic(15_358_872_602_548_358_953, 100),
{:ok, mosaic2} <- mosaic(637_801_466_534_309_632, 100),
{:ok, mosaic3} <- mosaic(4_202_990_315_812_765_508, 100) do
[mosaic1, mosaic2, mosaic3]
end
{:ok, schema} = transfer(recipient, mosaics, message: "00")
verifiable =
schema
|> pack()
|> KeyPair.sign(keypair)
slice =
verifiable.payload
|> String.slice(240, byte_size(verifiable.payload))
assert slice ==
"90E8FEBD671DD41BEE94EC3BA5831CB608A312C2F203BA84AC030003003" <>
"030002F00FA0DEDD9086400000000000000443F6D806C05543A640000000000000029C" <>
"F5FD941AD25D56400000000000000"
end
end
end
| 31.75 | 92 | 0.654418 |
f776663bec3f67e67b14fbf1be58f0382193155c | 1,783 | exs | Elixir | clients/pub_sub_lite/mix.exs | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | 1 | 2021-10-01T09:20:41.000Z | 2021-10-01T09:20:41.000Z | clients/pub_sub_lite/mix.exs | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/pub_sub_lite/mix.exs | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"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.PubSubLite.Mixfile do
use Mix.Project
@version "0.7.0"
def project() do
[
app: :google_api_pub_sub_lite,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/pub_sub_lite"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.4"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
Pub/Sub Lite API client library.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching", "Daniel Azuma"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/pub_sub_lite",
"Homepage" => "https://cloud.google.com/pubsub/lite/docs"
}
]
end
end
| 26.61194 | 103 | 0.649467 |
f776718815290179f170c3adf706c8c0b9ab01fa | 676 | exs | Elixir | config/test.exs | petermm/littlechat | b8672165ab5e6efd0d501f291de682a40b37a7b7 | [
"MIT"
] | 166 | 2020-07-15T14:47:19.000Z | 2022-03-25T03:57:35.000Z | config/test.exs | Jurshsmith/littlechat | 50fac2f907abbfcd574d31b4d4bdad7e51302da7 | [
"MIT"
] | 12 | 2020-07-01T23:32:47.000Z | 2021-03-18T21:21:28.000Z | config/test.exs | Jurshsmith/littlechat | 50fac2f907abbfcd574d31b4d4bdad7e51302da7 | [
"MIT"
] | 21 | 2020-07-15T14:59:39.000Z | 2022-03-20T21:05:16.000Z | use Mix.Config
# Configure your database
#
# The MIX_TEST_PARTITION environment variable can be used
# to provide built-in test partitioning in CI environment.
# Run `mix help test` for more information.
config :littlechat, Littlechat.Repo,
username: "postgres",
password: "postgres",
database: "littlechat_test#{System.get_env("MIX_TEST_PARTITION")}",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :littlechat, LittlechatWeb.Endpoint,
http: [port: 4002],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
| 29.391304 | 69 | 0.754438 |
f7768674eedc7f65b6653bd761409190fd7f9bfe | 1,037 | ex | Elixir | lib/tlc_app/application.ex | coolandcodes/CodeSplintaCollector | fb1339022c23c11c336393b131dc6c1df4afdbd8 | [
"MIT"
] | null | null | null | lib/tlc_app/application.ex | coolandcodes/CodeSplintaCollector | fb1339022c23c11c336393b131dc6c1df4afdbd8 | [
"MIT"
] | null | null | null | lib/tlc_app/application.ex | coolandcodes/CodeSplintaCollector | fb1339022c23c11c336393b131dc6c1df4afdbd8 | [
"MIT"
] | null | null | null | defmodule TlcApp.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
# Start the Ecto repository
TlcApp.Repo,
# Start the endpoint when the application starts
TlcApp.Web.Endpoint
# Starts a worker by calling: TlcApp.Worker.start_link(arg)
# {TlcApp.Worker, arg},
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: TlcApp.Supervisor]
case Supervisor.start_link(children, opts) do
{:ok, _} = res ->
TlcApp.Accounts.create_first_user()
res
x -> x
end
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
TlcApp.Web.Endpoint.config_change(changed, removed)
:ok
end
end
| 27.289474 | 65 | 0.682739 |
f776901f126d9339935369288548accd25aa17e5 | 1,100 | ex | Elixir | lib/playwright/console_message.ex | dbrody/playwright-elixir | 48611c08dbdb8e36aa4dd8aa2d97a4014b753815 | [
"MIT"
] | 30 | 2021-06-01T16:59:35.000Z | 2022-03-25T16:56:19.000Z | lib/playwright/console_message.ex | dbrody/playwright-elixir | 48611c08dbdb8e36aa4dd8aa2d97a4014b753815 | [
"MIT"
] | 35 | 2021-06-10T17:05:31.000Z | 2022-02-11T22:30:36.000Z | lib/playwright/console_message.ex | dbrody/playwright-elixir | 48611c08dbdb8e36aa4dd8aa2d97a4014b753815 | [
"MIT"
] | 4 | 2021-08-13T20:38:18.000Z | 2022-01-31T04:32:35.000Z | defmodule Playwright.ConsoleMessage do
@moduledoc """
`Playwright.ConsoleMessage` instances are dispatched by page and handled via
`Playwright.Page.on/3` for the `:console` event type.
"""
use Playwright.ChannelOwner
alias Playwright.ChannelOwner
@property :message_text
# ... from: :text
@property :message_type
# ..., from: :type
# callbacks
# ---------------------------------------------------------------------------
@impl ChannelOwner
def init(message, initializer) do
{:ok, %{message | message_text: initializer.text, message_type: initializer.type}}
end
# API
# ---------------------------------------------------------------------------
# ---
# @spec args(ConsoleMessage.t()) :: [JSHandle.t()]
# def args(message)
# @spec location(ConsoleMessage.t()) :: call_location()
# def location(message)
# @spec location(ConsoleMessage.t()) :: call_location()
# def location(message)
# @spec text(ConsoleMessage.t()) :: String.t()
# def text(message)
# @spec type(ConsoleMessage.t()) :: String.t()
# def type(message)
# ---
end
| 25 | 86 | 0.572727 |
f776a5e2454a6efd7f7c3c531abd27bfccc2e06d | 1,806 | ex | Elixir | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/trigger_filter.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/trigger_filter.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/trigger_filter.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.CloudRun.V1alpha1.Model.TriggerFilter do
@moduledoc """
## Attributes
* `attributes` (*type:* `map()`, *default:* `nil`) - Optional. Attributes filters events by exact match on event context attributes. Each key in the map is compared with the equivalent key in the event context. An event passes the filter if all values are equal to the specified values. Nested context attributes are not supported as keys. Only string values are supported. Note that this field is optional in knative. In fully managed, 'type' attribute is required due to different broker implementation.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:attributes => map()
}
field(:attributes, type: :map)
end
defimpl Poison.Decoder, for: GoogleApi.CloudRun.V1alpha1.Model.TriggerFilter do
def decode(value, options) do
GoogleApi.CloudRun.V1alpha1.Model.TriggerFilter.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudRun.V1alpha1.Model.TriggerFilter do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.425532 | 509 | 0.753599 |
f776abae557fd663cf6ab6da8b13002e819956dd | 575 | ex | Elixir | lib/copan/commands/appointment/create.ex | GabrielMalakias/Copan | cdf4dec19d9f9cefca59aa9f01fe33060fe7e019 | [
"MIT"
] | 1 | 2019-01-19T00:53:07.000Z | 2019-01-19T00:53:07.000Z | lib/copan/commands/appointment/create.ex | dkuku/copan | cdf4dec19d9f9cefca59aa9f01fe33060fe7e019 | [
"MIT"
] | null | null | null | lib/copan/commands/appointment/create.ex | dkuku/copan | cdf4dec19d9f9cefca59aa9f01fe33060fe7e019 | [
"MIT"
] | 1 | 2020-01-29T21:46:16.000Z | 2020-01-29T21:46:16.000Z | defmodule Copan.Commands.Appointment.Create do
@moduledoc """
Creates articles given a map
"""
import Ecto.Changeset
require IEx
def call(params) do
id = find_user!(params.user_id)
params
|> build_changeset
|> Copan.Repo.insert!(prefix: id)
end
def find_user!(user_id) do
Copan.Queries.User.find_by_reference_id!(user_id)
end
defp build_changeset(params) do
%Copan.Schema.Appointment{}
|> cast(params, [:status, :no_show, :reference_id, :starts_at])
|> validate_required([:status, :no_show, :reference_id])
end
end
| 20.535714 | 67 | 0.690435 |
f776b25e9fb2ed30d555afc70f79f242cd5a3087 | 1,533 | exs | Elixir | mix.exs | chasm/elmmeetup | 95f9850a075dcc6ea884279485c532ac2f4db803 | [
"MIT"
] | null | null | null | mix.exs | chasm/elmmeetup | 95f9850a075dcc6ea884279485c532ac2f4db803 | [
"MIT"
] | 1 | 2018-12-26T09:07:03.000Z | 2018-12-26T09:07:03.000Z | mix.exs | chasm/elmmeetup | 95f9850a075dcc6ea884279485c532ac2f4db803 | [
"MIT"
] | null | null | null | defmodule Elmmeetup.Mixfile do
use Mix.Project
def project do
[app: :elmmeetup,
version: "0.0.1",
elixir: "~> 1.0",
elixirc_paths: elixirc_paths(Mix.env),
compilers: [:phoenix, :gettext] ++ Mix.compilers,
build_embedded: Mix.env == :prod,
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: {Elmmeetup, []},
applications: [:phoenix, :phoenix_html, :cowboy, :logger, :gettext,
:phoenix_ecto, :postgrex]]
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.1.6"},
{:postgrex, ">= 0.0.0"},
{:phoenix_ecto, "~> 2.0"},
{:phoenix_html, "~> 2.4"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.9"},
{:cowboy, "~> 1.0"}]
end
# Aliases are shortcut or tasks specific to the current project.
# For example, to create, migrate and run the seeds file at once:
#
# $ mix ecto.setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
["ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"]]
end
end
| 28.924528 | 78 | 0.607306 |
f776f5b1b51f2a496aad901de235c51af97d6106 | 1,042 | ex | Elixir | lib/dialyxir/warnings/function_application_no_function.ex | Klohto/dialyxir | 97270a696a91450fde0e1283b892a92e69e98de9 | [
"Apache-2.0"
] | 1,455 | 2015-01-03T02:53:19.000Z | 2022-03-12T00:31:25.000Z | lib/dialyxir/warnings/function_application_no_function.ex | Klohto/dialyxir | 97270a696a91450fde0e1283b892a92e69e98de9 | [
"Apache-2.0"
] | 330 | 2015-05-14T13:53:13.000Z | 2022-03-29T17:12:23.000Z | lib/dialyxir/warnings/function_application_no_function.ex | Klohto/dialyxir | 97270a696a91450fde0e1283b892a92e69e98de9 | [
"Apache-2.0"
] | 146 | 2015-02-03T18:19:43.000Z | 2022-03-07T10:05:20.000Z | defmodule Dialyxir.Warnings.FunctionApplicationNoFunction do
@moduledoc """
The function being invoked exists, but has an arity mismatch.
## Example
defmodule Example do
def ok() do
fun = fn _ -> :ok end
fun.()
end
end
"""
@behaviour Dialyxir.Warning
@impl Dialyxir.Warning
@spec warning() :: :fun_app_no_fun
def warning(), do: :fun_app_no_fun
@impl Dialyxir.Warning
@spec format_short([String.t()]) :: String.t()
def format_short([_, _, arity]) do
"Function application will fail, because anonymous function has arity of #{arity}."
end
@impl Dialyxir.Warning
@spec format_long([String.t()]) :: String.t()
def format_long([op, type, arity]) do
pretty_op = Erlex.pretty_print(op)
pretty_type = Erlex.pretty_print_type(type)
"Function application will fail, because #{pretty_op} :: #{pretty_type} is not a function of arity #{arity}."
end
@impl Dialyxir.Warning
@spec explain() :: String.t()
def explain() do
@moduledoc
end
end
| 24.809524 | 113 | 0.662188 |
f77727e7938bfa75423679ea7de637e495262519 | 1,821 | exs | Elixir | clients/sql_admin/mix.exs | Contractbook/elixir-google-api | 342751041aaf8c2e7f76f9922cf24b9c5895802b | [
"Apache-2.0"
] | null | null | null | clients/sql_admin/mix.exs | Contractbook/elixir-google-api | 342751041aaf8c2e7f76f9922cf24b9c5895802b | [
"Apache-2.0"
] | null | null | null | clients/sql_admin/mix.exs | Contractbook/elixir-google-api | 342751041aaf8c2e7f76f9922cf24b9c5895802b | [
"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.SQLAdmin.Mixfile do
use Mix.Project
@version "0.43.1"
def project() do
[
app: :google_api_sql_admin,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/sql_admin"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.4"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
Cloud SQL Admin API client library. API for Cloud SQL database instance management
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching", "Daniel Azuma"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/sql_admin",
"Homepage" => "https://developers.google.com/cloud-sql/"
}
]
end
end
| 27.179104 | 100 | 0.653487 |
f777428839e912f157b72c9d37cb0b3b2776ae0a | 7,682 | exs | Elixir | test/lib/bamboo/adapters/mailgun_adapter_test.exs | mstratman/bamboo | 8ae537e0dee1c52c3195e359b8636156513f89f2 | [
"MIT"
] | null | null | null | test/lib/bamboo/adapters/mailgun_adapter_test.exs | mstratman/bamboo | 8ae537e0dee1c52c3195e359b8636156513f89f2 | [
"MIT"
] | null | null | null | test/lib/bamboo/adapters/mailgun_adapter_test.exs | mstratman/bamboo | 8ae537e0dee1c52c3195e359b8636156513f89f2 | [
"MIT"
] | null | null | null | defmodule Bamboo.MailgunAdapterTest do
use ExUnit.Case
alias Bamboo.Email
alias Bamboo.MailgunAdapter
@config %{adapter: MailgunAdapter, api_key: "dummyapikey", domain: "test.tt"}
@config_with_env_var_key %{
adapter: MailgunAdapter,
api_key: {:system, "MAILGUN_API_KEY"},
domain: {:system, "MAILGUN_DOMAIN"}
}
defmodule FakeMailgun do
use Plug.Router
plug(
Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Jason
)
plug(:match)
plug(:dispatch)
def start_server(parent) do
Agent.start_link(fn -> Map.new() end, name: __MODULE__)
Agent.update(__MODULE__, &Map.put(&1, :parent, parent))
port = get_free_port()
Application.put_env(:bamboo, :mailgun_base_uri, "http://localhost:#{port}")
Plug.Adapters.Cowboy.http(__MODULE__, [], port: port, ref: __MODULE__)
end
defp get_free_port do
{:ok, socket} = :ranch_tcp.listen(port: 0)
{:ok, port} = :inet.port(socket)
:erlang.port_close(socket)
port
end
def shutdown do
Plug.Adapters.Cowboy.shutdown(__MODULE__)
end
post "/test.tt/messages" do
case Map.get(conn.params, "from") do
"INVALID_EMAIL" -> send_resp(conn, 500, "Error!!")
_ -> send_resp(conn, 200, "SENT")
end
|> send_to_parent
end
defp send_to_parent(conn) do
parent = Agent.get(__MODULE__, fn set -> Map.get(set, :parent) end)
send(parent, {:fake_mailgun, conn})
conn
end
end
setup do
FakeMailgun.start_server(self())
on_exit(fn ->
FakeMailgun.shutdown()
end)
:ok
end
test "can read the settings from an ENV var" do
System.put_env("MAILGUN_API_KEY", "env_api_key")
System.put_env("MAILGUN_DOMAIN", "env_domain")
config = MailgunAdapter.handle_config(@config_with_env_var_key)
assert config[:api_key] == "env_api_key"
assert config[:domain] == "env_domain"
System.delete_env("MAILGUN_API_KEY")
System.delete_env("MAILGUN_DOMAIN")
end
test "raises if the api key is nil" do
assert_raise ArgumentError, ~r/no api_key set/, fn ->
MailgunAdapter.handle_config(%{domain: "test.tt"})
end
end
test "raises if the domain is nil" do
assert_raise ArgumentError, ~r/no domain set/, fn ->
MailgunAdapter.handle_config(%{api_key: "dummyapikey"})
end
end
test "raises if an invalid ENV var is used for the api_key" do
System.put_env("MAILGUN_DOMAIN", "env_domain")
assert_raise ArgumentError, ~r/no api_key set/, fn ->
new_email(from: "[email protected]") |> MailgunAdapter.deliver(@config_with_env_var_key)
end
assert_raise ArgumentError, ~r/no api_key set/, fn ->
MailgunAdapter.handle_config(@config_with_env_var_key)
end
System.delete_env("MAILGUN_DOMAIN")
end
test "raises if an invalid ENV var is used for the domain" do
System.put_env("MAILGUN_API_KEY", "env_api_key")
assert_raise ArgumentError, ~r/no domain set/, fn ->
new_email(from: "[email protected]") |> MailgunAdapter.deliver(@config_with_env_var_key)
end
assert_raise ArgumentError, ~r/no domain set/, fn ->
MailgunAdapter.handle_config(@config_with_env_var_key)
end
System.delete_env("MAILGUN_API_KEY")
end
test "deliver/2 sends the to the right url" do
new_email() |> MailgunAdapter.deliver(@config)
assert_receive {:fake_mailgun, %{request_path: request_path}}
assert request_path == "/test.tt/messages"
end
test "deliver/2 sends from, subject, text body, html body, headers and custom vars" do
email =
new_email(
from: "[email protected]",
subject: "My Subject",
text_body: "TEXT BODY",
html_body: "HTML BODY"
)
|> Email.put_header("X-My-Header", "my_header_value")
|> Email.put_header("Reply-To", "[email protected]")
|> Email.put_private(:mailgun_custom_vars, %{my_custom_var: 42, other_custom_var: 43})
MailgunAdapter.deliver(email, @config)
assert_receive {:fake_mailgun, %{params: params, req_headers: headers}}
assert params["from"] == elem(email.from, 1)
assert params["subject"] == email.subject
assert params["text"] == email.text_body
assert params["html"] == email.html_body
assert params["h:X-My-Header"] == "my_header_value"
assert params["v:my_custom_var"] == "42"
assert params["v:other_custom_var"] == "43"
assert params["h:Reply-To"] == "[email protected]"
hashed_token = Base.encode64("api:" <> @config.api_key)
assert {"authorization", "Basic #{hashed_token}"} in headers
end
# We keep two separate tests, with and without attachment, because the output produced by the adapter changes a lot. (MIME multipart body instead of URL-encoded form)
test "deliver/2 sends from, subject, text body, html body, headers, custom vars and attachment" do
attachment_source_path = Path.join(__DIR__, "../../../support/attachment.txt")
email =
new_email(
from: "[email protected]",
subject: "My Subject",
text_body: "TEXT BODY",
html_body: "HTML BODY"
)
|> Email.put_header("Reply-To", "[email protected]")
|> Email.put_header("X-My-Header", "my_header_value")
|> Email.put_private(:mailgun_custom_vars, %{my_custom_var: 42, other_custom_var: 43})
|> Email.put_attachment(attachment_source_path)
MailgunAdapter.deliver(email, @config)
assert_receive {:fake_mailgun, %{params: params, req_headers: headers}}
assert MailgunAdapter.supports_attachments?()
assert params["from"] == elem(email.from, 1)
assert params["subject"] == email.subject
assert params["text"] == email.text_body
assert params["html"] == email.html_body
assert params["h:X-My-Header"] == "my_header_value"
assert params["v:my_custom_var"] == "42"
assert params["v:other_custom_var"] == "43"
assert params["h:Reply-To"] == "[email protected]"
assert %Plug.Upload{content_type: content_type, filename: filename, path: download_path} =
params["attachment"]
assert content_type == "application/octet-stream"
assert filename == "attachment.txt"
assert File.read!(download_path) == File.read!(attachment_source_path)
hashed_token = Base.encode64("api:" <> @config.api_key)
assert {"authorization", "Basic #{hashed_token}"} in headers
end
test "deliver/2 correctly formats recipients" do
email =
new_email(
to: [{"To", "[email protected]"}, {nil, "[email protected]"}],
cc: [{"CC", "[email protected]"}],
bcc: [{"BCC", "[email protected]"}]
)
email |> MailgunAdapter.deliver(@config)
assert_receive {:fake_mailgun, %{params: params}}
assert params["to"] == "To <[email protected]>,[email protected]"
assert params["cc"] == "CC <[email protected]>"
assert params["bcc"] == "BCC <[email protected]>"
end
test "deliver/2 correctly formats reply-to" do
email =
new_email(
from: "[email protected]",
subject: "My Subject",
text_body: "TEXT BODY",
html_body: "HTML BODY"
)
|> Email.put_header("reply-to", "[email protected]")
MailgunAdapter.deliver(email, @config)
assert_receive {:fake_mailgun, %{params: params}}
assert params["h:Reply-To"] == "[email protected]"
end
test "raises if the response is not a success" do
email = new_email(from: "INVALID_EMAIL")
assert_raise Bamboo.ApiError, fn ->
email |> MailgunAdapter.deliver(@config)
end
end
defp new_email(attrs \\ []) do
attrs = Keyword.merge([from: "[email protected]", to: []], attrs)
Email.new_email(attrs) |> Bamboo.Mailer.normalize_addresses()
end
end
| 31.101215 | 168 | 0.65686 |
f77742927bd444a3af1d116f25867a9da4fd89df | 273 | ex | Elixir | apps/speedrun_blogengine/lib/speedrun_blogengine/application.ex | jhonndabi/speedrun_blogengine-1 | 047ce8b913b170f9f329fd86c0bf643953e0a761 | [
"Apache-2.0"
] | 11 | 2021-04-12T18:32:30.000Z | 2021-04-23T04:29:48.000Z | apps/speedrun_blogengine/lib/speedrun_blogengine/application.ex | jhonndabi/speedrun_blogengine-1 | 047ce8b913b170f9f329fd86c0bf643953e0a761 | [
"Apache-2.0"
] | 1 | 2021-09-18T01:14:50.000Z | 2021-09-18T01:14:50.000Z | apps/speedrun_blogengine/lib/speedrun_blogengine/application.ex | jhonndabi/speedrun_blogengine-1 | 047ce8b913b170f9f329fd86c0bf643953e0a761 | [
"Apache-2.0"
] | 11 | 2021-04-13T15:01:36.000Z | 2021-04-19T19:04:47.000Z | defmodule SpeedrunBlogengine.Application do
@moduledoc false
use Application
def start(_type, _args) do
children = [
SpeedrunBlogengine.Repo
]
Supervisor.start_link(children, strategy: :one_for_one, name: SpeedrunBlogengine.Supervisor)
end
end
| 19.5 | 96 | 0.74359 |
f777890ed4b39a7c87b99e2e5b3b4a4f0d021bc6 | 255 | exs | Elixir | config/config.exs | drathier/meeseeks_html5ever | 50d1d5b3c95345a49f4852a4dd3004c2eb29870c | [
"Apache-2.0",
"MIT"
] | 12 | 2017-04-11T15:16:51.000Z | 2021-09-12T00:09:03.000Z | config/config.exs | drathier/meeseeks_html5ever | 50d1d5b3c95345a49f4852a4dd3004c2eb29870c | [
"Apache-2.0",
"MIT"
] | 21 | 2017-05-05T13:24:47.000Z | 2021-11-20T18:02:44.000Z | config/config.exs | drathier/meeseeks_html5ever | 50d1d5b3c95345a49f4852a4dd3004c2eb29870c | [
"Apache-2.0",
"MIT"
] | 10 | 2017-12-14T12:31:27.000Z | 2021-10-15T11:55:25.000Z | use Mix.Config
config :meeseeks_html5ever, MeeseeksHtml5ever.Native,
path: "native/meeseeks_html5ever_nif",
cargo: :system,
default_features: false,
features: [],
mode: :release,
otp_app: :meeseeks_html5ever,
crate: :meeseeks_html5ever_nif
| 23.181818 | 53 | 0.760784 |
f777a26a3d349dfc90ef4efe88bd0f0f3443999f | 185 | ex | Elixir | apps/core/lib/auth_web/views/pow_email_confirmation/mailer_view.ex | votiakov/petal | ec03551da6dadc0c3482b25a5f5dcd400c36db43 | [
"MIT"
] | null | null | null | apps/core/lib/auth_web/views/pow_email_confirmation/mailer_view.ex | votiakov/petal | ec03551da6dadc0c3482b25a5f5dcd400c36db43 | [
"MIT"
] | null | null | null | apps/core/lib/auth_web/views/pow_email_confirmation/mailer_view.ex | votiakov/petal | ec03551da6dadc0c3482b25a5f5dcd400c36db43 | [
"MIT"
] | null | null | null | defmodule Legendary.AuthWeb.PowEmailConfirmation.MailerView do
use Legendary.AuthWeb, :mailer_view
def subject(:email_confirmation, _assigns), do: "Confirm your email address"
end
| 30.833333 | 78 | 0.816216 |
f777aeedb68f9eee8eab3f95d84895b7d13c9f57 | 270 | ex | Elixir | lib/phone/nanp/us/ct.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | lib/phone/nanp/us/ct.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | lib/phone/nanp/us/ct.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | defmodule Phone.NANP.US.CT do
@moduledoc false
use Helper.Area
def regex, do: ~r/^(1)(203|475|860|959)([2-9].{6})$/
def area_name, do: "Connecticut"
def area_type, do: "state"
def area_abbreviation, do: "CT"
matcher ["1203", "1475", "1860", "1959"]
end
| 20.769231 | 54 | 0.637037 |
f777ff9e4cdcc66d94bb9ad39b8082b49bb77326 | 2,896 | ex | Elixir | lib/vintage_net/connectivity/host_list.ex | nerves-networking/vintage_net | 8d4251a0ec995babf8f4d7aa7cc1d74b70646c72 | [
"Apache-2.0"
] | 85 | 2019-05-09T14:54:38.000Z | 2022-02-08T16:52:04.000Z | lib/vintage_net/connectivity/host_list.ex | fhunleth/vintage_net | 215495533cb642eeb172daba08208a454f19b36f | [
"Apache-2.0"
] | 132 | 2019-05-09T15:57:59.000Z | 2022-02-28T16:31:22.000Z | lib/vintage_net/connectivity/host_list.ex | fhunleth/vintage_net | 215495533cb642eeb172daba08208a454f19b36f | [
"Apache-2.0"
] | 14 | 2019-07-08T19:18:23.000Z | 2022-02-08T16:52:05.000Z | defmodule VintageNet.Connectivity.HostList do
@moduledoc false
import Record, only: [defrecord: 2]
require Logger
@typedoc """
IP address in tuple form or a hostname
"""
@type ip_or_hostname() :: :inet.ip_address() | String.t()
@type name_port() :: {ip_or_hostname(), 1..65535}
@type ip_port() :: {:inet.ip_address(), 1..65535}
@type hostent() :: record(:hostent, [])
defrecord :hostent, Record.extract(:hostent, from_lib: "kernel/include/inet.hrl")
@doc """
Load the internet host list from the application environment
This function performs basic checks on the list and tries to
help users on easy mistakes.
"""
@spec load(keyword()) :: [name_port()]
def load(config \\ Application.get_all_env(:vintage_net)) do
config_list = internet_host_list(config) ++ legacy_internet_host(config)
hosts =
config_list
|> Enum.map(&normalize/1)
|> Enum.reject(fn x -> x == :error end)
if hosts == [] do
Logger.warn("VintageNet: empty or invalid `:internet_host_list` so using defaults")
[{{1, 1, 1, 1}, 80}]
else
hosts
end
end
defp internet_host_list(config) do
case config[:internet_host_list] do
host_list when is_list(host_list) ->
host_list
_ ->
Logger.warn("VintageNet: :internet_host_list must be a list")
[]
end
end
defp legacy_internet_host(config) do
case config[:internet_host] do
nil ->
[]
host ->
Logger.warn(
"VintageNet: :internet_host key is deprecated. Replace with `internet_host_list: [{#{inspect(host)}, 80}]`"
)
[{host, 80}]
end
end
defp normalize({host, port}) when port > 0 and port < 65535 do
case VintageNet.IP.ip_to_tuple(host) do
{:ok, host_as_tuple} -> {host_as_tuple, port}
# Likely a domain name
{:error, _} when is_binary(host) -> {host, port}
_ -> :error
end
end
defp normalize(_), do: :error
@doc """
Resolve any unresolved host names and generate a list of hosts to ping
This returns at most 3 hosts to try at a time. If they all fail, this
should be called again to get another set. This involves DNS, so the
call can block.
"""
@spec create_ping_list([name_port()]) :: [ip_port()]
def create_ping_list(hosts) do
hosts
|> Enum.flat_map(&resolve/1)
|> Enum.uniq()
|> Enum.shuffle()
|> Enum.take(3)
end
defp resolve({ip, _port} = ip_port) when is_tuple(ip) do
[ip_port]
end
defp resolve({name, port}) when is_binary(name) do
# Only consider IPv4 for now
case :inet.gethostbyname(String.to_charlist(name)) do
{:ok, hostent(h_addr_list: addresses)} ->
for address <- addresses, do: {address, port}
_error ->
# DNS not working, so the internet is not working enough
# to consider this host
[]
end
end
end
| 25.857143 | 117 | 0.633978 |
f77824dc3340ff717b2cd9fa7281f62cfb67888f | 2,036 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_page_info_form_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_page_info_form_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_page_info_form_info.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.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1PageInfoFormInfo do
@moduledoc """
Represents form information.
## Attributes
* `parameterInfo` (*type:* `list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1PageInfoFormInfoParameterInfo.t)`, *default:* `nil`) - Optional for both WebhookRequest and WebhookResponse. The parameters contained in the form. Note that the webhook cannot add or remove any form parameter.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:parameterInfo =>
list(
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1PageInfoFormInfoParameterInfo.t()
)
| nil
}
field(:parameterInfo,
as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1PageInfoFormInfoParameterInfo,
type: :list
)
end
defimpl Poison.Decoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1PageInfoFormInfo do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1PageInfoFormInfo.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1PageInfoFormInfo do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.508475 | 306 | 0.75442 |
f7782606bf4a40a06d985b7a05aaf28871a52af4 | 59 | ex | Elixir | apps/enchat_web/lib/enchat_web/views/page_view.ex | Allypost/enchat | f9cff2906116550099f4574bf44e8dc1fea6d476 | [
"MIT"
] | null | null | null | apps/enchat_web/lib/enchat_web/views/page_view.ex | Allypost/enchat | f9cff2906116550099f4574bf44e8dc1fea6d476 | [
"MIT"
] | null | null | null | apps/enchat_web/lib/enchat_web/views/page_view.ex | Allypost/enchat | f9cff2906116550099f4574bf44e8dc1fea6d476 | [
"MIT"
] | null | null | null | defmodule EnchatWeb.PageView do
use EnchatWeb, :view
end
| 14.75 | 31 | 0.79661 |
f77826e1c30372998e072e13964c5688b6dd79e3 | 3,714 | ex | Elixir | deps/phoenix_html/lib/phoenix_html/form_data.ex | hallebadkapp/rumbl-ms | ae2ef9975658115f8c4d5c49c28d8bde00a74b83 | [
"MIT"
] | null | null | null | deps/phoenix_html/lib/phoenix_html/form_data.ex | hallebadkapp/rumbl-ms | ae2ef9975658115f8c4d5c49c28d8bde00a74b83 | [
"MIT"
] | null | null | null | deps/phoenix_html/lib/phoenix_html/form_data.ex | hallebadkapp/rumbl-ms | ae2ef9975658115f8c4d5c49c28d8bde00a74b83 | [
"MIT"
] | null | null | null | defprotocol Phoenix.HTML.FormData do
@moduledoc """
Converts a data structure into a `Phoenix.HTML.Form` struct.
"""
@doc """
Converts a data structure into a `Phoenix.HTML.Form` struct.
The options are the same options given to `form_for/4`. It
can be used by implementations to configure their behaviour
and it must be stored in the underlying struct, with any
custom field removed.
"""
@spec to_form(t, Keyword.t) :: Phoenix.HTML.Form.t
def to_form(data, options)
@doc """
Converts the field in the given form based on the data structure
into a `Phoenix.HTML.Form` struct.
The options are the same options given to `inputs_for/4`. It
can be used by implementations to configure their behaviour
and it must be stored in the underlying struct, with any
custom field removed.
"""
@spec to_form(t, Phoenix.HTML.Form.t, atom, Keyword.t) :: Phoenix.HTML.Form.t
def to_form(data, form, field, options)
@doc """
Returns the HTML5 validations that would apply to
the given field.
"""
@spec input_validations(t, atom) :: Keyword.t
def input_validations(data, field)
@doc """
Receives the given field and returns its input type (:text_input,
:select, etc). Returns `nil` if the type is unknown.
"""
@spec input_type(t, atom) :: atom | nil
def input_type(data, field)
end
defimpl Phoenix.HTML.FormData, for: Plug.Conn do
def to_form(conn, opts) do
{name, opts} = Keyword.pop(opts, :as)
name = to_string(name || warn_name(opts) || no_name_error!())
%Phoenix.HTML.Form{
source: conn,
impl: __MODULE__,
id: name,
name: name,
params: Map.get(conn.params, name) || %{},
options: opts
}
end
def to_form(conn, form, field, opts) do
{default, opts} = Keyword.pop(opts, :default, %{})
{prepend, opts} = Keyword.pop(opts, :prepend, [])
{append, opts} = Keyword.pop(opts, :append, [])
{name, opts} = Keyword.pop(opts, :as)
{id, opts} = Keyword.pop(opts, :id)
id = to_string(id || form.id <> "_#{field}")
name = to_string(name || warn_name(opts) || form.name <> "[#{field}]")
params = Map.get(form.params, Atom.to_string(field))
cond do
# cardinality: one
is_map(default) ->
[%Phoenix.HTML.Form{
source: conn,
impl: __MODULE__,
id: id,
name: name,
model: default,
params: params || %{},
options: opts}]
# cardinality: many
is_list(default) ->
entries =
if params do
params
|> Enum.sort_by(&elem(&1, 0))
|> Enum.map(&{nil, elem(&1, 1)})
else
Enum.map(prepend ++ default ++ append, &{&1, %{}})
end
for {{model, params}, index} <- Enum.with_index(entries) do
index_string = Integer.to_string(index)
%Phoenix.HTML.Form{
source: conn,
impl: __MODULE__,
index: index,
id: id <> "_" <> index_string,
name: name <> "[" <> index_string <> "]",
model: model,
params: params,
options: opts}
end
end
end
def input_type(_data, _field), do: :text_input
def input_validations(_data, _field), do: []
defp no_name_error! do
raise ArgumentError, "form_for/4 expects [as: NAME] to be given as option " <>
"when used with @conn"
end
defp warn_name(opts) do
if name = Keyword.get(opts, :name) do
IO.write :stderr, "the :name option in form_for/inputs_for is deprecated, " <>
"please use :as instead\n" <> Exception.format_stacktrace()
name
end
end
end
| 29.951613 | 84 | 0.595854 |
f77827a6fd378bba8aab2c6ef549d60154e7f75d | 374 | ex | Elixir | lib/radiator/media/chapter_image.ex | bhtabor/radiator | 39c137a18d36d6f418f9d1ffb7aa2c99011d66cf | [
"MIT"
] | 92 | 2019-01-03T11:46:23.000Z | 2022-02-19T21:28:44.000Z | lib/radiator/media/chapter_image.ex | bhtabor/radiator | 39c137a18d36d6f418f9d1ffb7aa2c99011d66cf | [
"MIT"
] | 350 | 2019-04-11T07:55:51.000Z | 2021-08-03T11:19:05.000Z | lib/radiator/media/chapter_image.ex | bhtabor/radiator | 39c137a18d36d6f418f9d1ffb7aa2c99011d66cf | [
"MIT"
] | 10 | 2019-04-18T12:47:27.000Z | 2022-01-25T20:49:15.000Z | defmodule Radiator.Media.ChapterImage do
use Arc.Definition
use Arc.Ecto.Definition
use Radiator.Media.CoverImageBase
def filename(version, {file, _chapter}) do
basename = Path.basename(file.file_name, Path.extname(file.file_name))
"#{basename}_#{version}"
end
def storage_dir(_version, {_file, chapter}) do
"chapter/#{chapter.audio_id}"
end
end
| 24.933333 | 74 | 0.73262 |
f77828a7f1063e2b7f321ee11dc83a365d892e8c | 1,840 | ex | Elixir | clients/content/lib/google_api/content/v21/model/repricing_rule_stats_based_rule.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/content/lib/google_api/content/v21/model/repricing_rule_stats_based_rule.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/content/lib/google_api/content/v21/model/repricing_rule_stats_based_rule.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.Content.V21.Model.RepricingRuleStatsBasedRule do
@moduledoc """
Definition of stats based rule.
## Attributes
* `percentageDelta` (*type:* `integer()`, *default:* `nil`) - The percent change against the price target. Valid from 0 to 100 inclusively.
* `priceDelta` (*type:* `String.t`, *default:* `nil`) - The price delta against the above price target. A positive value means the price should be adjusted to be above statistical measure, and a negative value means below. Currency code must not be included.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:percentageDelta => integer() | nil,
:priceDelta => String.t() | nil
}
field(:percentageDelta)
field(:priceDelta)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.RepricingRuleStatsBasedRule do
def decode(value, options) do
GoogleApi.Content.V21.Model.RepricingRuleStatsBasedRule.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.RepricingRuleStatsBasedRule do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.8 | 262 | 0.740761 |
f77852adbffe5f7bf9a92730882c14637179cebf | 1,545 | ex | Elixir | clients/custom_search/lib/google_api/custom_search/v1/model/promotion_image.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"Apache-2.0"
] | null | null | null | clients/custom_search/lib/google_api/custom_search/v1/model/promotion_image.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"Apache-2.0"
] | null | null | null | clients/custom_search/lib/google_api/custom_search/v1/model/promotion_image.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"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.CustomSearch.V1.Model.PromotionImage do
@moduledoc """
## Attributes
* `height` (*type:* `integer()`, *default:* `nil`) -
* `source` (*type:* `String.t`, *default:* `nil`) -
* `width` (*type:* `integer()`, *default:* `nil`) -
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:height => integer(),
:source => String.t(),
:width => integer()
}
field(:height)
field(:source)
field(:width)
end
defimpl Poison.Decoder, for: GoogleApi.CustomSearch.V1.Model.PromotionImage do
def decode(value, options) do
GoogleApi.CustomSearch.V1.Model.PromotionImage.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CustomSearch.V1.Model.PromotionImage do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 29.150943 | 78 | 0.69644 |
f7785e21d4d2143f1378de7afe40c5da95214b14 | 3,691 | exs | Elixir | apps/omg_watcher/test/omg_watcher/integration/block_getter_test.exs | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 177 | 2018-08-24T03:51:02.000Z | 2020-05-30T13:29:25.000Z | apps/omg_watcher/test/omg_watcher/integration/block_getter_test.exs | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 1,042 | 2018-08-25T00:52:39.000Z | 2020-06-01T05:15:17.000Z | apps/omg_watcher/test/omg_watcher/integration/block_getter_test.exs | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 47 | 2018-08-24T12:06:33.000Z | 2020-04-28T11:49:25.000Z | # Copyright 2019-2020 OMG Network 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 OMG.Watcher.Integration.BlockGetterTest do
@moduledoc """
This test is intended to be the major smoke/integration test of the Watcher
It tests whether valid/invalid blocks, deposits and exits are tracked correctly within the Watcher
"""
use ExUnitFixtures
use ExUnit.Case, async: false
use OMG.Watcher.Fixtures
use OMG.Watcher.Integration.Fixtures
use Plug.Test
require OMG.Watcher.Utxo
alias OMG.Eth
alias OMG.Watcher.BlockGetter
alias OMG.Watcher.Event
alias OMG.Watcher.Integration.BadChildChainServer
alias OMG.Watcher.Integration.TestHelper, as: IntegrationTest
alias Support.WatcherHelper
@timeout 40_000
@eth <<0::160>>
@moduletag :integration
@moduletag :watcher
@moduletag timeout: 100_000
@tag fixtures: [:in_beam_watcher, :test_server]
test "hash of returned block does not match hash submitted to the root chain", %{test_server: context} do
different_hash = <<0::256>>
block_with_incorrect_hash = %{OMG.Watcher.Block.hashed_txs_at([], 1000) | hash: different_hash}
# from now on the child chain server is broken until end of test
route =
BadChildChainServer.prepare_route_to_inject_bad_block(
context,
block_with_incorrect_hash,
different_hash
)
:sys.replace_state(BlockGetter, fn state ->
config = state.config
new_config = %{config | child_chain_url: "http://localhost:#{route.port}"}
%{state | config: new_config}
end)
# checking if both machines and humans learn about the byzantine condition
assert WatcherHelper.capture_log(fn ->
{:ok, _txhash} = Eth.submit_block(different_hash, 1, 20_000_000_000)
IntegrationTest.wait_for_byzantine_events([%Event.InvalidBlock{}.name], @timeout)
end) =~ inspect({:error, :incorrect_hash})
end
@tag fixtures: [:in_beam_watcher, :alice, :test_server]
test "bad transaction with not existing utxo, detected by interactions with State", %{
alice: alice,
test_server: context
} do
# preparing block with invalid transaction
recovered = OMG.Watcher.TestHelper.create_recovered([{1, 0, 0, alice}], @eth, [{alice, 10}])
block_with_incorrect_transaction = OMG.Watcher.Block.hashed_txs_at([recovered], 1000)
# from now on the child chain server is broken until end of test
route =
BadChildChainServer.prepare_route_to_inject_bad_block(
context,
block_with_incorrect_transaction
)
:sys.replace_state(BlockGetter, fn state ->
config = state.config
new_config = %{config | child_chain_url: "http://localhost:#{route.port}"}
%{state | config: new_config}
end)
invalid_block_hash = block_with_incorrect_transaction.hash
# checking if both machines and humans learn about the byzantine condition
assert WatcherHelper.capture_log(fn ->
{:ok, _txhash} = Eth.submit_block(invalid_block_hash, 1, 20_000_000_000)
IntegrationTest.wait_for_byzantine_events([%Event.InvalidBlock{}.name], @timeout)
end) =~ inspect(:tx_execution)
end
end
| 36.186275 | 107 | 0.720943 |
f77873467af7e007b1d21abd27cb0070a8d8c01b | 16,370 | ex | Elixir | apps/nmap/scratch.ex | lowlandresearch/kudzu | f65da5061c436afb114a2e95bc6d115b6ec7be53 | [
"MIT"
] | null | null | null | apps/nmap/scratch.ex | lowlandresearch/kudzu | f65da5061c436afb114a2e95bc6d115b6ec7be53 | [
"MIT"
] | 4 | 2020-05-16T16:05:33.000Z | 2020-05-16T19:52:12.000Z | apps/nmap/scratch.ex | lowlandresearch/kudzu | f65da5061c436afb114a2e95bc6d115b6ec7be53 | [
"MIT"
] | null | null | null | defmodule Nmap.Scratch do
defstruct [
# Function to be called upon success (i.e. exit status of 0). If
# the function returns :ok, then the Nmap.Process GenServer stops,
# otherwise, it continues to run.
:success,
# Function to be called upon failure (i.e. exit status != 0). If
# the function returns :ok, then the Nmap.Process GenServer stops,
# otherwise, it continues to run.
:failure,
# ----------------------------------------------------------------
# TARGET SPECIFICATION
#
# Can pass hostnames, IP addresses, networks, etc.
# Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.0-255.1-254
:targets, # List of targets
:iL, # Input from list of hosts/networks
:iR, # Choose random targets
:exclude, # Exclude hosts/network
:excludefile, # Exclude list from file
# ----------------------------------------------------------------
# HOST DISCOVERY
#
:sL, # List Scan - simply list targets to scan
:sn, # Ping Scan - disable port scan
:Pn, # Treat all hosts as online -- skip host discovery
:PS, # TCP SYN discovery to given ports
:PA, # TCP ACK discovery to given ports
:PU, # UDP discovery to given ports
:PY, # SCTP discovery to given ports
:PE, # ICMP echo discovery probe
:PP, # timestamp discovery probe
:PM, # netmask request discovery probe
:PO, # [protocol list]
#
# DNS
:n, # Never do DNS resolution
:R, # Always resolve [default: sometimes]
:dns_servers, # Specify custom DNS servers
:system_dns, # Use OS's DNS resolver
:traceroute, # Trace hop path to each host
# ----------------------------------------------------------------
# SCAN TECHNIQUES
#
# TCP
:sS, # SYN scans
:sT, # Connect() scans
:sA, # ACK scans
:sW, # Window scans
:sM, # Maimon scans
:sN, # Nullscans
:sF, # FIN scans
:sX, # Xmas scans
:scanflags, # <flags>: Customize TCP scan flags
#
# UDP
:sU, # UDP Scan
#
# SCTP
:sY, # INIT scans
:sZ, # COOKIE-ECHO scans
#
# Other
:sI, # <zombie host[:probeport]>: Idle scan
:sO, # IP protocol scan
:b, # <FTP relay host>: FTP bounce scan
# ----------------------------------------------------------------
# PORT SPECIFICATION AND SCAN ORDER
#
:p, # <port ranges>: Only scan specified ports
# Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9
#
# <port ranges>: Exclude the specified ports from scanning
:exclude_ports,
#
:F, # Fast mode - Scan fewer ports than the default scan
:r, # Scan ports consecutively - don't randomize
:top_ports, # <number>: Scan <number> most common ports
:port_ratio, # <ratio>: Scan ports more common than <ratio>
# ----------------------------------------------------------------
# SERVICE/VERSION DETECTION
:sV, # Probe open ports to determine service/version info
#
# <level>: Set from 0 (light) to 9 (try all probes)
:version_intensity,
# Limit to most likely probes (intensity 2)
:version_light,
# Try every single probe (intensity 9)
:version_all,
# Show detailed version scan activity (for debugging)
:version_trace,
# ----------------------------------------------------------------
# SCRIPT SCAN
:sC, # equivalent to --script=default
# <Lua scripts>: <Lua scripts> is a comma separated list of
# directories, script-files or script-categories
:script,
# <n1=v1,[n2=v2,...]>: provide arguments to scripts
:script_args,
# filename: provide NSE script args in a file
:script_args_file,
# Show all data sent and received
:script_trace,
# Update the script database.
:script_updatedb,
# ----------------------------------------------------------------
# OS DETECTION
#
:O, # Enable OS detection
:osscan_limit, # Limit OS detection to promising targets
:osscan_guess, # Guess OS more aggressively
# ----------------------------------------------------------------
# TIMING AND PERFORMANCE
#
# Options which take <time> are in seconds, or append 'ms'
# (milliseconds), 's' (seconds), 'm' (minutes), or 'h' (hours) to
# the value (e.g. 30m).
#
:T, # 0..5: Set timing template (higher is faster)
:min_hostgroup, # <size>: Parallel host scan group sizes
:max_hostgroup, # <size>: Parallel host scan group sizes
:min_parallelism, # <numprobes>: Probe parallelization
:max_parallelism, # <numprobes>: Probe parallelization
:min_rtt_timeout, # <time>: Specifies probe round trip time.
:max_rtt_timeout, # <time>: Specifies probe round trip time.
:initial_rtt_timeout, # <time>: Specifies probe round trip time.
# <tries>: Caps number of port scan probe retransmissions.
:max_retries,
# <time>: Give up on target after this long
:host_timeout,
:scan_delay, # <time>: Adjust delay between probes
:max_scan_delay, # <time>: Adjust delay between probes
# <number>: Send packets no slower than <number> per second
:min_rate,
# <number>: Send packets no faster than <number> per second
:max_rate,
# ----------------------------------------------------------------
# FIREWALL/IDS EVASION AND SPOOFING
#
:f, # <val>: fragment packets
:mtu, # <val>: optional MTU for packet fragmentation
:D, # <decoy1,decoy2[,ME],...>: Cloak a scan with decoys
:S, # <IP_Address>: Spoof source address
:e, # <iface>: Use specified interface
:g, # <portnum>: Use given source port number
:source_port, # <portnum>: Use given source port number
# <url1,[url2],...>: Relay connections through HTTP/SOCKS4 proxies
:proxies,
# <hex string>: Append a custom payload to sent packets
:data,
# <string>: Append a custom ASCII string to sent packets
:data_string,
:data_length, # <num>: Append random data to sent packets
:ip_options, # <options>: Send packets with specified ip options
:ttl, # <val>: Set IP time-to-live field
# <mac address/prefix/vendor name>: Spoof your MAC address
:spoof_mac,
:badsum, # Send packets with a bogus TCP/UDP/SCTP checksum
# ----------------------------------------------------------------
# OUTPUT
#
:oN, # <file>: Output scan in normal to the given filename.
:oX, # <file>: Output scan in XML to the given filename.
:oS, # <file>: Output scan in s|<rIpt kIddi3 to the given filename.
:oG, # <file>: Output scan in Grepable format to the given filename.
:oA, # <basename>: Output in the three major formats at once
:v, # Increase verbosity level (use -vv or more for greater effect)
:d, # Increase debugging level (use -dd or more for greater effect)
# Display the reason a port is in a particular state
:reason,
:open, # Only show open (or possibly open) ports
:packet_trace, # Show all packets sent and received
:iflist, # Print host interfaces and routes (for debugging)
:append_output, # Append to rather than clobber specified output files
:resume, # <filename>: Resume an aborted scan
# <path/URL>: XSL stylesheet to transform XML output to HTML
:stylesheet,
# Reference stylesheet from Nmap.Org for more portable XML
:webxml,
# Prevent associating of XSL stylesheet w/XML output
:no_stylesheet,
# ----------------------------------------------------------------
# MISC
#
:ipv6, # 6: Enable IPv6 scanning
# "Aggressive": Enable OS detection, version detection, script
# scanning, and traceroute
:A,
# <dirname>: Specify custom Nmap data file location
:datadir,
:servicedb, # Specify custom services file
:versiondb, # Specify custom service probes file
:send_eth, # Send using raw ethernet frames
:send_ip, # Send using IP packets
:privileged, # Assume that the user is fully privileged
:unprivileged, # Assume the user lacks raw socket privileges
:V, # Print version number
]
# for {k, v} <- Map.from_struct(post), v != nil, into: %{}, do: {k, v}
@type path() :: String.t()
@type url() :: String.t()
@type strlist() :: [String.t()]
@type portlist() :: [String.t() | integer]
@typedoc """
Type that represents the input parameters of the nmap network
scanner. Nearly one-to-one with the actual command line
options/arguments.
A few custom types are used:
- `path :: String.t()`
: File-system path
- `url :: String.t()`
: URL
- `strlist :: [String.t()]`
: List of strings
- `portlist :: [String.t() | integer]`
: List of ports, given as either integers or binaries (e.g. "125",
"T:125", or "U:125")
Also, `String.t()` is used to designate human-readable strings and
`binary` is used to designate actual potential binary data.
"""
@type t :: %Nmap.Scratch{
success: function,
failure: function,
targets: list,
iL: path,
iR: integer,
exclude: strlist,
excludefile: path,
# ----------------------------------------------------------------
# HOST DISCOVERY
#
sL: boolean,
sn: boolean,
Pn: boolean,
PS: portlist,
PA: portlist,
PU: portlist,
PY: portlist,
PE: boolean,
PP: boolean,
PM: boolean,
PO: strlist,
#
# DNS
n: boolean,
R: boolean,
dns_servers: strlist,
system_dns: boolean,
traceroute: boolean,
# ----------------------------------------------------------------
# SCAN TECHNIQUES
#
# TCP
sS: boolean,
sT: boolean,
sA: boolean,
sW: boolean,
sM: boolean,
sN: boolean,
sF: boolean,
sX: boolean,
scanflags: String.t(),
#
# UDP
sU: boolean,
#
# SCTP
sY: boolean,
sZ: boolean,
#
# Other
sI: strlist,
sO: boolean,
b: String.t(),
# ----------------------------------------------------------------
# PORT SPECIFICATION AND SCAN ORDER
#
p: portlist,
exclude_ports: portlist,
F: boolean,
r: boolean,
top_ports: integer,
port_ratio: number,
# ----------------------------------------------------------------
# SERVICE/VERSION DETECTION
sV: boolean,
version_intensity: 0..9,
version_light: boolean,
version_all: boolean,
version_trace: boolean,
# ----------------------------------------------------------------
# SCRIPT SCAN
sC: boolean,
script: strlist,
script_args: String.t(),
script_args_file: path,
script_trace: boolean,
script_updatedb: boolean,
# ----------------------------------------------------------------
# OS DETECTION
#
O: boolean,
osscan_limit: boolean,
osscan_guess: boolean,
# ----------------------------------------------------------------
# TIMING AND PERFORMANCE
#
# Options which take <time> are in seconds, or append 'ms'
# (milliseconds), 's' (seconds), 'm' (minutes), or 'h' (hours) to
# the value (e.g. 30m).
#
T: 0..5,
min_hostgroup: integer,
max_hostgroup: integer,
min_parallelism: integer,
max_parallelism: integer,
min_rtt_timeout: String.t(),
max_rtt_timeout: String.t(),
initial_rtt_timeout: String.t(),
max_retries: integer,
host_timeout: String.t(),
scan_delay: String.t(),
max_scan_delay: String.t(),
min_rate: integer,
max_rate: integer,
# ----------------------------------------------------------------
# FIREWALL/IDS EVASION AND SPOOFING
#
f: 1..2,
mtu: integer, # multiple of 8
D: strlist,
S: String.t(),
e: String.t(),
g: integer,
source_port: integer,
proxies: strlist,
data: binary,
data_string: String.t(),
data_length: integer,
ip_options: binary,
ttl: integer,
spoof_mac: String.t(),
badsum: boolean,
# ----------------------------------------------------------------
# OUTPUT
#
oN: path,
oX: path,
oS: path,
oG: path,
oA: path,
v: 1..3,
d: 1..3,
reason: boolean,
open: boolean,
packet_trace: boolean,
iflist: boolean,
append_output: boolean,
resume: path,
stylesheet: path | url,
webxml: boolean,
no_stylesheet: boolean,
# ----------------------------------------------------------------
# MISC
#
ipv6: boolean,
A: boolean,
datadir: path,
servicedb: path,
versiondb: path,
send_eth: boolean,
send_ip: boolean,
privileged: boolean,
unprivileged: boolean,
V: boolean,
}
@short_booleans [
:sL, :sn, :Pn, :PE, :PP, :PM, :n, :R, :sS, :sT, :sA, :sW, :sM,
:sN, :sF, :sX, :sU, :sY, :sZ, :sO, :F, :r, :sV, :sC, :O, :A, :V,
]
@long_booleans [
:system_dns, :traceroute, :version_light,
:version_all, :version_trace, :script_trace, :script_updatedb,
:osscan_limit, :osscan_guess, :badsum, :webxml, :no_stylesheet,
:ipv6, :send_eth, :send_ip, :privileged, :unprivileged,
:reason, :open, :packet_trace, :iflist, :append_output,
]
@portlists [
:PS, :PA, :PU, :PY, :p, :exclude_ports,
]
@strlists [
:PO, :dns_servers, :script, :D, :proxies,
:exclude,
]
@maps [
:script_args,
]
@ranges %{
version_intensity: 0..9,
T: 0..5,
f: 1..2,
v: 1..3,
d: 1..3,
}
def transform_portlist(list) when is_list(list) do
with {:ok, ports} <- Utils.all_ok_transform(list, &Utils.maybe_string/1),
arg_value <- ports |> Enum.join(",") do
{:ok, arg_value}
end
end
def transform_portlist(tuple) when is_tuple(tuple) do
tuple
|> Tuple.to_list
|> transform_portlist
end
def transform_portlist(nonlist), do: {:error, {:not_a_list, nonlist}}
def transform_strlist(list) when is_list(list) do
with {:ok, strings} <- Utils.all_ok_transform(list, &Utils.maybe_string/1),
arg_value <- strings |> Enum.join(",") do
{:ok, arg_value}
end
end
def transform_strlist(tuple) when is_tuple(tuple) do
tuple
|> Tuple.to_list
|> transform_strlist
end
def transform_strlist(nonlist), do: {:error, {:not_a_list, nonlist}}
def transform_map(map) when is_map(map) do
map
|> Enum.map(fn({k, v}) -> "#{k}=#{v}" end)
|> Enum.join(",")
end
def transform_map(nonmap), do: {:error, {:not_a_map, nonmap}}
def params_set(atoms, params) do
atoms
|> Enum.filter(fn(atom) -> Map.has_key?(params, atom) end )
|> Enum.filter(fn(atom) -> Map.get(params, atom) end)
end
@spec to_args(Nmap.Scratch.t()) :: String.t()
def to_args(params) do
short_booleans = @short_booleans
|> params_set(params)
|> Enum.map(fn(arg) -> "-#{arg}" end)
|> Enum.join(" ")
long_booleans = @long_booleans
|> params_set(params)
|> Enum.map(fn(arg) -> "--#{arg}" end)
|> Enum.join(" ")
portlists = @portlists
|> params_set(params)
|> Enum.map(
fn(arg) -> {arg, transform_portlist(Map.get(params, arg))} end
)
|> Enum.group_by(fn({arg, {atom, result}}) -> atom end)
strlists = @strlists
|> params_set(params)
|> Enum.map(
fn(arg) -> {arg, transform_strlist(Map.get(params, arg))} end
)
|> Enum.group_by(fn({arg, {atom, result}}) -> atom end)
{:ok, [short_booleans, long_booleans] |> Enum.join(" ")}
end
end
| 31.420345 | 79 | 0.526817 |
f778b39515e8f7e7fb854ecad2094a63351a5868 | 390 | ex | Elixir | web/channels/nope_channel.ex | tomaszj/nope-phoenix-app | 46bbc16158115bc7db3971049cc8cf617b8ac6e1 | [
"MIT"
] | null | null | null | web/channels/nope_channel.ex | tomaszj/nope-phoenix-app | 46bbc16158115bc7db3971049cc8cf617b8ac6e1 | [
"MIT"
] | null | null | null | web/channels/nope_channel.ex | tomaszj/nope-phoenix-app | 46bbc16158115bc7db3971049cc8cf617b8ac6e1 | [
"MIT"
] | null | null | null | defmodule NopeApp.NopeChannel do
use Phoenix.Channel
def join("nope_channel:", auth_msg, socket) do
{:ok, socket}
end
def join("nope_channel:" <> _private_subtopic, _message, _socket) do
{:error, %{reason: "unauthorized"}}
end
def handle_in("new:message", msg, socket) do
broadcast! socket, "new:message", %{user: msg["username"]}
{:noreply, socket}
end
end
| 24.375 | 70 | 0.674359 |
f778e2c1a5861be9a267d5c4323352547f7b78ca | 84,671 | ex | Elixir | clients/gke_hub/lib/google_api/gke_hub/v1/api/projects.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/gke_hub/lib/google_api/gke_hub/v1/api/projects.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/gke_hub/lib/google_api/gke_hub/v1/api/projects.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.GKEHub.V1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.GKEHub.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets information about a location.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Resource name for the location.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Location{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.GKEHub.V1.Model.Location.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_get(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Location{}])
end
@doc """
Lists information about the supported locations for this service.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The resource that owns the locations collection, if applicable.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - A filter to narrow down results to a preferred subset. The filtering language accepts strings like `"displayName=tokyo"`, and is documented in more detail in [AIP-160](https://google.aip.dev/160).
* `:pageSize` (*type:* `integer()`) - The maximum number of results to return. If not set, the service selects a default.
* `:pageToken` (*type:* `String.t`) - A page token received from the `next_page_token` field in the response. Send that page token to receive the subsequent page.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.ListLocationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.GKEHub.V1.Model.ListLocationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_list(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}/locations", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.ListLocationsResponse{}])
end
@doc """
Adds a new Feature.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent (project and location) where the Feature will be created. Specified in the format `projects/*/locations/*`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:featureId` (*type:* `String.t`) - The ID of the feature to create.
* `:requestId` (*type:* `String.t`) - A 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. The server will guarantee that for at least 60 minutes after the first request. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.GKEHub.V1.Model.Feature.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_features_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_features_create(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:featureId => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/features", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Operation{}])
end
@doc """
Removes a Feature.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The Feature resource name in the format `projects/*/locations/*/features/*`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:force` (*type:* `boolean()`) - If set to true, the delete will ignore any outstanding resources for this Feature (that is, `FeatureState.has_resources` is set to true). These resources will NOT be cleaned up or modified in any way.
* `:requestId` (*type:* `String.t`) - Optional. A 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. The server will guarantee that for at least 60 minutes after the first request. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_features_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_features_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:force => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Operation{}])
end
@doc """
Gets details of a single Feature.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The Feature resource name in the format `projects/*/locations/*/features/*`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Feature{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_features_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Feature.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_features_get(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Feature{}])
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` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:"options.requestedPolicyVersion"` (*type:* `integer()`) - Optional. The maximum policy version that will be used to format the policy. Valid values are 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with any conditional role bindings must specify version 3. Policies with no conditional role bindings may specify any valid value or leave the field unset. The policy in the response might use the policy version that you specified, or it might use a lower policy version. For example, if you specify version 3, but the policy has no conditional role bindings, the response uses version 1. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_features_get_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_features_get_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:"options.requestedPolicyVersion" => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+resource}:getIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Policy{}])
end
@doc """
Lists Features in a given project and location.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent (project and location) where the Features will be listed. Specified in the format `projects/*/locations/*`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - Lists Features that match the filter expression, following the syntax outlined in https://google.aip.dev/160. Examples: - Feature with the name "servicemesh" in project "foo-proj": name = "projects/foo-proj/locations/global/features/servicemesh" - Features that have a label called `foo`: labels.foo:* - Features that have a label called `foo` whose value is `bar`: labels.foo = bar
* `:orderBy` (*type:* `String.t`) - One or more fields to compare and use to sort the output. See https://google.aip.dev/132#ordering.
* `:pageSize` (*type:* `integer()`) - When requesting a 'page' of resources, `page_size` specifies number of resources to return. If unspecified or set to 0, all resources will be returned.
* `:pageToken` (*type:* `String.t`) - Token returned by previous call to `ListFeatures` which specifies the position in the list from where to continue listing the resources.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.ListFeaturesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_features_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.ListFeaturesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_features_list(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:orderBy => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/features", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.ListFeaturesResponse{}])
end
@doc """
Updates an existing Feature.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The Feature resource name in the format `projects/*/locations/*/features/*`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:requestId` (*type:* `String.t`) - A 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. The server will guarantee that for at least 60 minutes after the first request. 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).
* `:updateMask` (*type:* `String.t`) - Mask of fields to update.
* `:body` (*type:* `GoogleApi.GKEHub.V1.Model.Feature.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_features_patch(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_features_patch(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:requestId => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Operation{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy. Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being specified. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.GKEHub.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_features_set_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_features_set_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:setIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.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. Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.GKEHub.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_features_test_iam_permissions(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_features_test_iam_permissions(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:testIamPermissions", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.TestIamPermissionsResponse{}])
end
@doc """
Creates a new Membership. **This is currently only supported for GKE clusters on Google Cloud**. To register other clusters, follow the instructions at https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent (project and location) where the Memberships will be created. Specified in the format `projects/*/locations/*`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:membershipId` (*type:* `String.t`) - Required. Client chosen ID for the membership. `membership_id` must be a valid RFC 1123 compliant DNS label: 1. At most 63 characters in length 2. It must consist of lower case alphanumeric characters or `-` 3. It must start and end with an alphanumeric character Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, with a maximum length of 63 characters.
* `:requestId` (*type:* `String.t`) - Optional. A 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. The server will guarantee that for at least 60 minutes after the first request. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.GKEHub.V1.Model.Membership.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_memberships_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_memberships_create(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:membershipId => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/memberships", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Operation{}])
end
@doc """
Removes a Membership. **This is currently only supported for GKE clusters on Google Cloud**. To unregister other clusters, follow the instructions at https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The Membership resource name in the format `projects/*/locations/*/memberships/*`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:requestId` (*type:* `String.t`) - Optional. A 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. The server will guarantee that for at least 60 minutes after the first request. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_memberships_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_memberships_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Operation{}])
end
@doc """
Generates the manifest for deployment of the GKE connect agent. **This method is used internally by Google-provided libraries.** Most clients should not need to call this method directly.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The Membership resource name the Agent will associate with, in the format `projects/*/locations/*/memberships/*`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:imagePullSecretContent` (*type:* `String.t`) - Optional. The image pull secret content for the registry, if not public.
* `:isUpgrade` (*type:* `boolean()`) - Optional. If true, generate the resources for upgrade only. Some resources generated only for installation (e.g. secrets) will be excluded.
* `:namespace` (*type:* `String.t`) - Optional. Namespace for GKE Connect agent resources. Defaults to `gke-connect`. The Connect Agent is authorized automatically when run in the default namespace. Otherwise, explicit authorization must be granted with an additional IAM binding.
* `:proxy` (*type:* `String.t`) - Optional. URI of a proxy if connectivity from the agent to gkeconnect.googleapis.com requires the use of a proxy. Format must be in the form `http(s)://{proxy_address}`, depending on the HTTP/HTTPS protocol supported by the proxy. This will direct the connect agent's outbound traffic through a HTTP(S) proxy.
* `:registry` (*type:* `String.t`) - Optional. The registry to fetch the connect agent image from. Defaults to gcr.io/gkeconnect.
* `:version` (*type:* `String.t`) - Optional. The Connect agent version to use. Defaults to the most current version.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.GenerateConnectManifestResponse{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_memberships_generate_connect_manifest(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.GenerateConnectManifestResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_memberships_generate_connect_manifest(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:imagePullSecretContent => :query,
:isUpgrade => :query,
:namespace => :query,
:proxy => :query,
:registry => :query,
:version => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}:generateConnectManifest", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.GKEHub.V1.Model.GenerateConnectManifestResponse{}]
)
end
@doc """
Gets the details of a Membership.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The Membership resource name in the format `projects/*/locations/*/memberships/*`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Membership{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_memberships_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Membership.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_memberships_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Membership{}])
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` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:"options.requestedPolicyVersion"` (*type:* `integer()`) - Optional. The maximum policy version that will be used to format the policy. Valid values are 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with any conditional role bindings must specify version 3. Policies with no conditional role bindings may specify any valid value or leave the field unset. The policy in the response might use the policy version that you specified, or it might use a lower policy version. For example, if you specify version 3, but the policy has no conditional role bindings, the response uses version 1. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_memberships_get_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_memberships_get_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:"options.requestedPolicyVersion" => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+resource}:getIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Policy{}])
end
@doc """
Lists Memberships in a given project and location.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent (project and location) where the Memberships will be listed. Specified in the format `projects/*/locations/*`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - Optional. Lists Memberships that match the filter expression, following the syntax outlined in https://google.aip.dev/160. Examples: - Name is `bar` in project `foo-proj` and location `global`: name = "projects/foo-proj/locations/global/membership/bar" - Memberships that have a label called `foo`: labels.foo:* - Memberships that have a label called `foo` whose value is `bar`: labels.foo = bar - Memberships in the CREATING state: state = CREATING
* `:orderBy` (*type:* `String.t`) - Optional. One or more fields to compare and use to sort the output. See https://google.aip.dev/132#ordering.
* `:pageSize` (*type:* `integer()`) - Optional. When requesting a 'page' of resources, `page_size` specifies number of resources to return. If unspecified or set to 0, all resources will be returned.
* `:pageToken` (*type:* `String.t`) - Optional. Token returned by previous call to `ListMemberships` which specifies the position in the list from where to continue listing the resources.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.ListMembershipsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_memberships_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.ListMembershipsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_memberships_list(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:orderBy => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/memberships", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.ListMembershipsResponse{}])
end
@doc """
Updates an existing Membership.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The Membership resource name in the format `projects/*/locations/*/memberships/*`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:requestId` (*type:* `String.t`) - Optional. A 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. The server will guarantee that for at least 60 minutes after the first request. 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).
* `:updateMask` (*type:* `String.t`) - Required. Mask of fields to update.
* `:body` (*type:* `GoogleApi.GKEHub.V1.Model.Membership.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_memberships_patch(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_memberships_patch(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:requestId => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Operation{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy. Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being specified. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.GKEHub.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_memberships_set_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_memberships_set_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:setIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.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. Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.GKEHub.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_memberships_test_iam_permissions(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_memberships_test_iam_permissions(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:testIamPermissions", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.TestIamPermissionsResponse{}])
end
@doc """
Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource to be cancelled.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.GKEHub.V1.Model.CancelOperationRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_operations_cancel(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_operations_cancel(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}:cancel", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Empty{}])
end
@doc """
Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource to be deleted.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_operations_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_operations_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Empty{}])
end
@doc """
Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_operations_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_operations_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.Operation{}])
end
@doc """
Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id.
## Parameters
* `connection` (*type:* `GoogleApi.GKEHub.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation's parent resource.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - 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.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - The standard list filter.
* `:pageSize` (*type:* `integer()`) - The standard list page size.
* `:pageToken` (*type:* `String.t`) - The standard list page token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.GKEHub.V1.Model.ListOperationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec gkehub_projects_locations_operations_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.GKEHub.V1.Model.ListOperationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def gkehub_projects_locations_operations_list(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}/operations", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.GKEHub.V1.Model.ListOperationsResponse{}])
end
end
| 49.835786 | 802 | 0.626484 |
f778ebd616ac7284c0bdfdc159ebfedfed7dd906 | 1,965 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/model/streamingbuffer.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/big_query/lib/google_api/big_query/v2/model/streamingbuffer.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/big_query/lib/google_api/big_query/v2/model/streamingbuffer.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.BigQuery.V2.Model.Streamingbuffer do
@moduledoc """
## Attributes
* `estimatedBytes` (*type:* `String.t`, *default:* `nil`) - [Output-only] A lower-bound estimate of the number of bytes currently in the streaming buffer.
* `estimatedRows` (*type:* `String.t`, *default:* `nil`) - [Output-only] A lower-bound estimate of the number of rows currently in the streaming buffer.
* `oldestEntryTime` (*type:* `String.t`, *default:* `nil`) - [Output-only] Contains the timestamp of the oldest entry in the streaming buffer, in milliseconds since the epoch, if the streaming buffer is available.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:estimatedBytes => String.t() | nil,
:estimatedRows => String.t() | nil,
:oldestEntryTime => String.t() | nil
}
field(:estimatedBytes)
field(:estimatedRows)
field(:oldestEntryTime)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.Streamingbuffer do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.Streamingbuffer.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.Streamingbuffer do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.075472 | 217 | 0.724173 |
f77916be4d93051ea0b435a8cae6651cb6fd2ae2 | 2,129 | ex | Elixir | lib/example_web/controllers/todo_controller.ex | preston-aoki/distillery-aws-example | 722dcccd5bcad2ebabaa71dd8b03f4534456099a | [
"Apache-2.0"
] | 46 | 2018-08-06T23:18:46.000Z | 2020-11-26T12:43:49.000Z | lib/example_web/controllers/todo_controller.ex | preston-aoki/distillery-aws-example | 722dcccd5bcad2ebabaa71dd8b03f4534456099a | [
"Apache-2.0"
] | 15 | 2018-08-23T08:29:48.000Z | 2020-05-18T14:05:38.000Z | lib/example_web/controllers/todo_controller.ex | preston-aoki/distillery-aws-example | 722dcccd5bcad2ebabaa71dd8b03f4534456099a | [
"Apache-2.0"
] | 84 | 2018-08-27T11:56:59.000Z | 2022-01-28T00:33:47.000Z | defmodule ExampleWeb.TodoController do
use ExampleWeb, :controller
def index(conn, _params) do
case Example.Todo.all() do
{:ok, todos} ->
render(conn, "index.html", todos: todos)
{:error, reason} ->
conn
|> put_resp_content_type("text/plain")
|> send_resp(500, reason)
end
rescue
err ->
conn
|> put_resp_content_type("text/plain")
|> send_resp(500, Exception.message(err))
end
def list(conn, _params) do
case Example.Todo.all() do
{:ok, todos} ->
ok(conn, todos)
{:error, reason} ->
error(conn, "#{inspect reason}")
end
rescue
err ->
error(conn, Exception.message(err))
end
def create(conn, params) do
with changeset = Example.Todo.changeset(%Example.Todo{}, params),
{:ok, created} <- Example.Todo.create(changeset) do
IO.inspect created, label: :created
ok(conn, created)
else
{:error, reason} ->
error(conn, "#{inspect reason}")
end
rescue
err ->
error(conn, Exception.message(err))
end
def update(conn, %{"id" => id} = params) do
case Example.Todo.update(id, params) do
{:ok, _} ->
send_resp(conn, 200, "")
{:error, reason} ->
error(conn, "#{inspect reason}")
end
rescue
err ->
error(conn, Exception.message(err))
end
def delete(conn, %{"id" => id}) do
case Example.Todo.delete(id) do
:ok ->
send_resp(conn, 200, "")
{:error, reason} ->
error(conn, "#{inspect reason}")
end
rescue
err ->
error(conn, Exception.message(err))
end
def delete_all(conn, _) do
case Example.Todo.delete_all() do
:ok ->
send_resp(conn, 200, "")
{:error, reason} ->
error(conn, "#{inspect reason}")
end
rescue
err ->
error(conn, Exception.message(err))
end
defp ok(conn, content) do
json(conn, content)
end
defp error(conn, reason) do
err = %{message: reason}
conn
|> put_resp_content_type("application/json")
|> send_resp(400, Jason.encode!(err))
end
end
| 22.892473 | 69 | 0.57163 |
f7791bfe7e090889177c731cb96cc6081ceb3163 | 2,937 | ex | Elixir | clients/app_engine/lib/google_api/app_engine/v1/model/operation_metadata_v1.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/app_engine/lib/google_api/app_engine/v1/model/operation_metadata_v1.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/app_engine/lib/google_api/app_engine/v1/model/operation_metadata_v1.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.AppEngine.V1.Model.OperationMetadataV1 do
@moduledoc """
Metadata for the given google.longrunning.Operation.
## Attributes
* `createVersionMetadata` (*type:* `GoogleApi.AppEngine.V1.Model.CreateVersionMetadataV1.t`, *default:* `nil`) -
* `endTime` (*type:* `DateTime.t`, *default:* `nil`) - Time that this operation completed.@OutputOnly
* `ephemeralMessage` (*type:* `String.t`, *default:* `nil`) - Ephemeral message that may change every time the operation is polled. @OutputOnly
* `insertTime` (*type:* `DateTime.t`, *default:* `nil`) - Time that this operation was created.@OutputOnly
* `method` (*type:* `String.t`, *default:* `nil`) - API method that initiated this operation. Example: google.appengine.v1.Versions.CreateVersion.@OutputOnly
* `target` (*type:* `String.t`, *default:* `nil`) - Name of the resource that this operation is acting on. Example: apps/myapp/services/default.@OutputOnly
* `user` (*type:* `String.t`, *default:* `nil`) - User who requested this operation.@OutputOnly
* `warning` (*type:* `list(String.t)`, *default:* `nil`) - Durable messages that persist on every operation poll. @OutputOnly
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:createVersionMetadata => GoogleApi.AppEngine.V1.Model.CreateVersionMetadataV1.t(),
:endTime => DateTime.t(),
:ephemeralMessage => String.t(),
:insertTime => DateTime.t(),
:method => String.t(),
:target => String.t(),
:user => String.t(),
:warning => list(String.t())
}
field(:createVersionMetadata, as: GoogleApi.AppEngine.V1.Model.CreateVersionMetadataV1)
field(:endTime, as: DateTime)
field(:ephemeralMessage)
field(:insertTime, as: DateTime)
field(:method)
field(:target)
field(:user)
field(:warning, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.AppEngine.V1.Model.OperationMetadataV1 do
def decode(value, options) do
GoogleApi.AppEngine.V1.Model.OperationMetadataV1.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AppEngine.V1.Model.OperationMetadataV1 do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.191176 | 161 | 0.705141 |
f7794bac163277e0c169093170f6e09d82760d18 | 10,899 | ex | Elixir | lib/cache/guild/guild.ex | SpaceEEC/crux_cache | 359194162b3c12da16e44fb29dacd02f99eb0148 | [
"MIT"
] | 2 | 2018-05-22T07:13:50.000Z | 2018-07-05T13:51:42.000Z | lib/cache/guild/guild.ex | SpaceEEC/crux_cache | 359194162b3c12da16e44fb29dacd02f99eb0148 | [
"MIT"
] | null | null | null | lib/cache/guild/guild.ex | SpaceEEC/crux_cache | 359194162b3c12da16e44fb29dacd02f99eb0148 | [
"MIT"
] | null | null | null | defmodule Crux.Cache.Guild do
@moduledoc """
Default `Crux.Structs.Channel` cache.
Unlike other caches this one splits up to different guild processes handling their data individually.
"""
@behaviour Crux.Cache
@provider Crux.Cache.Default
use GenServer
alias Crux.Cache.Guild.Registry
alias Crux.Cache.Guild.Supervisor, as: GuildSupervisor
alias Crux.Structs.{Channel, Guild, Member, Role, User, VoiceState}
@doc false
@impl true
@spec start_link(Guild.t()) :: GenServer.on_start()
def start_link(%Guild{id: guild_id} = guild) do
name = {:via, Registry, guild_id}
GenServer.start_link(__MODULE__, guild, name: name)
end
@doc """
Looks up the `t:pid/0` of a `Crux.Cache.Guild`'s `GenServer` by guild id.
"""
@spec lookup(guild_id :: Crux.Rest.snowflake()) :: {:ok, pid()} | :error
def lookup(guild_id) do
with pid when is_pid(pid) <- Registry.whereis_name(guild_id),
true <- Process.alive?(pid) do
{:ok, pid}
else
_ ->
:error
end
end
@doc """
Inserts a:
* `Crux.Structs.Guild` itself
* `Crux.Structs.Member` in it
* Chunk of `Crux.Structs.Member`
* `Crux.Structs.Role`
* `Crux.Structs.Member`'s roles
* `Crux.Structs.VoiceState`
"""
@impl true
@spec insert(data :: term()) :: term()
def insert({guild_id, {:emojis, _emojis} = data}), do: do_cast(guild_id, {:update, data})
def insert(%Member{} = data), do: do_cast(data.guild_id, data)
def insert({guild_id, {:members, _members} = data}), do: do_cast(guild_id, {:update, data})
def insert(%Role{} = data), do: do_cast(data.guild_id, data)
def insert(%Channel{} = data), do: do_cast(data.guild_id, data)
# Presence / Role update
def insert({guild_id, {%User{}, _roles} = data}), do: do_cast(guild_id, data)
def insert(%VoiceState{} = data), do: do_cast(data.guild_id, data)
def insert(%Guild{} = data), do: do_cast(data.id, data)
@doc """
Updates or inserts a:
* `Crux.Structs.Guild` itself
* `Crux.Structs.Member` in it
* Chunk of `Crux.Structs.Member`
* `Crux.Structs.Role`
* `Crux.Structs.Member`'s roles
* `Crux.Structs.VoiceState`
"""
@impl true
@spec update(data :: term()) :: term()
def update({guild_id, {:emojis, _emojis} = data}), do: do_call(guild_id, {:update, data})
def update(%Member{} = data), do: do_call(data.guild_id, data)
def update({guild_id, {:members, _members} = data}), do: do_call(guild_id, {:update, data})
def update(%Role{} = data), do: do_call(data.guild_id, data)
def update(%Channel{} = data), do: do_call(data.guild_id, data)
# Presence / Role update
def update({guild_id, {%User{}, _roles} = data}), do: do_call(guild_id, data)
def update(%VoiceState{} = data), do: do_call(data.guild_id, data)
def update(%Guild{} = data), do: do_call(data.id, data)
@doc """
Deletes a:
* `Crux.Structs.Member` (if applicable, also their `Crux.Structs.VoiceState`) from the guild
* `Crux.Structs.Role` from the guild
* `Crux.Structs.Channel` from the guild
* `Crux.Structs.Guild` itself
> This will remove all associated channels and emojis from the appropriate caches.
"""
@impl true
@spec delete(
data_or_id ::
Crux.Rest.snowflake()
| Crux.Structs.Guild.t()
| Crux.Structs.Channel.t()
| Crux.Structs.Role.t()
| Crux.Structs.Member.t()
) :: :ok
def delete(data_or_id) do
{guild_id, data} = prepare_delete(data_or_id)
case lookup(guild_id) do
{:ok, pid} ->
GenServer.call(pid, {:delete, data})
:error ->
:ok
end
end
defp prepare_delete(guild_id) when is_number(guild_id), do: {guild_id, :remove}
defp prepare_delete(%Guild{id: guild_id}) when is_number(guild_id), do: {guild_id, :remove}
defp prepare_delete(%Channel{guild_id: guild_id} = channel) when is_number(guild_id),
do: {guild_id, channel}
defp prepare_delete(%Role{guild_id: guild_id} = role) when is_number(guild_id),
do: {guild_id, role}
defp prepare_delete(%Member{guild_id: guild_id} = member) when is_number(guild_id),
do: {guild_id, member}
@doc """
Fetches a guild from the cache by id.
"""
@impl true
@spec fetch(guild_id :: Crux.Rest.snowflake()) :: {:ok, Guild.t()} | :error
def fetch(guild_id),
do: with({:ok, pid} <- lookup(guild_id), do: {:ok, GenServer.call(pid, :fetch)})
@doc """
Fetches a guild from the cache by id, raises if not found.
"""
@impl true
@spec fetch!(guild_id :: Crux.Rest.snowflake()) :: Guild.t() | no_return()
def fetch!(guild_id) do
with {:ok, guild} <- fetch(guild_id) do
guild
else
_ ->
raise "Could not find a guild with the id #{inspect(guild_id)} in the cache."
end
end
defp do_call(guild_id, {atom, inner_data} = data) when is_atom(atom) do
case lookup(guild_id) do
{:ok, pid} ->
GenServer.call(pid, data)
:error ->
if match?(%Guild{}, inner_data) do
GuildSupervisor.start_child(inner_data)
else
require Logger
Logger.warn(fn ->
"[Crux][Cache][Guild]: No process for guild #{inspect(guild_id)}." <>
"Data: #{inspect(inner_data)}"
end)
end
inner_data
end
end
defp do_call(guild_id, data), do: do_call(guild_id, {:update, data})
defp do_cast(guild_id, {atom, inner_data} = data) when is_atom(atom) do
case lookup(guild_id) do
{:ok, pid} ->
GenServer.cast(pid, data)
:error ->
if match?(%Guild{}, inner_data) do
GuildSupervisor.start_child(inner_data)
else
require Logger
Logger.warn(fn ->
"[Crux][Cache][Guild]: No process for guild #{inspect(guild_id)}." <>
" Data: #{inspect(inner_data)}"
end)
end
end
:ok
end
defp do_cast(guild_id, data), do: do_cast(guild_id, {:update, data})
@impl true
def init(%Guild{} = guild), do: {:ok, guild}
@doc false
@impl true
def handle_call(:fetch, _from, guild), do: {:reply, guild, guild}
def handle_call(
{:update, {:emojis, emojis}},
_from,
%{emojis: old_emojis} = guild
) do
new_emojis = MapSet.new(emojis, &Map.get(&1, :id))
# Delete old emojis
old_emojis
|> MapSet.difference(new_emojis)
|> Enum.each(&@provider.emoji_cache().delete/1)
state = %{guild | emojis: new_emojis}
{:reply, new_emojis, state}
end
def handle_call(
{:update, %Member{user: user_id} = member},
_from,
%{members: members} = guild
) do
members =
case members do
%{^user_id => old_member} ->
%{members | user_id => Map.merge(old_member, member)}
_ ->
Map.put(members, user_id, member)
end
state = %{guild | members: members}
{:reply, Map.get(members, user_id), state}
end
def handle_call(
{:update, {:members, members}},
from,
guild
) do
res =
Enum.reduce_while(members, {%{}, guild}, fn member, {members, guild} ->
case handle_call({:update, member}, from, guild) do
{:reply, %Member{} = member, guild} ->
members = Map.put(members, member.user, member)
{:cont, {members, guild}}
_ ->
{:halt, nil}
end
end)
case res do
{members, %Guild{} = guild} when is_map(members) ->
{:reply, members, guild}
_ ->
{:reply, :error, guild}
end
end
def handle_call(
{:update, %Role{id: role_id} = role},
_from,
%{roles: roles} = guild
) do
state = %{guild | roles: Map.put(roles, role_id, role)}
{:reply, role, state}
end
def handle_call(
{:update, %Channel{id: channel_id} = channel},
_from,
%{channels: channels} = guild
) do
guild = %{guild | channels: MapSet.put(channels, channel_id)}
state = guild
{:reply, channel, state}
end
def handle_call(
{:update, {%User{id: user_id}, roles} = data},
_from,
%{members: members} = guild
) do
state =
case members do
%{^user_id => member} ->
member = %{member | roles: roles}
members = %{members | user_id => member}
%{guild | members: members}
_ ->
guild
end
{:reply, data, state}
end
def handle_call(
{:update, %VoiceState{user_id: user_id} = voice_state},
_from,
%{voice_states: voice_states} = guild
) do
voice_states = Map.put(voice_states, user_id, voice_state)
state = %{guild | voice_states: voice_states}
{:reply, voice_state, state}
end
def handle_call({:update, %Guild{} = new_guild}, _from, guild) do
state = Map.merge(guild, new_guild)
{:reply, guild, state}
end
def handle_call({:update, other}, _from, state) do
require Logger
Logger.warn(fn ->
"[Crux][Cache][Guild]: Received an unexpected insert or update: #{inspect(other)}"
end)
{:reply, :error, state}
end
def handle_call(
{:delete, %Role{id: role_id}},
_from,
%{roles: roles} = guild
) do
state = %{guild | roles: Map.delete(roles, role_id)}
{:reply, :ok, state}
end
def handle_call(
{:delete, %Channel{id: channel_id}},
_from,
%{channels: channels} = guild
) do
state = %{guild | channels: MapSet.delete(channels, channel_id)}
@provider.channel_cache().delete(channel_id)
{:reply, :ok, state}
end
def handle_call({:delete, %Member{user: user_id}}, _from, state),
do: delete_member(user_id, state)
def handle_call({:delete, %User{id: user_id}}, _from, state), do: delete_member(user_id, state)
def handle_call(
{:delete, :remove},
_from,
%{channels: channels, emojis: emojis} = state
) do
Enum.each(channels, &@provider.channel_cache().delete/1)
Enum.each(emojis, &@provider.emoji_cache().delete/1)
{:stop, :shutdown, :ok, state}
end
def handle_call({:delete, other}, _from, state) do
require Logger
Logger.warn(fn -> "[Crux][Cache][Guild]: Received an unexpected delete: #{inspect(other)}" end)
{:reply, :ok, state}
end
@doc false
@impl true
def handle_cast(message, state) do
state =
case handle_call(message, nil, state) do
{_, _, state} ->
state
{_, state} ->
state
_ ->
state
end
{:noreply, state}
end
defp delete_member(
user_id,
%{members: members, voice_states: voice_states} = guild
) do
state = %{
guild
| members: Map.delete(members, user_id),
voice_states: Map.delete(voice_states, user_id)
}
{:reply, :ok, state}
end
end
| 26.911111 | 105 | 0.595834 |
f77970aa948582fda14ebb848d9ed7b6c94be624 | 550 | exs | Elixir | test/livebook/runtime/erl_dist/io_forward_gl_test.exs | brettcannon/livebook | d6c9ab1783efa083aea2ead81e078bb920d57ad6 | [
"Apache-2.0"
] | 1 | 2021-05-21T22:14:23.000Z | 2021-05-21T22:14:23.000Z | test/livebook/runtime/erl_dist/io_forward_gl_test.exs | brettcannon/livebook | d6c9ab1783efa083aea2ead81e078bb920d57ad6 | [
"Apache-2.0"
] | 1 | 2021-09-18T01:09:08.000Z | 2021-09-18T01:09:08.000Z | test/livebook/runtime/erl_dist/io_forward_gl_test.exs | brettcannon/livebook | d6c9ab1783efa083aea2ead81e078bb920d57ad6 | [
"Apache-2.0"
] | null | null | null | defmodule Livebook.Runtime.ErlDist.IOForwardGLTest do
use ExUnit.Case, async: true
alias Livebook.Runtime.ErlDist.IOForwardGL
test "forwards requests to sender's group leader" do
{:ok, pid} = IOForwardGL.start_link()
group_leader_io =
ExUnit.CaptureIO.capture_io(:stdio, fn ->
# This sends an IO request to the IOForwardGL process.
# Our group leader is :stdio (by default) so we expect
# it to receive the string.
IO.puts(pid, "hey")
end)
assert group_leader_io == "hey\n"
end
end
| 27.5 | 62 | 0.676364 |
f779ba50a3a03bf5a203eab5b8628db82a4e1232 | 1,196 | exs | Elixir | mix.exs | fossabot/bejo | 7d25d68ef97bd77b7d53fc9a9546261fdc99bfba | [
"Apache-2.0"
] | null | null | null | mix.exs | fossabot/bejo | 7d25d68ef97bd77b7d53fc9a9546261fdc99bfba | [
"Apache-2.0"
] | null | null | null | mix.exs | fossabot/bejo | 7d25d68ef97bd77b7d53fc9a9546261fdc99bfba | [
"Apache-2.0"
] | null | null | null | defmodule Bejo.MixProject do
use Mix.Project
@app :bejo
def project do
[
app: @app,
version: "0.1.0",
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
escript: [main_module: Bejo.Cli],
deps: deps(),
xref: [exclude: [:router]],
elixirc_paths: elixirc_paths(Mix.env()),
releases: [{@app, release()}],
preferred_cli_env: [release: :prod]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[extra_applications: [:logger], mod: {Bejo.Application, []}]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:nimble_parsec, "~> 1.1.0"},
{:plug_cowboy, "~> 2.0"},
{:bakeware, github: "spawnfest/bakeware", tag: "v0.1.0", sparse: "bakeware", runtime: false}
]
end
defp release do
[
overwrite: true,
cookie: "#{@app}_cookie",
steps: [:assemble, &Bakeware.assemble/1, &Bejo.Deploy.copy_files/1],
strip_beams: Mix.env() == :prod,
quiet: true
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(:dev), do: ["lib"]
defp elixirc_paths(_), do: ["lib"]
end
| 24.408163 | 98 | 0.58612 |
f779e0b7560cbdc208e8354713506e8b943fb394 | 781 | ex | Elixir | lib/web/controllers/registration_controller.ex | shanesveller/grapevine | fe74ade1adff88dfe4c1ab55fee3902dbb4664fe | [
"MIT"
] | null | null | null | lib/web/controllers/registration_controller.ex | shanesveller/grapevine | fe74ade1adff88dfe4c1ab55fee3902dbb4664fe | [
"MIT"
] | null | null | null | lib/web/controllers/registration_controller.ex | shanesveller/grapevine | fe74ade1adff88dfe4c1ab55fee3902dbb4664fe | [
"MIT"
] | null | null | null | defmodule Web.RegistrationController do
use Web, :controller
alias Grapevine.Accounts
alias Web.SessionController
def new(conn, _params) do
changeset = Accounts.new()
conn
|> assign(:changeset, changeset)
|> render("new.html")
end
def create(conn, %{"user" => params}) do
case Accounts.register(params) do
{:ok, user} ->
conn
|> put_flash(:info, "You have registered! Welcome!")
|> put_session(:user_token, user.token)
|> SessionController.after_sign_in_redirect()
{:error, changeset} ->
conn
|> put_flash(:error, "There was a problem registering. Please try again.")
|> put_status(422)
|> assign(:changeset, changeset)
|> render("new.html")
end
end
end
| 24.40625 | 82 | 0.618438 |
f77a3d3edec5d2c8c3ff62d71e8ed15476c9f618 | 3,643 | ex | Elixir | lib/mix/tasks/ecto.load.ex | nasrulgunawan/ecto_sql | ace2c9daf07190a3f7debfa2060cd3ddd251b6c7 | [
"Apache-2.0"
] | 384 | 2018-10-03T17:52:39.000Z | 2022-03-24T17:54:21.000Z | lib/mix/tasks/ecto.load.ex | nasrulgunawan/ecto_sql | ace2c9daf07190a3f7debfa2060cd3ddd251b6c7 | [
"Apache-2.0"
] | 357 | 2018-10-06T13:47:33.000Z | 2022-03-29T08:18:02.000Z | deps/ecto_sql/lib/mix/tasks/ecto.load.ex | adrianomota/blog | ef3b2d2ed54f038368ead8234d76c18983caa75b | [
"MIT"
] | 251 | 2018-10-04T11:06:41.000Z | 2022-03-29T07:22:53.000Z | defmodule Mix.Tasks.Ecto.Load do
use Mix.Task
import Mix.Ecto
import Mix.EctoSQL
@shortdoc "Loads previously dumped database structure"
@default_opts [force: false, quiet: false]
@aliases [
d: :dump_path,
f: :force,
q: :quiet,
r: :repo
]
@switches [
dump_path: :string,
force: :boolean,
quiet: :boolean,
repo: [:string, :keep],
no_compile: :boolean,
no_deps_check: :boolean,
skip_if_loaded: :boolean
]
@moduledoc """
Loads the current environment's database structure for the
given repository from a previously dumped structure file.
The repository must be set under `:ecto_repos` in the
current app configuration or given via the `-r` option.
This task needs some shell utility to be present on the machine
running the task.
Database | Utility needed
:--------- | :-------------
PostgreSQL | psql
MySQL | mysql
## Example
$ mix ecto.load
## Command line options
* `-r`, `--repo` - the repo to load the structure info into
* `-d`, `--dump-path` - the path of the dump file to load from
* `-q`, `--quiet` - run the command quietly
* `-f`, `--force` - do not ask for confirmation when loading data.
Configuration is asked only when `:start_permanent` is set to true
(typically in production)
* `--no-compile` - does not compile applications before loading
* `--no-deps-check` - does not check dependencies before loading
* `--skip-if-loaded` - does not load the dump file if the repo has the migrations table up
"""
@impl true
def run(args, table_exists? \\ &Ecto.Adapters.SQL.table_exists?/2) do
{opts, _} = OptionParser.parse!(args, strict: @switches, aliases: @aliases)
opts = Keyword.merge(@default_opts, opts)
Enum.each(parse_repo(args), fn repo ->
ensure_repo(repo, args)
ensure_implements(
repo.__adapter__(),
Ecto.Adapter.Structure,
"load structure for #{inspect(repo)}"
)
{migration_repo, source} = Ecto.Migration.SchemaMigration.get_repo_and_source(repo, repo.config())
{:ok, loaded?, _} = Ecto.Migrator.with_repo(migration_repo, &table_exists?.(&1, source))
for repo <- Enum.uniq([repo, migration_repo]) do
cond do
loaded? and opts[:skip_if_loaded] ->
:ok
(skip_safety_warnings?() and not loaded?) or opts[:force] or confirm_load(repo, loaded?) ->
load_structure(repo, opts)
true ->
:ok
end
end
end)
end
defp skip_safety_warnings? do
Mix.Project.config()[:start_permanent] != true
end
defp confirm_load(repo, false) do
Mix.shell().yes?(
"Are you sure you want to load a new structure for #{inspect(repo)}? Any existing data in this repo may be lost."
)
end
defp confirm_load(repo, true) do
Mix.shell().yes?("""
It looks like a structure was already loaded for #{inspect(repo)}. Any attempt to load it again might fail.
Are you sure you want to proceed?
""")
end
defp load_structure(repo, opts) do
config = Keyword.merge(repo.config(), opts)
case repo.__adapter__().structure_load(source_repo_priv(repo), config) do
{:ok, location} ->
unless opts[:quiet] do
Mix.shell().info "The structure for #{inspect repo} has been loaded from #{location}"
end
{:error, term} when is_binary(term) ->
Mix.raise "The structure for #{inspect repo} couldn't be loaded: #{term}"
{:error, term} ->
Mix.raise "The structure for #{inspect repo} couldn't be loaded: #{inspect term}"
end
end
end
| 29.860656 | 119 | 0.637661 |
f77a51a15b8b32076f4eb957c69d60e0d507e57b | 2,593 | exs | Elixir | config/staging.exs | taylonr/couchjitsu_track | 0a31c450ac734f9d8b69849cb766de0e99f178c4 | [
"MIT"
] | null | null | null | config/staging.exs | taylonr/couchjitsu_track | 0a31c450ac734f9d8b69849cb766de0e99f178c4 | [
"MIT"
] | null | null | null | config/staging.exs | taylonr/couchjitsu_track | 0a31c450ac734f9d8b69849cb766de0e99f178c4 | [
"MIT"
] | null | null | null | use Mix.Config
# For production, we configure the host to read the PORT
# from the system environment. Therefore, you will need
# to set PORT=80 before running your server.
#
# You should also configure the url host to something
# meaningful, we use this information when generating URLs.
#
# Finally, we also include the path to a manifest
# containing the digested version of static files. This
# manifest is generated by the mix phoenix.digest task
# which you typically run after static files are built.
config :couchjitsu_track, CouchjitsuTrack.Endpoint,
http: [port: {:system, "PORT"}],
url: [scheme: "https", host: "devtrack.couchjitsu.com", port: 443],
# force_ssl: [rewrite_on: [:x_forwarded_proto]],
cache_static_manifest: "priv/static/manifest.json",
secret_key_base: System.get_env("SECRET_KEY_BASE")
# Do not print debug messages in production
config :logger, level: :info
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :couchjitsu_track, CouchjitsuTrack.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :couchjitsu_track, CouchjitsuTrack.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :couchjitsu_track, CouchjitsuTrack.Endpoint, server: true
#
# You will also need to set the application root to `.` in order
# for the new static assets to be served after a hot upgrade:
#
# config :couchjitsu_track, CouchjitsuTrack.Endpoint, root: "."
# Finally import the config/prod.secret.exs
# which should be versioned separately.
#import_config "prod.secret.exs"
config :couchjitsu_track, CouchjitsuTrack.Repo,
adapter: Ecto.Adapters.Postgres,
url: System.get_env("DATABASE_URL"),
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
ssl: true | 35.040541 | 70 | 0.726186 |
f77a75b2a926479df2de3450d01e2d58568be113 | 540 | ex | Elixir | lib/twitter/management/tweet.ex | SkullDarth/upnid-challenge-twitter-api | 799f2bfa8864848423eeddc24d3a5993152eb464 | [
"MIT"
] | 2 | 2019-12-05T21:37:48.000Z | 2020-01-02T02:43:33.000Z | lib/twitter/management/tweet.ex | SkullDarth/upnid-challenge-twitter-api | 799f2bfa8864848423eeddc24d3a5993152eb464 | [
"MIT"
] | null | null | null | lib/twitter/management/tweet.ex | SkullDarth/upnid-challenge-twitter-api | 799f2bfa8864848423eeddc24d3a5993152eb464 | [
"MIT"
] | null | null | null | defmodule Twitter.Management.Tweet do
use Ecto.Schema
import Ecto.Changeset
schema "tweets" do
field :description, :string
field :view_count, :integer
field :published, :boolean
field :like, :integer
# Create foreingKey tweet table to user table
belongs_to :user, Twitter.Management.User
timestamps()
end
@doc false
def changeset(tweet, attrs) do
tweet
|> cast(attrs, [:user_id, :description, :view_count, :published, :like ])
|> validate_required([:user_id, :description])
end
end
| 22.5 | 77 | 0.690741 |
f77a7c3bb236ea20d32e2179499611cf33297faa | 1,569 | ex | Elixir | apps/faqcheck/lib/faqcheck/repo.ex | csboling/faqcheck | bc182c365d466c8dcacc6b1a5fe9186a2c912cd4 | [
"CC0-1.0"
] | null | null | null | apps/faqcheck/lib/faqcheck/repo.ex | csboling/faqcheck | bc182c365d466c8dcacc6b1a5fe9186a2c912cd4 | [
"CC0-1.0"
] | 20 | 2021-09-08T04:07:31.000Z | 2022-03-10T21:52:24.000Z | apps/faqcheck/lib/faqcheck/repo.ex | csboling/faqcheck | bc182c365d466c8dcacc6b1a5fe9186a2c912cd4 | [
"CC0-1.0"
] | null | null | null | defmodule Faqcheck.Repo do
use Ecto.Repo,
otp_app: :faqcheck,
adapter: Ecto.Adapters.Postgres,
types: Faqcheck.PostgresTypes
use Quarto,
limit: 10
import Ecto.Changeset
import PaperTrail.Serializer
def versions(changeset, options \\ []) do
changeset
|> prepare_changes(fn cs ->
case cs.action do
:insert -> attach_versions(cs, options)
:update -> update_versions(cs, options)
_ -> changeset
end
end)
end
defp attach_versions(changeset, options) do
version_id = get_sequence_id("versions") + 1
# require IEx; IEx.pry
changeset_data =
# changeset.data
changeset
|> apply_changes()
|> Map.merge(%{
id: get_sequence_id(changeset) + 1,
first_version_id: version_id,
current_version_id: version_id
})
initial_version = make_version_struct %{event: "insert"},
changeset_data, options
changeset.repo.insert(initial_version, options)
changeset |> change(%{
first_version_id: version_id,
current_version_id: version_id
})
end
defp update_versions(changeset, options) do
version_data =
changeset.data
|> Map.merge(%{
current_version_id: get_sequence_id("versions")
})
target_changeset = changeset |> Map.merge(%{data: version_data})
target_version = make_version_struct %{event: "update"},
target_changeset, options
changeset.repo.insert(target_version)
changeset |> change(%{current_version_id: version_data.current_version_id})
end
end
| 26.59322 | 79 | 0.666667 |
f77a877f8539419d0070d2a6e63bb17c2b12d6a5 | 417 | exs | Elixir | test/chatbot_web/views/error_view_test.exs | mikehelmick/meme-bot | 52a84cfb3f5ddcdddadf59b0ba3976f9e3f23800 | [
"Apache-2.0"
] | 7 | 2019-04-05T06:12:56.000Z | 2021-04-03T11:39:40.000Z | test/chatbot_web/views/error_view_test.exs | mikehelmick/meme-bot | 52a84cfb3f5ddcdddadf59b0ba3976f9e3f23800 | [
"Apache-2.0"
] | null | null | null | test/chatbot_web/views/error_view_test.exs | mikehelmick/meme-bot | 52a84cfb3f5ddcdddadf59b0ba3976f9e3f23800 | [
"Apache-2.0"
] | 3 | 2019-04-20T13:05:48.000Z | 2019-06-05T16:52:46.000Z | defmodule ChatbotWeb.ErrorViewTest do
use ChatbotWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(ChatbotWeb.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(ChatbotWeb.ErrorView, "500.html", []) == "Internal Server Error"
end
end
| 27.8 | 92 | 0.733813 |
f77a937785095a7aa075925059f3fd327d5dfecb | 4,097 | ex | Elixir | lib/elixir/lib/tuple.ex | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | 1 | 2021-05-20T13:08:37.000Z | 2021-05-20T13:08:37.000Z | lib/elixir/lib/tuple.ex | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/tuple.ex | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | null | null | null | defmodule Tuple do
@moduledoc """
Functions for working with tuples.
Tuples are ordered collections of elements; tuples can contain elements of any
type, and a tuple can contain elements of different types. Curly braces can be
used to create tuples:
iex> {}
{}
iex> {1, :two, "three"}
{1, :two, "three"}
Tuples store elements contiguously in memory; this means that accessing a
tuple element by index (which can be done through the `Kernel.elem/2`
function) is a constant-time operation:
iex> tuple = {1, :two, "three"}
iex> elem(tuple, 0)
1
iex> elem(tuple, 2)
"three"
Same goes for getting the tuple size (via `Kernel.tuple_size/1`):
iex> tuple_size({})
0
iex> tuple_size({1, 2, 3})
3
Tuples being stored contiguously in memory also means that updating a tuple
(for example replacing an element with `Kernel.put_elem/3`) will make a copy
of the whole tuple.
Tuples are not meant to be used as a "collection" type (which is also
suggested by the absence of an implementation of the `Enumerable` protocol for
tuples): they're mostly meant to be used as a fixed-size container for
multiple elements. For example, tuples are often used to have functions return
"enriched" values: a common pattern is for functions to return `{:ok, value}`
for successful cases and `{:error, reason}` for unsuccessful cases. For
example, this is exactly what `File.read/1` does: it returns `{:ok, contents}`
if reading the given file is successful, or `{:error, reason}` otherwise
(e.g., `{:error, :enoent}` if the file doesn't exist).
This module provides functions to work with tuples; some more functions to
work with tuples can be found in `Kernel` (`Kernel.tuple_size/1`,
`Kernel.elem/2`, `Kernel.put_elem/3`, and others).
"""
@doc """
Creates a new tuple.
Creates a tuple of `size` containing the
given `data` at every position.
Inlined by the compiler.
## Examples
iex> Tuple.duplicate(:hello, 3)
{:hello, :hello, :hello}
"""
@spec duplicate(term, non_neg_integer) :: tuple
def duplicate(data, size) do
:erlang.make_tuple(size, data)
end
@doc """
Inserts an element into a tuple.
Inserts `value` into `tuple` at the given `index`.
Raises an `ArgumentError` if `index` is negative or greater than the
length of `tuple`. Index is zero-based.
Inlined by the compiler.
## Examples
iex> tuple = {:bar, :baz}
iex> Tuple.insert_at(tuple, 0, :foo)
{:foo, :bar, :baz}
iex> Tuple.insert_at(tuple, 2, :bong)
{:bar, :baz, :bong}
"""
@spec insert_at(tuple, non_neg_integer, term) :: tuple
def insert_at(tuple, index, value) do
:erlang.insert_element(index + 1, tuple, value)
end
@doc """
Inserts an element at the end of a tuple.
Returns a new tuple with the element appended at the end, and contains
the elements in `tuple` followed by `value` as the last element.
Inlined by the compiler.
## Examples
iex> tuple = {:foo, :bar}
iex> Tuple.append(tuple, :baz)
{:foo, :bar, :baz}
"""
@spec append(tuple, term) :: tuple
def append(tuple, value) do
:erlang.append_element(tuple, value)
end
@doc """
Removes an element from a tuple.
Deletes the element at the given `index` from `tuple`.
Raises an `ArgumentError` if `index` is negative or greater than
or equal to the length of `tuple`. Index is zero-based.
Inlined by the compiler.
## Examples
iex> tuple = {:foo, :bar, :baz}
iex> Tuple.delete_at(tuple, 0)
{:bar, :baz}
"""
@spec delete_at(tuple, non_neg_integer) :: tuple
def delete_at(tuple, index) do
:erlang.delete_element(index + 1, tuple)
end
@doc """
Converts a tuple to a list.
Returns a new list with all the tuple elements.
Inlined by the compiler.
## Examples
iex> tuple = {:foo, :bar, :baz}
iex> Tuple.to_list(tuple)
[:foo, :bar, :baz]
"""
@spec to_list(tuple) :: list
def to_list(tuple) do
:erlang.tuple_to_list(tuple)
end
end
| 26.953947 | 80 | 0.660971 |
f77a9a464b496af826cc03b6da9d06d7219ac227 | 2,708 | ex | Elixir | clients/dataflow/lib/google_api/dataflow/v1b3/model/step.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/dataflow/lib/google_api/dataflow/v1b3/model/step.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/dataflow/lib/google_api/dataflow/v1b3/model/step.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.Dataflow.V1b3.Model.Step do
@moduledoc """
Defines a particular step within a Cloud Dataflow job. A job consists of multiple steps, each of which performs some specific operation as part of the overall job. Data is typically passed from one step to another as part of the job. Here's an example of a sequence of steps which together implement a Map-Reduce job: * Read a collection of data from some source, parsing the collection's elements. * Validate the elements. * Apply a user-defined function to map each element to some value and extract an element-specific key value. * Group elements with the same key into a single element with that key, transforming a multiply-keyed collection into a uniquely-keyed collection. * Write the elements out to some data sink. Note that the Cloud Dataflow service may be used to run many different types of jobs, not just Map-Reduce.
## Attributes
- kind (String): The kind of step in the Cloud Dataflow job. Defaults to: `null`.
- name (String): The name that identifies the step. This must be unique for each step with respect to all other steps in the Cloud Dataflow job. Defaults to: `null`.
- properties (Object): Named properties associated with the step. Each kind of predefined step has its own required set of properties. Must be provided on Create. Only retrieved with JOB_VIEW_ALL. Defaults to: `null`.
"""
defstruct [
:"kind",
:"name",
:"properties"
]
end
defimpl Poison.Decoder, for: GoogleApi.Dataflow.V1b3.Model.Step do
import GoogleApi.Dataflow.V1b3.Deserializer
def decode(value, options) do
value
|> deserialize(:"properties", :struct, GoogleApi.Dataflow.V1b3.Model.Object, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Dataflow.V1b3.Model.Step do
def encode(value, options) do
GoogleApi.Dataflow.V1b3.Deserializer.serialize_non_nil(value, options)
end
end
| 52.076923 | 875 | 0.751108 |
f77ae850177bc7396b73773d173f8392fb62e98e | 430 | ex | Elixir | lib/farmbot/asset/tool.ex | defcon201/farmbot_os | acc22702afbb13be461c9d80591604958117ff75 | [
"MIT"
] | null | null | null | lib/farmbot/asset/tool.ex | defcon201/farmbot_os | acc22702afbb13be461c9d80591604958117ff75 | [
"MIT"
] | null | null | null | lib/farmbot/asset/tool.ex | defcon201/farmbot_os | acc22702afbb13be461c9d80591604958117ff75 | [
"MIT"
] | 1 | 2020-12-16T16:39:32.000Z | 2020-12-16T16:39:32.000Z | defmodule Farmbot.Asset.Tool do
@moduledoc "A Tool is an item that lives in a ToolSlot"
use Ecto.Schema
import Ecto.Changeset
schema "tools" do
field(:name, :string)
end
use Farmbot.Repo.Syncable
@required_fields [:id, :name]
def changeset(farm_event, params \\ %{}) do
farm_event
|> cast(params, @required_fields)
|> validate_required(@required_fields)
|> unique_constraint(:id)
end
end
| 20.47619 | 57 | 0.690698 |
f77b0ea8c19deb6d3a3458ad12d5029ef98ba783 | 4,007 | ex | Elixir | lib/petal_components/tabs.ex | doughsay/petal_components | 75e30ab078a205cb642ebea7c5d0ca8357f41464 | [
"MIT"
] | null | null | null | lib/petal_components/tabs.ex | doughsay/petal_components | 75e30ab078a205cb642ebea7c5d0ca8357f41464 | [
"MIT"
] | null | null | null | lib/petal_components/tabs.ex | doughsay/petal_components | 75e30ab078a205cb642ebea7c5d0ca8357f41464 | [
"MIT"
] | null | null | null | defmodule PetalComponents.Tabs do
use Phoenix.Component
import PetalComponents.Link
# prop class, :string
# prop underline, :boolean, default: false
# slot default
def tabs(assigns) do
assigns =
assigns
|> assign_new(:underline, fn -> false end)
|> assign_new(:class, fn -> "" end)
~H"""
<div class={Enum.join([
"flex gap-x-8 gap-y-2",
(if @underline, do: "border-b border-gray-200 dark:border-gray-600", else: ""),
@class
], " ")}>
<%= render_slot(@inner_block) %>
</div>
"""
end
# prop class, :string
# prop label, :string
# prop link_type, :string, options: ["a", "live_patch", "live_redirect"]
# prop number, :integer
# prop underline, :boolean, default: false
# prop is_active, :boolean, default: false
# slot default
def tab(assigns) do
assigns =
assigns
|> assign_new(:label, fn -> nil end)
|> assign_new(:class, fn -> "" end)
|> assign_new(:inner_block, fn -> nil end)
|> assign_new(:number, fn -> nil end)
|> assign_new(:link_type, fn -> "a" end)
|> assign_new(:is_active, fn -> false end)
|> assign_new(:underline, fn -> false end)
|> assign_new(:extra_assigns, fn ->
assigns_to_attributes(assigns, [
:class,
:inner_block,
:number,
:link_type,
:is_active,
:underline,
:label
])
end)
~H"""
<.link link_type={@link_type} label={@label} to={@to} class={get_tab_class(@is_active, @underline)} {@extra_assigns}>
<%= if @number do %>
<.render_label_or_slot {assigns} />
<span class={get_tab_number_class(@is_active, @underline)}>
<%= @number %>
</span>
<% else %>
<.render_label_or_slot {assigns} />
<% end %>
</.link>
"""
end
def render_label_or_slot(assigns) do
~H"""
<%= if @inner_block do %>
<%= render_slot(@inner_block) %>
<% else %>
<%= @label %>
<% end %>
"""
end
# Pill CSS
defp get_tab_class(is_active, false) do
base_classes = "whitespace-nowrap px-3 py-2 flex font-medium items-center text-sm rounded-md"
active_classes =
if is_active,
do: "bg-primary-100 dark:bg-gray-800 text-primary-600",
else:
"text-gray-500 hover:text-gray-600 dark:hover:text-gray-400 dark:hover:bg-gray-800 hover:bg-gray-100"
Enum.join([base_classes, active_classes], " ")
end
# Underline CSS
defp get_tab_class(is_active, underline) do
base_classes = "whitespace-nowrap flex items-center py-3 px-3 border-b-2 font-medium text-sm"
active_classes =
if is_active,
do: "border-primary-500 text-primary-600",
else:
"border-transparent text-gray-500 dark:hover:text-gray-400 dark:hover:border-gray-400 hover:text-gray-600"
underline_classes =
if is_active && underline,
do: "",
else: "hover:border-gray-300"
Enum.join([base_classes, active_classes, underline_classes], " ")
end
# Underline
defp get_tab_number_class(is_active, true = underline) do
base_classes = "whitespace-nowrap ml-2 py-0.5 px-2 rounded-full text-xs font-normal"
active_classes =
if is_active,
do: "bg-primary-100 text-primary-600",
else: "bg-gray-100 text-gray-500"
underline_classes =
if underline && is_active,
do: "bg-primary-100 dark:bg-primary-600 text-primary-600 dark:text-white",
else: "bg-gray-100 dark:bg-gray-600 dark:text-white text-gray-500"
Enum.join([base_classes, active_classes, underline_classes], " ")
end
# Pill
defp get_tab_number_class(is_active, false) do
base_classes = "whitespace-nowrap ml-2 py-0.5 px-2 rounded-full text-xs font-normal"
active_classes =
if is_active,
do: "bg-primary-600 text-white",
else: "bg-gray-500 dark:bg-gray-600 text-white"
Enum.join([base_classes, active_classes], " ")
end
end
| 28.827338 | 121 | 0.608435 |
f77b675aeb4f4e9cb9b962636728689a62eb9240 | 3,861 | ex | Elixir | lib/json_web_token/jwt.ex | PatrickSachs/json_web_token_ex | 0c87b1e8ec2e383cb79b4450191c164c9a1a677c | [
"MIT"
] | null | null | null | lib/json_web_token/jwt.ex | PatrickSachs/json_web_token_ex | 0c87b1e8ec2e383cb79b4450191c164c9a1a677c | [
"MIT"
] | null | null | null | lib/json_web_token/jwt.ex | PatrickSachs/json_web_token_ex | 0c87b1e8ec2e383cb79b4450191c164c9a1a677c | [
"MIT"
] | null | null | null | defmodule JsonWebToken.Jwt do
@moduledoc """
Encode claims for transmission as a JSON object that is used as the payload of a JSON Web
Signature (JWS) structure, enabling the claims to be integrity protected with a Message
Authentication Code (MAC), to be later verified
see http://tools.ietf.org/html/rfc7519
"""
alias JsonWebToken.Jws
@algorithm_default "HS256"
@header_default %{typ: "JWT"}
# JOSE header types from: https://tools.ietf.org/html/rfc7515
@header_jose_keys [:alg, :jku, :jwk, :kid, :x5u, :x5c, :x5t, :"x5t#S256", :typ, :cty, :crit]
@doc """
Return a JSON Web Token (JWT), a string representing a set of claims as a JSON object that is
encoded in a JWS
## Example
iex> claims = %{iss: "joe", exp: 1300819380, "http://example.com/is_root": true}
...> key = "gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9C"
...> JsonWebToken.Jwt.sign(claims, %{key: key})
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiZXhwIjoxMzAwODE5MzgwfQ.Ktfu3EdLz0SpuTIMpMoRZMtZsCATWJHeDEBGrsZE6LI"
see http://tools.ietf.org/html/rfc7519#section-7.1
"""
def sign(claims, options) do
header = config_header(options)
payload = claims_to_json(claims)
jws_message(header, payload, options[:key], header[:alg])
end
@doc """
Given an options map, return a map of header options
## Example
iex> JsonWebToken.Jwt.config_header(alg: "RS256", key: "key")
%{typ: "JWT", alg: "RS256"}
Filters out unsupported claims options and ignores any encryption keys
"""
def config_header(options) when is_map(options) do
{jose_registered_headers, _other_headers} = Map.split(options, @header_jose_keys)
@header_default
|> Map.merge(jose_registered_headers)
|> Map.merge(%{alg: algorithm(options)})
end
def config_header(options) when is_list(options) do
options |> Map.new |> config_header
end
defp algorithm(options) do
alg = options[:alg] || @algorithm_default
alg_or_default(alg, alg == "")
end
defp alg_or_default(_, true), do: @algorithm_default
defp alg_or_default(alg, _), do: alg
defp claims_to_json(nil), do: raise "Claims nil"
defp claims_to_json(""), do: raise "Claims blank"
defp claims_to_json(claims) do
claims
|> JsonWebToken.Util.json_library.encode
|> claims_json
end
defp claims_json({:ok, json}), do: json
defp claims_json({:error, _}), do: raise "Failed to encode claims as JSON"
defp jws_message(header, payload, _, "none"), do: Jws.unsecured_message(header, payload)
defp jws_message(header, payload, key, _), do: Jws.sign(header, payload, key)
@doc """
Return a tuple {ok: claims (map)} if the signature is verified, or {:error, "invalid"} otherwise
## Example
iex> jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiZXhwIjoxMzAwODE5MzgwfQ.Ktfu3EdLz0SpuTIMpMoRZMtZsCATWJHeDEBGrsZE6LI"
...> key = "gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9C"
...> JsonWebToken.Jwt.verify(jwt, %{key: key})
{:ok, %{iss: "joe", exp: 1300819380, "http://example.com/is_root": true}}
see http://tools.ietf.org/html/rfc7519#section-7.2
"""
def verify(jwt, options) do
payload(Jws.verify jwt, algorithm(options), options[:key])
end
defp payload({:error, "invalid"}), do: {:error, "invalid"}
defp payload({:ok, jws}), do: {:ok, jws_payload(jws)}
defp jws_payload(jws) do
[_, encoded_payload, _] = String.split(jws, ".")
payload_to_map(encoded_payload)
end
defp payload_to_map(encoded_payload) do
encoded_payload
|> Base.url_decode64!(padding: false)
|> JsonWebToken.Util.json_library.decode(keys: :atoms)
|> claims_map
end
defp claims_map({:ok, map}), do: map
defp claims_map({:error, _}), do: raise "Failed to decode claims from JSON"
end
| 35.1 | 186 | 0.70474 |
f77b7508ef0534319e01ecb81e34a2c8e3744ef9 | 282 | ex | Elixir | lib/twitter_wall_web/cors_router.ex | IvanRublev/TwitterWall | ca3f900dfaf64c5d59ac903f697da87e9fcc9914 | [
"MIT"
] | 1 | 2020-01-27T17:43:01.000Z | 2020-01-27T17:43:01.000Z | lib/twitter_wall_web/cors_router.ex | IvanRublev/TwitterWall | ca3f900dfaf64c5d59ac903f697da87e9fcc9914 | [
"MIT"
] | 6 | 2021-03-09T22:08:16.000Z | 2021-06-30T23:48:20.000Z | lib/twitter_wall_web/cors_router.ex | IvanRublev/TwitterWall | ca3f900dfaf64c5d59ac903f697da87e9fcc9914 | [
"MIT"
] | null | null | null | defmodule TwitterWallWeb.CORSRouter do
@moduledoc """
Module configuring Corsica plugin to enable /api endpoint to be CORS compatible.
"""
use Corsica.Router,
origins: "*",
allow_credentials: true,
allow_headers: :all,
max_age: 600
resource("/api/*")
end
| 21.692308 | 82 | 0.691489 |
f77b88acbe0e4bafc55ddf4f69ba848fb7ae1f76 | 452 | exs | Elixir | priv/repo/migrations/20181217222526_create_book_locations.exs | allen-garvey/booklist-phoenix | b3c87713d742b64684c222cd3e5869dc9fbd2bd2 | [
"MIT"
] | 4 | 2019-10-04T16:11:15.000Z | 2021-08-18T21:00:13.000Z | apps/booklist/priv/repo/migrations/20181217222526_create_book_locations.exs | allen-garvey/phoenix-umbrella | 1d444bbd62a5e7b5f51d317ce2be71ee994125d5 | [
"MIT"
] | 5 | 2020-03-16T23:52:25.000Z | 2021-09-03T16:52:17.000Z | priv/repo/migrations/20181217222526_create_book_locations.exs | allen-garvey/booklist-phoenix | b3c87713d742b64684c222cd3e5869dc9fbd2bd2 | [
"MIT"
] | null | null | null | defmodule Booklist.Repo.Migrations.CreateBookLocations do
use Ecto.Migration
def change do
create table(:book_locations) do
add :call_number, :text
add :book_id, references(:books, on_delete: :nothing), null: false
add :location_id, references(:locations, on_delete: :nothing), null: false
timestamps()
end
create index(:book_locations, [:book_id])
create index(:book_locations, [:location_id])
end
end
| 26.588235 | 80 | 0.705752 |
f77b8c26e6e9f6095eee453c9b708536fb890cf1 | 1,999 | exs | Elixir | test/test_helper.exs | lgandersen/jocker_dist | b5e676f8d9e60bbc8bc7a82ccd1e05389f2cd5b5 | [
"BSD-2-Clause"
] | null | null | null | test/test_helper.exs | lgandersen/jocker_dist | b5e676f8d9e60bbc8bc7a82ccd1e05389f2cd5b5 | [
"BSD-2-Clause"
] | null | null | null | test/test_helper.exs | lgandersen/jocker_dist | b5e676f8d9e60bbc8bc7a82ccd1e05389f2cd5b5 | [
"BSD-2-Clause"
] | null | null | null | alias Jocker.Engine.{ZFS, Config, Container, Layer}
ExUnit.start()
ExUnit.configure(
seed: 0,
trace: true,
max_failures: 1
)
defmodule TestHelper do
def now() do
:timer.sleep(10)
DateTime.to_iso8601(DateTime.utc_now())
end
def collect_container_output(id) do
output = collect_container_output_(id, [])
output |> Enum.reverse() |> Enum.join("")
end
defp collect_container_output_(id, output) do
receive do
{:container, ^id, {:shutdown, :jail_stopped}} ->
output
{:container, ^id, msg} ->
collect_container_output_(id, [msg | output])
unknown ->
IO.puts(
"\nUnknown message received while collecting container output: #{inspect(unknown)}"
)
end
end
def clear_zroot() do
{:ok, _pid} = Config.start_link([])
zroot = Config.get("zroot")
Agent.stop(Config)
ZFS.destroy_force(zroot)
ZFS.create(zroot)
end
def devfs_mounted(%Container{layer_id: layer_id}) do
%Layer{mountpoint: mountpoint} = Jocker.Engine.MetaData.get_layer(layer_id)
devfs_path = Path.join(mountpoint, "dev")
case System.cmd("sh", ["-c", "mount | grep \"devfs on #{devfs_path}\""]) do
{"", 1} -> false
{_output, 0} -> true
end
end
def build_and_return_image(context, dockerfile, tag) do
quiet = true
{:ok, pid} = Jocker.Engine.Image.build(context, dockerfile, tag, quiet)
{img, _messages} = receive_imagebuilder_results(pid, [])
img
end
def receive_imagebuilder_results(pid, msg_list) do
receive do
{:image_builder, ^pid, {:image_finished, img}} ->
{img, Enum.reverse(msg_list)}
{:image_builder, ^pid, msg} ->
receive_imagebuilder_results(pid, [msg | msg_list])
other ->
IO.puts("\nError! Received unkown message #{inspect(other)}")
end
end
def create_tmp_dockerfile(content, dockerfile, context \\ "./") do
:ok = File.write(Path.join(context, dockerfile), content, [:write])
end
end
| 25.303797 | 93 | 0.641821 |
f77b9032028e393ead55433591a873cc081e0bda | 219 | exs | Elixir | test/controllers/page_controller_test.exs | keichan34/phoenix_exfile_test_app | 63de22ab04a61ef7f13a53f2b34d3c752a1def7a | [
"MIT"
] | 1 | 2016-04-19T11:56:32.000Z | 2016-04-19T11:56:32.000Z | test/controllers/page_controller_test.exs | keichan34/phoenix_exfile_test_app | 63de22ab04a61ef7f13a53f2b34d3c752a1def7a | [
"MIT"
] | 1 | 2016-08-05T07:52:34.000Z | 2016-09-02T03:45:03.000Z | test/controllers/page_controller_test.exs | keichan34/phoenix_exfile_test_app | 63de22ab04a61ef7f13a53f2b34d3c752a1def7a | [
"MIT"
] | null | null | null | defmodule PhoenixExfileTestApp.PageControllerTest do
use PhoenixExfileTestApp.ConnCase
test "GET /", %{conn: conn} do
conn = get conn, "/"
assert html_response(conn, 200) =~ "Welcome to Phoenix!"
end
end
| 24.333333 | 60 | 0.712329 |
f77ba16bb1e1f254d0e8417c51c996b17aad6b37 | 313 | ex | Elixir | web/channels/user_channel.ex | drdean/jelly | 44ca6d90e0c7ce62ccd458795f54dac4d10e8cfc | [
"MIT"
] | null | null | null | web/channels/user_channel.ex | drdean/jelly | 44ca6d90e0c7ce62ccd458795f54dac4d10e8cfc | [
"MIT"
] | null | null | null | web/channels/user_channel.ex | drdean/jelly | 44ca6d90e0c7ce62ccd458795f54dac4d10e8cfc | [
"MIT"
] | null | null | null | defmodule JellyBoard.UserChannel do
use JellyBoard.Web, :channel
def join("users:" <> user_id, _params, socket) do
current_user = socket.assigns.current_user
if String.to_integer(user_id) == current_user.id do
{:ok, socket}
else
{:error, %{reason: "Invalid user"}}
end
end
end
| 22.357143 | 55 | 0.670927 |
f77bca2b94c333f21c4fec71c46b7b299fe93ae4 | 177 | ex | Elixir | lib/teiserver_web/views/account/relationships_view.ex | icexuick/teiserver | 22f2e255e7e21f977e6b262acf439803626a506c | [
"MIT"
] | 6 | 2021-02-08T10:42:53.000Z | 2021-04-25T12:12:03.000Z | lib/teiserver_web/views/account/relationships_view.ex | icexuick/teiserver | 22f2e255e7e21f977e6b262acf439803626a506c | [
"MIT"
] | 14 | 2021-08-01T02:36:14.000Z | 2022-01-30T21:15:03.000Z | lib/teiserver_web/views/account/relationships_view.ex | icexuick/teiserver | 22f2e255e7e21f977e6b262acf439803626a506c | [
"MIT"
] | 7 | 2021-05-13T12:55:28.000Z | 2022-01-14T06:39:06.000Z | defmodule TeiserverWeb.Account.RelationshipsView do
use TeiserverWeb, :view
def colours(), do: StylingHelper.colours(:info)
def icon(), do: StylingHelper.icon(:info)
end
| 25.285714 | 51 | 0.762712 |
f77bda0d565f544eecc0ebc76b39ed90835a9282 | 13,051 | exs | Elixir | test/integration/controlling_test.exs | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"Apache-2.0"
] | null | null | null | test/integration/controlling_test.exs | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"Apache-2.0"
] | null | null | null | test/integration/controlling_test.exs | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"Apache-2.0"
] | null | null | null | defmodule Oban.Integration.ControllingTest do
use Oban.Case
alias Oban.{Connection, Registry}
@moduletag :integration
describe "start_queue/2" do
test "validating options" do
name = start_supervised_oban!(queues: [])
assert_invalid_opts(name, :start_queue, [])
assert_invalid_opts(name, :start_queue, queue: nil)
assert_invalid_opts(name, :start_queue, limit: -1)
assert_invalid_opts(name, :start_queue, local_only: -1)
assert_invalid_opts(name, :start_queue, wat: -1)
end
test "starting individual queues dynamically" do
name = start_supervised_oban!(queues: [alpha: 9])
wait_for_notifier(name)
assert :ok = Oban.start_queue(name, queue: :gamma, limit: 5, refresh_interval: 10)
assert :ok = Oban.start_queue(name, queue: :delta, limit: 6, paused: true)
assert :ok = Oban.start_queue(name, queue: :alpha, limit: 5)
with_backoff(fn ->
assert %{limit: 9} = Oban.check_queue(name, queue: :alpha)
assert %{limit: 5, refresh_interval: 10} = Oban.check_queue(name, queue: :gamma)
assert %{limit: 6, paused: true} = Oban.check_queue(name, queue: :delta)
end)
end
test "starting individual queues only on the local node" do
name1 = start_supervised_oban!(queues: [])
name2 = start_supervised_oban!(queues: [])
wait_for_notifier(name1)
wait_for_notifier(name2)
assert :ok = Oban.start_queue(name1, queue: :alpha, limit: 1, local_only: true)
with_backoff(fn ->
assert supervised_queue?(name1, "alpha")
refute supervised_queue?(name2, "alpha")
end)
end
end
describe "stop_queue/2" do
test "validating options" do
name = start_supervised_oban!(queues: [])
assert_invalid_opts(name, :start_queue, queue: nil)
assert_invalid_opts(name, :start_queue, local_only: -1)
end
test "stopping individual queues" do
name = start_supervised_oban!(queues: [alpha: 5, delta: 5, gamma: 5])
wait_for_notifier(name)
assert supervised_queue?(name, "delta")
assert supervised_queue?(name, "gamma")
assert :ok = Oban.stop_queue(name, queue: :delta)
assert :ok = Oban.stop_queue(name, queue: :gamma)
with_backoff(fn ->
assert supervised_queue?(name, "alpha")
refute supervised_queue?(name, "delta")
refute supervised_queue?(name, "gamma")
end)
end
test "stopping individual queues only on the local node" do
name1 = start_supervised_oban!(queues: [alpha: 1])
name2 = start_supervised_oban!(queues: [alpha: 1])
wait_for_notifier(name2)
assert :ok = Oban.stop_queue(name2, queue: :alpha, local_only: true)
with_backoff(fn ->
assert supervised_queue?(name1, "alpha")
refute supervised_queue?(name2, "alpha")
end)
end
test "trying to stop queues that don't exist" do
name = start_supervised_oban!(queues: [])
assert :ok = Oban.pause_queue(name, queue: :alpha)
assert_raise ArgumentError, "queue :alpha does not exist locally", fn ->
Oban.pause_queue(name, queue: :alpha, local_only: true)
end
end
end
describe "pause_queue/2 and resume_queue/2" do
test "validating options" do
name = start_supervised_oban!(queues: [])
assert_invalid_opts(name, :pause_queue, queue: nil)
assert_invalid_opts(name, :pause_queue, local_only: -1)
assert_invalid_opts(name, :resume_queue, queue: nil)
assert_invalid_opts(name, :resume_queue, local_only: -1)
end
test "pausing and resuming individual queues" do
name = start_supervised_oban!(queues: [alpha: 5])
wait_for_notifier(name)
assert :ok = Oban.pause_queue(name, queue: :alpha)
with_backoff(fn ->
assert %{paused: true} = Oban.check_queue(name, queue: :alpha)
end)
assert :ok = Oban.resume_queue(name, queue: :alpha)
with_backoff(fn ->
assert %{paused: false} = Oban.check_queue(name, queue: :alpha)
end)
end
test "pausing queues only on the local node" do
name1 = start_supervised_oban!(queues: [alpha: 1])
name2 = start_supervised_oban!(queues: [alpha: 1])
wait_for_notifier(name1)
wait_for_notifier(name2)
assert :ok = Oban.pause_queue(name2, queue: :alpha, local_only: true)
with_backoff(fn ->
assert %{paused: false} = Oban.check_queue(name1, queue: :alpha)
assert %{paused: true} = Oban.check_queue(name2, queue: :alpha)
end)
end
test "resuming queues only on the local node" do
name1 = start_supervised_oban!(queues: [alpha: 1])
name2 = start_supervised_oban!(queues: [alpha: 1])
wait_for_notifier(name1)
wait_for_notifier(name2)
assert :ok = Oban.pause_queue(name1, queue: :alpha)
with_backoff(fn ->
assert %{paused: true} = Oban.check_queue(name1, queue: :alpha)
assert %{paused: true} = Oban.check_queue(name2, queue: :alpha)
end)
assert :ok = Oban.resume_queue(name1, queue: :alpha, local_only: true)
with_backoff(fn ->
assert %{paused: false} = Oban.check_queue(name1, queue: :alpha)
assert %{paused: true} = Oban.check_queue(name2, queue: :alpha)
end)
end
test "trying to resume queues that don't exist" do
name = start_supervised_oban!(queues: [])
assert :ok = Oban.resume_queue(name, queue: :alpha)
assert_raise ArgumentError, "queue :alpha does not exist locally", fn ->
Oban.resume_queue(name, queue: :alpha, local_only: true)
end
end
test "trying to pause queues that don't exist" do
name = start_supervised_oban!(queues: [])
assert :ok = Oban.pause_queue(name, queue: :alpha)
assert_raise ArgumentError, "queue :alpha does not exist locally", fn ->
Oban.pause_queue(name, queue: :alpha, local_only: true)
end
end
end
describe "scale_queue/2" do
test "validating options" do
name = start_supervised_oban!(queues: [])
assert_invalid_opts(name, :scale_queue, [])
assert_invalid_opts(name, :scale_queue, queue: nil)
assert_invalid_opts(name, :scale_queue, limit: -1)
assert_invalid_opts(name, :scale_queue, local_only: -1)
end
test "scaling queues up" do
name = start_supervised_oban!(queues: [alpha: 1])
wait_for_notifier(name)
assert :ok = Oban.scale_queue(name, queue: :alpha, limit: 5)
with_backoff(fn ->
assert %{limit: 5} = Oban.check_queue(name, queue: :alpha)
end)
end
test "forwarding scaling options for alternative engines" do
# This is an abuse of `scale` because other engines support other options and passing
# `paused` verifies that other options are supported.
name = start_supervised_oban!(queues: [alpha: 1])
wait_for_notifier(name)
assert :ok = Oban.scale_queue(name, queue: :alpha, limit: 5, paused: true)
with_backoff(fn ->
assert %{limit: 5, paused: true} = Oban.check_queue(name, queue: :alpha)
end)
end
test "scaling queues only on the local node" do
name1 = start_supervised_oban!(queues: [alpha: 2])
name2 = start_supervised_oban!(queues: [alpha: 2])
wait_for_notifier(name1)
wait_for_notifier(name2)
assert :ok = Oban.scale_queue(name2, queue: :alpha, limit: 1, local_only: true)
with_backoff(fn ->
assert %{limit: 2} = Oban.check_queue(name1, queue: :alpha)
assert %{limit: 1} = Oban.check_queue(name2, queue: :alpha)
end)
end
test "trying to scale queues that don't exist" do
name = start_supervised_oban!(queues: [])
assert :ok = Oban.scale_queue(name, queue: :alpha, limit: 1)
assert_raise ArgumentError, "queue :alpha does not exist locally", fn ->
Oban.scale_queue(name, queue: :alpha, limit: 1, local_only: true)
end
end
end
test "killing an executing job by its id" do
name = start_supervised_oban!(queues: [alpha: 5])
job = insert!(ref: 1, sleep: 100)
assert_receive {:started, 1}
Oban.cancel_job(name, job.id)
refute_receive {:ok, 1}, 200
assert %Job{state: "cancelled", cancelled_at: %_{}} = Repo.reload(job)
assert %{running: []} = Oban.check_queue(name, queue: :alpha)
end
test "cancelling jobs that may or may not be executing" do
name = start_supervised_oban!(queues: [alpha: 5])
job_a = insert!(%{ref: 1}, schedule_in: 10)
job_b = insert!(%{ref: 2}, schedule_in: 10, state: "retryable")
job_c = insert!(%{ref: 3}, state: "completed")
job_d = insert!(%{ref: 4, sleep: 200})
assert_receive {:started, 4}
assert :ok = Oban.cancel_job(name, job_a.id)
assert :ok = Oban.cancel_job(name, job_b.id)
assert :ok = Oban.cancel_job(name, job_c.id)
assert :ok = Oban.cancel_job(name, job_d.id)
refute_receive {:ok, 4}, 250
assert %Job{state: "cancelled", cancelled_at: %_{}} = Repo.reload(job_a)
assert %Job{state: "cancelled", cancelled_at: %_{}} = Repo.reload(job_b)
assert %Job{state: "completed", cancelled_at: nil} = Repo.reload(job_c)
assert %Job{state: "cancelled", cancelled_at: %_{}} = Repo.reload(job_d)
end
test "cancelling all jobs that may or may not be executing" do
name = start_supervised_oban!(queues: [alpha: 5])
job_a = insert!(%{ref: 1}, schedule_in: 10)
job_b = insert!(%{ref: 2}, schedule_in: 10, state: "retryable")
job_c = insert!(%{ref: 3}, state: "completed")
job_d = insert!(%{ref: 4, sleep: 200})
assert_receive {:started, 4}
assert {:ok, 3} = Oban.cancel_all_jobs(name, Job)
refute_receive {:ok, 4}, 250
assert %Job{state: "cancelled", cancelled_at: %_{}} = Repo.reload(job_a)
assert %Job{state: "cancelled", cancelled_at: %_{}} = Repo.reload(job_b)
assert %Job{state: "completed", cancelled_at: nil} = Repo.reload(job_c)
assert %Job{state: "cancelled", cancelled_at: %_{}} = Repo.reload(job_d)
end
test "dispatching jobs from a queue via database trigger" do
name = start_supervised_oban!(queues: [alpha: 5])
wait_for_notifier(name)
insert!(ref: 1, action: "OK")
assert_receive {:ok, 1}
end
test "retrying jobs from multiple states" do
name = start_supervised_oban!(queues: [])
job_a = insert!(%{ref: 1}, state: "discarded", max_attempts: 20, attempt: 20)
job_b = insert!(%{ref: 2}, state: "completed", max_attempts: 20)
job_c = insert!(%{ref: 3}, state: "available", max_attempts: 20)
job_d = insert!(%{ref: 4}, state: "retryable", max_attempts: 20)
job_e = insert!(%{ref: 5}, state: "executing", max_attempts: 1, attempt: 1)
job_f = insert!(%{ref: 6}, state: "scheduled", max_attempts: 1, attempt: 1)
assert :ok = Oban.retry_job(name, job_a.id)
assert :ok = Oban.retry_job(name, job_b.id)
assert :ok = Oban.retry_job(name, job_c.id)
assert :ok = Oban.retry_job(name, job_d.id)
assert :ok = Oban.retry_job(name, job_e.id)
assert :ok = Oban.retry_job(name, job_f.id)
assert %Job{state: "available", max_attempts: 21} = Repo.reload(job_a)
assert %Job{state: "available", max_attempts: 20} = Repo.reload(job_b)
assert %Job{state: "available", max_attempts: 20} = Repo.reload(job_c)
assert %Job{state: "available", max_attempts: 20} = Repo.reload(job_d)
assert %Job{state: "executing", max_attempts: 1} = Repo.reload(job_e)
assert %Job{state: "scheduled", max_attempts: 1} = Repo.reload(job_f)
end
test "retrying all retryable jobs" do
name = start_supervised_oban!(queues: [])
job_a = insert!(%{ref: 1}, state: "discarded", max_attempts: 20, attempt: 20)
job_b = insert!(%{ref: 2}, state: "completed", max_attempts: 20)
job_c = insert!(%{ref: 3}, state: "available", max_attempts: 20)
job_d = insert!(%{ref: 4}, state: "retryable", max_attempts: 20)
job_e = insert!(%{ref: 5}, state: "executing", max_attempts: 1, attempt: 1)
job_f = insert!(%{ref: 6}, state: "scheduled", max_attempts: 1, attempt: 1)
assert {:ok, 3} = Oban.retry_all_jobs(name, Job)
assert %Job{state: "available", max_attempts: 21} = Repo.reload(job_a)
assert %Job{state: "available", max_attempts: 20} = Repo.reload(job_b)
assert %Job{state: "available", max_attempts: 20} = Repo.reload(job_c)
assert %Job{state: "available", max_attempts: 20} = Repo.reload(job_d)
assert %Job{state: "executing", max_attempts: 1} = Repo.reload(job_e)
assert %Job{state: "scheduled", max_attempts: 1} = Repo.reload(job_f)
end
defp supervised_queue?(oban_name, queue_name) do
oban_name
|> Registry.whereis({:producer, queue_name})
|> is_pid()
end
defp wait_for_notifier(oban_name) do
with_backoff(fn ->
assert oban_name
|> Registry.via(Connection)
|> Connection.connected?()
end)
end
defp assert_invalid_opts(oban_name, function_name, opts) do
assert_raise ArgumentError, fn -> apply(oban_name, function_name, [opts]) end
end
end
| 34.075718 | 91 | 0.655275 |
f77be324857fc32aaac45d5799f977a9fffcec48 | 305 | ex | Elixir | test/support/dummy_rpc.ex | alisinabh/exw3 | 672820414b98f24a7d6027cbf292f0cc30b282fe | [
"Apache-2.0"
] | null | null | null | test/support/dummy_rpc.ex | alisinabh/exw3 | 672820414b98f24a7d6027cbf292f0cc30b282fe | [
"Apache-2.0"
] | null | null | null | test/support/dummy_rpc.ex | alisinabh/exw3 | 672820414b98f24a7d6027cbf292f0cc30b282fe | [
"Apache-2.0"
] | null | null | null | defmodule ExW3.DummyRPC do
@moduledoc "Dummy Json RPC Mock module for testing calls"
def eth_call(_data), do: mock()
def eth_send(_data), do: mock()
def mock_response(resp), do: Application.put_env(:exw3, :dummy_rpc_resp, resp)
def mock, do: Application.fetch_env!(:exw3, :dummy_rpc_resp)
end
| 30.5 | 80 | 0.737705 |
f77be8577aee43c7a5289bdfc0bf587f1f57e953 | 923 | ex | Elixir | apps/core/lib/core/contract_requests/capitation/contract_requests.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 8 | 2019-06-14T11:34:49.000Z | 2021-08-05T19:14:24.000Z | apps/core/lib/core/contract_requests/capitation/contract_requests.ex | edenlabllc/ehealth.api.public | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 1 | 2019-07-08T15:20:22.000Z | 2019-07-08T15:20:22.000Z | apps/core/lib/core/contract_requests/capitation/contract_requests.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 6 | 2018-05-11T13:59:32.000Z | 2022-01-19T20:15:22.000Z | defmodule Core.CapitationContractRequests do
@moduledoc false
alias Core.ContractRequests.CapitationContractRequest
use Core.ContractRequests, schema: CapitationContractRequest
import Ecto.Query
@read_repo Application.get_env(:core, :repos)[:read_repo]
def get_contract_requests_to_deactivate(legal_entity_id) do
CapitationContractRequest
|> select([cr], %{schema: "contract_request", entity: cr})
|> where([cr], cr.type == ^CapitationContractRequest.type())
|> where([cr], cr.contractor_legal_entity_id == ^legal_entity_id)
|> where(
[cr],
cr.status in ^[
CapitationContractRequest.status(:new),
CapitationContractRequest.status(:in_process),
CapitationContractRequest.status(:approved),
CapitationContractRequest.status(:pending_nhs_sign),
CapitationContractRequest.status(:nhs_signed)
]
)
|> @read_repo.all()
end
end
| 32.964286 | 69 | 0.72156 |
f77bf1a8ee4e9063a85b26d2fe60d1fc0ca89736 | 735 | exs | Elixir | apps/performance/mix.exs | calebcarroll1/smartcitiesdata | b0f03496f6c592c82ba14aebf6c5996311cf3cd0 | [
"Apache-2.0"
] | 18 | 2020-11-13T15:38:24.000Z | 2021-05-26T00:40:08.000Z | apps/performance/mix.exs | calebcarroll1/smartcitiesdata | b0f03496f6c592c82ba14aebf6c5996311cf3cd0 | [
"Apache-2.0"
] | 365 | 2020-09-21T12:31:40.000Z | 2021-09-25T14:54:21.000Z | apps/performance/mix.exs | calebcarroll1/smartcitiesdata | b0f03496f6c592c82ba14aebf6c5996311cf3cd0 | [
"Apache-2.0"
] | 3 | 2020-10-06T16:17:49.000Z | 2021-09-03T17:11:41.000Z | defmodule Performance.MixProject do
use Mix.Project
def project do
[
app: :performance,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
def application do
[
extra_applications: [:logger]
]
end
defp deps do
[
{:combinatorics, "~> 0.1.0", only: [:integration]},
{:smart_city_test, "~> 0.8", only: [:test, :integration]},
{:benchee, "~> 1.0", only: [:integration]},
{:exprof, "~> 0.2.3", only: [:integration]},
{:retry, "~> 0.13"}
]
end
end
| 21.617647 | 64 | 0.514286 |
f77c073629f8ddc9d728d28999727468e6fcc51d | 11,373 | exs | Elixir | test/drunkard/recipes_test.exs | shaddysignal/drunkard | 8365c75cd98414dfe38481956e90dda26a177bdd | [
"Unlicense"
] | 2 | 2020-07-05T21:27:33.000Z | 2021-12-12T22:56:00.000Z | test/drunkard/recipes_test.exs | shaddysignal/drunkard | 8365c75cd98414dfe38481956e90dda26a177bdd | [
"Unlicense"
] | 1 | 2021-05-11T08:14:48.000Z | 2021-05-11T08:14:48.000Z | test/drunkard/recipes_test.exs | shaddysignal/drunkard | 8365c75cd98414dfe38481956e90dda26a177bdd | [
"Unlicense"
] | 1 | 2020-07-05T21:27:46.000Z | 2020-07-05T21:27:46.000Z | defmodule Drunkard.RecipesTest do
use Drunkard.DataCase
alias Drunkard.Recipes
describe "ingredients" do
alias Drunkard.Recipes.Ingredient
@valid_attrs %{name: "some name"}
@update_attrs %{name: "some updated name"}
@invalid_attrs %{name: nil}
def ingredient_fixture(attrs \\ %{}) do
{:ok, ingredient} =
attrs
|> Enum.into(@valid_attrs)
|> Recipes.create_ingredient()
ingredient
end
test "list_ingredients/0 returns all ingredients" do
ingredient = ingredient_fixture()
assert Recipes.list_ingredients() == [ingredient]
end
test "get_ingredient!/1 returns the ingredient with given id" do
ingredient = ingredient_fixture()
assert Recipes.get_ingredient!(ingredient.id) == ingredient
end
test "create_ingredient/1 with valid data creates a ingredient" do
assert {:ok, %Ingredient{} = ingredient} = Recipes.create_ingredient(@valid_attrs)
assert ingredient.name == "some name"
end
test "create_ingredient/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Recipes.create_ingredient(@invalid_attrs)
end
test "update_ingredient/2 with valid data updates the ingredient" do
ingredient = ingredient_fixture()
assert {:ok, %Ingredient{} = ingredient} = Recipes.update_ingredient(ingredient, @update_attrs)
assert ingredient.name == "some updated name"
end
test "update_ingredient/2 with invalid data returns error changeset" do
ingredient = ingredient_fixture()
assert {:error, %Ecto.Changeset{}} = Recipes.update_ingredient(ingredient, @invalid_attrs)
assert ingredient == Recipes.get_ingredient!(ingredient.id)
end
test "delete_ingredient/1 deletes the ingredient" do
ingredient = ingredient_fixture()
assert {:ok, %Ingredient{}} = Recipes.delete_ingredient(ingredient)
assert_raise Ecto.NoResultsError, fn -> Recipes.get_ingredient!(ingredient.id) end
end
test "change_ingredient/1 returns a ingredient changeset" do
ingredient = ingredient_fixture()
assert %Ecto.Changeset{} = Recipes.change_ingredient(ingredient)
end
end
describe "glasses" do
alias Drunkard.Recipes.Glass
@valid_attrs %{desc: "some desc", image_path: "some image_path", name: "some name"}
@update_attrs %{desc: "some updated desc", image_path: "some updated image_path", name: "some updated name"}
@invalid_attrs %{desc: nil, image_path: nil, name: nil}
def glass_fixture(attrs \\ %{}) do
{:ok, glass} =
attrs
|> Enum.into(@valid_attrs)
|> Recipes.create_glass()
glass
end
test "list_glasses/0 returns all glasses" do
glass = glass_fixture()
assert Recipes.list_glasses() == [glass]
end
test "get_glass!/1 returns the glass with given id" do
glass = glass_fixture()
assert Recipes.get_glass!(glass.id) == glass
end
test "create_glass/1 with valid data creates a glass" do
assert {:ok, %Glass{} = glass} = Recipes.create_glass(@valid_attrs)
assert glass.desc == "some desc"
assert glass.image_path == "some image_path"
assert glass.name == "some name"
end
test "create_glass/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Recipes.create_glass(@invalid_attrs)
end
test "update_glass/2 with valid data updates the glass" do
glass = glass_fixture()
assert {:ok, %Glass{} = glass} = Recipes.update_glass(glass, @update_attrs)
assert glass.desc == "some updated desc"
assert glass.image_path == "some updated image_path"
assert glass.name == "some updated name"
end
test "update_glass/2 with invalid data returns error changeset" do
glass = glass_fixture()
assert {:error, %Ecto.Changeset{}} = Recipes.update_glass(glass, @invalid_attrs)
assert glass == Recipes.get_glass!(glass.id)
end
test "delete_glass/1 deletes the glass" do
glass = glass_fixture()
assert {:ok, %Glass{}} = Recipes.delete_glass(glass)
assert_raise Ecto.NoResultsError, fn -> Recipes.get_glass!(glass.id) end
end
test "change_glass/1 returns a glass changeset" do
glass = glass_fixture()
assert %Ecto.Changeset{} = Recipes.change_glass(glass)
end
end
describe "recipes" do
alias Drunkard.Recipes.Recipe
@valid_attrs %{glass: "some glass", name: "some name"}
@update_attrs %{glass: "some updated glass", name: "some updated name"}
@invalid_attrs %{glass: nil, name: nil}
def recipe_fixture(attrs \\ %{}) do
{:ok, recipe} =
attrs
|> Enum.into(@valid_attrs)
|> Recipes.create_recipe()
recipe
end
test "list_recipes/0 returns all recipes" do
recipe = recipe_fixture()
assert Recipes.list_recipes() == [recipe]
end
test "get_recipe!/1 returns the recipe with given id" do
recipe = recipe_fixture()
assert Recipes.get_recipe!(recipe.id) == recipe
end
test "create_recipe/1 with valid data creates a recipe" do
assert {:ok, %Recipe{} = recipe} = Recipes.create_recipe(@valid_attrs)
assert recipe.glass == "some glass"
assert recipe.name == "some name"
end
test "create_recipe/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Recipes.create_recipe(@invalid_attrs)
end
test "update_recipe/2 with valid data updates the recipe" do
recipe = recipe_fixture()
assert {:ok, %Recipe{} = recipe} = Recipes.update_recipe(recipe, @update_attrs)
assert recipe.glass == "some updated glass"
assert recipe.name == "some updated name"
end
test "update_recipe/2 with invalid data returns error changeset" do
recipe = recipe_fixture()
assert {:error, %Ecto.Changeset{}} = Recipes.update_recipe(recipe, @invalid_attrs)
assert recipe == Recipes.get_recipe!(recipe.id)
end
test "delete_recipe/1 deletes the recipe" do
recipe = recipe_fixture()
assert {:ok, %Recipe{}} = Recipes.delete_recipe(recipe)
assert_raise Ecto.NoResultsError, fn -> Recipes.get_recipe!(recipe.id) end
end
test "change_recipe/1 returns a recipe changeset" do
recipe = recipe_fixture()
assert %Ecto.Changeset{} = Recipes.change_recipe(recipe)
end
end
describe "recipe_ingredients" do
alias Drunkard.Recipes.RecipeIngredient
@valid_attrs %{amount: "120.5", ingredient: "some ingredient", is_garnish: true, is_optional: true, unit: "some unit"}
@update_attrs %{amount: "456.7", ingredient: "some updated ingredient", is_garnish: false, is_optional: false, unit: "some updated unit"}
@invalid_attrs %{amount: nil, ingredient: nil, is_garnish: nil, is_optional: nil, unit: nil}
def recipe_ingredient_fixture(attrs \\ %{}) do
{:ok, recipe_ingredient} =
attrs
|> Enum.into(@valid_attrs)
|> Recipes.create_recipe_ingredient()
recipe_ingredient
end
test "list_recipe_ingredients/0 returns all recipe_ingredients" do
recipe_ingredient = recipe_ingredient_fixture()
assert Recipes.list_recipe_ingredients() == [recipe_ingredient]
end
test "get_recipe_ingredient!/1 returns the recipe_ingredient with given id" do
recipe_ingredient = recipe_ingredient_fixture()
assert Recipes.get_recipe_ingredient!(recipe_ingredient.id) == recipe_ingredient
end
test "create_recipe_ingredient/1 with valid data creates a recipe_ingredient" do
assert {:ok, %RecipeIngredient{} = recipe_ingredient} = Recipes.create_recipe_ingredient(@valid_attrs)
assert recipe_ingredient.amount == Decimal.new("120.5")
assert recipe_ingredient.ingredient == "some ingredient"
assert recipe_ingredient.is_garnish == true
assert recipe_ingredient.is_optional == true
assert recipe_ingredient.unit == "some unit"
end
test "create_recipe_ingredient/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Recipes.create_recipe_ingredient(@invalid_attrs)
end
test "update_recipe_ingredient/2 with valid data updates the recipe_ingredient" do
recipe_ingredient = recipe_ingredient_fixture()
assert {:ok, %RecipeIngredient{} = recipe_ingredient} = Recipes.update_recipe_ingredient(recipe_ingredient, @update_attrs)
assert recipe_ingredient.amount == Decimal.new("456.7")
assert recipe_ingredient.ingredient == "some updated ingredient"
assert recipe_ingredient.is_garnish == false
assert recipe_ingredient.is_optional == false
assert recipe_ingredient.unit == "some updated unit"
end
test "update_recipe_ingredient/2 with invalid data returns error changeset" do
recipe_ingredient = recipe_ingredient_fixture()
assert {:error, %Ecto.Changeset{}} = Recipes.update_recipe_ingredient(recipe_ingredient, @invalid_attrs)
assert recipe_ingredient == Recipes.get_recipe_ingredient!(recipe_ingredient.id)
end
test "delete_recipe_ingredient/1 deletes the recipe_ingredient" do
recipe_ingredient = recipe_ingredient_fixture()
assert {:ok, %RecipeIngredient{}} = Recipes.delete_recipe_ingredient(recipe_ingredient)
assert_raise Ecto.NoResultsError, fn -> Recipes.get_recipe_ingredient!(recipe_ingredient.id) end
end
test "change_recipe_ingredient/1 returns a recipe_ingredient changeset" do
recipe_ingredient = recipe_ingredient_fixture()
assert %Ecto.Changeset{} = Recipes.change_recipe_ingredient(recipe_ingredient)
end
end
describe "tags" do
alias Drunkard.Recipes.Tag
@valid_attrs %{name: "some name"}
@update_attrs %{name: "some updated name"}
@invalid_attrs %{name: nil}
def tag_fixture(attrs \\ %{}) do
{:ok, tag} =
attrs
|> Enum.into(@valid_attrs)
|> Recipes.create_tag()
tag
end
test "list_tags/0 returns all tags" do
tag = tag_fixture()
assert Recipes.list_tags() == [tag]
end
test "get_tag!/1 returns the tag with given id" do
tag = tag_fixture()
assert Recipes.get_tag!(tag.id) == tag
end
test "create_tag/1 with valid data creates a tag" do
assert {:ok, %Tag{} = tag} = Recipes.create_tag(@valid_attrs)
assert tag.name == "some name"
end
test "create_tag/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Recipes.create_tag(@invalid_attrs)
end
test "update_tag/2 with valid data updates the tag" do
tag = tag_fixture()
assert {:ok, %Tag{} = tag} = Recipes.update_tag(tag, @update_attrs)
assert tag.name == "some updated name"
end
test "update_tag/2 with invalid data returns error changeset" do
tag = tag_fixture()
assert {:error, %Ecto.Changeset{}} = Recipes.update_tag(tag, @invalid_attrs)
assert tag == Recipes.get_tag!(tag.id)
end
test "delete_tag/1 deletes the tag" do
tag = tag_fixture()
assert {:ok, %Tag{}} = Recipes.delete_tag(tag)
assert_raise Ecto.NoResultsError, fn -> Recipes.get_tag!(tag.id) end
end
test "change_tag/1 returns a tag changeset" do
tag = tag_fixture()
assert %Ecto.Changeset{} = Recipes.change_tag(tag)
end
end
end
| 36.104762 | 141 | 0.688649 |
f77c08e4aed6de4dfaa9104a3baff72fc270b541 | 1,878 | ex | Elixir | clients/service_directory/lib/google_api/service_directory/v1beta1/model/namespace.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/service_directory/lib/google_api/service_directory/v1beta1/model/namespace.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/service_directory/lib/google_api/service_directory/v1beta1/model/namespace.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.ServiceDirectory.V1beta1.Model.Namespace do
@moduledoc """
A container for services. Namespaces allow administrators to group services together and define permissions for a collection of services.
## Attributes
* `labels` (*type:* `map()`, *default:* `nil`) - Optional. Resource labels associated with this Namespace. No more than 64 user labels can be associated with a given resource. Label keys and values can be no longer than 63 characters.
* `name` (*type:* `String.t`, *default:* `nil`) - Immutable. The resource name for the namespace in the format 'projects/*/locations/*/namespaces/*'.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:labels => map(),
:name => String.t()
}
field(:labels, type: :map)
field(:name)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceDirectory.V1beta1.Model.Namespace do
def decode(value, options) do
GoogleApi.ServiceDirectory.V1beta1.Model.Namespace.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceDirectory.V1beta1.Model.Namespace do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.56 | 238 | 0.735889 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.