hexsha stringlengths 40 40 | size int64 2 991k | ext stringclasses 2 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 208 | max_stars_repo_name stringlengths 6 106 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses list | max_stars_count int64 1 33.5k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 208 | max_issues_repo_name stringlengths 6 106 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses list | max_issues_count int64 1 16.3k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 208 | max_forks_repo_name stringlengths 6 106 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses list | max_forks_count int64 1 6.91k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 991k | avg_line_length float64 1 36k | max_line_length int64 1 977k | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ff96cdb63d1d6e69f7c3f68819c7a0f187131cee | 3,431 | ex | Elixir | farmbot_core/lib/farmbot_core/asset_workers/regimen_instance_worker.ex | EarthEngineering/facetop_os | c82a7f1e8098d3a03dddbd2f2cb46cda7b88b6fb | [
"MIT"
] | 1 | 2021-04-22T10:18:50.000Z | 2021-04-22T10:18:50.000Z | farmbot_core/lib/farmbot_core/asset_workers/regimen_instance_worker.ex | bluewaysw/farmbot_os | 3449864bc5c17a688ec2fe75e4a5cf247da57806 | [
"MIT"
] | null | null | null | farmbot_core/lib/farmbot_core/asset_workers/regimen_instance_worker.ex | bluewaysw/farmbot_os | 3449864bc5c17a688ec2fe75e4a5cf247da57806 | [
"MIT"
] | null | null | null | defimpl FarmbotCore.AssetWorker, for: FarmbotCore.Asset.RegimenInstance do
@moduledoc """
An instance of a running Regimen. Asset.Regimen is the blueprint by which a
Regimen "instance" is created.
"""
use GenServer
require Logger
require FarmbotCore.Logger
alias FarmbotCeleryScript.AST
alias FarmbotCore.Asset
alias FarmbotCore.Asset.{RegimenInstance, FarmEvent, Sequence, Regimen}
@impl FarmbotCore.AssetWorker
def preload(%RegimenInstance{}), do: [:farm_event, :regimen, :executions]
@impl FarmbotCore.AssetWorker
def tracks_changes?(%RegimenInstance{}), do: false
@impl FarmbotCore.AssetWorker
def start_link(regimen_instance, args) do
GenServer.start_link(__MODULE__, [regimen_instance, args])
end
@impl GenServer
def init([regimen_instance, _args]) do
with %Regimen{} <- regimen_instance.regimen,
%FarmEvent{} <- regimen_instance.farm_event do
send self(), :schedule
{:ok, %{regimen_instance: regimen_instance}}
else
_ -> {:stop, "Regimen instance not preloaded."}
end
end
@impl GenServer
def handle_info(:schedule, state) do
regimen_instance = state.regimen_instance
# load the sequence and calculate the scheduled_at time
Enum.map(regimen_instance.regimen.regimen_items, fn(%{time_offset: offset, sequence_id: sequence_id}) ->
scheduled_at = DateTime.add(regimen_instance.epoch, offset, :millisecond)
sequence = Asset.get_sequence(sequence_id) || raise("sequence #{sequence_id} is not synced")
%{scheduled_at: scheduled_at, sequence: sequence}
end)
# get rid of any item that has already been scheduled/executed
|> Enum.reject(fn(%{scheduled_at: scheduled_at}) ->
Asset.get_regimen_instance_execution(regimen_instance, scheduled_at)
end)
|> Enum.each(fn(%{scheduled_at: at, sequence: sequence}) ->
schedule_sequence(regimen_instance, sequence, at)
end)
{:noreply, state}
end
def handle_info({FarmbotCeleryScript, {:scheduled_execution, scheduled_at, executed_at, result}}, state) do
status = case result do
:ok -> "ok"
{:error, reason} ->
FarmbotCore.Logger.error(2, "Regimen scheduled at #{scheduled_at} failed to execute: #{reason}")
reason
end
_ = Asset.add_execution_to_regimen_instance!(state.regimen_instance, %{
scheduled_at: scheduled_at,
executed_at: executed_at,
status: status
})
{:noreply, state}
end
# TODO(RickCarlino) This function essentially copy/pastes a regimen body into
# the `locals` of a sequence, which works but is not-so-clean. Refactor later
# when we have a better idea of the problem.
@doc false
def schedule_sequence(%RegimenInstance{} = regimen_instance, %Sequence{} = sequence, at) do
# FarmEvent is the furthest outside of the scope
farm_event_params = AST.decode(regimen_instance.farm_event.body)
# Regimen is the second scope
regimen_params = AST.decode(regimen_instance.regimen.body)
# there may be many sequence scopes from here downward
celery_ast = AST.decode(sequence)
celery_args =
celery_ast.args
|> Map.put(:sequence_name, sequence.name)
|> Map.put(:locals, %{celery_ast.args.locals | body: celery_ast.args.locals.body ++ regimen_params ++ farm_event_params})
celery_ast = %{celery_ast | args: celery_args}
FarmbotCeleryScript.schedule(celery_ast, at, sequence)
end
end
| 37.703297 | 127 | 0.717575 |
ff96ecfb8a04332a840f0651bfbfb9be7952571b | 1,281 | ex | Elixir | lib/issues/table_formatter.ex | LucasPaszinski/github_issues | 9da6c91d37b54727037d39d063d50ff0a18c4f8d | [
"MIT"
] | null | null | null | lib/issues/table_formatter.ex | LucasPaszinski/github_issues | 9da6c91d37b54727037d39d063d50ff0a18c4f8d | [
"MIT"
] | null | null | null | lib/issues/table_formatter.ex | LucasPaszinski/github_issues | 9da6c91d37b54727037d39d063d50ff0a18c4f8d | [
"MIT"
] | null | null | null | defmodule Issues.TableFormater do
def print_table_for_columns(rows, headers) do
with data_by_columns = split_into_columns(rows, headers),
columns_widths = widths_of(data_by_columns),
format = format_for(columns_widths) do
puts_one_line_in_columns(headers, format)
IO.puts(separator(columns_widths))
puts_in_columns(data_by_columns, format)
end
end
def split_into_columns(rows,headers) do
for header <- headers do
for row <- rows do
printable(row[header])
end
end
end
def printable(str) when is_binary(str), do: str
def printable(str), do: to_string(str)
def widths_of(columns) do
for column <- columns, do: column |> Enum.map(&String.length(&1)) |> Enum.max
end
def format_for(columns_widths) do
Enum.map_join(columns_widths, " | ", fn width -> "~#{width}s" end) <> "~n"
end
def separator(columns_widths) do
Enum.map_join(columns_widths, "-+-", fn width -> List.duplicate("-", width) end)
end
def puts_in_columns(data_by_columns, format) do
data_by_columns
|> List.zip
|> Enum.map(&Tuple.to_list(&1))
|> Enum.each(&puts_one_line_in_columns(&1,format))
end
def puts_one_line_in_columns(fields, format) do
:io.format(format,fields)
end
end
| 27.847826 | 84 | 0.685402 |
ff96f29a78317159395c9c33de4d788bafed3c46 | 104 | exs | Elixir | test/srp/identity_verifier_test.exs | thiamsantos/spr | c1db6c338543ecb9ec4d855d05a125a490c1606b | [
"Apache-2.0"
] | 15 | 2018-11-03T18:39:21.000Z | 2022-02-21T22:17:50.000Z | test/srp/identity_verifier_test.exs | thiamsantos/spr | c1db6c338543ecb9ec4d855d05a125a490c1606b | [
"Apache-2.0"
] | 7 | 2018-10-27T00:13:08.000Z | 2019-05-14T16:43:36.000Z | test/srp/identity_verifier_test.exs | thiamsantos/spr | c1db6c338543ecb9ec4d855d05a125a490c1606b | [
"Apache-2.0"
] | 3 | 2019-05-14T16:24:04.000Z | 2019-07-06T21:47:40.000Z | defmodule SRP.IdentityVerifierTest do
use ExUnit.Case, async: true
doctest SRP.IdentityVerifier
end
| 20.8 | 37 | 0.817308 |
ff96f5b78593f0b30e975ca5b38f4e044ccc108c | 6,328 | ex | Elixir | apps/mishka_html/lib/mishka_html_web/live/components/admin/user/list_component.ex | mishka-group/mishka-cms | 4e34ed646f807687f4ae809e862acb6f2c5aacef | [
"Apache-2.0"
] | 35 | 2021-06-26T09:05:50.000Z | 2022-03-30T15:41:22.000Z | apps/mishka_html/lib/mishka_html_web/live/components/admin/user/list_component.ex | mishka-group/mishka-cms | 4e34ed646f807687f4ae809e862acb6f2c5aacef | [
"Apache-2.0"
] | 101 | 2021-01-01T09:54:07.000Z | 2022-03-28T10:02:24.000Z | apps/mishka_html/lib/mishka_html_web/live/components/admin/user/list_component.ex | mishka-group/mishka-cms | 4e34ed646f807687f4ae809e862acb6f2c5aacef | [
"Apache-2.0"
] | 8 | 2021-01-17T17:08:07.000Z | 2022-03-11T16:12:06.000Z | defmodule MishkaHtmlWeb.Admin.User.ListComponent do
use MishkaHtmlWeb, :live_component
def render(assigns) do
~L"""
<div class="col bw admin-blog-post-list">
<div class="table-responsive">
<table class="table vazir">
<thead>
<tr>
<th scope="col" id="div-image"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "تصویر") %></th>
<th scope="col" id="div-title"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "نام کامل") %></th>
<th scope="col" id="div-category"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "نام کاربری") %></th>
<th scope="col" id="div-status"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "ایمیل") %></th>
<th scope="col" id="div-priority"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "وضعیت") %></th>
<th scope="col" id="div-update"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "ثبت") %></th>
<th scope="col" id="div-opration"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "عملیات") %></th>
</tr>
</thead>
<tbody>
<%= for {item, color} <- Enum.zip(@users, Stream.cycle(["wlist", "glist"])) do %>
<tr class="blog-list vazir <%= if color == "glist", do: "odd-list-of-blog-posts" %>">
<td class="align-middle col-sm-2 admin-list-img">
<img src="/images/no-user-image.jpg" alt="<%= item.full_name %>">
</td>
<td class="align-middle text-center" id="<%= "title-#{item.id}" %>">
<%= live_redirect "#{MishkaHtml.full_name_sanitize(item.full_name)}",
to: Routes.live_path(@socket, MishkaHtmlWeb.AdminUserLive, id: item.id)
%>
</td>
<td class="align-middle text-center">
<%= live_redirect "#{MishkaHtml.username_sanitize(item.username)}",
to: Routes.live_path(@socket, MishkaHtmlWeb.AdminUserLive, id: item.id)
%>
</td>
<td class="align-middle text-center">
<%= MishkaHtml.email_sanitize(item.email) %>
</td>
<td class="align-middle text-center">
<%
field = Enum.find(MishkaHtmlWeb.AdminUserLive.basic_menu_list, fn x -> x.type == "status" end)
{title, _type} = Enum.find(field.options, fn {_title, type} -> type == item.status end)
%>
<%= title %>
</td>
<td class="align-middle text-center">
<%= live_component @socket, MishkaHtmlWeb.Public.TimeConverterComponent,
span_id: "inserted-at-#{item.id}-component",
time: item.inserted_at
%>
</td>
<td class="align-middle text-center" id="<%= "opration-#{item.id}" %>">
<a class="btn btn-outline-primary vazir" phx-click="delete" phx-value-id="<%= item.id %>">حذف</a>
<%= live_redirect MishkaTranslator.Gettext.dgettext("html_live_component", "ویرایش"),
to: Routes.live_path(@socket, MishkaHtmlWeb.AdminUserLive, id: item.id),
class: "btn btn-outline-danger vazir"
%>
<% user_role = item.roles %>
<div class="clearfix"></div>
<div class="space20"></div>
<div class="col">
<label for="country" class="form-label">
<%= MishkaTranslator.Gettext.dgettext("html_live_component", "انتخاب دسترسی") %>
</label>
<form phx-change="search_role">
<input class="form-control" type="text" placeholder="<%= MishkaTranslator.Gettext.dgettext("html_live_component", "جستجوی پیشرفته") %>" name="name">
</form>
<form phx-change="user_role">
<input type="hidden" value="<%= item.id %>" name="user_id">
<select class="form-select" id="role" name="role" size="2" style="min-height: 150px;">
<option value="delete_user_role"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "بدون دسترسی") %></option>
<%= for item <- @roles.entries do %>
<option value="<%= item.id %>" <%= if(!is_nil(user_role) and item.id == user_role.id, do: "selected") %>><%= item.name %></option>
<% end %>
</select>
</form>
</div>
</td>
</tr>
<% end %>
</tbody>
</table>
<div class="space20"></div>
<div class="col-sm-10">
<%= if @users.entries != [] do %>
<%= live_component @socket, MishkaHtmlWeb.Public.PaginationComponent ,
id: :pagination,
pagination_url: @pagination_url,
data: @users,
filters: @filters,
count: @count
%>
</div>
<% end %>
</div>
</div>
"""
end
def handle_event("close", _, socket) do
{:noreply, push_patch(socket, to: socket.assigns.return_to)}
end
end
| 57.009009 | 184 | 0.437579 |
ff96fb893118b4eb4b7ae98211be7b873dfde4a3 | 1,167 | ex | Elixir | clients/private_ca/lib/google_api/private_ca/v1beta1/connection.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/private_ca/lib/google_api/private_ca/v1beta1/connection.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/private_ca/lib/google_api/private_ca/v1beta1/connection.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.PrivateCA.V1beta1.Connection do
@moduledoc """
Handle Tesla connections for GoogleApi.PrivateCA.V1beta1.
"""
@type t :: Tesla.Env.client()
use GoogleApi.Gax.Connection,
scopes: [
# See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
"https://www.googleapis.com/auth/cloud-platform"
],
otp_app: :google_api_private_ca,
base_url: "https://privateca.googleapis.com/"
end
| 35.363636 | 114 | 0.741217 |
ff97080d44a4530283d8f1bd4ad1f09183e6a838 | 875 | ex | Elixir | lib/rocketpay_web/controllers/accounts_controller.ex | tairone-livinalli/rocketpay | f58be9330b678a486d717613790e9e3d9f0fe9d1 | [
"MIT"
] | null | null | null | lib/rocketpay_web/controllers/accounts_controller.ex | tairone-livinalli/rocketpay | f58be9330b678a486d717613790e9e3d9f0fe9d1 | [
"MIT"
] | null | null | null | lib/rocketpay_web/controllers/accounts_controller.ex | tairone-livinalli/rocketpay | f58be9330b678a486d717613790e9e3d9f0fe9d1 | [
"MIT"
] | null | null | null | defmodule RocketpayWeb.AccountsController do
use RocketpayWeb, :controller
alias Rocketpay.Account
alias Rocketpay.Accounts.Transactions.Response, as: TransactionResponse
action_fallback RocketpayWeb.FallbackController
def deposit(conn, params) do
with {:ok, %Account{} = account} <- Rocketpay.deposit(params) do
conn
|> put_status(:ok)
|> render("deposit.json", account: account)
end
end
def withdraw(conn, params) do
with {:ok, %Account{} = account} <- Rocketpay.withdraw(params) do
conn
|> put_status(:ok)
|> render("withdraw.json", account: account)
end
end
def transaction(conn, params) do
with {:ok, %TransactionResponse{} = transaction} <- Rocketpay.transaction(params) do
conn
|> put_status(:ok)
|> render("transaction.json", transaction: transaction)
end
end
end
| 26.515152 | 88 | 0.678857 |
ff971819292631bf2babc04bf3784d6e9a24b14c | 127 | ex | Elixir | lib/blog/repo.ex | cuongkta/login_logout_elixir | 71ad24e1077402fa719ce52fb3bc2a77510b1b86 | [
"Apache-2.0"
] | null | null | null | lib/blog/repo.ex | cuongkta/login_logout_elixir | 71ad24e1077402fa719ce52fb3bc2a77510b1b86 | [
"Apache-2.0"
] | null | null | null | lib/blog/repo.ex | cuongkta/login_logout_elixir | 71ad24e1077402fa719ce52fb3bc2a77510b1b86 | [
"Apache-2.0"
] | null | null | null | defmodule Blog.Repo do
#use Ecto.Repo, otp_app: :blog
use Ecto.Repo, adapter: Ecto.Adapters.Postgres, otp_app: :blog
end
| 18.142857 | 64 | 0.732283 |
ff972d8ba6469eba95945f032bef0c398cb4079a | 586 | exs | Elixir | test/wobserver2/util/port_test.exs | aruki-delivery/wobserver | 7db6b219b405defc1e28bd86836f9a90eed235b6 | [
"MIT"
] | null | null | null | test/wobserver2/util/port_test.exs | aruki-delivery/wobserver | 7db6b219b405defc1e28bd86836f9a90eed235b6 | [
"MIT"
] | null | null | null | test/wobserver2/util/port_test.exs | aruki-delivery/wobserver | 7db6b219b405defc1e28bd86836f9a90eed235b6 | [
"MIT"
] | null | null | null | defmodule Wobserver2.PortTest do
use ExUnit.Case
alias Wobserver2.Port
describe "list" do
test "returns a list" do
assert is_list(Port.list())
end
test "returns a list of maps" do
assert is_map(List.first(Port.list()))
end
test "returns a list of table information" do
assert %{
id: _,
port: _,
name: _,
links: _,
connected: _,
input: _,
output: _,
os_pid: _
} = List.first(Port.list())
end
end
end
| 20.206897 | 49 | 0.494881 |
ff97814fb1606fc0b1622b2bc5cae3a9529207a3 | 723 | ex | Elixir | lib/expokefight_web/gettext.ex | vbertazzo/expokefight | 19b6bd39af43e17c3ee14eab845cb24fb71d6d80 | [
"MIT"
] | null | null | null | lib/expokefight_web/gettext.ex | vbertazzo/expokefight | 19b6bd39af43e17c3ee14eab845cb24fb71d6d80 | [
"MIT"
] | null | null | null | lib/expokefight_web/gettext.ex | vbertazzo/expokefight | 19b6bd39af43e17c3ee14eab845cb24fb71d6d80 | [
"MIT"
] | null | null | null | defmodule ExpokefightWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import ExpokefightWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :expokefight
end
| 28.92 | 72 | 0.683264 |
ff97ae3ddeba5b4a375fc3f2cc3b635d249d019e | 3,634 | ex | Elixir | lib/grizzly/zwave/commands/node_add_dsk_report.ex | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 76 | 2019-09-04T16:56:58.000Z | 2022-03-29T06:54:36.000Z | lib/grizzly/zwave/commands/node_add_dsk_report.ex | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 124 | 2019-09-05T14:01:24.000Z | 2022-02-28T22:58:14.000Z | lib/grizzly/zwave/commands/node_add_dsk_report.ex | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 10 | 2019-10-23T19:25:45.000Z | 2021-11-17T13:21:20.000Z | defmodule Grizzly.ZWave.Commands.NodeAddDSKReport do
@moduledoc """
The Z-Wave Command `NODE_ADD_DSK_REPORT`
This report is used by the including controller to ask for the DSK
for the device that is being included.
## Params
- `:seq_number` - sequence number for the command (required)
- `:input_dsk_length` - the required number of bytes must be in the `:dsk`
field to be authenticated (optional default: `0`)
- `:dsk` - the DSK for the device see `Grizzly.ZWave.DSK` for more
information (required)
The `:input_dsk_length` field can be set to 0 if not provided. That means that
device does not require any user input to the DSK set command to authenticate
the device. This case is normal when `:s2_unauthenticated` or client side
authentication has been given.
"""
@behaviour Grizzly.ZWave.Command
alias Grizzly.ZWave.{DSK, Command, DecodeError}
alias Grizzly.ZWave.CommandClasses.NetworkManagementInclusion
@type param ::
{:seq_number, Grizzly.seq_number()}
| {:input_dsk_length, 0..16}
| {:dsk, DSK.t()}
@impl true
@spec new([param]) :: {:ok, Command.t()}
def new(params) do
:ok = validate_seq_number(params)
:ok = validate_dsk(params)
params = validate_and_ensure_input_dsk_length(params)
command = %Command{
name: :node_add_dsk_report,
command_byte: 0x13,
command_class: NetworkManagementInclusion,
params: params,
impl: __MODULE__
}
{:ok, command}
end
@impl true
def encode_params(command) do
seq_number = Command.param!(command, :seq_number)
input_dsk_length = Command.param!(command, :input_dsk_length)
dsk = Command.param!(command, :dsk)
{:ok, dsk} = DSK.parse(dsk)
<<seq_number, input_dsk_length>> <> dsk.raw
end
@impl true
@spec decode_params(binary()) :: {:ok, [param()]} | {:error, DecodeError.t()}
def decode_params(<<seq_number, _::size(4), input_dsk_length::size(4), dsk_bin::binary>>) do
{:ok, [seq_number: seq_number, input_dsk_length: input_dsk_length, dsk: DSK.new(dsk_bin)]}
end
defp validate_seq_number(params) do
case Keyword.get(params, :seq_number) do
nil ->
raise ArgumentError, """
When building the Z-Wave command #{inspect(__MODULE__)} the param :seq_number is
required.
Please ensure you passing a :seq_number option to the command
"""
seq_number when seq_number >= 0 and seq_number <= 255 ->
:ok
seq_number ->
raise ArgumentError, """
When build the Z-Wave command #{inspect(__MODULE__)} the param :seq_number should be
be an integer between 0 and 255 (0xFF) inclusive.
It looks like you passed: #{inspect(seq_number)}
"""
end
end
defp validate_dsk(params) do
case Keyword.get(params, :dsk) do
nil ->
raise ArgumentError, """
When building the Z-Wave command #{inspect(__MODULE__)} the param :dsk is
required.
Please ensure you passing a :dsk option to the command
"""
_dsk ->
:ok
end
end
def validate_and_ensure_input_dsk_length(params) do
case Keyword.get(params, :input_dsk_length) do
nil ->
Keyword.put(params, :input_dsk_length, 0)
length when length >= 0 and length <= 16 ->
params
length ->
raise ArgumentError, """
When build the Z-Wave command #{inspect(__MODULE__)} the param :input_dsk_length should be
be an integer between 0 and 16 inclusive.
It looks like you passed: #{inspect(length)}
"""
end
end
end
| 29.786885 | 98 | 0.656577 |
ff97bf8eeb43996c411d19d0cf530c1580ca23ad | 3,989 | ex | Elixir | DL-SMTP/DL-SMTP.ELEMENT-IoT.ex | Realscrat/decentlab-decoders | 3ca5006cd85e3772a15a1b3fff3922c50979eeb6 | [
"MIT"
] | 13 | 2020-01-18T22:08:44.000Z | 2022-02-06T14:19:57.000Z | DL-SMTP/DL-SMTP.ELEMENT-IoT.ex | johannesE/decentlab-decoders | c290ea1218de2c82d665fdc9f71f16682e12d917 | [
"MIT"
] | 4 | 2019-05-10T07:17:41.000Z | 2021-10-20T16:24:04.000Z | DL-SMTP/DL-SMTP.ELEMENT-IoT.ex | johannesE/decentlab-decoders | c290ea1218de2c82d665fdc9f71f16682e12d917 | [
"MIT"
] | 15 | 2019-06-04T06:13:32.000Z | 2022-02-15T07:28:52.000Z |
# https://www.decentlab.com/products/soil-moisture-and-temperature-profile-for-lorawan
defmodule Parser do
use Platform.Parsing.Behaviour
## test payloads
# 020b50000309018a8c09438a9809278a920b3c8aa50c9c8a8c11e08aa500000000000000000b3b
# 020b5000020b3b
def fields do
[
%{field: "soil_moisture_at_depth_0", display: "Soil moisture at depth 0", unit: ""},
%{field: "soil_temperature_at_depth_0", display: "Soil temperature at depth 0", unit: "°C"},
%{field: "soil_moisture_at_depth_1", display: "Soil moisture at depth 1", unit: ""},
%{field: "soil_temperature_at_depth_1", display: "Soil temperature at depth 1", unit: "°C"},
%{field: "soil_moisture_at_depth_2", display: "Soil moisture at depth 2", unit: ""},
%{field: "soil_temperature_at_depth_2", display: "Soil temperature at depth 2", unit: "°C"},
%{field: "soil_moisture_at_depth_3", display: "Soil moisture at depth 3", unit: ""},
%{field: "soil_temperature_at_depth_3", display: "Soil temperature at depth 3", unit: "°C"},
%{field: "soil_moisture_at_depth_4", display: "Soil moisture at depth 4", unit: ""},
%{field: "soil_temperature_at_depth_4", display: "Soil temperature at depth 4", unit: "°C"},
%{field: "soil_moisture_at_depth_5", display: "Soil moisture at depth 5", unit: ""},
%{field: "soil_temperature_at_depth_5", display: "Soil temperature at depth 5", unit: "°C"},
%{field: "soil_moisture_at_depth_6", display: "Soil moisture at depth 6", unit: ""},
%{field: "soil_temperature_at_depth_6", display: "Soil temperature at depth 6", unit: "°C"},
%{field: "soil_moisture_at_depth_7", display: "Soil moisture at depth 7", unit: ""},
%{field: "soil_temperature_at_depth_7", display: "Soil temperature at depth 7", unit: "°C"},
%{field: "battery_voltage", display: "Battery voltage", unit: "V"}
]
end
def parse(<<2, device_id::size(16), flags::binary-size(2), words::binary>>, _meta) do
{_remaining, result} =
{words, %{:device_id => device_id, :protocol_version => 2}}
|> sensor0(flags)
|> sensor1(flags)
result
end
defp sensor0({<<x0::size(16), x1::size(16), x2::size(16), x3::size(16), x4::size(16), x5::size(16), x6::size(16), x7::size(16), x8::size(16), x9::size(16), x10::size(16), x11::size(16), x12::size(16), x13::size(16), x14::size(16), x15::size(16), remaining::binary>>, result},
<<_::size(15), 1::size(1), _::size(0)>>) do
{remaining,
Map.merge(result,
%{
:soil_moisture_at_depth_0 => (x0 - 2500) / 500,
:soil_temperature_at_depth_0 => (x1 - 32768) / 100,
:soil_moisture_at_depth_1 => (x2 - 2500) / 500,
:soil_temperature_at_depth_1 => (x3 - 32768) / 100,
:soil_moisture_at_depth_2 => (x4 - 2500) / 500,
:soil_temperature_at_depth_2 => (x5 - 32768) / 100,
:soil_moisture_at_depth_3 => (x6 - 2500) / 500,
:soil_temperature_at_depth_3 => (x7 - 32768) / 100,
:soil_moisture_at_depth_4 => (x8 - 2500) / 500,
:soil_temperature_at_depth_4 => (x9 - 32768) / 100,
:soil_moisture_at_depth_5 => (x10 - 2500) / 500,
:soil_temperature_at_depth_5 => (x11 - 32768) / 100,
:soil_moisture_at_depth_6 => (x12 - 2500) / 500,
:soil_temperature_at_depth_6 => (x13 - 32768) / 100,
:soil_moisture_at_depth_7 => (x14 - 2500) / 500,
:soil_temperature_at_depth_7 => (x15 - 32768) / 100
})}
end
defp sensor0(result, _flags), do: result
defp sensor1({<<x0::size(16), remaining::binary>>, result},
<<_::size(14), 1::size(1), _::size(1)>>) do
{remaining,
Map.merge(result,
%{
:battery_voltage => x0 / 1000
})}
end
defp sensor1(result, _flags), do: result
end | 51.141026 | 277 | 0.60015 |
ff97d7c07cca30b4415cb3103527e933da0957be | 6,366 | exs | Elixir | test/plug/session/cookie_test.exs | qcam/plug | c547f2bd7a64aec7c4759dcc1ed88b6eab0c7499 | [
"Apache-2.0"
] | null | null | null | test/plug/session/cookie_test.exs | qcam/plug | c547f2bd7a64aec7c4759dcc1ed88b6eab0c7499 | [
"Apache-2.0"
] | null | null | null | test/plug/session/cookie_test.exs | qcam/plug | c547f2bd7a64aec7c4759dcc1ed88b6eab0c7499 | [
"Apache-2.0"
] | null | null | null | defmodule Plug.Session.CookieTest do
use ExUnit.Case, async: true
use Plug.Test
alias Plug.Session.COOKIE, as: CookieStore
@default_opts [
store: :cookie,
key: "foobar",
encryption_salt: "encrypted cookie salt",
signing_salt: "signing salt",
log: false
]
@secret String.duplicate("abcdef0123456789", 8)
@signing_opts Plug.Session.init(Keyword.put(@default_opts, :encrypt, false))
@encrypted_opts Plug.Session.init(@default_opts)
defmodule CustomSerializer do
def encode(%{"foo" => "bar"}), do: {:ok, "encoded session"}
def encode(%{"foo" => "baz"}), do: {:ok, "another encoded session"}
def encode(%{}), do: {:ok, ""}
def encode(_), do: :error
def decode("encoded session"), do: {:ok, %{"foo" => "bar"}}
def decode("another encoded session"), do: {:ok, %{"foo" => "baz"}}
def decode(nil), do: {:ok, nil}
def decode(_), do: :error
end
opts = Keyword.put(@default_opts, :serializer, CustomSerializer)
@custom_serializer_opts Plug.Session.init(opts)
defp sign_conn(conn, secret \\ @secret) do
put_in(conn.secret_key_base, secret)
|> Plug.Session.call(@signing_opts)
|> fetch_session
end
defp encrypt_conn(conn) do
put_in(conn.secret_key_base, @secret)
|> Plug.Session.call(@encrypted_opts)
|> fetch_session
end
defp custom_serialize_conn(conn) do
put_in(conn.secret_key_base, @secret)
|> Plug.Session.call(@custom_serializer_opts)
|> fetch_session
end
test "requires signing_salt option to be defined" do
assert_raise ArgumentError, ~r/expects :signing_salt as option/, fn ->
Plug.Session.init(Keyword.delete(@default_opts, :signing_salt))
end
end
test "requires the secret to be at least 64 bytes" do
assert_raise ArgumentError, ~r/to be at least 64 bytes/, fn ->
conn(:get, "/")
|> sign_conn("abcdef")
|> put_session("foo", "bar")
|> send_resp(200, "OK")
end
end
test "defaults key generator opts" do
key_generator_opts = CookieStore.init(@default_opts).key_opts
assert key_generator_opts[:iterations] == 1000
assert key_generator_opts[:length] == 32
assert key_generator_opts[:digest] == :sha256
end
test "uses specified key generator opts" do
opts =
@default_opts
|> Keyword.put(:key_iterations, 2000)
|> Keyword.put(:key_length, 64)
|> Keyword.put(:key_digest, :sha)
key_generator_opts = CookieStore.init(opts).key_opts
assert key_generator_opts[:iterations] == 2000
assert key_generator_opts[:length] == 64
assert key_generator_opts[:digest] == :sha
end
test "requires serializer option to be an atom" do
assert_raise ArgumentError, ~r/expects :serializer option to be a module/, fn ->
Plug.Session.init(Keyword.put(@default_opts, :serializer, "CustomSerializer"))
end
end
test "uses :external_term_format cookie serializer by default" do
assert Plug.Session.init(@default_opts).store_config.serializer == :external_term_format
end
test "uses custom cookie serializer" do
assert @custom_serializer_opts.store_config.serializer == CustomSerializer
end
## Signed
test "session cookies are signed" do
conn = %{secret_key_base: @secret}
cookie = CookieStore.put(conn, nil, %{"foo" => "baz"}, @signing_opts.store_config)
assert is_binary(cookie)
assert CookieStore.get(conn, cookie, @signing_opts.store_config) == {:term, %{"foo" => "baz"}}
assert CookieStore.get(conn, "bad", @signing_opts.store_config) == {nil, %{}}
end
test "gets and sets signed session cookie" do
conn =
conn(:get, "/")
|> sign_conn()
|> put_session("foo", "bar")
|> send_resp(200, "")
assert conn(:get, "/")
|> recycle_cookies(conn)
|> sign_conn()
|> get_session("foo") == "bar"
end
test "deletes signed session cookie" do
conn =
conn(:get, "/")
|> sign_conn()
|> put_session("foo", "bar")
|> configure_session(drop: true)
|> send_resp(200, "")
assert conn(:get, "/")
|> recycle_cookies(conn)
|> sign_conn()
|> get_session("foo") == nil
end
## Encrypted
test "session cookies are encrypted" do
conn = %{secret_key_base: @secret}
cookie = CookieStore.put(conn, nil, %{"foo" => "baz"}, @encrypted_opts.store_config)
assert is_binary(cookie)
assert CookieStore.get(conn, cookie, @encrypted_opts.store_config) ==
{:term, %{"foo" => "baz"}}
assert CookieStore.get(conn, "bad", @encrypted_opts.store_config) == {nil, %{}}
end
test "gets and sets encrypted session cookie" do
conn =
conn(:get, "/")
|> encrypt_conn()
|> put_session("foo", "bar")
|> send_resp(200, "")
assert conn(:get, "/")
|> recycle_cookies(conn)
|> encrypt_conn()
|> get_session("foo") == "bar"
end
test "deletes encrypted session cookie" do
conn =
conn(:get, "/")
|> encrypt_conn()
|> put_session("foo", "bar")
|> configure_session(drop: true)
|> send_resp(200, "")
assert conn(:get, "/")
|> recycle_cookies(conn)
|> encrypt_conn()
|> get_session("foo") == nil
end
## Custom Serializer
test "session cookies are serialized by the custom serializer" do
conn = %{secret_key_base: @secret}
cookie = CookieStore.put(conn, nil, %{"foo" => "baz"}, @custom_serializer_opts.store_config)
assert is_binary(cookie)
assert CookieStore.get(conn, cookie, @custom_serializer_opts.store_config) ==
{:custom, %{"foo" => "baz"}}
end
test "gets and sets custom serialized session cookie" do
conn =
conn(:get, "/")
|> custom_serialize_conn()
|> put_session("foo", "bar")
|> send_resp(200, "")
assert conn(:get, "/")
|> recycle_cookies(conn)
|> custom_serialize_conn()
|> get_session("foo") == "bar"
end
test "deletes custom serialized session cookie" do
conn =
conn(:get, "/")
|> custom_serialize_conn()
|> put_session("foo", "bar")
|> configure_session(drop: true)
|> send_resp(200, "")
assert conn(:get, "/")
|> recycle_cookies(conn)
|> custom_serialize_conn()
|> get_session("foo") == nil
end
end
| 29.472222 | 98 | 0.625825 |
ff97ef103a20bf0dac00f533107ca8521f53c146 | 2,260 | ex | Elixir | lib/mix/tasks/compile.nerves_package.ex | petermm/nerves | 173b0a424177f45f77db4206406d9c98f1d73e95 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/compile.nerves_package.ex | petermm/nerves | 173b0a424177f45f77db4206406d9c98f1d73e95 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/compile.nerves_package.ex | petermm/nerves | 173b0a424177f45f77db4206406d9c98f1d73e95 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Compile.NervesPackage do
use Mix.Task
import Mix.Nerves.IO
require Logger
@moduledoc """
Build a Nerves Artifact from a Nerves Package
"""
@shortdoc "Nerves Package Compiler"
@recursive true
@impl true
def run(_args) do
debug_info("Compile.NervesPackage start")
if Nerves.Env.enabled?() do
config = Mix.Project.config()
bootstrap_started?()
|> bootstrap_check()
Nerves.Env.ensure_loaded(Mix.Project.config()[:app])
package = Nerves.Env.package(config[:app])
toolchain = Nerves.Env.toolchain()
ret =
if Nerves.Artifact.stale?(package) do
Nerves.Artifact.build(package, toolchain)
:ok
else
:noop
end
debug_info("Compile.NervesPackage end")
ret
else
debug_info("Compile.NervesPackage disabled")
:noop
end
end
@doc false
def bootstrap_check(true), do: :ok
def bootstrap_check(false) do
error =
cond do
in_umbrella?(File.cwd!()) ->
"""
Compiling Nerves packages from the top of umbrella projects isn't supported.
Please cd into the application directory and try again.
"""
true ->
"""
Compiling Nerves packages requires nerves_bootstrap to be started.
Please ensure that MIX_TARGET is set in your environment and that you have added
the proper aliases to your mix.exs file:
def project do
[
# ...
aliases: [loadconfig: [&bootstrap/1]],
]
end
defp bootstrap(args) do
Application.start(:nerves_bootstrap)
Mix.Task.run("loadconfig", args)
end
"""
end
Mix.raise(error)
end
defp bootstrap_started?() do
Application.started_applications()
|> Enum.map(&Tuple.to_list/1)
|> Enum.map(&List.first/1)
|> Enum.member?(:nerves_bootstrap)
end
defp in_umbrella?(app_path) do
umbrella = Path.expand(Path.join([app_path, "..", ".."]))
mix_path = Path.join(umbrella, "mix.exs")
apps_path = Path.join(umbrella, "apps")
File.exists?(mix_path) && File.exists?(apps_path)
end
end
| 23.789474 | 90 | 0.595575 |
ff980efda11afdc357629ba67dbf1f2fa958ec9b | 403 | exs | Elixir | apps/tai/lib/tai/events/stream_error_test.exs | ihorkatkov/tai | 09f9f15d2c385efe762ae138a8570f1e3fd41f26 | [
"MIT"
] | 1 | 2019-12-19T05:16:26.000Z | 2019-12-19T05:16:26.000Z | apps/tai/lib/tai/events/stream_error_test.exs | ihorkatkov/tai | 09f9f15d2c385efe762ae138a8570f1e3fd41f26 | [
"MIT"
] | null | null | null | apps/tai/lib/tai/events/stream_error_test.exs | ihorkatkov/tai | 09f9f15d2c385efe762ae138a8570f1e3fd41f26 | [
"MIT"
] | 1 | 2020-05-03T23:32:11.000Z | 2020-05-03T23:32:11.000Z | defmodule Tai.Events.StreamErrorTest do
use ExUnit.Case, async: true
test ".to_data/1 transforms reason to a string" do
event = %Tai.Events.StreamError{
venue_id: :my_venue,
reason: {:function_clause, "Some error"}
}
assert Tai.LogEvent.to_data(event) == %{
venue_id: :my_venue,
reason: ~s({:function_clause, "Some error"})
}
end
end
| 25.1875 | 57 | 0.617866 |
ff9811e9adb25678447e10bbd8872fb07ed181c7 | 328 | ex | Elixir | lib/streaming_metrics.ex | smartcitiesdata/streaming-metrics | deada3f52d9763e5b257199a6c2ec0a098515616 | [
"Apache-2.0"
] | 1 | 2019-07-09T15:49:02.000Z | 2019-07-09T15:49:02.000Z | lib/streaming_metrics.ex | smartcitiesdata/streaming-metrics | deada3f52d9763e5b257199a6c2ec0a098515616 | [
"Apache-2.0"
] | 1 | 2021-05-28T16:43:38.000Z | 2021-05-28T16:43:38.000Z | lib/streaming_metrics.ex | Datastillery/streaming_metrics | deada3f52d9763e5b257199a6c2ec0a098515616 | [
"Apache-2.0"
] | null | null | null | defmodule StreamingMetrics do
@moduledoc false
use Application
def start(_type, _args) do
Application.get_env(:streaming_metrics, :collector, StreamingMetrics.ConsoleMetricCollector).init()
children = [
StreamingMetrics.Hostname
]
Supervisor.start_link(children, strategy: :one_for_one)
end
end
| 21.866667 | 103 | 0.75 |
ff98658f46976429b5fff035950a9d7e5c8f7808 | 1,393 | ex | Elixir | lib/polimorfismo_web/endpoint.ex | jobsonita/rocketseat-yt-cd-111-elixir-protocols | d5e683ff53fa764dd4b8adae6f75ef1abd010d97 | [
"MIT"
] | null | null | null | lib/polimorfismo_web/endpoint.ex | jobsonita/rocketseat-yt-cd-111-elixir-protocols | d5e683ff53fa764dd4b8adae6f75ef1abd010d97 | [
"MIT"
] | null | null | null | lib/polimorfismo_web/endpoint.ex | jobsonita/rocketseat-yt-cd-111-elixir-protocols | d5e683ff53fa764dd4b8adae6f75ef1abd010d97 | [
"MIT"
] | null | null | null | defmodule PolimorfismoWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :polimorfismo
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_polimorfismo_key",
signing_salt: "4rr7pO2N"
]
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :polimorfismo,
gzip: false,
only: ~w(assets fonts images favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
plug Phoenix.CodeReloader
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug PolimorfismoWeb.Router
end
| 29.020833 | 97 | 0.720029 |
ff9871513365c04a92da7abf34ea1fd679d03287 | 847 | ex | Elixir | apps/concierge_site/lib/users/confirmation_message.ex | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | null | null | null | apps/concierge_site/lib/users/confirmation_message.ex | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | 21 | 2021-03-12T17:05:30.000Z | 2022-02-16T21:48:35.000Z | apps/concierge_site/lib/users/confirmation_message.ex | mbta/alerts_concierge | d8e643445ef06f80ca273f2914c6959daea146f6 | [
"MIT"
] | 1 | 2021-12-09T15:09:53.000Z | 2021-12-09T15:09:53.000Z | defmodule ConciergeSite.ConfirmationMessage do
@moduledoc """
Handles user confirmation messaging
"""
alias AlertProcessor.Model.Notification
alias AlertProcessor.Dissemination.NotificationSender
alias ConciergeSite.Dissemination.{Email, Mailer}
def send_email_confirmation(user) do
user
|> Email.confirmation_email()
|> Mailer.deliver_later()
end
def send_sms_confirmation("", _), do: {:ok, nil}
def send_sms_confirmation(phone_number, "true") do
%Notification{
header:
"You have been subscribed to T-Alerts. " <>
"To stop receiving texts, reply STOP (cannot resubscribe for 30 days) " <>
"or visit alerts.mbta.com. Data rates may apply.",
phone_number: phone_number
}
|> NotificationSender.send()
end
def send_sms_confirmation(_, _), do: {:ok, nil}
end
| 28.233333 | 84 | 0.698937 |
ff98722f7674b8d592df7f00d2a61fd03cde8387 | 479 | exs | Elixir | config/config.exs | gcalmettes/fieldbot-aoc | a64868eb3c7b5e6c621cfb4fc9439b569a3a0d56 | [
"BSD-3-Clause"
] | 1 | 2020-12-09T12:48:23.000Z | 2020-12-09T12:48:23.000Z | config/config.exs | gcalmettes/fieldbot-aoc | a64868eb3c7b5e6c621cfb4fc9439b569a3a0d56 | [
"BSD-3-Clause"
] | 3 | 2021-01-12T19:28:12.000Z | 2021-12-01T21:35:21.000Z | config/config.exs | gcalmettes/fieldbot-aoc | a64868eb3c7b5e6c621cfb4fc9439b569a3a0d56 | [
"BSD-3-Clause"
] | 1 | 2021-01-10T12:27:15.000Z | 2021-01-10T12:27:15.000Z | import Config
config :elixir, :time_zone_database, Tzdata.TimeZoneDatabase
config :aoc, Aoc.Scheduler,
jobs: [
{"0 4 * * *", &Aoc.Scheduler.aocbot_updates/0},
{"0 1,12,18 * * *", &Aoc.Scheduler.aocbot_stats/0},
{"1 5 * * *", &Aoc.Scheduler.aocbot_today/0},
{"5,20,35,50 * * *", &Aoc.Scheduler.aocbot_heartbeat/0}
]
config :aoc, Aoc.Client,
cookie: "AocWebsiteCookie"
config :aoc, Aoc.Server,
username: "matrix-username",
password: "matrix-password"
| 25.210526 | 60 | 0.655532 |
ff987e8a7b5207aeb6e39790b7173b4135371203 | 1,868 | ex | Elixir | lib/mix/lib/mix/tasks/local.hex.ex | IvanRublev/elixir | 1ce201aa1ebbfc1666c4e4bde64f706a89629d59 | [
"Apache-2.0"
] | 2 | 2018-11-15T06:38:14.000Z | 2018-11-17T18:03:14.000Z | lib/mix/lib/mix/tasks/local.hex.ex | IvanRublev/elixir | 1ce201aa1ebbfc1666c4e4bde64f706a89629d59 | [
"Apache-2.0"
] | 1 | 2019-04-25T12:52:49.000Z | 2019-04-25T13:27:31.000Z | lib/mix/lib/mix/tasks/local.hex.ex | IvanRublev/elixir | 1ce201aa1ebbfc1666c4e4bde64f706a89629d59 | [
"Apache-2.0"
] | 1 | 2018-01-09T20:10:59.000Z | 2018-01-09T20:10:59.000Z | defmodule Mix.Tasks.Local.Hex do
use Mix.Task
@hex_list_path "/installs/hex-1.x.csv"
@hex_archive_path "/installs/[ELIXIR_VERSION]/hex-[HEX_VERSION].ez"
@shortdoc "Installs Hex locally"
@moduledoc """
Installs Hex locally.
mix local.hex
## Command line options
* `--force` - forces installation without a shell prompt; primarily
intended for automation in build systems like `make`
* `--if-missing` - performs installation only if Hex is not installed yet;
intended to avoid repeatedly reinstalling Hex in automation when a script
may be run multiple times
If both options are set, `--force` takes precedence.
## Mirrors
If you want to change the [default mirror](https://repo.hex.pm)
used for fetching Hex, set the `HEX_MIRROR` environment variable.
"""
@switches [if_missing: :boolean, force: :boolean]
@impl true
def run(argv) do
{opts, _} = OptionParser.parse!(argv, switches: @switches)
should_install? =
if Keyword.get(opts, :if_missing, false) do
not Code.ensure_loaded?(Hex)
else
true
end
argv =
if Keyword.get(opts, :force, false) do
["--force"]
else
[]
end
should_install? && run_install(argv)
end
defp run_install(argv) do
hex_mirror = Mix.Hex.mirror()
{elixir_version, hex_version, sha512} =
Mix.Local.find_matching_versions_from_signed_csv!("Hex", hex_mirror <> @hex_list_path)
url =
(hex_mirror <> @hex_archive_path)
|> String.replace("[ELIXIR_VERSION]", elixir_version)
|> String.replace("[HEX_VERSION]", hex_version)
# Unload the Hex module we loaded earlier to avoid conflicts when Hex is updated
# and then used without restarting the VM
:code.purge(Hex)
Mix.Tasks.Archive.Install.run([url, "--sha512", sha512 | argv])
end
end
| 26.309859 | 92 | 0.668094 |
ff988d839754621025d321102b4f632ebbc51c2d | 3,638 | ex | Elixir | lib/client.ex | xirsys/xturn-websocket-logger | b10f038ec9de64978f919ad91ead905b0816f1af | [
"Apache-2.0"
] | null | null | null | lib/client.ex | xirsys/xturn-websocket-logger | b10f038ec9de64978f919ad91ead905b0816f1af | [
"Apache-2.0"
] | null | null | null | lib/client.ex | xirsys/xturn-websocket-logger | b10f038ec9de64978f919ad91ead905b0816f1af | [
"Apache-2.0"
] | null | null | null | ### ----------------------------------------------------------------------
###
### Copyright (c) 2013 - 2018 Lee Sylvester and Xirsys LLC <experts@xirsys.com>
###
### All rights reserved.
###
### XTurn is licensed by Xirsys 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.
###
### See LICENSE for the full license text.
###
### ----------------------------------------------------------------------
defmodule Xirsys.XTurn.WebSocketLogger.Client do
@moduledoc """
"""
use GenServer
require Logger
@vsn "0"
@stun_marker 0
alias Xirsys.XTurn.WebSocketLogger.SocketHandler
alias XMediaLib.Stun
#########################################################################################################################
# Interface functions
#########################################################################################################################
def start_link(),
do: GenServer.start_link(__MODULE__, [], name: __MODULE__)
#########################################################################################################################
# OTP functions
#########################################################################################################################
def init(_) do
Logger.info("Initialising websocket logger")
{:ok, %{}}
end
def handle_cast({:process_message, sender, data}, state) do
Registry.WebSocketLogger
|> Registry.dispatch(SocketHandler.key(), fn entries ->
for {pid, _} <- entries do
if pid != self() do
Process.send(pid, parse_msg(data, sender), [])
end
end
end)
{:noreply, state}
end
def terminate(_reason, state) do
{:ok, state}
end
#########################################################################################################################
# Private functions
#########################################################################################################################
defp parse_msg(%{
client_ip: ip,
client_port: cport,
message: <<@stun_marker::2, _::14, _rest::binary>> = msg
}, sender) do
case Stun.pretty(msg) do
{:ok, dec_msg} ->
%{
type: "stun",
sender: sender,
client_ip: parse_ip(ip),
client_port: cport,
message: dec_msg
}
|> Jason.encode!()
_ ->
"Failed to parse message"
end
end
defp parse_msg(%{
client_ip: ip,
client_port: cport,
message: <<1::2, _num::14, _length::16, _rest::binary>>
}, sender),
do:
%{
type: "channel_data",
sender: sender,
client_ip: parse_ip(ip),
client_port: cport
}
|> Jason.encode!()
defp parse_msg(msg, sender) when is_binary(msg), do: "#{sender}: #{inspect msg}"
defp parse_msg(msg, sender), do: "TODO, #{sender}: #{inspect(msg)}"
defp parse_ip({i0, i1, i2, i3}), do: "#{i0}.#{i1}.#{i2}.#{i3}"
defp parse_ip({i0, i1, i2, i3, i4, i5, i6, i7}),
do: "#{i0}:#{i1}:#{i2}:#{i3}:#{i4}:#{i5}:#{i6}:#{i7}"
end
| 31.362069 | 123 | 0.448873 |
ff98c5b960ef7887bc3777e0222baa5ebc8f584a | 292 | ex | Elixir | lib/phoenix_absinthe_dataloader_kv_web/resolvers.ex | alexandrubagu/phoenie_absinthe_dataloader_kv | b75ceabe6e384a56b40144e35624bcbd823af273 | [
"MIT"
] | null | null | null | lib/phoenix_absinthe_dataloader_kv_web/resolvers.ex | alexandrubagu/phoenie_absinthe_dataloader_kv | b75ceabe6e384a56b40144e35624bcbd823af273 | [
"MIT"
] | 3 | 2020-05-08T21:01:07.000Z | 2020-05-08T21:01:07.000Z | lib/phoenix_absinthe_dataloader_kv_web/resolvers.ex | alexandrubagu/phoenie_absinthe_dataloader_kv | b75ceabe6e384a56b40144e35624bcbd823af273 | [
"MIT"
] | 2 | 2019-02-14T13:43:45.000Z | 2020-02-28T22:04:33.000Z | defmodule PhoenixAbsintheDataloaderKvWeb.Resolvers do
alias PhoenixAbsintheDataloaderKv.Core
def list_webpages(_parent, _args, _resolution) do
{:ok, Core.list_webpages()}
end
def get_link(%{id: webpage_id}, _args, _resolution) do
{:ok, Core.get_links(webpage_id)}
end
end
| 24.333333 | 56 | 0.756849 |
ff98e00c20589a2b8c7915b8a897a769023e11ac | 2,148 | ex | Elixir | clients/fonts/lib/google_api/fonts/v1/deserializer.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/fonts/lib/google_api/fonts/v1/deserializer.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/fonts/lib/google_api/fonts/v1/deserializer.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.Fonts.V1.Deserializer do
@moduledoc """
Helper functions for deserializing responses into models
"""
@doc """
Update the provided model with a deserialization of a nested value
"""
@spec deserialize(struct(), :atom, :atom, struct(), keyword()) :: struct()
def deserialize(model, _field, :list, nil, _options), do: model
def deserialize(model, field, :list, mod, options) do
model
|> Map.update!(field, &(Poison.Decode.decode(&1, Keyword.merge(options, [as: [struct(mod)]]))))
end
def deserialize(model, field, :struct, mod, options) do
model
|> Map.update!(field, &(Poison.Decode.decode(&1, Keyword.merge(options, [as: struct(mod)]))))
end
def deserialize(model, _field, :map, nil, _options), do: model
def deserialize(model, field, :map, mod, options) do
model
|> Map.update!(field, &(Map.new(&1, fn {key, val} -> {key, Poison.Decode.decode(val, Keyword.merge(options, [as: struct(mod)]))} end)))
end
def deserialize(model, field, :date, _, _options) do
case DateTime.from_iso8601(Map.get(model, field)) do
{:ok, datetime} ->
Map.put(model, field, datetime)
_ ->
model
end
end
def serialize_non_nil(model, options) do
model
|> Map.from_struct
|> Enum.filter(fn {_k, v} -> v != nil end)
|> Enum.into(%{})
|> Poison.Encoder.encode(options)
end
end
| 35.8 | 139 | 0.687616 |
ff992abf6a202198db81b36280e3803ed37c8573 | 1,209 | ex | Elixir | lib/2020/day3.ex | Bentheburrito/adventofcode | 6fca0933c2a0e541567fe9f8bc34df4a048b5d8a | [
"MIT"
] | null | null | null | lib/2020/day3.ex | Bentheburrito/adventofcode | 6fca0933c2a0e541567fe9f8bc34df4a048b5d8a | [
"MIT"
] | null | null | null | lib/2020/day3.ex | Bentheburrito/adventofcode | 6fca0933c2a0e541567fe9f8bc34df4a048b5d8a | [
"MIT"
] | null | null | null | defmodule AOC.Day3 do
def run(input) do
map = input |> String.split("\n")
trees1 = AOC.time(&tree_count/3, [map, 3, 1])
IO.puts "Number of trees hit (3, 1): #{trees1}"
trees2 = AOC.time(&tree_count/3, [map, 1, 1])
IO.puts "Number of trees hit (1, 1): #{trees2}"
trees3 = AOC.time(&tree_count/3, [map, 5, 1])
IO.puts "Number of trees hit (5, 1): #{trees3}"
trees4 = AOC.time(&tree_count/3, [map, 7, 1])
IO.puts "Number of trees hit (7, 1): #{trees4}"
trees5 = AOC.time(&tree_count/3, [map, 1, 2])
IO.puts "Number of trees hit (1, 2): #{trees5}"
IO.puts "Multipied together: #{trees1 * trees2 * trees3 * trees4 * trees5}"
end
def tree_count(map, travel_right, travel_down) when travel_down > 1, do: tree_count(Enum.take_every(map, travel_down), travel_right, 1)
def tree_count(map, travel_right, _travel_down) do
map_width = List.first(map) |> String.length()
Enum.reduce(map, %{trees: 0, column: 0}, fn (map_row, %{trees: trees, column: col}) ->
square = String.at(map_row, col)
new_col = col + travel_right
%{
trees: square == "#" && trees + 1 || trees,
column: new_col >= map_width && new_col - map_width || new_col
}
end) |> Map.get(:trees)
end
end
| 37.78125 | 136 | 0.638544 |
ff992d2b3bb9da5eaa8449bd9964fc3ac5821ce8 | 389 | ex | Elixir | apps/hefty/lib/hefty/trader_supervisor.ex | Soimil/Igthorn | 6187a94d7a75a28f3c42b357fa7cc211cfe4bafe | [
"MIT"
] | null | null | null | apps/hefty/lib/hefty/trader_supervisor.ex | Soimil/Igthorn | 6187a94d7a75a28f3c42b357fa7cc211cfe4bafe | [
"MIT"
] | null | null | null | apps/hefty/lib/hefty/trader_supervisor.ex | Soimil/Igthorn | 6187a94d7a75a28f3c42b357fa7cc211cfe4bafe | [
"MIT"
] | null | null | null | defmodule Hefty.TraderSupervisor do
use Supervisor
def start_link() do
Supervisor.start_link(
__MODULE__,
[],
name: __MODULE__
)
end
def init(_args) do
children = [
worker(Hefty.NaiveTrader, [])
]
opts = [strategy: :simple_one_for_one, max_restarts: 5, max_seconds: 5]
Supervisor.init(
children,
opts
)
end
end
| 15.56 | 75 | 0.611825 |
ff9957e0deb9dc0cd094d533e3319489711cac47 | 237 | exs | Elixir | apps/error/spec/spec_helper.exs | mikrofusion/passwordless | 26621389cc0e8e307080b1eb5be42b0527e6611b | [
"MIT"
] | null | null | null | apps/error/spec/spec_helper.exs | mikrofusion/passwordless | 26621389cc0e8e307080b1eb5be42b0527e6611b | [
"MIT"
] | null | null | null | apps/error/spec/spec_helper.exs | mikrofusion/passwordless | 26621389cc0e8e307080b1eb5be42b0527e6611b | [
"MIT"
] | null | null | null | ExUnit.start
{:ok, _} = Application.ensure_all_started(:ex_machina)
Code.require_file("spec/factories/factory.exs")
ESpec.configure fn(config) ->
config.before fn ->
:ok
end
config.finally fn(_shared) ->
:ok
end
end
| 13.941176 | 54 | 0.687764 |
ff996125b0e47fde30a15873e808aa3065dc472b | 96 | exs | Elixir | examples/phoenix_example/test/phoenix_example_web/views/layout_view_test.exs | kianmeng/ex_health | f7311d5e23e8cfbb6dd91381a52a420345331535 | [
"MIT"
] | 9 | 2019-03-16T21:24:57.000Z | 2021-12-29T21:31:16.000Z | examples/phoenix_example/test/phoenix_example_web/views/layout_view_test.exs | kianmeng/ex_health | f7311d5e23e8cfbb6dd91381a52a420345331535 | [
"MIT"
] | 13 | 2018-12-11T16:43:26.000Z | 2022-02-09T23:08:01.000Z | examples/phoenix_example/test/phoenix_example_web/views/layout_view_test.exs | kianmeng/ex_health | f7311d5e23e8cfbb6dd91381a52a420345331535 | [
"MIT"
] | 4 | 2019-09-18T00:54:04.000Z | 2021-05-09T05:30:47.000Z | defmodule PhoenixExampleWeb.LayoutViewTest do
use PhoenixExampleWeb.ConnCase, async: true
end
| 24 | 45 | 0.854167 |
ff9991e84a3514f30b36e28d6937e49a9985543d | 3,915 | exs | Elixir | host_core/test/e2e/echo_test.exs | nickisonpar/wasmcloud-otp | eab10ddba11d86f5172441b8f8075c97d47d9a8e | [
"Apache-2.0"
] | null | null | null | host_core/test/e2e/echo_test.exs | nickisonpar/wasmcloud-otp | eab10ddba11d86f5172441b8f8075c97d47d9a8e | [
"Apache-2.0"
] | null | null | null | host_core/test/e2e/echo_test.exs | nickisonpar/wasmcloud-otp | eab10ddba11d86f5172441b8f8075c97d47d9a8e | [
"Apache-2.0"
] | null | null | null | defmodule HostCore.E2E.EchoTest do
use ExUnit.Case, async: false
setup do
{:ok, evt_watcher} =
GenServer.start_link(HostCoreTest.EventWatcher, HostCore.Host.lattice_prefix())
[
evt_watcher: evt_watcher
]
end
@echo_key HostCoreTest.Constants.echo_key()
@echo_path HostCoreTest.Constants.echo_path()
@echo_unpriv_key HostCoreTest.Constants.echo_unpriv_key()
@echo_unpriv_path HostCoreTest.Constants.echo_unpriv_path()
@httpserver_link HostCoreTest.Constants.default_link()
@httpserver_path HostCoreTest.Constants.httpserver_path()
test "echo roundtrip", %{:evt_watcher => evt_watcher} do
on_exit(fn -> HostCore.Host.purge() end)
{:ok, bytes} = File.read(@echo_path)
{:ok, _pid} = HostCore.Actors.ActorSupervisor.start_actor(bytes)
:ok = HostCoreTest.EventWatcher.wait_for_actor_start(evt_watcher, @echo_key)
{:ok, _pid} =
HostCore.Providers.ProviderSupervisor.start_provider_from_file(
@httpserver_path,
@httpserver_link
)
{:ok, bytes} = File.read(@httpserver_path)
{:ok, par} = HostCore.WasmCloud.Native.par_from_bytes(bytes |> IO.iodata_to_binary())
httpserver_key = par.claims.public_key
httpserver_contract = par.contract_id
:ok =
HostCoreTest.EventWatcher.wait_for_provider_start(
evt_watcher,
httpserver_contract,
@httpserver_link,
httpserver_key
)
actor_count =
Map.get(HostCore.Actors.ActorSupervisor.all_actors(), @echo_key)
|> length
assert actor_count == 1
assert elem(Enum.at(HostCore.Providers.ProviderSupervisor.all_providers(), 0), 1) ==
httpserver_key
:ok =
HostCore.Linkdefs.Manager.put_link_definition(
@echo_key,
httpserver_contract,
@httpserver_link,
httpserver_key,
%{PORT: "8080"}
)
:ok =
HostCoreTest.EventWatcher.wait_for_linkdef(
evt_watcher,
@echo_key,
httpserver_contract,
@httpserver_link
)
HTTPoison.start()
{:ok, _resp} = HTTPoison.get("http://localhost:8080/foo/bar")
end
test "unprivileged actor cannot receive undeclared invocations", %{:evt_watcher => evt_watcher} do
on_exit(fn -> HostCore.Host.purge() end)
{:ok, bytes} = File.read(@echo_unpriv_path)
{:ok, _pid} = HostCore.Actors.ActorSupervisor.start_actor(bytes)
:ok = HostCoreTest.EventWatcher.wait_for_actor_start(evt_watcher, @echo_unpriv_key)
actor_count =
Map.get(HostCore.Actors.ActorSupervisor.all_actors(), @echo_unpriv_key)
|> length
assert actor_count == 1
{:ok, bytes} = File.read(@httpserver_path)
{:ok, par} = HostCore.WasmCloud.Native.par_from_bytes(bytes |> IO.iodata_to_binary())
httpserver_key = par.claims.public_key
httpserver_contract = par.contract_id
# OK to put link definition with no claims information
assert HostCore.Linkdefs.Manager.put_link_definition(
@echo_unpriv_key,
httpserver_contract,
@httpserver_link,
httpserver_key,
%{PORT: "8084"}
) == :ok
{:ok, _pid} =
HostCore.Providers.ProviderSupervisor.start_provider_from_file(
@httpserver_path,
@httpserver_link
)
:ok =
HostCoreTest.EventWatcher.wait_for_provider_start(
evt_watcher,
httpserver_contract,
@httpserver_link,
httpserver_key
)
# For now, okay to put a link definition without proper claims
assert HostCore.Linkdefs.Manager.put_link_definition(
@echo_unpriv_key,
httpserver_contract,
@httpserver_link,
httpserver_key,
%{PORT: "8084"}
) == :ok
HTTPoison.start()
{:ok, resp} = HTTPoison.get("http://localhost:8084/foobar")
assert resp.body == ""
assert resp.status_code == 500
end
end
| 29.43609 | 100 | 0.66539 |
ff9a01b522d5664f88bbd8e09c86683e037a9d21 | 1,249 | exs | Elixir | mix.exs | typesend/princess | 948f3afdeab20deef3debecddc3440031f836e36 | [
"MIT"
] | 3 | 2020-05-24T01:30:14.000Z | 2020-06-20T20:32:37.000Z | mix.exs | typesend/princess | 948f3afdeab20deef3debecddc3440031f836e36 | [
"MIT"
] | null | null | null | mix.exs | typesend/princess | 948f3afdeab20deef3debecddc3440031f836e36 | [
"MIT"
] | null | null | null | defmodule Princess.MixProject do
use Mix.Project
def project do
[
app: :princess,
version: "0.1.0",
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
description: description(),
package: package(),
deps: deps(),
name: "Princess",
source_url: "https://github.com/typesend/princess",
homepage_url: "https://github.com/typesend/princess",
docs: docs()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:ex_doc, "~> 0.22", only: :dev, runtime: false}
]
end
defp description() do
"Generate print-ready PDF files using HTML, JavaScript, and CSS. Heavy lifting is performed by PrinceXML."
end
defp package() do
[
files: ~w(lib priv .formatter.exs mix.exs README* LICENSE*),
licenses: ["MIT"],
links: %{
"GitHub" => "https://github.com/typesend/princess",
"PrinceXML" => "https://princexml.com"
}
]
end
defp docs() do
[
main: "Princess",
logo: "priv/princess.png",
extras: ["README.md"]
]
end
end
| 21.912281 | 110 | 0.582866 |
ff9a0c8c33e3fd99dc569ba82b6f96a53e9b99f9 | 567 | exs | Elixir | prime/mix.exs | TraceyOnim/prime_numbers | 91b2fd4d54135466e3681307d9b419bb151a05b3 | [
"Apache-2.0"
] | null | null | null | prime/mix.exs | TraceyOnim/prime_numbers | 91b2fd4d54135466e3681307d9b419bb151a05b3 | [
"Apache-2.0"
] | null | null | null | prime/mix.exs | TraceyOnim/prime_numbers | 91b2fd4d54135466e3681307d9b419bb151a05b3 | [
"Apache-2.0"
] | null | null | null | defmodule Prime.MixProject do
use Mix.Project
def project do
[
app: :prime,
version: "0.1.0",
elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
| 19.551724 | 87 | 0.573192 |
ff9a2a5212e9c0a33d55751fe6d2539abf8bc4d0 | 84 | ex | Elixir | lib/phoenix_example_app_web/views/session_view.ex | dreamingechoes/phoenix-example-app | 9b3e9cd0c7acbe2ffee627c58b0150fe0e811780 | [
"MIT"
] | 2 | 2018-06-03T19:33:09.000Z | 2020-01-14T03:19:05.000Z | lib/phoenix_example_app_web/views/session_view.ex | dreamingechoes/phoenix-example-app | 9b3e9cd0c7acbe2ffee627c58b0150fe0e811780 | [
"MIT"
] | null | null | null | lib/phoenix_example_app_web/views/session_view.ex | dreamingechoes/phoenix-example-app | 9b3e9cd0c7acbe2ffee627c58b0150fe0e811780 | [
"MIT"
] | 1 | 2018-06-22T00:00:39.000Z | 2018-06-22T00:00:39.000Z | defmodule PhoenixExampleAppWeb.SessionView do
use PhoenixExampleAppWeb, :view
end
| 21 | 45 | 0.857143 |
ff9a583b32deb681526f404b2cce4db0de48cfe2 | 3,056 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/resource_policy_aggregated_list.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/resource_policy_aggregated_list.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/resource_policy_aggregated_list.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Model.ResourcePolicyAggregatedList do
@moduledoc """
Contains a list of resourcePolicies.
## Attributes
* `etag` (*type:* `String.t`, *default:* `nil`) -
* `id` (*type:* `String.t`, *default:* `nil`) - [Output Only] Unique identifier for the resource; defined by the server.
* `items` (*type:* `%{optional(String.t) => GoogleApi.Compute.V1.Model.ResourcePoliciesScopedList.t}`, *default:* `nil`) - A list of ResourcePolicy resources.
* `kind` (*type:* `String.t`, *default:* `compute#resourcePolicyAggregatedList`) - Type of resource.
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
* `selfLink` (*type:* `String.t`, *default:* `nil`) - [Output Only] Server-defined URL for this resource.
* `warning` (*type:* `GoogleApi.Compute.V1.Model.ResourcePolicyAggregatedListWarning.t`, *default:* `nil`) - [Output Only] Informational warning message.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:etag => String.t(),
:id => String.t(),
:items => %{
optional(String.t()) => GoogleApi.Compute.V1.Model.ResourcePoliciesScopedList.t()
},
:kind => String.t(),
:nextPageToken => String.t(),
:selfLink => String.t(),
:warning => GoogleApi.Compute.V1.Model.ResourcePolicyAggregatedListWarning.t()
}
field(:etag)
field(:id)
field(:items, as: GoogleApi.Compute.V1.Model.ResourcePoliciesScopedList, type: :map)
field(:kind)
field(:nextPageToken)
field(:selfLink)
field(:warning, as: GoogleApi.Compute.V1.Model.ResourcePolicyAggregatedListWarning)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.ResourcePolicyAggregatedList do
def decode(value, options) do
GoogleApi.Compute.V1.Model.ResourcePolicyAggregatedList.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.ResourcePolicyAggregatedList do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 45.61194 | 393 | 0.71106 |
ff9a5b53c1a3c5992d2c6ebfb145f56151e4f3b3 | 3,077 | ex | Elixir | clients/jobs/lib/google_api/jobs/v2/model/compensation_entry.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/jobs/lib/google_api/jobs/v2/model/compensation_entry.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/jobs/lib/google_api/jobs/v2/model/compensation_entry.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.Jobs.V2.Model.CompensationEntry do
@moduledoc """
A compensation entry that represents one component of compensation, such
as base pay, bonus, or other compensation type.
Annualization: One compensation entry can be annualized if
- it contains valid amount or range.
- and its expected_units_per_year is set or can be derived.
Its annualized range is determined as (amount or range) times
expected_units_per_year.
## Attributes
* `amount` (*type:* `GoogleApi.Jobs.V2.Model.Money.t`, *default:* `nil`) - Optional. Compensation amount.
* `description` (*type:* `String.t`, *default:* `nil`) - Optional. Compensation description. For example, could
indicate equity terms or provide additional context to an estimated
bonus.
* `expectedUnitsPerYear` (*type:* `float()`, *default:* `nil`) - Optional. Expected number of units paid each year. If not specified, when
Job.employment_types is FULLTIME, a default value is inferred
based on unit. Default values:
- HOURLY: 2080
- DAILY: 260
- WEEKLY: 52
- MONTHLY: 12
- ANNUAL: 1
* `range` (*type:* `GoogleApi.Jobs.V2.Model.CompensationRange.t`, *default:* `nil`) - Optional. Compensation range.
* `type` (*type:* `String.t`, *default:* `nil`) - Required. Compensation type.
* `unit` (*type:* `String.t`, *default:* `nil`) - Optional. Frequency of the specified amount.
Default is CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:amount => GoogleApi.Jobs.V2.Model.Money.t(),
:description => String.t(),
:expectedUnitsPerYear => float(),
:range => GoogleApi.Jobs.V2.Model.CompensationRange.t(),
:type => String.t(),
:unit => String.t()
}
field(:amount, as: GoogleApi.Jobs.V2.Model.Money)
field(:description)
field(:expectedUnitsPerYear)
field(:range, as: GoogleApi.Jobs.V2.Model.CompensationRange)
field(:type)
field(:unit)
end
defimpl Poison.Decoder, for: GoogleApi.Jobs.V2.Model.CompensationEntry do
def decode(value, options) do
GoogleApi.Jobs.V2.Model.CompensationEntry.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Jobs.V2.Model.CompensationEntry do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.4625 | 142 | 0.703932 |
ff9a5c99358a0453805f955519b1739905dba597 | 975 | exs | Elixir | elixir/config/test.exs | VitorFirmino/NLW-7 | 16d3319c6bcf2308ef6ea5fdf8257be78887a190 | [
"MIT"
] | null | null | null | elixir/config/test.exs | VitorFirmino/NLW-7 | 16d3319c6bcf2308ef6ea5fdf8257be78887a190 | [
"MIT"
] | null | null | null | elixir/config/test.exs | VitorFirmino/NLW-7 | 16d3319c6bcf2308ef6ea5fdf8257be78887a190 | [
"MIT"
] | null | null | null | import 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 :elixer, Elixer.Repo,
username: "postgres",
password: "postgres",
database: "elixer_test#{System.get_env("MIX_TEST_PARTITION")}",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox,
pool_size: 10
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :elixer, ElixerWeb.Endpoint,
http: [ip: {127, 0, 0, 1}, port: 4002],
secret_key_base: "cMcjWVzQK0cDNjJp9+E0A92KYdvnnEvl3twoA7SDi17BxFNsEH+L7sLyv2oY4R9h",
server: false
# In test we don't send emails.
config :elixer, Elixer.Mailer, adapter: Swoosh.Adapters.Test
# Print only warnings and errors during test
config :logger, level: :warn
# Initialize plugs at runtime for faster test compilation
config :phoenix, :plug_init_mode, :runtime
| 31.451613 | 86 | 0.757949 |
ff9a6f59d7f3d24fefc41a30407c6f825abf23f6 | 489 | ex | Elixir | lib/re_web/auth/guardian_pipeline.ex | diemesleno/backend | a55f9c846cc826b5269f3fd6ce19223f0c6a1682 | [
"MIT"
] | 1 | 2020-01-23T04:24:58.000Z | 2020-01-23T04:24:58.000Z | lib/re_web/auth/guardian_pipeline.ex | diemesleno/backend | a55f9c846cc826b5269f3fd6ce19223f0c6a1682 | [
"MIT"
] | null | null | null | lib/re_web/auth/guardian_pipeline.ex | diemesleno/backend | a55f9c846cc826b5269f3fd6ce19223f0c6a1682 | [
"MIT"
] | 1 | 2019-12-31T16:11:21.000Z | 2019-12-31T16:11:21.000Z | defmodule ReWeb.GuardianPipeline do
@moduledoc """
Module to define guardian related plugs into a pipeline
"""
@claims %{typ: "access"}
use Guardian.Plug.Pipeline,
otp_app: :re,
module: ReWeb.Guardian,
error_handler: ReWeb.Guardian.AuthErrorHandler
plug(Guardian.Plug.VerifySession, claims: @claims)
plug(Guardian.Plug.VerifyHeader, claims: @claims, realm: "Token")
plug(Guardian.Plug.EnsureAuthenticated)
plug(Guardian.Plug.LoadResource, ensure: true)
end
| 28.764706 | 67 | 0.742331 |
ff9ab25bc086be9b58ff372f9856497d25b13608 | 2,356 | exs | Elixir | test/Rules/RuleEvaluator_test.exs | davidgrupp/Flea | a15bb7d4b121b08155862b390dfe1626bbdc5840 | [
"Apache-2.0"
] | null | null | null | test/Rules/RuleEvaluator_test.exs | davidgrupp/Flea | a15bb7d4b121b08155862b390dfe1626bbdc5840 | [
"Apache-2.0"
] | null | null | null | test/Rules/RuleEvaluator_test.exs | davidgrupp/Flea | a15bb7d4b121b08155862b390dfe1626bbdc5840 | [
"Apache-2.0"
] | null | null | null | defmodule RuleEvaluatorTest do
use ExUnit.Case
test "evaluate single - v IS f - 0.5", do: evaluate_single({ 0, 0, 10, 20, :is, 15, 0.5 })
test "evaluate single - v NOT f - 0.5", do: evaluate_single({ 0, 0, 10, 20, :isnot, 15, 0.5 })
test "evaluate single - v IS f - 0.75", do: evaluate_single({ 0, 0, 10, 20, :is, 12.5, 0.75 })
test "evaluate single - v NOT f - 0.25", do: evaluate_single({ 0, 0, 10, 20, :isnot, 12.5, 0.25 })
test "evaluate single - v IS f - 1", do: evaluate_single({ 0, 0, 10, 20, :is, 5, 1 })
test "evaluate single - v NOT f - 0", do: evaluate_single({ 0, 0, 10, 20, :isnot, 5, 0 })
def evaluate_single({ a, b, c, d, is_op, val, expected_result }) do
mem_func = %Flea.TrapezoidMemFunc{ a: a, b: b, c: c, d: d }
cond1 = %Flea.RuleCondition{ clause: %Flea.RuleClause{ variable: :v, operator: is_op, mem_func: mem_func } }
input_values = [{ :v, val }]
conditions = [cond1]
result = Flea.RuleEvaluator.evaluate(conditions, input_values)
assert result == expected_result
end
test "evaluate double - v1 IS f1 AND v2 IS f2", do: evaluate_double({ 0, 10, 20, :is, :and, 0, 10, 30, :is, 15, 0.5 })
test "evaluate double - v1 IS f1 AND v2 NOT f2", do: evaluate_double({ 0, 10, 20, :is, :and, 0, 10, 30, :isnot, 15, 0.25 })
test "evaluate double - v1 IS f1 OR v2 IS f2", do: evaluate_double({ 0, 10, 20, :is, :or, 0, 10, 30, :is, 15, 0.75 })
test "evaluate double - v1 IS f1 OR v2 NOT f2", do: evaluate_double({ 0, 10, 20, :is, :or, 0, 10, 30, :isnot, 15, 0.5 })
def evaluate_double({ a1, b1, c1, is_op1, conj, a2, b2, c2, is_op2, val, expected_result }) do
mem_func1 = %Flea.TriangleMemFunc{ a: a1, b: b1, c: c1 }
cond1 = %Flea.RuleCondition{ clause: %Flea.RuleClause{ variable: :v1, operator: is_op1, mem_func: mem_func1 } }
mem_func2 = %Flea.TriangleMemFunc{ a: a2, b: b2, c: c2 }
cond2 = %Flea.RuleCondition{ conjunction: conj, clause: %Flea.RuleClause{ variable: :v2, operator: is_op2, mem_func: mem_func2 } }
input_values = [{ :v1, val }, { :v2, val }]
conditions = [cond1, cond2]
result = Flea.RuleEvaluator.evaluate(conditions, input_values)
assert result == expected_result
end
end | 51.217391 | 138 | 0.58871 |
ff9ab2bb487e2dc6c3f5f976cde34e06ff049f2d | 2,349 | ex | Elixir | clients/content/lib/google_api/content/v21/model/orders_reject_return_line_item_request.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v21/model/orders_reject_return_line_item_request.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v21/model/orders_reject_return_line_item_request.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.Content.V21.Model.OrdersRejectReturnLineItemRequest do
@moduledoc """
## Attributes
* `lineItemId` (*type:* `String.t`, *default:* `nil`) - The ID of the line item to return. Either lineItemId or productId is required.
* `operationId` (*type:* `String.t`, *default:* `nil`) - The ID of the operation. Unique across all operations for a given order.
* `productId` (*type:* `String.t`, *default:* `nil`) - The ID of the product to return. This is the REST ID used in the products service. Either lineItemId or productId is required.
* `quantity` (*type:* `integer()`, *default:* `nil`) - The quantity to return and refund.
* `reason` (*type:* `String.t`, *default:* `nil`) - The reason for the return.
* `reasonText` (*type:* `String.t`, *default:* `nil`) - The explanation of the reason.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:lineItemId => String.t(),
:operationId => String.t(),
:productId => String.t(),
:quantity => integer(),
:reason => String.t(),
:reasonText => String.t()
}
field(:lineItemId)
field(:operationId)
field(:productId)
field(:quantity)
field(:reason)
field(:reasonText)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.OrdersRejectReturnLineItemRequest do
def decode(value, options) do
GoogleApi.Content.V21.Model.OrdersRejectReturnLineItemRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.OrdersRejectReturnLineItemRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.887097 | 185 | 0.699021 |
ff9ab4fe1e6c137ea4756cb877d7e2e22674b523 | 12,229 | exs | Elixir | apps/blockchain/test/blockchain/transaction_test.exs | atoulme/mana | cff3fd96c23feaaeb9fe32df3c0d35ee6dc548a5 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | apps/blockchain/test/blockchain/transaction_test.exs | atoulme/mana | cff3fd96c23feaaeb9fe32df3c0d35ee6dc548a5 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | apps/blockchain/test/blockchain/transaction_test.exs | atoulme/mana | cff3fd96c23feaaeb9fe32df3c0d35ee6dc548a5 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | defmodule Blockchain.TransactionTest do
use ExUnit.Case, async: true
use EthCommonTest.Harness
doctest Blockchain.Transaction
alias Blockchain.{Account, Chain, Transaction}
alias Blockchain.Account.Repo
alias Blockchain.Transaction.Signature
alias EVM.MachineCode
alias ExthCrypto.Hash.Keccak
alias MerklePatriciaTree.Trie
@forks ~w(
Byzantium
Constantinople
TangerineWhistle
SpuriousDragon
Frontier
Homestead
)
@forks_that_require_chain_id ~w(
Byzantium
Constantinople
EIP158
)
@mainnet_chain_id 1
define_common_tests(
"TransactionTests",
[
ignore: [
"ttWrongRLP/",
"ttSignature/TransactionWithTooFewRLPElements.json",
"ttSignature/TransactionWithTooManyRLPElements.json"
]
],
fn test_name, test_data ->
parsed_test = parse_test(test_data, test_name)
for {fork, test} <- parsed_test.tests_by_fork do
chain_id = chain_id_for_fork(fork)
for {method, value} <- test do
case method do
:hash ->
assert Keccak.kec(parsed_test.rlp) == value
:sender ->
assert Signature.sender(parsed_test.transaction, chain_id) == {:ok, value}
end
end
end
end
)
defp chain_id_for_fork(fork) do
if Enum.member?(@forks_that_require_chain_id, fork) do
@mainnet_chain_id
else
nil
end
end
defp parse_test(test, test_name) do
rlp = test[test_name]["rlp"] |> maybe_hex()
transaction =
rlp
|> ExRLP.decode()
|> Transaction.deserialize()
%{
tests_by_fork: organize_tests_by_fork(test[test_name]),
rlp: rlp,
transaction: transaction
}
end
defp organize_tests_by_fork(tests) do
tests
|> Map.take(@forks)
|> Enum.into(%{}, fn {fork, fork_tests} ->
{
fork,
fork_tests
|> Enum.into(%{}, fn {key_to_test, value} ->
{String.to_atom(key_to_test), maybe_hex(value)}
end)
}
end)
end
describe "when handling transactions" do
test "serialize and deserialize" do
tx = %Transaction{
nonce: 5,
gas_price: 6,
gas_limit: 7,
to: <<1::160>>,
value: 8,
v: 27,
r: 9,
s: 10,
data: "hi"
}
expected_tx =
tx
|> Transaction.serialize()
|> ExRLP.encode()
|> ExRLP.decode()
|> Transaction.deserialize()
assert tx == expected_tx
end
end
describe "input_data/1" do
test "returns the init data when it is a contract creation transaction" do
machine_code = MachineCode.compile([:stop])
tx = %Transaction{to: <<>>, init: machine_code}
assert Transaction.input_data(tx) == machine_code
end
test "returns the data when it is a message call transaction" do
machine_code = MachineCode.compile([:stop])
tx = %Transaction{to: <<1::160>>, data: machine_code}
assert Transaction.input_data(tx) == machine_code
end
end
describe "execute/3" do
test "creates a new contract" do
beneficiary = <<0x05::160>>
private_key = <<1::256>>
# based on simple private key
sender =
<<126, 95, 69, 82, 9, 26, 105, 18, 93, 93, 252, 183, 184, 194, 101, 144, 41, 57, 91, 223>>
contract_address = Account.Address.new(sender, 6)
assembly = [
:push1,
3,
:push1,
5,
:add,
:push1,
0x00,
:mstore,
:push1,
32,
:push1,
0,
:return
]
machine_code = MachineCode.compile(assembly)
unsigned_tx = %Transaction{
nonce: 5,
gas_price: 3,
gas_limit: 100_000,
to: <<>>,
value: 5,
init: machine_code
}
tx = Transaction.Signature.sign_transaction(unsigned_tx, private_key)
chain = Chain.test_config("Frontier")
{account_repo, gas, receipt} =
MerklePatriciaTree.Test.random_ets_db()
|> Trie.new()
|> Account.put_account(sender, %Account{balance: 400_000, nonce: 5})
|> Transaction.execute(tx, %Block.Header{beneficiary: beneficiary}, chain)
state = Repo.commit(account_repo).state
assert gas == 28_180
assert receipt.logs == []
addresses = [sender, beneficiary, contract_address]
actual_accounts = Account.get_accounts(state, addresses)
expected_accounts = [
%Blockchain.Account{balance: 315_455, nonce: 6},
%Blockchain.Account{balance: 84_540},
%Blockchain.Account{
balance: 5,
nonce: 0,
code_hash:
<<243, 247, 169, 254, 54, 79, 170, 185, 59, 33, 109, 165, 10, 50, 20, 21, 79, 34, 160,
162, 180, 21, 178, 58, 132, 200, 22, 158, 139, 99, 110, 227>>
}
]
assert actual_accounts == expected_accounts
end
test "executes a message call to a contract" do
beneficiary = <<0x05::160>>
private_key = <<1::256>>
# based on simple private key
sender =
<<126, 95, 69, 82, 9, 26, 105, 18, 93, 93, 252, 183, 184, 194, 101, 144, 41, 57, 91, 223>>
contract_address = Account.Address.new(sender, 6)
assembly = [
:push1,
3,
:push1,
5,
:add,
:push1,
0x00,
:mstore,
:push1,
0,
:push1,
32,
:return
]
machine_code = MachineCode.compile(assembly)
unsigned_tx = %Transaction{
nonce: 5,
gas_price: 3,
gas_limit: 100_000,
to: contract_address,
value: 5,
data: machine_code
}
tx = Transaction.Signature.sign_transaction(unsigned_tx, private_key)
db = MerklePatriciaTree.Test.random_ets_db()
chain = Chain.test_config("Frontier")
{account_repo, gas, receipt} =
db
|> Trie.new()
|> Account.put_account(sender, %Account{balance: 400_000, nonce: 5})
|> Account.put_code(contract_address, machine_code)
|> Transaction.execute(tx, %Block.Header{beneficiary: beneficiary}, chain)
state = Repo.commit(account_repo).state
assert gas == 21_780
assert receipt.logs == []
addresses = [sender, beneficiary, contract_address]
actual_accounts = Account.get_accounts(state, addresses)
expected_accounts = [
%Account{balance: 334_655, nonce: 6},
%Account{balance: 65_340},
%Account{
balance: 5,
code_hash:
<<216, 114, 80, 103, 17, 50, 164, 75, 162, 123, 123, 99, 162, 105, 226, 15, 215, 200,
136, 216, 29, 106, 193, 119, 1, 173, 138, 37, 219, 39, 23, 231>>
}
]
assert actual_accounts == expected_accounts
end
test "for a transaction with a stop" do
beneficiary_address = <<0x05::160>>
private_key = <<1::256>>
# Based on simple private key.
sender_address =
<<126, 95, 69, 82, 9, 26, 105, 18, 93, 93, 252, 183, 184, 194, 101, 144, 41, 57, 91, 223>>
sender_account = %Account{balance: 400_000, nonce: 5}
contract_address = Account.Address.new(sender_address, 6)
machine_code = MachineCode.compile([:stop])
tx =
%Transaction{
nonce: 5,
gas_price: 3,
gas_limit: 100_000,
to: <<>>,
value: 5,
init: machine_code
}
|> Transaction.Signature.sign_transaction(private_key)
chain = Chain.test_config("Frontier")
{account_repo, gas_used, receipt} =
MerklePatriciaTree.Test.random_ets_db()
|> Trie.new()
|> Account.put_account(sender_address, sender_account)
|> Transaction.execute(tx, %Block.Header{beneficiary: beneficiary_address}, chain)
state = Repo.commit(account_repo).state
expected_sender = %Account{balance: 336_983, nonce: 6}
expected_beneficiary = %Account{balance: 63_012}
expected_contract = %Account{balance: 5, nonce: 0}
assert gas_used == 21_004
assert receipt.logs == []
assert Account.get_account(state, sender_address) == expected_sender
assert Account.get_account(state, beneficiary_address) == expected_beneficiary
assert Account.get_account(state, contract_address) == expected_contract
end
end
describe "execute transaction with revert (Byzantium)" do
test "reverts message call state except for gas used, increments nonce, and marks tx status as failed (0)" do
chain = Chain.test_config("Byzantium")
private_key = <<1::256>>
gas_price = 3
beneficiary = %{address: <<0x05::160>>}
sender = %{
address:
<<126, 95, 69, 82, 9, 26, 105, 18, 93, 93, 252, 183, 184, 194, 101, 144, 41, 57, 91,
223>>,
nonce: 6
}
contract_address = Account.Address.new(sender.address, sender.nonce)
machine_code =
MachineCode.compile([
:push1,
3,
:push1,
5,
:add,
:push1,
0x00,
:revert
])
unsigned_tx = %Transaction{
nonce: 5,
gas_price: gas_price,
gas_limit: 100_000,
to: contract_address,
value: 5,
data: machine_code
}
tx = Transaction.Signature.sign_transaction(unsigned_tx, private_key)
{account_repo, gas, receipt} =
MerklePatriciaTree.Test.random_ets_db()
|> Trie.new()
|> Account.put_account(sender.address, %Account{balance: 400_000, nonce: sender.nonce})
|> Account.put_code(contract_address, machine_code)
|> Transaction.execute(tx, %Block.Header{beneficiary: beneficiary.address}, chain)
state = Repo.commit(account_repo).state
assert gas == 21_495
assert receipt.logs == []
sender_account = Account.get_account(state, sender.address)
beneficiary_account = Account.get_account(state, beneficiary.address)
contract_account = Account.get_account(state, contract_address)
assert sender_account == %Account{
balance: 400_000 - gas * gas_price,
nonce: sender.nonce + 1
}
assert beneficiary_account == %Account{balance: gas * gas_price}
assert contract_account == %Account{balance: 0, code_hash: Keccak.kec(machine_code)}
end
test "reverts contract creation state except for gas used, increments nonce, and marks tx status as failed (0)" do
chain = Chain.test_config("Byzantium")
private_key = <<1::256>>
gas_price = 3
beneficiary = %{address: <<0x05::160>>}
sender = %{
address:
<<126, 95, 69, 82, 9, 26, 105, 18, 93, 93, 252, 183, 184, 194, 101, 144, 41, 57, 91,
223>>,
nonce: 6
}
machine_code =
MachineCode.compile([
:push1,
3,
:push1,
5,
:add,
:push1,
0x00,
:revert
])
unsigned_tx = %Transaction{
nonce: 5,
gas_price: gas_price,
gas_limit: 100_000,
to: <<>>,
value: 5,
init: machine_code
}
tx = Transaction.Signature.sign_transaction(unsigned_tx, private_key)
{account_repo, gas, receipt} =
MerklePatriciaTree.Test.random_ets_db()
|> Trie.new()
|> Account.put_account(sender.address, %Account{balance: 400_000, nonce: sender.nonce})
|> Transaction.execute(tx, %Block.Header{beneficiary: beneficiary.address}, chain)
state = Repo.commit(account_repo).state
assert gas == 53_495
assert receipt.logs == []
sender_account = Account.get_account(state, sender.address)
beneficiary_account = Account.get_account(state, beneficiary.address)
assert sender_account == %Account{
balance: 400_000 - gas * gas_price,
nonce: sender.nonce + 1
}
assert beneficiary_account == %Account{balance: gas * gas_price}
contract_address = Account.Address.new(sender.address, sender.nonce)
assert is_nil(Account.get_account(state, contract_address))
end
end
end
| 26.995585 | 118 | 0.590155 |
ff9ab5bacc3e48c09b1f43bfd5bc1171bcb8132f | 1,342 | ex | Elixir | kousa/lib/broth/message/_types/operator.ex | Bilal-Akkil/dogehouse | 11aebdd1ae7e97732e43e618f0662f2afbee22a6 | [
"MIT"
] | 2 | 2021-05-15T12:46:12.000Z | 2021-05-15T14:15:16.000Z | kousa/lib/broth/message/_types/operator.ex | ActuallyTomas/dogehouse | 8c3d2cd1d7e99e173f0658759467a391c4a90c4e | [
"MIT"
] | null | null | null | kousa/lib/broth/message/_types/operator.ex | ActuallyTomas/dogehouse | 8c3d2cd1d7e99e173f0658759467a391c4a90c4e | [
"MIT"
] | 1 | 2021-05-05T15:57:23.000Z | 2021-05-05T15:57:23.000Z | import EctoEnum
alias Broth.Message.User
alias Broth.Message.Room
alias Broth.Message.Chat
alias Broth.Message.Auth
alias Broth.Message.Misc
defenum(
Broth.Message.Types.Operator,
[
# user commands and casts: 0..63
{User.GetFollowing, 1},
{User.GetFollowers, 2},
{User.Follow, 3},
{User.Ban, 4},
{User.Update, 5},
{User.GetInfo, 6},
{User.GetRelationship, 7},
{User.Block, 10},
{User.Unfollow, 11},
{User.CreateBot, 12},
{User.Unblock, 13},
# room commands and casts: 64..127
{Room.Invite, 65},
{Room.Update, 66},
{Room.GetInviteList, 67},
{Room.Leave, 68},
{Room.Ban, 69},
{Room.SetRole, 70},
{Room.SetAuth, 71},
{Room.Join, 72},
{Room.UpdateScheduled, 74},
{Room.DeleteScheduled, 75},
{Room.Create, 76},
{Room.CreateScheduled, 77},
{Room.Unban, 78},
{Room.GetScheduled, 79},
{Room.GetInfo, 80},
{Room.GetTop, 81},
{Room.SetActiveSpeaker, 82},
{Room.Mute, 83},
{Room.GetBannedUsers, 84},
{Room.Deafen, 85},
# chat commands and casts: 128..191
{Chat.Ban, 129},
{Chat.Send, 130},
{Chat.Delete, 131},
{Chat.Unban, 132},
# auth and maintenance commands 192..254
{Auth.Request, 193},
{Misc.Search, 210},
# etc 255 - 317
{BrothTest.MessageTest.TestOperator, 255}
]
)
| 23.54386 | 45 | 0.607303 |
ff9acc80cadee0173676682c813bfdeaa195be41 | 1,123 | ex | Elixir | lib/camino_challenge_web/controllers/params/ContratoParams.ex | kadmohardy/camino_challenge | 53117f763c0a51b0825cac18b799b7d772781671 | [
"MIT"
] | null | null | null | lib/camino_challenge_web/controllers/params/ContratoParams.ex | kadmohardy/camino_challenge | 53117f763c0a51b0825cac18b799b7d772781671 | [
"MIT"
] | null | null | null | lib/camino_challenge_web/controllers/params/ContratoParams.ex | kadmohardy/camino_challenge | 53117f763c0a51b0825cac18b799b7d772781671 | [
"MIT"
] | null | null | null | defmodule CaminoChallenge.Api.Params.ContratoParams do
alias CaminoChallenge.Validations
require Logger
use Params.Schema, %{
nome: :string,
descricao: :string,
partes: :string,
data: :date,
arquivo: CaminoChallenge.Uploaders.Pdf.Type
}
import Ecto.Changeset
def child(ch, params) do
ch
|> cast(params, [:nome, :descricao, :data, :partes, :arquivo])
|> validate_required([:nome, :descricao, :data, :partes, :arquivo])
|> validate_partes_list()
end
defp validate_partes_list(changeset) do
get_field(changeset, :partes)
|> validate_uuid_partes_list(changeset)
end
defp validate_uuid_partes_list(nil, changeset),
do: add_error(changeset, :partes, "A lista não corresponde a UUIDs validos")
defp validate_uuid_partes_list(uuids, changeset) do
uuids_validation =
Enum.all?(uuids |> String.split(","), fn item ->
Validations.valid_uuid?(item)
end)
IO.puts(uuids_validation)
if uuids_validation do
changeset
else
add_error(changeset, :partes, "A lista não corresponde a UUIDs validos")
end
end
end
| 24.955556 | 80 | 0.690116 |
ff9add1088cf83060ef3ef107189e7ffed22f8f4 | 3,472 | exs | Elixir | test/grizzly/zwave/commands/door_lock_configuration_report_test.exs | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 76 | 2019-09-04T16:56:58.000Z | 2022-03-29T06:54:36.000Z | test/grizzly/zwave/commands/door_lock_configuration_report_test.exs | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 124 | 2019-09-05T14:01:24.000Z | 2022-02-28T22:58:14.000Z | test/grizzly/zwave/commands/door_lock_configuration_report_test.exs | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 10 | 2019-10-23T19:25:45.000Z | 2021-11-17T13:21:20.000Z | defmodule Grizzly.ZWave.Commands.DoorLockConfigurationReportTest do
use ExUnit.Case, async: true
alias Grizzly.ZWave.Commands.DoorLockConfigurationReport
describe "creates the command and validates params" do
test "v1-3" do
params = [
operation_type: :constant_operation,
manual_outside_door_handles: [1, 2],
manual_inside_door_handles: [3, 4],
lock_timeout: 65
]
{:ok, _command} = DoorLockConfigurationReport.new(params)
end
test "v4" do
params = [
operation_type: :constant_operation,
manual_outside_door_handles: [1, 2],
manual_inside_door_handles: [3, 4],
lock_timeout: 65,
auto_relock_time: 125,
hold_and_release_time: 126,
block_to_block?: true,
twist_assist?: false
]
{:ok, _command} = DoorLockConfigurationReport.new(params)
end
end
describe "encodes params correctly" do
test "v1-3" do
params = [
operation_type: :constant_operation,
manual_outside_door_handles: [1, 2],
manual_inside_door_handles: [3, 4],
lock_timeout: 65
]
{:ok, command} = DoorLockConfigurationReport.new(params)
expected_params_binary = DoorLockConfigurationReport.encode_params(command)
assert <<0x01, 0x03::size(4), 0x0C::size(4), 0x01, 0x05>> == expected_params_binary
end
test "v4" do
params = [
operation_type: :constant_operation,
manual_outside_door_handles: [1, 2],
manual_inside_door_handles: [3, 4],
lock_timeout: 65,
auto_relock_time: 125,
hold_and_release_time: 30,
block_to_block?: true,
twist_assist?: false
]
{:ok, command} = DoorLockConfigurationReport.new(params)
expected_params_binary = DoorLockConfigurationReport.encode_params(command)
assert <<0x01, 0x03::size(4), 0x0C::size(4), 0x01, 0x05, 125::integer-unsigned-size(16),
30::integer-unsigned-size(16), 0x00::size(6), 0x01::size(1),
0x00::size(1)>> == expected_params_binary
end
end
describe "decodes params correctly" do
test "v1-3" do
params_binary = <<0x01, 0x03::size(4), 0x0C::size(4), 0x01, 0x05>>
{:ok, params} = DoorLockConfigurationReport.decode_params(params_binary)
assert Keyword.get(params, :operation_type) == :constant_operation
assert Enum.sort(Keyword.get(params, :manual_outside_door_handles)) == [1, 2]
assert Enum.sort(Keyword.get(params, :manual_inside_door_handles)) == [3, 4]
assert Keyword.get(params, :lock_timeout) == 65
end
test "v4" do
params_binary =
<<0x01, 0x03::size(4), 0x0C::size(4), 0x01, 0x05, 125::integer-unsigned-size(16),
30::integer-unsigned-size(16), 0x00::size(6), 0x01::size(1), 0x00::size(1)>>
{:ok, params} = DoorLockConfigurationReport.decode_params(params_binary)
assert Keyword.get(params, :operation_type) == :constant_operation
assert Enum.sort(Keyword.get(params, :manual_outside_door_handles)) == [1, 2]
assert Enum.sort(Keyword.get(params, :manual_inside_door_handles)) == [3, 4]
assert Keyword.get(params, :lock_timeout) == 65
assert Keyword.get(params, :auto_relock_time) == 125
assert Keyword.get(params, :hold_and_release_time) == 30
assert Keyword.get(params, :block_to_block?) == true
assert Keyword.get(params, :twist_assist?) == false
end
end
end
| 36.166667 | 94 | 0.658986 |
ff9af1b559b4e9a61df8fab1fa5752092346a00c | 6,609 | ex | Elixir | lib/evo.ex | cas27/evo | 4ca1945749014917b7a3af870c1cd4db645cb09b | [
"Apache-2.0"
] | 3 | 2016-07-20T22:45:32.000Z | 2017-05-03T17:15:39.000Z | lib/evo.ex | cas27/evo | 4ca1945749014917b7a3af870c1cd4db645cb09b | [
"Apache-2.0"
] | null | null | null | lib/evo.ex | cas27/evo | 4ca1945749014917b7a3af870c1cd4db645cb09b | [
"Apache-2.0"
] | null | null | null | defmodule Evo do
use Application
alias Evo.Cart
alias Evo.Cart.Supervisor, as: CartSupervisor
@doc """
Adds an Ecto.Cart.CartItem to the cart
## Example
iex> cart_id = 101
iex> Evo.create_or_get_cart(cart_id)
iex> item = %Evo.Cart.CartItem{id: "APPL2", name: "Apple",
...> price: 0.20, qty: 2}
iex> {:ok, _} = Evo.add_item(cart_id, item)
iex> item = %{name: "Apple", price: 0.20, qty: 2}
iex> Evo.add_item(cart_id, item)
:error
If you add a duplicate item to your cart it will update the quanity.
**note** To be considered a duplicate item it must have the same `id` and
`meta` also the price of the item will reflect the newest added item
## Example
iex> cart_id = 102
iex> Evo.create_or_get_cart(cart_id)
iex> item1 = %Evo.Cart.CartItem{id: "SKU12", qty: 2, price: 10.50}
iex> item2 = %Evo.Cart.CartItem{id: "SKU12", qty: 2, price: 9.50}
iex> item3 = %Evo.Cart.CartItem{id: "SKU12", qty: 2, price: 11.50,
...> meta: %{extended_warranty: true}}
iex> Evo.add_item(cart_id, item1)
iex> Evo.add_item(cart_id, item2)
iex> Evo.add_item(cart_id, item3)
{:ok, %Evo.Cart{discount: 0.0, total: 61.0, subtotal: 61.0,
items: [
%Evo.Cart.CartItem{id: "SKU12", qty: 2, price: 11.50, name: "",
meta: %{extended_warranty: true}},
%Evo.Cart.CartItem{id: "SKU12", qty: 4, price: 9.50, name: "", meta: %{}}
]}}
"""
def add_item(cart_id, item) do
{:ok, cart_pid} = CartSupervisor.get_cart(cart_id)
Cart.add_item(cart_pid, item)
end
@doc """
Applies an amount discounted from the cart total
## Example
iex> cart_id = 103
iex> Evo.create_or_get_cart(cart_id)
iex> Evo.add_item(cart_id, %Evo.Cart.CartItem{
...> id: "FOO2", name: "Foosball", price: 4.99, qty: 1})
iex> Evo.apply_discount(cart_id, 2.00)
{:ok, %Evo.Cart{discount: 2.00, items: [%Evo.Cart.CartItem{
name: "Foosball", price: 4.99, qty: 1, meta: %{}, id: "FOO2"}],
total: 2.99, subtotal: 2.99}}
"""
def apply_discount(cart_id, discount) do
{:ok, cart_pid} = CartSupervisor.get_cart(cart_id)
Cart.apply_discount(cart_pid, discount)
end
@doc """
Gets the contents of the cart at the given `cart_id`
## Example
iex> cart_id = 104
iex> Evo.create_or_get_cart(cart_id)
iex> Evo.add_item(cart_id, %Evo.Cart.CartItem{
...> id: "APPL2", name: "Apple", price: 0.20, qty: 2})
iex> Evo.cart_contents(cart_id)
{:ok, %Evo.Cart{discount: 0.0, items: [%Evo.Cart.CartItem{name: "Apple",
price: 0.20, qty: 2, meta: %{}, id: "APPL2"}],
total: 0.4, subtotal: 0.4}}
"""
def cart_contents(cart_id) do
{:ok, cart_pid} = CartSupervisor.get_cart(cart_id)
Cart.get_cart(cart_pid)
end
@doc """
Creates a cart given `cart_id` and returns the `pid`
## Examples
iex> cart_id = 105
iex> cart_pid = Evo.create_or_get_cart(cart_id)
iex> is_pid(cart_pid)
true
iex> Evo.create_or_get_cart(cart_id) == cart_pid
true
"""
def create_or_get_cart(cart_id) do
CartSupervisor.create_or_get_cart(cart_id)
end
@doc """
Deletes a cart process given the `cart_id`
## Example
iex> cart_id = 106
iex> Evo.create_or_get_cart(cart_id)
iex> Evo.delete_cart(cart_id)
:ok
iex> Evo.delete_cart(99999999)
{:error, "Cart not found"}
"""
def delete_cart(cart_id), do: CartSupervisor.delete_cart(cart_id)
@doc """
Removes an item from the cart given a `cart_id` and `Evo.Cart.CartItem`
## Example
iex> cart_id = 107
iex> Evo.create_or_get_cart(cart_id)
iex> item1 = %Evo.Cart.CartItem{id: "SKU129", qty: 1}
iex> item2 = %Evo.Cart.CartItem{id: "SKU129", qty: 1,
...> meta: %{personalize: "Jenny"}}
iex> Evo.add_item(cart_id, item1)
iex> Evo.add_item(cart_id, item2)
iex> Evo.remove_item(cart_id, "SKU129")
{:ok ,%Evo.Cart{total: 0.0, discount: 0.0, items: [
%Evo.Cart.CartItem{id: "SKU129", name: "", qty: 1, price: 0.0, meta:
%{personalize: "Jenny"}
}
]}
}
iex> Evo.remove_item(cart_id, "SKU129", %{personalize: "Jenny"})
{:ok ,%Evo.Cart{total: 0.0, discount: 0.0, items: []}}
"""
def remove_item(cart_id, item_id, meta \\ %{}) do
{:ok, cart_pid} = CartSupervisor.get_cart(cart_id)
Cart.remove_item(cart_pid, item_id, meta)
end
@doc """
Updates the quantities of the given items given `cart_id` and list of
`Evo.Cart.CartItem`
## Examples
iex> cart_id = 108
iex> Evo.create_or_get_cart(cart_id)
iex> item = %Evo.Cart.CartItem{id: "SKU55", qty: 5}
iex> item2 = %Evo.Cart.CartItem{id: "SKU56", qty: 5}
iex> Evo.add_item(cart_id, item)
iex> Evo.add_item(cart_id, item2)
iex> Evo.update_quantities(cart_id, [item, item])
{:ok, %Evo.Cart{discount: 0.0, total: 0.0, items: [
%Evo.Cart.CartItem{id: "SKU55", name: "", price: 0.0, qty: 15,
meta: %{}},
%Evo.Cart.CartItem{id: "SKU56", name: "", price: 0.0, qty: 5,
meta: %{}}
]}}
iex> item3 = %Evo.Cart.CartItem{id: "SKU56", qty: -5}
iex> Evo.update_quantities(cart_id, [item3])
{:ok, %Evo.Cart{discount: 0.0, total: 0.0, items: [
%Evo.Cart.CartItem{id: "SKU55", name: "", price: 0.0, qty: 15,
meta: %{}}
]}}
"""
def update_quantities(cart_id, items) when is_list(items) do
{:ok, cart_pid} = CartSupervisor.get_cart(cart_id)
Cart.update_quantities(cart_pid, items)
end
@doc """
Updates the shipping details of the cart
## Example
iex> cart_id = 109
iex> Evo.create_or_get_cart(cart_id)
iex> Evo.add_item(109, %Evo.Cart.CartItem{id: "SKU12", qty: 1, price: 84})
iex> Evo.update_shipping(cart_id,
...> %{carrier: "UPS", class: "Ground", cost: 34.55})
{:ok,
%Evo.Cart{discount: 0.0,
items: [%Evo.Cart.CartItem{id: "SKU12", meta: %{}, name: "", price: 84,
qty: 1}], shipping: %{carrier: "UPS", class: "Ground", cost: 34.55},
total: 118.55, subtotal: 84.0}}
"""
def update_shipping(cart_id, shipping) do
{:ok, cart_pid} = CartSupervisor.get_cart(cart_id)
Cart.update_shipping(cart_pid, shipping)
end
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
supervisor(Evo.Cart.Supervisor, [])
]
opts = [strategy: :one_for_one, name: Evo.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 31.174528 | 81 | 0.605084 |
ff9b01171d116ceeecbc3ad0ccf8bf8b9297a317 | 3,040 | ex | Elixir | lib/cdev/nif.ex | elixir-circuits/circuits_cdev | c78af04742b289d4f791932895ae7bee9d346f68 | [
"Apache-2.0"
] | 10 | 2019-10-21T15:40:36.000Z | 2021-05-04T19:40:09.000Z | lib/cdev/nif.ex | elixir-circuits/circuits_cdev | c78af04742b289d4f791932895ae7bee9d346f68 | [
"Apache-2.0"
] | 4 | 2021-02-27T22:59:55.000Z | 2021-11-22T22:27:22.000Z | lib/cdev/nif.ex | elixir-circuits/circuits_cdev | c78af04742b289d4f791932895ae7bee9d346f68 | [
"Apache-2.0"
] | 4 | 2019-10-21T17:20:20.000Z | 2022-02-19T17:05:40.000Z | defmodule Circuits.Cdev.Nif do
@moduledoc false
# Lower level nif bindings
@on_load {:load_nif, 0}
@compile {:autoload, false}
alias Circuits.Cdev
def load_nif() do
nif_binary = Application.app_dir(:circuits_cdev, "priv/cdev_nif")
:erlang.load_nif(to_charlist(nif_binary), 0)
end
@doc """
Open a GPIO chip
"""
@spec chip_open_nif(charlist()) :: {:ok, reference()} | {:error, atom}
def chip_open_nif(_path) do
:erlang.nif_error(:nif_not_loaded)
end
@doc """
Get the information about a chip
"""
@spec get_chip_info_nif(reference()) ::
{:ok, name :: charlist(), label :: charlist(), num_lines :: non_neg_integer()}
| {:error, atom()}
def get_chip_info_nif(_chip_ref) do
:erlang.nif_error(:nif_not_loaded)
end
@doc """
Get the information about a line
"""
@spec get_line_info_nif(reference(), Cdev.offset()) ::
{:ok, name :: charlist(), consumer :: charlist(), active_low :: non_neg_integer(),
open_drain :: non_neg_integer()}
| {:error, atom()}
def get_line_info_nif(_chip_ref, _offset) do
:erlang.nif_error(:nif_not_loaded)
end
@doc """
Listen for an event
This function requires an event handle and a event data resource.
"""
@spec listen_event_nif(reference(), reference(), reference()) :: :ok | {:error, atom()}
def listen_event_nif(_event_handle, _event_data, _ref) do
:erlang.nif_error(:nif_not_loaded)
end
@doc """
Get an event data resource to be used with for listening for events.
"""
@spec make_event_data_nif(reference()) :: {:ok, reference()} | {:error, atom()}
def make_event_data_nif(_event_handle) do
:erlang.nif_error(:nif_not_loaded)
end
@doc """
Read the event data from the event handle
"""
@spec read_event_data_nif(reference(), reference()) ::
{:ok, value :: non_neg_integer(), timestamp :: non_neg_integer()} | {:error, atom()}
def read_event_data_nif(_event_handle, _event_data) do
:erlang.nif_error(:nif_not_loaded)
end
@doc """
Read a list of values from the line handle
"""
@spec read_values_nif(reference()) :: {:ok, [Cdev.offset_value()]} | {:error, atom()}
def read_values_nif(_line_handle_ref) do
:erlang.nif_error(:nif_not_loaded)
end
@doc """
Request an event handle to be used for listening for events
"""
@spec request_event_nif(reference(), Cdev.offset()) :: {:ok, reference()} | {:error, atom()}
def request_event_nif(_chip_ref, _offset) do
:erlang.nif_error(:nif_not_loaded)
end
@doc """
Request lines to control
"""
@spec request_lines_nif(reference(), [Cdev.offset()], 0 | 1) ::
{:ok, reference()} | {:error, atom()}
def request_lines_nif(_chip_ref, _offset, _direction) do
:erlang.nif_error(:nif_not_loaded)
end
@doc """
Set the values of the GPIO line(s)
"""
@spec set_values_nif(reference(), [Cdev.offset_value()]) :: :ok | {:error, atom()}
def set_values_nif(_handle_ref, _values) do
:erlang.nif_error(:nif_not_loaded)
end
end
| 28.679245 | 94 | 0.6625 |
ff9b1d79126c064b2c7d371f4c36508119ffc05f | 1,152 | ex | Elixir | lib/certbot/provider/static.ex | maartenvanvliet/certbot | 587bb80058d9e204c0e688d74179dadb70862a94 | [
"MIT"
] | 11 | 2019-07-12T17:25:21.000Z | 2021-03-27T21:07:42.000Z | lib/certbot/provider/static.ex | maartenvanvliet/certbot | 587bb80058d9e204c0e688d74179dadb70862a94 | [
"MIT"
] | 37 | 2019-07-19T09:25:22.000Z | 2022-03-24T04:17:25.000Z | lib/certbot/provider/static.ex | maartenvanvliet/certbot | 587bb80058d9e204c0e688d74179dadb70862a94 | [
"MIT"
] | 1 | 2020-01-04T23:48:06.000Z | 2020-01-04T23:48:06.000Z | defmodule Certbot.Provider.Static do
@moduledoc """
Static certificate provider
Expects a `certificates` keyword with a map of hostnames as keys and
`%Certbot.Certificate{}` structs as values.
Also an example of a simple certificate provider.
```elixir
defmodule Myapp.StaticProvider do
use Certbot.Provider.Acme,
certificates: %{
"example.com" => %Certbot.Certificate{
cert: cert_der,
key: {:RSAPrivateKey, key_der}
}
}
end
```
"""
defmacro __using__(opts) do
quote location: :keep do
@behaviour Certbot.Provider
@defaults unquote(opts)
alias Certbot.Provider.Static
def get_by_hostname(hostname, opts \\ []) do
opts = Keyword.merge(@defaults, opts)
Static.get_by_hostname(hostname, opts)
end
end
end
@spec get_by_hostname(binary, keyword) :: nil | Certbot.Certificate.t()
def get_by_hostname(hostname, opts \\ []) do
certificates = Keyword.fetch!(opts, :certificates)
case Map.get(certificates, hostname) do
%Certbot.Certificate{} = certificate -> certificate
_ -> nil
end
end
end
| 24 | 73 | 0.655382 |
ff9b3066dc15961b72a6e2db79db6565c2400472 | 1,366 | exs | Elixir | test/mp_api_web/controllers/password_reset_controller_test.exs | jsvelasquezv/mp_api | 9a2262188b5b12c0e2ecd9284a8e7f445d2be4a0 | [
"MIT"
] | null | null | null | test/mp_api_web/controllers/password_reset_controller_test.exs | jsvelasquezv/mp_api | 9a2262188b5b12c0e2ecd9284a8e7f445d2be4a0 | [
"MIT"
] | null | null | null | test/mp_api_web/controllers/password_reset_controller_test.exs | jsvelasquezv/mp_api | 9a2262188b5b12c0e2ecd9284a8e7f445d2be4a0 | [
"MIT"
] | null | null | null | defmodule MpApiWeb.PasswordResetControllerTest do
use MpApiWeb.ConnCase
import MpApiWeb.AuthCase
setup %{conn: conn} do
add_reset_user("gladys@example.com")
{:ok, %{conn: conn}}
end
test "user can create a password reset request", %{conn: conn} do
valid_attrs = %{email: "gladys@example.com"}
conn = post(conn, password_reset_path(conn, :create), password_reset: valid_attrs)
assert json_response(conn, 201)["info"]["detail"]
end
test "create function fails for no user", %{conn: conn} do
invalid_attrs = %{email: "prettylady@example.com"}
conn = post(conn, password_reset_path(conn, :create), password_reset: invalid_attrs)
assert json_response(conn, 201)["info"]["detail"]
end
test "reset password succeeds for correct key", %{conn: conn} do
valid_attrs = %{email: "gladys@example.com", password: "^hEsdg*F899", key: gen_key("gladys@example.com")}
conn = put(conn, password_reset_path(conn, :update), password_reset: valid_attrs)
assert json_response(conn, 200)["info"]["detail"]
end
test "reset password fails for incorrect key", %{conn: conn} do
invalid_attrs = %{email: "gladys@example.com", password: "^hEsdg*F899", key: "garbage"}
conn = put(conn, password_reset_path(conn, :update), password_reset: invalid_attrs)
assert json_response(conn, 422)["errors"] != %{}
end
end
| 37.944444 | 109 | 0.700586 |
ff9b68433a9a53a08503becfb35b0f324f976eda | 3,202 | ex | Elixir | lib/ucx_chat/emoji_one.ex | smpallen99/ucx_chat | 0dd98d0eb5e0537521844520ea2ba63a08fd3f19 | [
"MIT"
] | 60 | 2017-05-09T19:08:26.000Z | 2021-01-20T11:09:42.000Z | lib/ucx_chat/emoji_one.ex | smpallen99/ucx_chat | 0dd98d0eb5e0537521844520ea2ba63a08fd3f19 | [
"MIT"
] | 6 | 2017-05-10T15:43:16.000Z | 2020-07-15T07:14:41.000Z | lib/ucx_chat/emoji_one.ex | smpallen99/ucx_chat | 0dd98d0eb5e0537521844520ea2ba63a08fd3f19 | [
"MIT"
] | 10 | 2017-05-10T04:13:54.000Z | 2020-12-28T10:30:27.000Z | defmodule EmojiOne do
import EmojiOne.Data
require Logger
@shortname Enum.to_list(?a..?z) ++ Enum.to_list(?A..?Z) ++ Enum.to_list(?0..?9) ++ '-_'
@shortname_regex ~r/^:[a-zA-Z0-9_-]+:$/
@default_src_path "/images"
def shortname_to_image(text, opts \\ []) do
opts = options opts
opts_shortname = options opts, fn opts ->
opts[:single_class] && Regex.match?(@shortname_regex, text) && shortname_unicode()[text]
end
if opts[:ascii] do
do_ascii_to_image(text, opts)
else
text
end
|> parse_shortname("", "", opts_shortname)
end
defp parse_shortname("", "", acc, _),
do: acc
defp parse_shortname("", buffer, acc, _),
do: acc <> buffer
defp parse_shortname(":" <> head, "", acc, opts),
do: parse_shortname(head, ":", acc, opts)
defp parse_shortname(":" <> head, ":" <> buff, acc, opts) do
shortname = ":" <> buff <> ":"
if unicode = shortname_unicode()[shortname] do
hash = shortname_hash()[shortname]
parse_shortname(head, "", acc <> opts[:parser].(shortname, unicode, hash, opts), opts)
else
parse_shortname(head, "", acc <> shortname, opts)
end
end
defp parse_shortname(<<ch::8>> <> head, "", acc, opts),
do: parse_shortname(head, "", acc <> <<ch::8>>, opts)
defp parse_shortname(<<ch::8>> <> head, buff, acc, opts) when ch in @shortname,
do: parse_shortname(head, buff <> <<ch::8>>, acc, opts)
defp parse_shortname(<<ch::8>> <> head, buff, acc, opts),
do: parse_shortname(head, "", acc <> buff <> <<ch::8>>, opts)
def replace_emoji(key, unicode, hash, opts) do
extra_class = if ext = opts[:extra_class], do: " " <> ext, else: ""
id_class = if cls = opts[:id_class], do: " " <> cls <> hash, else: ""
cls = opts[:class] || "emojione"
case opts[:wrapper] do
nil ->
src_path = opts[:src_path] || @default_src_path
src_version = opts[:src_version] || ""
img_type = opts[:img_type] || ".png"
src = src_path <> "/#{hash}" <> img_type <> src_version
~s(<img class="#{cls}#{id_class}#{extra_class}" alt="#{key}" src="#{src}">)
wrapper ->
~s(<#{wrapper} class="#{cls}#{id_class}#{extra_class}" title="#{key}">#{unicode}</#{wrapper}>)
end
end
def ascii_to_image(text, opts \\ []) do
do_ascii_to_image text, options(opts)
end
defp do_ascii_to_image(text, opts) do
keys = ascii_keys()
tokens = String.split(text, " ")
opts = options opts, fn opts ->
opts[:single_class] && length(tokens) == 1
end
tokens
|> Enum.map(fn text ->
if text in keys, do: opts[:parser].(text, ascii_unicode()[text], ascii_hash()[text], opts), else: text
end)
|> Enum.join(" ")
end
defp options(opts) do
:ucx_chat
|> Application.get_env(:emoji_one, [])
|> Enum.into(%{})
|> Map.merge(Enum.into(opts, %{}))
|> Map.put_new(:parser, &replace_emoji/4)
|> Map.put_new(:extra_class, "")
end
defp options(opts, single_fun) do
if single_fun.(opts) do
sc = opts[:single_class] || ""
update_in(opts, [:extra_class], fn
"" -> sc
ext -> ext <> " " <> sc
end)
else
opts
end
end
end
| 30.207547 | 108 | 0.582136 |
ff9b820811cd029b2c6c6aae1fe50b5917929193 | 2,255 | ex | Elixir | clients/gax/lib/google_api/gax/response.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/gax/lib/google_api/gax/response.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/gax/lib/google_api/gax/response.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2018 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.
defmodule GoogleApi.Gax.Response do
@moduledoc """
This module helps decode Tesla responses
"""
@successful_request_response 200..299
alias GoogleApi.Gax.DataWrapper
@doc """
Handle the response for a Tesla request
## Parameters
- response ({:ok, Tesla.Env} | {:error, reason}) - The response object
- struct (struct | false) - The shape of the struct to deserialize into. If false, returns the Tesla response.
- opts (KeywordList) - [optional] Optional parameters
- :dataWrapped (boolean()): If true, the remove the wrapping "data" field. Defaults to false.
- :decode (boolean()): If false, returns the entire reponse. Defaults to true.
- :struct (module)
## Returns
{:ok, struct} on success
{:error, info} on failure
"""
@spec decode({:ok, Tesla.Env.t()}, keyword()) :: {:ok, struct()} | {:error, Tesla.Env.t()}
def decode(env, opts \\ [])
def decode({:error, reason}, _), do: {:error, reason}
def decode({:ok, %Tesla.Env{status: status} = env}, _)
when status not in @successful_request_response do
{:error, env}
end
def decode({:ok, %Tesla.Env{body: body} = env}, opts) do
if Keyword.get(opts, :decode, true) do
data_wrapped = Keyword.get(opts, :data_wrapped, false)
struct = Keyword.get(opts, :struct, nil)
do_decode(body, data_wrapped, struct)
else
{:ok, env}
end
end
defp do_decode(nil, _data_wrapped, _struct) do
{:ok, nil}
end
defp do_decode(body, true, struct) do
Poison.decode(body, as: %DataWrapper{}, struct: struct)
end
defp do_decode(body, _data_wrapped, struct) do
Poison.decode(body, as: struct)
end
end
| 30.890411 | 112 | 0.684701 |
ff9bcd0660503fd49b171f6d2ca1e4af7afd0a60 | 1,522 | ex | Elixir | backend-elixir/apps/pixelflut_canvas/lib/canvas_client.ex | ftsell/pixelflu | 3e8699f11b89f25c683801bda27b7c770ac5b8df | [
"MIT"
] | 7 | 2019-01-16T19:43:25.000Z | 2022-03-23T05:29:07.000Z | backend-elixir/apps/pixelflut_canvas/lib/canvas_client.ex | ftsell/pixelflu | 3e8699f11b89f25c683801bda27b7c770ac5b8df | [
"MIT"
] | 1 | 2021-06-02T11:53:54.000Z | 2021-06-02T11:53:54.000Z | backend-elixir/apps/pixelflut_canvas/lib/canvas_client.ex | ftsell/pixelflu | 3e8699f11b89f25c683801bda27b7c770ac5b8df | [
"MIT"
] | 1 | 2021-10-06T21:18:58.000Z | 2021-10-06T21:18:58.000Z | defmodule PixelflutCanvas.CanvasClient do
@moduledoc false
@doc """
Sets a pixel on the canvas to the specified color.
The color is simply a 3-byte bitstring which gets saved and returned later; it is not
interpreted by the CanvasServer in any way.
Coordinates start at zero and shall not be larger than the canvases width or height.
"""
@spec set_pixel(pid(), number(), number(), bitstring()) :: :ok
def set_pixel(server \\ PixelflutCanvas.CanvasServer, x, y, color) do
GenServer.cast(server, {:set_pixel, [x: x, y: y, color: color]})
end
@doc """
Returns the pixel color at the specified location
"""
@spec get_pixel(pid(), number(), number()) :: {:ok, bitstring()} | {:error, :invalid_coordinates}
def get_pixel(server \\ PixelflutCanvas.CanvasServer, x, y) do
GenServer.call(server, {:get_pixel, [x: x, y: y]})
end
@doc"""
Returns the canvases size as keyword list with :width and :height keys
"""
@spec get_size(pid()) :: [width: number(), height: number()]
def get_size(server \\ PixelflutCanvas.CanvasServer) do
GenServer.call(server, {:get_size})
end
@doc """
Returns the canvas encoded in the specified format.
Since encodings are done in background, the result is not always immediate after having called set_pixel.
"""
@spec get_encoded(pid(), atom()) :: {:ok, bitstring()} | {:error, :invalid_encoding}
def get_encoded(server \\ PixelflutCanvas.CanvasServer, algorithm) do
GenServer.call(server, {:get_encoded, algorithm})
end
end
| 37.121951 | 107 | 0.698423 |
ff9bd11a83de8a7a27af8905733aaca1623115c4 | 2,977 | ex | Elixir | lib/wechat_pay/payment_methods/native.ex | sjava/wechat_pay | 101fd27668f01463d93c1a50033787cfb19bf3e5 | [
"MIT"
] | null | null | null | lib/wechat_pay/payment_methods/native.ex | sjava/wechat_pay | 101fd27668f01463d93c1a50033787cfb19bf3e5 | [
"MIT"
] | null | null | null | lib/wechat_pay/payment_methods/native.ex | sjava/wechat_pay | 101fd27668f01463d93c1a50033787cfb19bf3e5 | [
"MIT"
] | null | null | null | defmodule WechatPay.Native do
@moduledoc """
The **Native** payment method.
[Official document](https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_1)
"""
alias WechatPay.API.Client
alias WechatPay.Config
alias WechatPay.API
import WechatPay.Shared
defmacro __using__(mod) do
quote do
@behaviour WechatPay.Native.Behaviour
defdelegate config, to: unquote(mod)
define_shared_behaviour(WechatPay.Native.Behaviour)
@impl WechatPay.Native.Behaviour
def shorten_url(url), do: WechatPay.Native.shorten_url(url, config())
end
end
@doc """
Place an order
[Official document](https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1)
"""
@spec place_order(map, Config.t()) ::
{:ok, map} | {:error, WechatPay.Error.t() | HTTPoison.Error.t()}
defdelegate place_order(attrs, config), to: API
@doc """
Query the order
[Official document](https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_2)
"""
@spec query_order(map, Configt.t()) ::
{:ok, map} | {:error, WechatPay.Error.t() | HTTPoison.Error.t()}
defdelegate query_order(attrs, config), to: API
@doc """
Close the order
[Official document](https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_3)
"""
@spec close_order(map, Config.t()) ::
{:ok, map} | {:error, WechatPay.Error.t() | HTTPoison.Error.t()}
defdelegate close_order(attrs, config), to: API
@doc """
Request to refund
[Official document](https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_4)
"""
@spec refund(map, Config.t()) ::
{:ok, map} | {:error, WechatPay.Error.t() | HTTPoison.Error.t()}
defdelegate refund(attrs, config), to: API
@doc """
Query the refund
[Official document](https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_5)
"""
@spec query_refund(map, Config.t()) ::
{:ok, map} | {:error, WechatPay.Error.t() | HTTPoison.Error.t()}
defdelegate query_refund(attrs, config), to: API
@doc """
Download bill
[Official document](https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_6)
"""
@spec download_bill(map, Config.t()) :: {:ok, String.t()} | {:error, HTTPoison.Error.t()}
defdelegate download_bill(attrs, config), to: API
@doc """
Report
[Official document](https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_8)
"""
@spec report(map, Config.t()) ::
{:ok, map} | {:error, WechatPay.Error.t() | HTTPoison.Error.t()}
defdelegate report(attrs, config), to: API
@doc """
Shorten the URL to reduce the QR image size
[Official document](https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_9)
"""
@spec shorten_url(
String.t(),
Config.t()
) :: {:ok, String.t()} | {:error, WechatPay.Error.t() | HTTPoison.Error.t()}
def shorten_url(url, config) do
Client.post("tools/shorturl", %{long_url: URI.encode(url)}, [], config)
end
end
| 29.186275 | 91 | 0.649647 |
ff9bdb6035460fd50e50755b30b8e76bff47417f | 3,192 | ex | Elixir | clients/cloud_asset/lib/google_api/cloud_asset/v1/model/google_cloud_asset_v1_big_query_destination.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/cloud_asset/lib/google_api/cloud_asset/v1/model/google_cloud_asset_v1_big_query_destination.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/cloud_asset/lib/google_api/cloud_asset/v1/model/google_cloud_asset_v1_big_query_destination.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudAsset.V1.Model.GoogleCloudAssetV1BigQueryDestination do
@moduledoc """
A BigQuery destination.
## Attributes
* `dataset` (*type:* `String.t`, *default:* `nil`) - Required. The BigQuery dataset in format "projects/projectId/datasets/datasetId", to which the analysis results should be exported. If this dataset does not exist, the export call will return an INVALID_ARGUMENT error.
* `partitionKey` (*type:* `String.t`, *default:* `nil`) - The partition key for BigQuery partitioned table.
* `tablePrefix` (*type:* `String.t`, *default:* `nil`) - Required. The prefix of the BigQuery tables to which the analysis results will be written. Tables will be created based on this table_prefix if not exist: * _analysis table will contain export operation's metadata. * _analysis_result will contain all the IamPolicyAnalysisResult. When [partition_key] is specified, both tables will be partitioned based on the [partition_key].
* `writeDisposition` (*type:* `String.t`, *default:* `nil`) - Optional. Specifies the action that occurs if the destination table or partition already exists. The following values are supported: * WRITE_TRUNCATE: If the table or partition already exists, BigQuery overwrites the entire table or all the partitions data. * WRITE_APPEND: If the table or partition already exists, BigQuery appends the data to the table or the latest partition. * WRITE_EMPTY: If the table already exists and contains data, an error is returned. The default value is WRITE_APPEND. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Details are at https://cloud.google.com/bigquery/docs/loading-data-local#appending_to_or_overwriting_a_table_using_a_local_file.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:dataset => String.t(),
:partitionKey => String.t(),
:tablePrefix => String.t(),
:writeDisposition => String.t()
}
field(:dataset)
field(:partitionKey)
field(:tablePrefix)
field(:writeDisposition)
end
defimpl Poison.Decoder, for: GoogleApi.CloudAsset.V1.Model.GoogleCloudAssetV1BigQueryDestination do
def decode(value, options) do
GoogleApi.CloudAsset.V1.Model.GoogleCloudAssetV1BigQueryDestination.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudAsset.V1.Model.GoogleCloudAssetV1BigQueryDestination do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 57 | 785 | 0.759712 |
ff9be1e87dac7e1f917d4b1b4e0028f26303bdbf | 3,081 | ex | Elixir | lib/pow/phoenix/controllers/registration_controller.ex | dweremeichik/pow | 8c45624c1bf40487680abf5a077549fad2de2141 | [
"MIT"
] | null | null | null | lib/pow/phoenix/controllers/registration_controller.ex | dweremeichik/pow | 8c45624c1bf40487680abf5a077549fad2de2141 | [
"MIT"
] | null | null | null | lib/pow/phoenix/controllers/registration_controller.ex | dweremeichik/pow | 8c45624c1bf40487680abf5a077549fad2de2141 | [
"MIT"
] | null | null | null | defmodule Pow.Phoenix.RegistrationController do
@moduledoc false
use Pow.Phoenix.Controller
alias Plug.Conn
alias Pow.Plug
plug :require_not_authenticated when action in [:new, :create]
plug :require_authenticated when action in [:edit, :update, :delete]
plug :assign_create_path when action in [:new, :create]
plug :assign_update_path when action in [:edit, :update]
@spec process_new(Conn.t(), map()) :: {:ok, map(), Conn.t()}
def process_new(conn, _params) do
{:ok, Plug.change_user(conn), conn}
end
@spec respond_new({:ok, map(), Conn.t()}) :: Conn.t()
def respond_new({:ok, changeset, conn}) do
conn
|> assign(:changeset, changeset)
|> render("new.html")
end
@spec process_create(Conn.t(), map()) :: {:ok | :error, map(), Conn.t()}
def process_create(conn, %{"user" => user_params}) do
Plug.create_user(conn, user_params)
end
@spec respond_create({:ok | :error, map(), Conn.t()}) :: Conn.t()
def respond_create({:ok, _user, conn}) do
conn
|> put_flash(:info, messages(conn).user_has_been_created(conn))
|> redirect(to: routes(conn).after_registration_path(conn))
end
def respond_create({:error, changeset, conn}) do
conn
|> assign(:changeset, changeset)
|> render("new.html")
end
@spec process_edit(Conn.t(), map()) :: {:ok, map(), Conn.t()}
def process_edit(conn, _params) do
{:ok, Plug.change_user(conn), conn}
end
@spec respond_edit({:ok, map(), Conn.t()}) :: Conn.t()
def respond_edit({:ok, changeset, conn}) do
conn
|> assign(:changeset, changeset)
|> render("edit.html")
end
@spec process_update(Conn.t(), map()) :: {:ok | :error, map(), Conn.t()}
def process_update(conn, %{"user" => user_params}) do
Plug.update_user(conn, user_params)
end
@spec respond_update({:ok, map(), Conn.t()}) :: Conn.t()
def respond_update({:ok, _user, conn}) do
conn
|> put_flash(:info, messages(conn).user_has_been_updated(conn))
|> redirect(to: routes(conn).after_user_updated_path(conn))
end
def respond_update({:error, changeset, conn}) do
conn
|> assign(:changeset, changeset)
|> render("edit.html")
end
@spec process_delete(Conn.t(), map()) :: {:ok | :error, map(), Conn.t()}
def process_delete(conn, _params) do
Plug.delete_user(conn)
end
@spec respond_delete({:ok | :error, map(), Conn.t()}) :: Conn.t()
def respond_delete({:ok, _user, conn}) do
conn
|> put_flash(:info, messages(conn).user_has_been_deleted(conn))
|> redirect(to: routes(conn).after_user_deleted_path(conn))
end
def respond_delete({:error, _changeset, conn}) do
conn
|> put_flash(:error, messages(conn).user_could_not_be_deleted(conn))
|> redirect(to: routes(conn).path_for(conn, __MODULE__, :edit))
end
defp assign_create_path(conn, _opts) do
path = routes(conn).path_for(conn, __MODULE__, :create)
Conn.assign(conn, :action, path)
end
defp assign_update_path(conn, _opts) do
path = routes(conn).path_for(conn, __MODULE__, :update)
Conn.assign(conn, :action, path)
end
end
| 31.438776 | 74 | 0.658877 |
ff9beeacb315857d0a780468fa00ebb26dbf64f3 | 711 | ex | Elixir | lib/ex_stone_openbank/api/models/payment_account.ex | polvalente/ex-stone-openbank | f60720abbf755ebf7824fe0de435e47e8cc5c3f5 | [
"Apache-2.0"
] | null | null | null | lib/ex_stone_openbank/api/models/payment_account.ex | polvalente/ex-stone-openbank | f60720abbf755ebf7824fe0de435e47e8cc5c3f5 | [
"Apache-2.0"
] | null | null | null | lib/ex_stone_openbank/api/models/payment_account.ex | polvalente/ex-stone-openbank | f60720abbf755ebf7824fe0de435e47e8cc5c3f5 | [
"Apache-2.0"
] | null | null | null | defmodule ExStoneOpenbank.API.Model.PaymentAccount do
@moduledoc """
PaymentAccount model
"""
use ExStoneOpenbank.Model
@fields [
:account_code,
:branch_code,
:id,
:owner_document,
:owner_id,
:owner_name,
:restricted_features,
:status
]
embedded_schema do
field :account_code, :string
field :branch_code, :string
field :id, Ecto.UUID
field :owner_document, :string
field :owner_id, :string
field :owner_name, :string
field :restricted_features, :boolean
field :status, :string
end
@doc false
def changeset(model \\ %__MODULE__{}, params) do
model
|> cast(params, @fields)
|> validate_required(@fields)
end
end
| 19.75 | 53 | 0.66526 |
ff9c1adeb89fa16ab6ec83aacff948288bcbbb38 | 5,024 | exs | Elixir | test/plug_rest/conn_test.exs | ashishthete/plug_rest | 0dff5e130e3627909df54cb410bb8f891e3fa60c | [
"Apache-2.0"
] | null | null | null | test/plug_rest/conn_test.exs | ashishthete/plug_rest | 0dff5e130e3627909df54cb410bb8f891e3fa60c | [
"Apache-2.0"
] | null | null | null | test/plug_rest/conn_test.exs | ashishthete/plug_rest | 0dff5e130e3627909df54cb410bb8f891e3fa60c | [
"Apache-2.0"
] | null | null | null | defmodule PlugRest.ConnTest do
use ExUnit.Case
use Plug.Test
import PlugRest.Conn
test "parse content type header" do
content_type = "application/json"
actual_header = conn(:post, "/")
|> put_req_header("content-type", content_type)
|> parse_media_type_header("content-type")
expected_header = {"application", "json", %{}}
assert actual_header == expected_header
end
test "parse bad content type header" do
content_type = "application"
parsed = conn(:post, "/")
|> put_req_header("content-type", content_type)
|> parse_media_type_header("content-type")
assert parsed == :error
end
test "parsing charset in content-type should return lower case" do
content_type = "text/plain;charset=UTF-8"
actual_header = conn(:post, "/")
|> put_req_header("content-type", content_type)
|> parse_media_type_header("content-type")
expected_header = {"text", "plain", %{"charset" => "utf-8"}}
assert actual_header == expected_header
end
test "parse content type accept header" do
accept = "text/html,text/html;level=1;q=0.9,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8;text/html;err"
{:ok, actual_media_types} = conn(:get, "/")
|> put_req_header("accept", accept)
|> parse_media_range_header("accept")
expected_media_types = [{{"text", "html", %{}}, 1.0, %{}},
{{"text", "html", %{"level" => "1"}}, 0.9, %{}},
{{"application", "xhtml+xml", %{}}, 1.0, %{}},
{{"application", "xml", %{}}, 0.9, %{}},
{{"*", "*", %{}}, 0.8, %{}}]
assert actual_media_types == expected_media_types
end
test "parse malformed accept header as media range" do
accept = "1"
media_range = conn(:get, "/")
|> put_req_header("accept", accept)
|> parse_media_range_header("accept")
assert media_range == :error
end
test "parse language accept header" do
accept = "da, en-gb;q=0.8, en;q=0.7"
actual_headers = conn(:get, "/")
|> put_req_header("accept-language", accept)
|> parse_quality_header("accept-language")
expected_headers = [{"da", 1.0}, {"en-gb", 0.8}, {"en", 0.7}]
assert actual_headers == expected_headers
end
test "parse charset accept header" do
accept = "iso-8859-5, unicode-1-1;q=0.8"
actual_headers = conn(:get, "/")
|> put_req_header("accept-charset", accept)
|> parse_quality_header("accept-charset")
expected_headers = [{"iso-8859-5", 1.0}, {"unicode-1-1", 0.8}]
assert actual_headers == expected_headers
end
test "parse if-match header" do
if_match = "\"xyzzy\""
actual_headers = conn(:get, "/")
|> put_req_header("if-match", if_match)
|> parse_entity_tag_header("if-match")
expected_headers = [{:strong, "xyzzy"}]
assert actual_headers == expected_headers
end
test "parse multiple if-match values" do
if_match = "\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""
actual_headers = conn(:get, "/")
|> put_req_header("if-match", if_match)
|> parse_entity_tag_header("if-match")
expected_headers = [{:strong, "xyzzy"}, {:strong, "r2d2xxxx"}, {:strong, "c3piozzzz"}]
assert actual_headers == expected_headers
end
test "parse wildcard if-match" do
if_match = "*"
actual_headers = conn(:get, "/")
|> put_req_header("if-match", if_match)
|> parse_entity_tag_header("if-match")
expected_headers = :*
assert actual_headers == expected_headers
end
test "parse strong if-none-match" do
if_none_match = "\"xyzzy\""
actual_headers = conn(:get, "/")
|> put_req_header("if-none-match", if_none_match)
|> parse_entity_tag_header("if-none-match")
expected_headers = [{:strong, "xyzzy"}]
assert actual_headers == expected_headers
end
test "parse weak if-none-match" do
if_none_match = "W/\"xyzzy\""
actual_headers = conn(:get, "/")
|> put_req_header("if-none-match", if_none_match)
|> parse_entity_tag_header("if-none-match")
expected_headers = [{:weak, "xyzzy"}]
assert actual_headers == expected_headers
end
test "parse if-modified-since header" do
if_modified_since = "Sun, 17 Jul 2016 19:54:31 GMT"
actual_headers = conn(:get, "/")
|> put_req_header("if-modified-since", if_modified_since)
|> parse_date_header("if-modified-since")
expected_headers = {{2016, 7, 17}, {19, 54, 31}}
assert actual_headers == expected_headers
end
test "parse if-unmodified-since header" do
if_unmodified_since = "Sun, 17 Jul 2016 19:54:31 GMT"
actual_headers = conn(:get, "/")
|> put_req_header("if-unmodified-since", if_unmodified_since)
|> parse_date_header("if-unmodified-since")
expected_headers = {{2016, 7, 17}, {19, 54, 31}}
assert actual_headers == expected_headers
end
test "parse bad date header" do
if_unmodified_since = "bad"
conn = conn(:get, "/")
|> put_req_header("if-unmodified-since", if_unmodified_since)
assert parse_date_header(conn, "if-unmodified-since") == []
end
end
| 26.723404 | 116 | 0.644307 |
ff9c29b14b480c7a7b3453831fcf596f61cbb96d | 1,243 | ex | Elixir | lib/bootstrap_form/input_builder.ex | feliperenan/bootstrap_form | a12d0665973687bfefeee499f8581398a25ccf75 | [
"MIT"
] | 6 | 2019-02-07T00:37:24.000Z | 2021-05-29T23:37:32.000Z | lib/bootstrap_form/input_builder.ex | feliperenan/bootstrap_form | a12d0665973687bfefeee499f8581398a25ccf75 | [
"MIT"
] | 7 | 2019-02-07T00:19:39.000Z | 2019-11-04T17:01:50.000Z | lib/bootstrap_form/input_builder.ex | feliperenan/bootstrap_form | a12d0665973687bfefeee499f8581398a25ccf75 | [
"MIT"
] | 3 | 2019-10-30T13:49:44.000Z | 2021-09-26T23:45:02.000Z | defmodule BootstrapForm.InputBuilder do
@moduledoc false
@callback build(BootstrapForm.form(), BootstrapForm.field(), Keyword.t()) ::
BootstrapForm.safe_html()
@implementation_types %{
checkbox: BootstrapForm.Checkbox,
email_input: BootstrapForm.EmailInput,
password_input: BootstrapForm.PasswordInput,
radio_button: BootstrapForm.RadioButton,
select: BootstrapForm.Select,
textarea: BootstrapForm.Textarea,
text_input: BootstrapForm.TextInput,
collection_checkboxes: BootstrapForm.CollectionCheckboxes,
collection_radio_buttons: BootstrapForm.CollectionRadioButtons
}
@doc """
Build an input according to the given type.
This function delegates the build for some module listed in @implementation_types. Case an unknow
type is given, an error is going to be raised.
"""
@spec build(
atom,
BootstrapForm.form(),
BootstrapForm.field(),
Keyword.t()
) :: BootstrapForm.safe_html()
def build(type, form, field_name, options \\ []) do
case @implementation_types[type] do
nil -> raise "type: :#{type} is not yet implemented"
implementation -> implementation.build(form, field_name, options)
end
end
end
| 32.710526 | 99 | 0.709574 |
ff9c397a124a59a358f8823eba9db4ec17b788cc | 1,030 | exs | Elixir | issues/test/cli_test.exs | douchuan/elixir_intro | 3c841405740c5842e868e99514ba271dbf6fd95f | [
"MIT"
] | 1 | 2021-09-16T03:32:39.000Z | 2021-09-16T03:32:39.000Z | issues/test/cli_test.exs | douchuan/elixir_intro | 3c841405740c5842e868e99514ba271dbf6fd95f | [
"MIT"
] | null | null | null | issues/test/cli_test.exs | douchuan/elixir_intro | 3c841405740c5842e868e99514ba271dbf6fd95f | [
"MIT"
] | null | null | null | defmodule CliTest do
use ExUnit.Case
import Issues.CLI,
only: [parse_args: 1, sort_into_ascending_order: 1, convert_to_list_of_hashdicts: 1]
test ":help returned by option parsing with -h and --help options" do
assert parse_args(["-h", "anything"]) == :help
assert parse_args(["--help", "anything"]) == :help
end
test "three values returned if three given" do
assert parse_args(["user", "project", "99"]) == {"user", "project", 99}
end
test "count is defaulted if tow values given" do
assert parse_args(["user", "project"]) == {"user", "project", 4}
end
test "sort ascending orders the correct way" do
result =
["c", "a", "b"]
|> fake_created_at_list
|> sort_into_ascending_order
issues = for issue <- result, do: issue["created_at"]
assert issues == ~w{a b c}
end
defp fake_created_at_list(values) do
data =
for value <- values,
do: [{"created_at", value}, {"other_data", "xxx"}]
convert_to_list_of_hashdicts(data)
end
end
| 27.105263 | 88 | 0.640777 |
ff9c813569395fd92c8029122c8bab760e691484 | 45,416 | ex | Elixir | clients/logging/lib/google_api/logging/v2/api/billing_accounts.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/logging/lib/google_api/logging/v2/api/billing_accounts.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/logging/lib/google_api/logging/v2/api/billing_accounts.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.Logging.V2.Api.BillingAccounts do
@moduledoc """
API calls for all endpoints tagged `BillingAccounts`.
"""
alias GoogleApi.Logging.V2.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Creates a new exclusion in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `parent`. Required. The parent resource in which to create the exclusion: \"projects/[PROJECT_ID]\" \"organizations/[ORGANIZATION_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]\" \"folders/[FOLDER_ID]\" Examples: \"projects/my-logging-project\", \"organizations/123456789\".
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :body (LogExclusion):
## Returns
{:ok, %GoogleApi.Logging.V2.Model.LogExclusion{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_exclusions_create(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Logging.V2.Model.LogExclusion.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_exclusions_create(connection, billing_accounts_id, opts \\ []) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/exclusions", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.LogExclusion{})
end
@doc """
Deletes an exclusion.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `name`. Required. The resource name of an existing exclusion to delete: \"projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]\" \"organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]\" \"folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]\" Example: \"projects/my-project-id/exclusions/my-exclusion-id\".
- exclusions_id (String.t): Part of `name`. See documentation of `billingAccountsId`.
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
## Returns
{:ok, %GoogleApi.Logging.V2.Model.Empty{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_exclusions_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Logging.V2.Model.Empty.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_exclusions_delete(
connection,
billing_accounts_id,
exclusions_id,
opts \\ []
) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/exclusions/{exclusionsId}", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id),
"exclusionsId" => URI.encode_www_form(exclusions_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.Empty{})
end
@doc """
Gets the description of an exclusion.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `name`. Required. The resource name of an existing exclusion: \"projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]\" \"organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]\" \"folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]\" Example: \"projects/my-project-id/exclusions/my-exclusion-id\".
- exclusions_id (String.t): Part of `name`. See documentation of `billingAccountsId`.
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
## Returns
{:ok, %GoogleApi.Logging.V2.Model.LogExclusion{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_exclusions_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Logging.V2.Model.LogExclusion.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_exclusions_get(
connection,
billing_accounts_id,
exclusions_id,
opts \\ []
) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/exclusions/{exclusionsId}", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id),
"exclusionsId" => URI.encode_www_form(exclusions_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.LogExclusion{})
end
@doc """
Lists all the exclusions in a parent resource.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `parent`. Required. The parent resource whose exclusions are to be listed. \"projects/[PROJECT_ID]\" \"organizations/[ORGANIZATION_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]\" \"folders/[FOLDER_ID]\"
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :pageToken (String.t): Optional. If present, then retrieve the next batch of results from the preceding call to this method. pageToken must be the value of nextPageToken from the previous response. The values of other method parameters should be identical to those in the previous call.
- :pageSize (integer()): Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of nextPageToken in the response indicates that more results might be available.
## Returns
{:ok, %GoogleApi.Logging.V2.Model.ListExclusionsResponse{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_exclusions_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Logging.V2.Model.ListExclusionsResponse.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_exclusions_list(connection, billing_accounts_id, opts \\ []) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:pageToken => :query,
:pageSize => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/exclusions", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.ListExclusionsResponse{})
end
@doc """
Changes one or more properties of an existing exclusion.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `name`. Required. The resource name of the exclusion to update: \"projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]\" \"organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]\" \"folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]\" Example: \"projects/my-project-id/exclusions/my-exclusion-id\".
- exclusions_id (String.t): Part of `name`. See documentation of `billingAccountsId`.
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :updateMask (String.t): Required. A nonempty list of fields to change in the existing exclusion. New values for the fields are taken from the corresponding fields in the LogExclusion included in this request. Fields not mentioned in update_mask are not changed and are ignored in the request.For example, to change the filter and description of an exclusion, specify an update_mask of \"filter,description\".
- :body (LogExclusion):
## Returns
{:ok, %GoogleApi.Logging.V2.Model.LogExclusion{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_exclusions_patch(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Logging.V2.Model.LogExclusion.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_exclusions_patch(
connection,
billing_accounts_id,
exclusions_id,
opts \\ []
) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/exclusions/{exclusionsId}", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id),
"exclusionsId" => URI.encode_www_form(exclusions_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.LogExclusion{})
end
@doc """
Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `logName`. Required. The resource name of the log to delete: \"projects/[PROJECT_ID]/logs/[LOG_ID]\" \"organizations/[ORGANIZATION_ID]/logs/[LOG_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]\" \"folders/[FOLDER_ID]/logs/[LOG_ID]\" [LOG_ID] must be URL-encoded. For example, \"projects/my-project-id/logs/syslog\", \"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity\". For more information about log names, see LogEntry.
- logs_id (String.t): Part of `logName`. See documentation of `billingAccountsId`.
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
## Returns
{:ok, %GoogleApi.Logging.V2.Model.Empty{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_logs_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Logging.V2.Model.Empty.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_logs_delete(connection, billing_accounts_id, logs_id, opts \\ []) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/logs/{logsId}", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id),
"logsId" => URI.encode_www_form(logs_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.Empty{})
end
@doc """
Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `parent`. Required. The resource name that owns the logs: \"projects/[PROJECT_ID]\" \"organizations/[ORGANIZATION_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]\" \"folders/[FOLDER_ID]\"
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :pageToken (String.t): Optional. If present, then retrieve the next batch of results from the preceding call to this method. pageToken must be the value of nextPageToken from the previous response. The values of other method parameters should be identical to those in the previous call.
- :pageSize (integer()): Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of nextPageToken in the response indicates that more results might be available.
## Returns
{:ok, %GoogleApi.Logging.V2.Model.ListLogsResponse{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_logs_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Logging.V2.Model.ListLogsResponse.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_logs_list(connection, billing_accounts_id, opts \\ []) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:pageToken => :query,
:pageSize => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/logs", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.ListLogsResponse{})
end
@doc """
Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's writer_identity is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `parent`. Required. The resource in which to create the sink: \"projects/[PROJECT_ID]\" \"organizations/[ORGANIZATION_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]\" \"folders/[FOLDER_ID]\" Examples: \"projects/my-logging-project\", \"organizations/123456789\".
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :uniqueWriterIdentity (boolean()): Optional. Determines the kind of IAM identity returned as writer_identity in the new sink. If this value is omitted or set to false, and if the sink's parent is a project, then the value returned as writer_identity is the same group or service account used by Stackdriver Logging before the addition of writer identities to this API. The sink's destination must be in the same project as the sink itself.If this field is set to true, or if the sink is owned by a non-project resource such as an organization, then the value of writer_identity will be a unique service account used only for exports from the new sink. For more information, see writer_identity in LogSink.
- :body (LogSink):
## Returns
{:ok, %GoogleApi.Logging.V2.Model.LogSink{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_sinks_create(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Logging.V2.Model.LogSink.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_sinks_create(connection, billing_accounts_id, opts \\ []) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:uniqueWriterIdentity => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/sinks", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.LogSink{})
end
@doc """
Deletes a sink. If the sink has a unique writer_identity, then that service account is also deleted.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `sinkName`. Required. The full resource name of the sink to delete, including the parent resource and the sink identifier: \"projects/[PROJECT_ID]/sinks/[SINK_ID]\" \"organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]\" \"folders/[FOLDER_ID]/sinks/[SINK_ID]\" Example: \"projects/my-project-id/sinks/my-sink-id\".
- sinks_id (String.t): Part of `sinkName`. See documentation of `billingAccountsId`.
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
## Returns
{:ok, %GoogleApi.Logging.V2.Model.Empty{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_sinks_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Logging.V2.Model.Empty.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_sinks_delete(connection, billing_accounts_id, sinks_id, opts \\ []) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/sinks/{sinksId}", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id),
"sinksId" => URI.encode_www_form(sinks_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.Empty{})
end
@doc """
Gets a sink.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `sinkName`. Required. The resource name of the sink: \"projects/[PROJECT_ID]/sinks/[SINK_ID]\" \"organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]\" \"folders/[FOLDER_ID]/sinks/[SINK_ID]\" Example: \"projects/my-project-id/sinks/my-sink-id\".
- sinks_id (String.t): Part of `sinkName`. See documentation of `billingAccountsId`.
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
## Returns
{:ok, %GoogleApi.Logging.V2.Model.LogSink{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_sinks_get(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Logging.V2.Model.LogSink.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_sinks_get(connection, billing_accounts_id, sinks_id, opts \\ []) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/sinks/{sinksId}", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id),
"sinksId" => URI.encode_www_form(sinks_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.LogSink{})
end
@doc """
Lists sinks.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `parent`. Required. The parent resource whose sinks are to be listed: \"projects/[PROJECT_ID]\" \"organizations/[ORGANIZATION_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]\" \"folders/[FOLDER_ID]\"
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :pageToken (String.t): Optional. If present, then retrieve the next batch of results from the preceding call to this method. pageToken must be the value of nextPageToken from the previous response. The values of other method parameters should be identical to those in the previous call.
- :pageSize (integer()): Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of nextPageToken in the response indicates that more results might be available.
## Returns
{:ok, %GoogleApi.Logging.V2.Model.ListSinksResponse{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_sinks_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Logging.V2.Model.ListSinksResponse.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_sinks_list(connection, billing_accounts_id, opts \\ []) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:pageToken => :query,
:pageSize => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/sinks", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.ListSinksResponse{})
end
@doc """
Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: destination, and filter. The updated sink might also have a new writer_identity; see the unique_writer_identity field.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `sinkName`. Required. The full resource name of the sink to update, including the parent resource and the sink identifier: \"projects/[PROJECT_ID]/sinks/[SINK_ID]\" \"organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]\" \"folders/[FOLDER_ID]/sinks/[SINK_ID]\" Example: \"projects/my-project-id/sinks/my-sink-id\".
- sinks_id (String.t): Part of `sinkName`. See documentation of `billingAccountsId`.
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :uniqueWriterIdentity (boolean()): Optional. See sinks.create for a description of this field. When updating a sink, the effect of this field on the value of writer_identity in the updated sink depends on both the old and new values of this field: If the old and new values of this field are both false or both true, then there is no change to the sink's writer_identity. If the old value is false and the new value is true, then writer_identity is changed to a unique service account. It is an error if the old value is true and the new value is set to false or defaulted to false.
- :updateMask (String.t): Optional. Field mask that specifies the fields in sink that need an update. A sink field will be overwritten if, and only if, it is in the update mask. name and output only fields cannot be updated.An empty updateMask is temporarily treated as using the following mask for backwards compatibility purposes: destination,filter,includeChildren At some point in the future, behavior will be removed and specifying an empty updateMask will be an error.For a detailed FieldMask definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmaskExample: updateMask=filter.
- :body (LogSink):
## Returns
{:ok, %GoogleApi.Logging.V2.Model.LogSink{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_sinks_patch(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Logging.V2.Model.LogSink.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_sinks_patch(connection, billing_accounts_id, sinks_id, opts \\ []) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:uniqueWriterIdentity => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/sinks/{sinksId}", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id),
"sinksId" => URI.encode_www_form(sinks_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.LogSink{})
end
@doc """
Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: destination, and filter. The updated sink might also have a new writer_identity; see the unique_writer_identity field.
## Parameters
- connection (GoogleApi.Logging.V2.Connection): Connection to server
- billing_accounts_id (String.t): Part of `sinkName`. Required. The full resource name of the sink to update, including the parent resource and the sink identifier: \"projects/[PROJECT_ID]/sinks/[SINK_ID]\" \"organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]\" \"billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]\" \"folders/[FOLDER_ID]/sinks/[SINK_ID]\" Example: \"projects/my-project-id/sinks/my-sink-id\".
- sinks_id (String.t): Part of `sinkName`. See documentation of `billingAccountsId`.
- opts (KeywordList): [optional] Optional parameters
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :uniqueWriterIdentity (boolean()): Optional. See sinks.create for a description of this field. When updating a sink, the effect of this field on the value of writer_identity in the updated sink depends on both the old and new values of this field: If the old and new values of this field are both false or both true, then there is no change to the sink's writer_identity. If the old value is false and the new value is true, then writer_identity is changed to a unique service account. It is an error if the old value is true and the new value is set to false or defaulted to false.
- :updateMask (String.t): Optional. Field mask that specifies the fields in sink that need an update. A sink field will be overwritten if, and only if, it is in the update mask. name and output only fields cannot be updated.An empty updateMask is temporarily treated as using the following mask for backwards compatibility purposes: destination,filter,includeChildren At some point in the future, behavior will be removed and specifying an empty updateMask will be an error.For a detailed FieldMask definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmaskExample: updateMask=filter.
- :body (LogSink):
## Returns
{:ok, %GoogleApi.Logging.V2.Model.LogSink{}} on success
{:error, info} on failure
"""
@spec logging_billing_accounts_sinks_update(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Logging.V2.Model.LogSink.t()} | {:error, Tesla.Env.t()}
def logging_billing_accounts_sinks_update(connection, billing_accounts_id, sinks_id, opts \\ []) do
optional_params = %{
:access_token => :query,
:key => :query,
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:uniqueWriterIdentity => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/v2/billingAccounts/{billingAccountsId}/sinks/{sinksId}", %{
"billingAccountsId" => URI.encode_www_form(billing_accounts_id),
"sinksId" => URI.encode_www_form(sinks_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Logging.V2.Model.LogSink{})
end
end
| 54.390419 | 719 | 0.689493 |
ff9cadb85983b0bb15c1fec2f20da8b4fb3c532a | 587 | exs | Elixir | src/004/p004.exs | murilocamargos/polyglot-euler | cbc48d2542a3c44b2fa2714decad961be6074233 | [
"MIT"
] | null | null | null | src/004/p004.exs | murilocamargos/polyglot-euler | cbc48d2542a3c44b2fa2714decad961be6074233 | [
"MIT"
] | null | null | null | src/004/p004.exs | murilocamargos/polyglot-euler | cbc48d2542a3c44b2fa2714decad961be6074233 | [
"MIT"
] | null | null | null | #!/usr/bin/env elixir
defmodule Problem004 do
defp reverse_number(x) do
x
|> Integer.to_string()
|> String.reverse()
|> String.to_integer()
end
defp is_palindrome(x), do: x == reverse_number(x)
defp get_palindrome_multiples(x, a, b) do
a..b
|> Stream.map(&(&1 * x))
|> Stream.filter(&is_palindrome(&1))
|> Enum.to_list()
end
def solve do
100..999
|> Stream.map(&get_palindrome_multiples(&1, 100, 999))
|> Enum.to_list()
|> List.flatten()
|> Enum.max()
end
end
IO.puts Problem004.solve
| 20.241379 | 59 | 0.579216 |
ff9d6faf49e9118de834a0199ba9dccda434d7b0 | 8,752 | ex | Elixir | lib/surface.ex | mathewdgardner/surface | cd01707b5bd383fb6d1337dc55f0b9b4014581d7 | [
"MIT"
] | null | null | null | lib/surface.ex | mathewdgardner/surface | cd01707b5bd383fb6d1337dc55f0b9b4014581d7 | [
"MIT"
] | null | null | null | lib/surface.ex | mathewdgardner/surface | cd01707b5bd383fb6d1337dc55f0b9b4014581d7 | [
"MIT"
] | 1 | 2020-04-21T18:49:15.000Z | 2020-04-21T18:49:15.000Z | defmodule Surface do
@moduledoc """
Surface is component based library for **Phoenix LiveView**.
Built on top of the new `Phoenix.LiveComponent` API, Surface provides
a more declarative way to express and use components in Phoenix.
Full documentation and live examples can be found at [surface-demo.msaraiva.io](http://surface-demo.msaraiva.io)
This module defines the `~H` sigil that should be used to translate Surface
code into Phoenix templates.
In order to have `~H` available for any Phoenix view, add the following import to your web
file in `lib/my_app_web.ex`:
# lib/my_app_web.ex
...
def view do
quote do
...
import Surface
end
end
## Defining components
To create a component you need to define a module and `use` one of the available component types:
* `Surface.Component` - A stateless component.
* `Surface.LiveComponent` - A live stateful component.
* `Surface.LiveView` - A wrapper component around `Phoenix.LiveView`.
* `Surface.MacroComponent` - A low-level component which is responsible for translating its own content at compile time.
### Example
# A functional stateless component
defmodule Button do
use Surface.Component
property click, :event
property kind, :string, default: "is-info"
def render(assigns) do
~H"\""
<button class="button {{ @kind }}" phx-click={{ @click }}>
<slot/>
</button>
"\""
end
end
You can visit the documentation of each type of component for further explanation and examples.
"""
@doc """
Translates Surface code into Phoenix templates.
"""
defmacro sigil_H({:<<>>, _, [string]}, _) do
line_offset = __CALLER__.line + 1
string
|> Surface.Translator.run(line_offset, __CALLER__, __CALLER__.file)
|> EEx.compile_string(
engine: Phoenix.LiveView.Engine,
line: line_offset,
file: __CALLER__.file
)
end
@doc false
def component(module, assigns) do
module.render(assigns)
end
def component(module, assigns, []) do
module.render(assigns)
end
@doc false
def put_default_props(props, mod) do
Enum.reduce(mod.__props__(), props, fn %{name: name, opts: opts}, acc ->
default = Keyword.get(opts, :default)
Map.put_new(acc, name, default)
end)
end
@doc false
def begin_context(props, current_context, mod) do
assigns = put_gets_into_assigns(props, current_context, mod.__context_gets__())
initialized_context_assigns =
with true <- function_exported?(mod, :init_context, 1),
{:ok, values} <- mod.init_context(assigns) do
Map.new(values)
else
false ->
[]
{:error, message} ->
runtime_error(message)
result ->
runtime_error(
"unexpected return value from init_context/1. " <>
"Expected {:ok, keyword()} | {:error, String.t()}, got: #{inspect(result)}"
)
end
{assigns, new_context} =
put_sets_into_assigns_and_context(
assigns,
current_context,
initialized_context_assigns,
mod.__context_sets__()
)
assigns = Map.put(assigns, :__surface_context__, new_context)
{assigns, new_context}
end
@doc false
def end_context(context, mod) do
Enum.reduce(mod.__context_sets__(), context, fn %{name: name, opts: opts}, acc ->
to = Keyword.fetch!(opts, :to)
context_entry = acc |> Map.get(to, %{}) |> Map.delete(name)
if context_entry == %{} do
Map.delete(acc, to)
else
Map.put(acc, to, context_entry)
end
end)
end
@doc false
def attr_value(attr, value) do
if String.Chars.impl_for(value) do
value
else
runtime_error(
"invalid value for attribute \"#{attr}\". Expected a type that implements " <>
"the String.Chars protocol (e.g. string, boolean, integer, atom, ...), " <>
"got: #{inspect(value)}"
)
end
end
@doc false
def style(value, show) when is_binary(value) do
if show do
quot(value)
else
semicolon = if String.ends_with?(value, ";") || value == "", do: "", else: ";"
quot([value, semicolon, "display: none;"])
end
end
def style(value, _show) do
runtime_error(
"invalid value for attribute \"style\". Expected a string " <>
"got: #{inspect(value)}"
)
end
@doc false
def css_class(list) when is_list(list) do
Enum.reduce(list, [], fn item, classes ->
case item do
{class, true} ->
[to_string(class) | classes]
class when is_binary(class) or is_atom(class) ->
[to_string(class) | classes]
_ ->
classes
end
end)
|> Enum.reverse()
|> Enum.join(" ")
end
def css_class(value) when is_binary(value) do
value
end
@doc false
def boolean_attr(name, value) do
if value do
name
else
""
end
end
@doc false
def event_value(key, [event], caller_cid) do
event_value(key, event, caller_cid)
end
def event_value(key, [name | opts], caller_cid) do
event = Map.new(opts) |> Map.put(:name, name)
event_value(key, event, caller_cid)
end
def event_value(_key, nil, _caller_cid) do
nil
end
def event_value(_key, name, nil) when is_binary(name) do
%{name: name, target: :live_view}
end
def event_value(_key, name, caller_cid) when is_binary(name) do
%{name: name, target: to_string(caller_cid)}
end
def event_value(_key, %{name: _, target: _} = event, _caller_cid) do
event
end
def event_value(key, event, _caller_cid) do
runtime_error(
"invalid value for event \"#{key}\". Expected an :event or :string, got: #{inspect(event)}"
)
end
@doc false
def on_phx_event(phx_event, [event], caller_cid) do
on_phx_event(phx_event, event, caller_cid)
end
def on_phx_event(phx_event, [event | opts], caller_cid) do
value = Map.new(opts) |> Map.put(:name, event)
on_phx_event(phx_event, value, caller_cid)
end
def on_phx_event(phx_event, %{name: name, target: :live_view}, _caller_cid) do
[phx_event, "=", quot(name)]
end
def on_phx_event(phx_event, %{name: name, target: target}, _caller_cid) do
[phx_event, "=", quot(name), " phx-target=", quot(target)]
end
# Stateless component or a liveview (no caller_id)
def on_phx_event(phx_event, event, nil) when is_binary(event) do
[phx_event, "=", quot(event)]
end
def on_phx_event(phx_event, event, caller_cid) when is_binary(event) do
[phx_event, "=", quot(event), " phx-target=", to_string(caller_cid)]
end
def on_phx_event(_phx_event, nil, _caller_cid) do
[]
end
def on_phx_event(phx_event, event, _caller_cid) do
runtime_error(
"invalid value for \":on-#{phx_event}\". " <>
"Expected a :string or :event, got: #{inspect(event)}"
)
end
@doc false
def phx_event(_phx_event, value) when is_binary(value) do
value
end
def phx_event(phx_event, value) do
runtime_error(
"invalid value for \"#{phx_event}\". LiveView bindings only accept values " <>
"of type :string. If you want to pass an :event, please use directive " <>
":on-#{phx_event} instead. Expected a :string, got: #{inspect(value)}"
)
end
defp quot(value) do
[{:safe, "\""}, value, {:safe, "\""}]
end
defp runtime_error(message) do
stacktrace =
self()
|> Process.info(:current_stacktrace)
|> elem(1)
|> Enum.drop(2)
reraise(message, stacktrace)
end
defp put_gets_into_assigns(assigns, context, gets) do
Enum.reduce(gets, assigns, fn %{name: name, opts: opts}, acc ->
key = Keyword.get(opts, :as, name)
from = Keyword.fetch!(opts, :from)
# TODO: raise an error if it's required and it hasn't been set
value = context[from][name]
Map.put_new(acc, key, value)
end)
end
defp put_sets_into_assigns_and_context(assigns, context, values, sets) do
Enum.reduce(sets, {assigns, context}, fn %{name: name, opts: opts}, {assigns, context} ->
to = Keyword.fetch!(opts, :to)
scope = Keyword.get(opts, :scope)
case Map.fetch(values, name) do
{:ok, value} ->
new_context_entry =
context
|> Map.get(to, %{})
|> Map.put(name, value)
new_context = Map.put(context, to, new_context_entry)
new_assigns =
if scope == :only_children, do: assigns, else: Map.put(assigns, name, value)
{new_assigns, new_context}
:error ->
{assigns, context}
end
end)
end
end
| 26.361446 | 124 | 0.622029 |
ff9d7ac2c7baec6a52eab2d339bd4c9589d8f17c | 120,869 | ex | Elixir | clients/classroom/lib/google_api/classroom/v1/api/courses.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/classroom/lib/google_api/classroom/v1/api/courses.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/classroom/lib/google_api/classroom/v1/api/courses.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.Classroom.V1.Api.Courses do
@moduledoc """
API calls for all endpoints tagged `Courses`.
"""
alias GoogleApi.Classroom.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Creates an alias for a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create the alias or for access errors. * `NOT_FOUND` if the course does not exist. * `ALREADY_EXISTS` if the alias already exists. * `FAILED_PRECONDITION` if the alias requested does not make sense for the requesting user or course (for example, if a user not in a domain attempts to access a domain-scoped alias).
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course to alias. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (CourseAlias):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.CourseAlias{}} on success
{:error, info} on failure
"""
@spec classroom_courses_aliases_create(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.CourseAlias.t()} | {:error, Tesla.Env.t()}
def classroom_courses_aliases_create(connection, course_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/courses/{courseId}/aliases", %{
"courseId" => URI.encode_www_form(course_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.CourseAlias{})
end
@doc """
Deletes an alias of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to remove the alias or for access errors. * `NOT_FOUND` if the alias does not exist. * `FAILED_PRECONDITION` if the alias requested does not make sense for the requesting user or course (for example, if a user not in a domain attempts to delete a domain-scoped alias).
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course whose alias should be deleted. This identifier can be either the Classroom-assigned identifier or an alias.
- alias (String.t): Alias to delete. This may not be the Classroom-assigned identifier.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec classroom_courses_aliases_delete(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def classroom_courses_aliases_delete(connection, course_id, alias, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/courses/{courseId}/aliases/{alias}", %{
"courseId" => URI.encode_www_form(course_id),
"alias" => URI.encode_www_form(alias)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Empty{})
end
@doc """
Returns a list of aliases for a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the course or for access errors. * `NOT_FOUND` if the course does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): The identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :pageToken (String.t): nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token.
- :pageSize (integer()): Maximum number of items to return. Zero or unspecified indicates that the server may assign a maximum. The server may return fewer than the specified number of results.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.ListCourseAliasesResponse{}} on success
{:error, info} on failure
"""
@spec classroom_courses_aliases_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.ListCourseAliasesResponse.t()}
| {:error, Tesla.Env.t()}
def classroom_courses_aliases_list(connection, course_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:pageToken => :query,
:pageSize => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses/{courseId}/aliases", %{
"courseId" => URI.encode_www_form(course_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.ListCourseAliasesResponse{})
end
@doc """
Creates an announcement. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course, create announcements in the requested course, share a Drive attachment, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course does not exist. * `FAILED_PRECONDITION` for the following request error: * AttachmentNotVisible
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (Announcement):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Announcement{}} on success
{:error, info} on failure
"""
@spec classroom_courses_announcements_create(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Announcement.t()} | {:error, Tesla.Env.t()}
def classroom_courses_announcements_create(connection, course_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/courses/{courseId}/announcements", %{
"courseId" => URI.encode_www_form(course_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Announcement{})
end
@doc """
Deletes an announcement. This request must be made by the Developer Console project of the [OAuth client ID](https://support.google.com/cloud/answer/6158849) used to create the corresponding announcement item. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting developer project did not create the corresponding announcement, if the requesting user is not permitted to delete the requested course or for access errors. * `FAILED_PRECONDITION` if the requested announcement has already been deleted. * `NOT_FOUND` if no course exists with the requested ID.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- id (String.t): Identifier of the announcement to delete. This identifier is a Classroom-assigned identifier.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec classroom_courses_announcements_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Classroom.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def classroom_courses_announcements_delete(connection, course_id, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/courses/{courseId}/announcements/{id}", %{
"courseId" => URI.encode_www_form(course_id),
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Empty{})
end
@doc """
Returns an announcement. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or announcement, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course or announcement does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- id (String.t): Identifier of the announcement.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Announcement{}} on success
{:error, info} on failure
"""
@spec classroom_courses_announcements_get(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Announcement.t()} | {:error, Tesla.Env.t()}
def classroom_courses_announcements_get(connection, course_id, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses/{courseId}/announcements/{id}", %{
"courseId" => URI.encode_www_form(course_id),
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Announcement{})
end
@doc """
Returns a list of announcements that the requester is permitted to view. Course students may only view `PUBLISHED` announcements. Course teachers and domain administrators may view all announcements. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :announcementStates ([String.t]): Restriction on the `state` of announcements returned. If this argument is left unspecified, the default value is `PUBLISHED`.
- :orderBy (String.t): Optional sort ordering for results. A comma-separated list of fields with an optional sort direction keyword. Supported field is `updateTime`. Supported direction keywords are `asc` and `desc`. If not specified, `updateTime desc` is the default behavior. Examples: `updateTime asc`, `updateTime`
- :pageToken (String.t): nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token.
- :pageSize (integer()): Maximum number of items to return. Zero or unspecified indicates that the server may assign a maximum. The server may return fewer than the specified number of results.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.ListAnnouncementsResponse{}} on success
{:error, info} on failure
"""
@spec classroom_courses_announcements_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.ListAnnouncementsResponse.t()}
| {:error, Tesla.Env.t()}
def classroom_courses_announcements_list(connection, course_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:announcementStates => :query,
:orderBy => :query,
:pageToken => :query,
:pageSize => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses/{courseId}/announcements", %{
"courseId" => URI.encode_www_form(course_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.ListAnnouncementsResponse{})
end
@doc """
Modifies assignee mode and options of an announcement. Only a teacher of the course that contains the announcement may call this method. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or course work or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course or course work does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- id (String.t): Identifier of the announcement.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (ModifyAnnouncementAssigneesRequest):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Announcement{}} on success
{:error, info} on failure
"""
@spec classroom_courses_announcements_modify_assignees(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Classroom.V1.Model.Announcement.t()} | {:error, Tesla.Env.t()}
def classroom_courses_announcements_modify_assignees(connection, course_id, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/courses/{courseId}/announcements/{id}:modifyAssignees", %{
"courseId" => URI.encode_www_form(course_id),
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Announcement{})
end
@doc """
Updates one or more fields of an announcement. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting developer project did not create the corresponding announcement or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `FAILED_PRECONDITION` if the requested announcement has already been deleted. * `NOT_FOUND` if the requested course or announcement does not exist
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- id (String.t): Identifier of the announcement.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :updateMask (String.t): Mask that identifies which fields on the announcement to update. This field is required to do an update. The update fails if invalid fields are specified. If a field supports empty values, it can be cleared by specifying it in the update mask and not in the Announcement object. If a field that does not support empty values is included in the update mask and not set in the Announcement object, an `INVALID_ARGUMENT` error will be returned. The following fields may be specified by teachers: * `text` * `state` * `scheduled_time`
- :body (Announcement):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Announcement{}} on success
{:error, info} on failure
"""
@spec classroom_courses_announcements_patch(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Classroom.V1.Model.Announcement.t()} | {:error, Tesla.Env.t()}
def classroom_courses_announcements_patch(connection, course_id, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/courses/{courseId}/announcements/{id}", %{
"courseId" => URI.encode_www_form(course_id),
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Announcement{})
end
@doc """
Creates course work. The resulting course work (and corresponding student submissions) are associated with the Developer Console project of the [OAuth client ID](https://support.google.com/cloud/answer/6158849) used to make the request. Classroom API requests to modify course work and student submissions must be made with an OAuth client ID from the associated Developer Console project. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course, create course work in the requested course, share a Drive attachment, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course does not exist. * `FAILED_PRECONDITION` for the following request error: * AttachmentNotVisible
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (CourseWork):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.CourseWork{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_create(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.CourseWork.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_create(connection, course_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/courses/{courseId}/courseWork", %{
"courseId" => URI.encode_www_form(course_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.CourseWork{})
end
@doc """
Deletes a course work. This request must be made by the Developer Console project of the [OAuth client ID](https://support.google.com/cloud/answer/6158849) used to create the corresponding course work item. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting developer project did not create the corresponding course work, if the requesting user is not permitted to delete the requested course or for access errors. * `FAILED_PRECONDITION` if the requested course work has already been deleted. * `NOT_FOUND` if no course exists with the requested ID.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- id (String.t): Identifier of the course work to delete. This identifier is a Classroom-assigned identifier.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Classroom.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_delete(connection, course_id, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/courses/{courseId}/courseWork/{id}", %{
"courseId" => URI.encode_www_form(course_id),
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Empty{})
end
@doc """
Returns course work. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or course work, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course or course work does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- id (String.t): Identifier of the course work.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.CourseWork{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_get(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.CourseWork.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_get(connection, course_id, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses/{courseId}/courseWork/{id}", %{
"courseId" => URI.encode_www_form(course_id),
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.CourseWork{})
end
@doc """
Returns a list of course work that the requester is permitted to view. Course students may only view `PUBLISHED` course work. Course teachers and domain administrators may view all course work. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :orderBy (String.t): Optional sort ordering for results. A comma-separated list of fields with an optional sort direction keyword. Supported fields are `updateTime` and `dueDate`. Supported direction keywords are `asc` and `desc`. If not specified, `updateTime desc` is the default behavior. Examples: `dueDate asc,updateTime desc`, `updateTime,dueDate desc`
- :pageToken (String.t): nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token.
- :pageSize (integer()): Maximum number of items to return. Zero or unspecified indicates that the server may assign a maximum. The server may return fewer than the specified number of results.
- :courseWorkStates ([String.t]): Restriction on the work status to return. Only courseWork that matches is returned. If unspecified, items with a work status of `PUBLISHED` is returned.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.ListCourseWorkResponse{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.ListCourseWorkResponse.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_list(connection, course_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:orderBy => :query,
:pageToken => :query,
:pageSize => :query,
:courseWorkStates => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses/{courseId}/courseWork", %{
"courseId" => URI.encode_www_form(course_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.ListCourseWorkResponse{})
end
@doc """
Modifies assignee mode and options of a coursework. Only a teacher of the course that contains the coursework may call this method. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or course work or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course or course work does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- id (String.t): Identifier of the coursework.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (ModifyCourseWorkAssigneesRequest):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.CourseWork{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_modify_assignees(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Classroom.V1.Model.CourseWork.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_modify_assignees(connection, course_id, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/courses/{courseId}/courseWork/{id}:modifyAssignees", %{
"courseId" => URI.encode_www_form(course_id),
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.CourseWork{})
end
@doc """
Updates one or more fields of a course work. See google.classroom.v1.CourseWork for details of which fields may be updated and who may change them. This request must be made by the Developer Console project of the [OAuth client ID](https://support.google.com/cloud/answer/6158849) used to create the corresponding course work item. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting developer project did not create the corresponding course work, if the user is not permitted to make the requested modification to the student submission, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `FAILED_PRECONDITION` if the requested course work has already been deleted. * `NOT_FOUND` if the requested course, course work, or student submission does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- id (String.t): Identifier of the course work.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :updateMask (String.t): Mask that identifies which fields on the course work to update. This field is required to do an update. The update fails if invalid fields are specified. If a field supports empty values, it can be cleared by specifying it in the update mask and not in the CourseWork object. If a field that does not support empty values is included in the update mask and not set in the CourseWork object, an `INVALID_ARGUMENT` error will be returned. The following fields may be specified by teachers: * `title` * `description` * `state` * `due_date` * `due_time` * `max_points` * `scheduled_time` * `submission_modification_mode`
- :body (CourseWork):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.CourseWork{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_patch(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.CourseWork.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_patch(connection, course_id, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/courses/{courseId}/courseWork/{id}", %{
"courseId" => URI.encode_www_form(course_id),
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.CourseWork{})
end
@doc """
Returns a student submission. * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course, course work, or student submission or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course, course work, or student submission does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- course_work_id (String.t): Identifier of the course work.
- id (String.t): Identifier of the student submission.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.StudentSubmission{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_student_submissions_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Classroom.V1.Model.StudentSubmission.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_student_submissions_get(
connection,
course_id,
course_work_id,
id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}",
%{
"courseId" => URI.encode_www_form(course_id),
"courseWorkId" => URI.encode_www_form(course_work_id),
"id" => URI.encode_www_form(id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.StudentSubmission{})
end
@doc """
Returns a list of student submissions that the requester is permitted to view, factoring in the OAuth scopes of the request. `-` may be specified as the `course_work_id` to include student submissions for multiple course work items. Course students may only view their own work. Course teachers and domain administrators may view all student submissions. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or course work, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- course_work_id (String.t): Identifier of the student work to request. This may be set to the string literal `\"-\"` to request student work for all course work in the specified course.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :userId (String.t): Optional argument to restrict returned student work to those owned by the student with the specified identifier. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `\"me\"`, indicating the requesting user
- :late (String.t): Requested lateness value. If specified, returned student submissions are restricted by the requested value. If unspecified, submissions are returned regardless of `late` value.
- :pageToken (String.t): nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token.
- :pageSize (integer()): Maximum number of items to return. Zero or unspecified indicates that the server may assign a maximum. The server may return fewer than the specified number of results.
- :states ([String.t]): Requested submission states. If specified, returned student submissions match one of the specified submission states.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.ListStudentSubmissionsResponse{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_student_submissions_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.Classroom.V1.Model.ListStudentSubmissionsResponse.t()}
| {:error, Tesla.Env.t()}
def classroom_courses_course_work_student_submissions_list(
connection,
course_id,
course_work_id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:userId => :query,
:late => :query,
:pageToken => :query,
:pageSize => :query,
:states => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions", %{
"courseId" => URI.encode_www_form(course_id),
"courseWorkId" => URI.encode_www_form(course_work_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.ListStudentSubmissionsResponse{})
end
@doc """
Modifies attachments of student submission. Attachments may only be added to student submissions belonging to course work objects with a `workType` of `ASSIGNMENT`. This request must be made by the Developer Console project of the [OAuth client ID](https://support.google.com/cloud/answer/6158849) used to create the corresponding course work item. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or course work, if the user is not permitted to modify attachments on the requested student submission, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course, course work, or student submission does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- course_work_id (String.t): Identifier of the course work.
- id (String.t): Identifier of the student submission.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (ModifyAttachmentsRequest):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.StudentSubmission{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_student_submissions_modify_attachments(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Classroom.V1.Model.StudentSubmission.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_student_submissions_modify_attachments(
connection,
course_id,
course_work_id,
id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}:modifyAttachments",
%{
"courseId" => URI.encode_www_form(course_id),
"courseWorkId" => URI.encode_www_form(course_work_id),
"id" => URI.encode_www_form(id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.StudentSubmission{})
end
@doc """
Updates one or more fields of a student submission. See google.classroom.v1.StudentSubmission for details of which fields may be updated and who may change them. This request must be made by the Developer Console project of the [OAuth client ID](https://support.google.com/cloud/answer/6158849) used to create the corresponding course work item. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting developer project did not create the corresponding course work, if the user is not permitted to make the requested modification to the student submission, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course, course work, or student submission does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- course_work_id (String.t): Identifier of the course work.
- id (String.t): Identifier of the student submission.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :updateMask (String.t): Mask that identifies which fields on the student submission to update. This field is required to do an update. The update fails if invalid fields are specified. The following fields may be specified by teachers: * `draft_grade` * `assigned_grade`
- :body (StudentSubmission):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.StudentSubmission{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_student_submissions_patch(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Classroom.V1.Model.StudentSubmission.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_student_submissions_patch(
connection,
course_id,
course_work_id,
id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url(
"/v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}",
%{
"courseId" => URI.encode_www_form(course_id),
"courseWorkId" => URI.encode_www_form(course_work_id),
"id" => URI.encode_www_form(id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.StudentSubmission{})
end
@doc """
Reclaims a student submission on behalf of the student that owns it. Reclaiming a student submission transfers ownership of attached Drive files to the student and update the submission state. Only the student that owns the requested student submission may call this method, and only for a student submission that has been turned in. This request must be made by the Developer Console project of the [OAuth client ID](https://support.google.com/cloud/answer/6158849) used to create the corresponding course work item. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or course work, unsubmit the requested student submission, or for access errors. * `FAILED_PRECONDITION` if the student submission has not been turned in. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course, course work, or student submission does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- course_work_id (String.t): Identifier of the course work.
- id (String.t): Identifier of the student submission.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (ReclaimStudentSubmissionRequest):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_student_submissions_reclaim(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Classroom.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_student_submissions_reclaim(
connection,
course_id,
course_work_id,
id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}:reclaim",
%{
"courseId" => URI.encode_www_form(course_id),
"courseWorkId" => URI.encode_www_form(course_work_id),
"id" => URI.encode_www_form(id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Empty{})
end
@doc """
Returns a student submission. Returning a student submission transfers ownership of attached Drive files to the student and may also update the submission state. Unlike the Classroom application, returning a student submission does not set assignedGrade to the draftGrade value. Only a teacher of the course that contains the requested student submission may call this method. This request must be made by the Developer Console project of the [OAuth client ID](https://support.google.com/cloud/answer/6158849) used to create the corresponding course work item. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or course work, return the requested student submission, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course, course work, or student submission does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- course_work_id (String.t): Identifier of the course work.
- id (String.t): Identifier of the student submission.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (ReturnStudentSubmissionRequest):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_student_submissions_return(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Classroom.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_student_submissions_return(
connection,
course_id,
course_work_id,
id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}:return",
%{
"courseId" => URI.encode_www_form(course_id),
"courseWorkId" => URI.encode_www_form(course_work_id),
"id" => URI.encode_www_form(id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Empty{})
end
@doc """
Turns in a student submission. Turning in a student submission transfers ownership of attached Drive files to the teacher and may also update the submission state. This may only be called by the student that owns the specified student submission. This request must be made by the Developer Console project of the [OAuth client ID](https://support.google.com/cloud/answer/6158849) used to create the corresponding course work item. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or course work, turn in the requested student submission, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course, course work, or student submission does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- course_work_id (String.t): Identifier of the course work.
- id (String.t): Identifier of the student submission.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (TurnInStudentSubmissionRequest):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec classroom_courses_course_work_student_submissions_turn_in(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Classroom.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def classroom_courses_course_work_student_submissions_turn_in(
connection,
course_id,
course_work_id,
id,
opts \\ []
) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}:turnIn",
%{
"courseId" => URI.encode_www_form(course_id),
"courseWorkId" => URI.encode_www_form(course_work_id),
"id" => URI.encode_www_form(id)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Empty{})
end
@doc """
Creates a course. The user specified in `ownerId` is the owner of the created course and added as a teacher. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create courses or for access errors. * `NOT_FOUND` if the primary teacher is not a valid user. * `FAILED_PRECONDITION` if the course owner's account is disabled or for the following request errors: * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if an alias was specified in the `id` and already exists.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (Course):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Course{}} on success
{:error, info} on failure
"""
@spec classroom_courses_create(Tesla.Env.client(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Course.t()} | {:error, Tesla.Env.t()}
def classroom_courses_create(connection, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/courses")
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Course{})
end
@doc """
Deletes a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- id (String.t): Identifier of the course to delete. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec classroom_courses_delete(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def classroom_courses_delete(connection, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/courses/{id}", %{
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Empty{})
end
@doc """
Returns a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- id (String.t): Identifier of the course to return. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Course{}} on success
{:error, info} on failure
"""
@spec classroom_courses_get(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Course.t()} | {:error, Tesla.Env.t()}
def classroom_courses_get(connection, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses/{id}", %{
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Course{})
end
@doc """
Returns a list of courses that the requesting user is permitted to view, restricted to those that match the request. Returned courses are ordered by creation time, with the most recently created coming first. This method returns the following error codes: * `PERMISSION_DENIED` for access errors. * `INVALID_ARGUMENT` if the query argument is malformed. * `NOT_FOUND` if any users specified in the query arguments do not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :studentId (String.t): Restricts returned courses to those having a student with the specified identifier. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `\"me\"`, indicating the requesting user
- :pageToken (String.t): nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token.
- :pageSize (integer()): Maximum number of items to return. Zero or unspecified indicates that the server may assign a maximum. The server may return fewer than the specified number of results.
- :teacherId (String.t): Restricts returned courses to those having a teacher with the specified identifier. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `\"me\"`, indicating the requesting user
- :courseStates ([String.t]): Restricts returned courses to those in one of the specified states The default value is ACTIVE, ARCHIVED, PROVISIONED, DECLINED.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.ListCoursesResponse{}} on success
{:error, info} on failure
"""
@spec classroom_courses_list(Tesla.Env.client(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.ListCoursesResponse.t()} | {:error, Tesla.Env.t()}
def classroom_courses_list(connection, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:studentId => :query,
:pageToken => :query,
:pageSize => :query,
:teacherId => :query,
:courseStates => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses")
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.ListCoursesResponse{})
end
@doc """
Updates one or more fields in a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to modify the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. * `INVALID_ARGUMENT` if invalid fields are specified in the update mask or if no update mask is supplied. * `FAILED_PRECONDITION` for the following request errors: * CourseNotModifiable
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- id (String.t): Identifier of the course to update. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :updateMask (String.t): Mask that identifies which fields on the course to update. This field is required to do an update. The update will fail if invalid fields are specified. The following fields are valid: * `name` * `section` * `descriptionHeading` * `description` * `room` * `courseState` * `ownerId` Note: patches to ownerId are treated as being effective immediately, but in practice it may take some time for the ownership transfer of all affected resources to complete. When set in a query parameter, this field should be specified as `updateMask=<field1>,<field2>,...`
- :body (Course):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Course{}} on success
{:error, info} on failure
"""
@spec classroom_courses_patch(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Course.t()} | {:error, Tesla.Env.t()}
def classroom_courses_patch(connection, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/courses/{id}", %{
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Course{})
end
@doc """
Adds a user as a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create students in this course or for access errors. * `NOT_FOUND` if the requested course ID does not exist. * `FAILED_PRECONDITION` if the requested user's account is disabled, for the following request errors: * CourseMemberLimitReached * CourseNotModifiable * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if the user is already a student or teacher in the course.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course to create the student in. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :enrollmentCode (String.t): Enrollment code of the course to create the student in. This code is required if userId corresponds to the requesting user; it may be omitted if the requesting user has administrative permissions to create students for any user.
- :body (Student):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Student{}} on success
{:error, info} on failure
"""
@spec classroom_courses_students_create(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Student.t()} | {:error, Tesla.Env.t()}
def classroom_courses_students_create(connection, course_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:enrollmentCode => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/courses/{courseId}/students", %{
"courseId" => URI.encode_www_form(course_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Student{})
end
@doc """
Deletes a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete students of this course or for access errors. * `NOT_FOUND` if no student of this course has the requested ID or if the course does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- user_id (String.t): Identifier of the student to delete. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `\"me\"`, indicating the requesting user
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec classroom_courses_students_delete(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def classroom_courses_students_delete(connection, course_id, user_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/courses/{courseId}/students/{userId}", %{
"courseId" => URI.encode_www_form(course_id),
"userId" => URI.encode_www_form(user_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Empty{})
end
@doc """
Returns a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to view students of this course or for access errors. * `NOT_FOUND` if no student of this course has the requested ID or if the course does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- user_id (String.t): Identifier of the student to return. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `\"me\"`, indicating the requesting user
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Student{}} on success
{:error, info} on failure
"""
@spec classroom_courses_students_get(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Student.t()} | {:error, Tesla.Env.t()}
def classroom_courses_students_get(connection, course_id, user_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses/{courseId}/students/{userId}", %{
"courseId" => URI.encode_www_form(course_id),
"userId" => URI.encode_www_form(user_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Student{})
end
@doc """
Returns a list of students of this course that the requester is permitted to view. This method returns the following error codes: * `NOT_FOUND` if the course does not exist. * `PERMISSION_DENIED` for access errors.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :pageToken (String.t): nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token.
- :pageSize (integer()): Maximum number of items to return. Zero means no maximum. The server may return fewer than the specified number of results.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.ListStudentsResponse{}} on success
{:error, info} on failure
"""
@spec classroom_courses_students_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.ListStudentsResponse.t()} | {:error, Tesla.Env.t()}
def classroom_courses_students_list(connection, course_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:pageToken => :query,
:pageSize => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses/{courseId}/students", %{
"courseId" => URI.encode_www_form(course_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.ListStudentsResponse{})
end
@doc """
Creates a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create teachers in this course or for access errors. * `NOT_FOUND` if the requested course ID does not exist. * `FAILED_PRECONDITION` if the requested user's account is disabled, for the following request errors: * CourseMemberLimitReached * CourseNotModifiable * CourseTeacherLimitReached * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if the user is already a teacher or student in the course.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (Teacher):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Teacher{}} on success
{:error, info} on failure
"""
@spec classroom_courses_teachers_create(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Teacher.t()} | {:error, Tesla.Env.t()}
def classroom_courses_teachers_create(connection, course_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/courses/{courseId}/teachers", %{
"courseId" => URI.encode_www_form(course_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Teacher{})
end
@doc """
Deletes a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete teachers of this course or for access errors. * `NOT_FOUND` if no teacher of this course has the requested ID or if the course does not exist. * `FAILED_PRECONDITION` if the requested ID belongs to the primary teacher of this course.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- user_id (String.t): Identifier of the teacher to delete. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `\"me\"`, indicating the requesting user
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec classroom_courses_teachers_delete(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def classroom_courses_teachers_delete(connection, course_id, user_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/courses/{courseId}/teachers/{userId}", %{
"courseId" => URI.encode_www_form(course_id),
"userId" => URI.encode_www_form(user_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Empty{})
end
@doc """
Returns a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to view teachers of this course or for access errors. * `NOT_FOUND` if no teacher of this course has the requested ID or if the course does not exist.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- user_id (String.t): Identifier of the teacher to return. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `\"me\"`, indicating the requesting user
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Teacher{}} on success
{:error, info} on failure
"""
@spec classroom_courses_teachers_get(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Teacher.t()} | {:error, Tesla.Env.t()}
def classroom_courses_teachers_get(connection, course_id, user_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses/{courseId}/teachers/{userId}", %{
"courseId" => URI.encode_www_form(course_id),
"userId" => URI.encode_www_form(user_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Teacher{})
end
@doc """
Returns a list of teachers of this course that the requester is permitted to view. This method returns the following error codes: * `NOT_FOUND` if the course does not exist. * `PERMISSION_DENIED` for access errors.
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- course_id (String.t): Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :pageToken (String.t): nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token.
- :pageSize (integer()): Maximum number of items to return. Zero means no maximum. The server may return fewer than the specified number of results.
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.ListTeachersResponse{}} on success
{:error, info} on failure
"""
@spec classroom_courses_teachers_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.ListTeachersResponse.t()} | {:error, Tesla.Env.t()}
def classroom_courses_teachers_list(connection, course_id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:pageToken => :query,
:pageSize => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/courses/{courseId}/teachers", %{
"courseId" => URI.encode_www_form(course_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.ListTeachersResponse{})
end
@doc """
Updates a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to modify the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. * `FAILED_PRECONDITION` for the following request errors: * CourseNotModifiable
## Parameters
- connection (GoogleApi.Classroom.V1.Connection): Connection to server
- id (String.t): Identifier of the course to update. This identifier can be either the Classroom-assigned identifier or an alias.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :access_token (String.t): OAuth access token.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :body (Course):
## Returns
{:ok, %GoogleApi.Classroom.V1.Model.Course{}} on success
{:error, info} on failure
"""
@spec classroom_courses_update(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Classroom.V1.Model.Course.t()} | {:error, Tesla.Env.t()}
def classroom_courses_update(connection, id, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:quotaUser => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:oauth_token => :query,
:"$.xgafv" => :query,
:alt => :query,
:access_token => :query,
:key => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/v1/courses/{id}", %{
"id" => URI.encode_www_form(id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Classroom.V1.Model.Course{})
end
end
| 53.434571 | 999 | 0.683095 |
ff9d7dce852db4ed2937b7df930b58e24f95dd6c | 1,846 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_webhook_request_fulfillment_info.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_webhook_request_fulfillment_info.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_webhook_request_fulfillment_info.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.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3WebhookRequestFulfillmentInfo do
@moduledoc """
Represents fulfillment information communicated to the webhook.
## Attributes
* `tag` (*type:* `String.t`, *default:* `nil`) - Always present. The value of the Fulfillment.tag field will be populated in this field by Dialogflow when the associated webhook is called. The tag is typically used by the webhook service to identify which fulfillment is being called, but it could be used for other purposes.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:tag => String.t() | nil
}
field(:tag)
end
defimpl Poison.Decoder,
for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3WebhookRequestFulfillmentInfo do
def decode(value, options) do
GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3WebhookRequestFulfillmentInfo.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3WebhookRequestFulfillmentInfo do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.5 | 329 | 0.761105 |
ff9dd924fd059718bc1c09ab815ab876a8ad3fb8 | 840 | exs | Elixir | test/advent_of_code_2019/cli_test.exs | scorphus/advent-of-code-2019 | 48305ff3b13b23cac60bed02349775d8feb05a3b | [
"BSD-3-Clause"
] | null | null | null | test/advent_of_code_2019/cli_test.exs | scorphus/advent-of-code-2019 | 48305ff3b13b23cac60bed02349775d8feb05a3b | [
"BSD-3-Clause"
] | null | null | null | test/advent_of_code_2019/cli_test.exs | scorphus/advent-of-code-2019 | 48305ff3b13b23cac60bed02349775d8feb05a3b | [
"BSD-3-Clause"
] | null | null | null | defmodule AdventOfCode2019.CLITest do
use ExUnit.Case
import Mock
test "AdventOfCode2019.CLI.main halts" do
with_mock System, halt: fn code -> code end do
with_mock IO, puts: fn _data -> :ok end do
assert AdventOfCode2019.CLI.main([]) == 1
assert_called(IO.puts(:_))
end
end
end
test "AdventOfCode2019.CLI.main runs stream_lines" do
with_mock AdventOfCode2019,
stream_lines: fn _in_stream, _day_part -> :ok end do
with_mock IO,
puts: fn data -> data end,
stream: fn _stdio, _line -> ["much", "lines"] end do
assert AdventOfCode2019.CLI.main(["1", "2"]) == :ok
assert_called(IO.stream(:stdio, :line))
assert_called(IO.puts(:ok))
assert_called(AdventOfCode2019.stream_lines(["much", "lines"], "1.2"))
end
end
end
end
| 28.965517 | 78 | 0.633333 |
ff9df538db826e09f6de11a7afeff59114168d85 | 318 | ex | Elixir | lib/messengyr/web/controllers/user_controller.ex | josecarlo-macariola/messengyr | b0d141b3665b22be1efd740fde823c20e2ee9615 | [
"Unlicense"
] | null | null | null | lib/messengyr/web/controllers/user_controller.ex | josecarlo-macariola/messengyr | b0d141b3665b22be1efd740fde823c20e2ee9615 | [
"Unlicense"
] | null | null | null | lib/messengyr/web/controllers/user_controller.ex | josecarlo-macariola/messengyr | b0d141b3665b22be1efd740fde823c20e2ee9615 | [
"Unlicense"
] | null | null | null | defmodule Messengyr.Web.UserController do
use Messengyr.Web, :controller
alias Messengyr.Accounts
action_fallback Messengyr.Web.FallbackController
def show(conn, %{"id" => user_id}) do
user = Accounts.get_user(user_id)
if user do
render(conn, "show.json", user: user)
end
end
end
| 18.705882 | 50 | 0.694969 |
ff9e3e44aacc9fe3adc58926fe66adb9c9dfba25 | 518 | ex | Elixir | lib/parse_helpers/unwrap.ex | kianmeng/url | e65a0f3cff4bea203c7965d4d7c4cf612169d726 | [
"Apache-2.0"
] | 13 | 2018-11-26T09:08:52.000Z | 2022-01-21T10:21:35.000Z | lib/parse_helpers/unwrap.ex | kianmeng/url | e65a0f3cff4bea203c7965d4d7c4cf612169d726 | [
"Apache-2.0"
] | 1 | 2021-05-11T18:48:26.000Z | 2021-05-11T18:48:26.000Z | lib/parse_helpers/unwrap.ex | kipcole9/url | 0840f51a96f618b0123bdf33cebcaac517b830e3 | [
"Apache-2.0"
] | null | null | null | defmodule URL.ParseHelpers.Unwrap do
@moduledoc false
@doc false
def unwrap({:ok, acc, "", _, _, _}) when is_list(acc) do
{:ok, acc}
end
@doc false
def unwrap({:error, reason, rest, _, {line, _}, _offset}) do
{:error, {URL.Parser.ParseError, "#{reason}. Detected on line #{inspect line} at #{inspect(rest, printable_limit: 20)}"}}
end
@doc false
def unwrap({:ok, acc, rest, _, _, _}) when is_list(acc) do
{:error, {URL.Parser.ParseError, "Error detected at #{inspect rest}"}}
end
end | 28.777778 | 125 | 0.638996 |
ff9e5265e1a211e3facb269e6e99012cf8f77052 | 3,288 | ex | Elixir | lib/fn/api/routes.ex | fnproject/fn_elixir | 9f3361b251b41b92284ca86cbd02d60753a26d55 | [
"Apache-2.0"
] | 2 | 2017-10-07T09:09:50.000Z | 2018-01-31T13:36:17.000Z | lib/fn/api/routes.ex | fnproject/fn_elixir | 9f3361b251b41b92284ca86cbd02d60753a26d55 | [
"Apache-2.0"
] | null | null | null | lib/fn/api/routes.ex | fnproject/fn_elixir | 9f3361b251b41b92284ca86cbd02d60753a26d55 | [
"Apache-2.0"
] | null | null | null | defmodule Fn.Api.Routes do
@moduledoc """
Documentation for Fn.Api.Routes.
"""
use Tesla
plug Tesla.Middleware.BaseUrl, "https://127.0.0.1:8080/v1"
plug Tesla.Middleware.JSON
@doc """
Get route list by app name.
This will list routes for a particular app, returned in alphabetical order.
"""
def apps_app_routes_get(app, image, cursor, per_page) do
method = [method: :get]
url = [url: "/apps/#{app}/routes"]
query_params = [query: [{:"image", image}, {:"cursor", cursor}, {:"per_page", per_page}]]
header_params = []
body_params = []
form_params = []
params = query_params ++ header_params ++ body_params ++ form_params
opts = []
options = method ++ url ++ params ++ opts
request(options)
end
@doc """
Create new Route
Create a new route in an app, if app doesn't exists, it creates the app. Post does not skip validation of zero values.
"""
def apps_app_routes_post(app, body) do
method = [method: :post]
url = [url: "/apps/#{app}/routes"]
query_params = []
header_params = []
body_params = [body: body]
form_params = []
params = query_params ++ header_params ++ body_params ++ form_params
opts = []
options = method ++ url ++ params ++ opts
request(options)
end
@doc """
Deletes the route
Deletes the route.
"""
def apps_app_routes_route_delete(app, route) do
method = [method: :delete]
url = [url: "/apps/{app}/routes/#{route}"]
query_params = []
header_params = []
body_params = []
form_params = []
params = query_params ++ header_params ++ body_params ++ form_params
opts = []
options = method ++ url ++ params ++ opts
request(options)
end
@doc """
Gets route by name
Gets a route by name.
"""
def apps_app_routes_route_get(app, route) do
method = [method: :get]
url = [url: "/apps/{app}/routes/#{route}"]
query_params = []
header_params = []
body_params = []
form_params = []
params = query_params ++ header_params ++ body_params ++ form_params
opts = []
options = method ++ url ++ params ++ opts
request(options)
end
@doc """
Update a Route, Fails if the route or app does not exist. Accepts partial updates / skips validation of zero values.
Update a route
"""
def apps_app_routes_route_patch(app, route, body) do
method = [method: :patch]
url = [url: "/apps/{app}/routes/#{route}"]
query_params = []
header_params = []
body_params = [body: body]
form_params = []
params = query_params ++ header_params ++ body_params ++ form_params
opts = []
options = method ++ url ++ params ++ opts
request(options)
end
@doc """
Create a Route if it does not exist. Update if it does. Will also create app if it does not exist. Put does not skip validation of zero values
Update or Create a route
"""
def apps_app_routes_route_put(app, route, body) do
method = [method: :put]
url = [url: "/apps/{app}/routes/#{route}"]
query_params = []
header_params = []
body_params = [body: body]
form_params = []
params = query_params ++ header_params ++ body_params ++ form_params
opts = []
options = method ++ url ++ params ++ opts
request(options)
end
end
| 26.304 | 144 | 0.626825 |
ff9e6fa0be347524eccb005e8ab7368a61602aa7 | 353 | exs | Elixir | priv/repo/seeds.exs | cciuenf/lovelaceccuenf_bot | 22a9d4e25d59cf3e5f1de4c4de8e257a6b44fba9 | [
"MIT"
] | null | null | null | priv/repo/seeds.exs | cciuenf/lovelaceccuenf_bot | 22a9d4e25d59cf3e5f1de4c4de8e257a6b44fba9 | [
"MIT"
] | null | null | null | priv/repo/seeds.exs | cciuenf/lovelaceccuenf_bot | 22a9d4e25d59cf3e5f1de4c4de8e257a6b44fba9 | [
"MIT"
] | null | null | null | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Lovelace.Repo.insert!(%Lovelace.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 29.416667 | 61 | 0.708215 |
ff9e8a27a9a87d18d6f8457b7314cded51354c10 | 1,008 | ex | Elixir | hexdocs__pm__phoenix__up_and_running.html/hello/lib/hello_web/controllers/page_controller.ex | jim80net/elixir_tutorial_projects | db19901a9305b297faa90642bebcc08455621b52 | [
"Unlicense"
] | null | null | null | hexdocs__pm__phoenix__up_and_running.html/hello/lib/hello_web/controllers/page_controller.ex | jim80net/elixir_tutorial_projects | db19901a9305b297faa90642bebcc08455621b52 | [
"Unlicense"
] | null | null | null | hexdocs__pm__phoenix__up_and_running.html/hello/lib/hello_web/controllers/page_controller.ex | jim80net/elixir_tutorial_projects | db19901a9305b297faa90642bebcc08455621b52 | [
"Unlicense"
] | null | null | null | defmodule HelloWeb.PageController do
use HelloWeb, :controller
def index(conn, %{"_format" => "json"}) do
pages = [%{title: "foo"}, %{title: "bar"}]
render(conn, :index, pages: pages)
end
def index(conn, %{"just_status" => "true"}) do
conn
|> put_resp_content_type("text/plain")
|> send_resp(201, "")
end
def index(conn, %{"redirect" => "true"}) do
redirect(conn, to: Routes.page_path(conn, :redirect_test))
end
def index(conn, %{"redirect" => "external"}) do
redirect(conn, external: "https://hexdocs.pm/phoenix/controllers.html#content")
end
def index(conn, _params) do
pages = [%{title: "foo"}, %{title: "bar"}]
render(conn, :index, pages: pages)
end
def index_admin(conn, _params) do
conn
|> put_layout("admin.html")
|> render("index.html")
end
def redirect_test(conn, _params) do
render(conn, :index)
end
def show(conn, _params) do
page = %{title: "foo"}
render(conn, "show.json", page: page)
end
end
| 23.44186 | 83 | 0.621032 |
ff9e8db64b59cc714c115d0065ac2be11a248185 | 505 | ex | Elixir | learningElixir/lib/learningElixir_web/views/error_view.ex | Maxweston/learning-elixir | 7b80372d25410377404ddb55632f35e964b42c1a | [
"MIT"
] | null | null | null | learningElixir/lib/learningElixir_web/views/error_view.ex | Maxweston/learning-elixir | 7b80372d25410377404ddb55632f35e964b42c1a | [
"MIT"
] | null | null | null | learningElixir/lib/learningElixir_web/views/error_view.ex | Maxweston/learning-elixir | 7b80372d25410377404ddb55632f35e964b42c1a | [
"MIT"
] | null | null | null | defmodule LearningElixirWeb.ErrorView do
use LearningElixirWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.html", _assigns) do
# "Internal Server Error"
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| 29.705882 | 61 | 0.742574 |
ff9e966b3327e5d4970fa77c69374a55ca07bf8e | 2,892 | ex | Elixir | apps/omg_watcher/lib/omg_watcher/exit_processor/request.ex | karmonezz/elixir-omg | 3b26fc072fa553992277e1b9c4bad37b3d61ec6a | [
"Apache-2.0"
] | 1 | 2020-05-01T12:30:09.000Z | 2020-05-01T12:30:09.000Z | apps/omg_watcher/lib/omg_watcher/exit_processor/request.ex | karmonezz/elixir-omg | 3b26fc072fa553992277e1b9c4bad37b3d61ec6a | [
"Apache-2.0"
] | null | null | null | apps/omg_watcher/lib/omg_watcher/exit_processor/request.ex | karmonezz/elixir-omg | 3b26fc072fa553992277e1b9c4bad37b3d61ec6a | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule OMG.Watcher.ExitProcessor.Request do
@moduledoc """
Encapsulates the state of processing of `OMG.Watcher.ExitProcessor` pipelines
Holds all the necessary query date and the respective response
NOTE: this is highly experimental, to test out new patterns to follow when doing the Functional Core vs Imperative
Shell separation. **Do not yet** follow outside of here. I'm not sure whether such struct offers much and it
has its problems. Decide and update this note after OMG-384 or OMG-383
EDIT: the multitude and duplication of the fields here is a clear sign that this design loses.
EDIT2: probably splitting this struct up, so that there isn't so many fields (`IFEInclusionRequest`,
`ValidityRequest`, `SEChallengeRequest` etc), might be the way to go
"""
alias OMG.Block
alias OMG.Utxo
defstruct [
:eth_height_now,
:blknum_now,
utxos_to_check: [],
spends_to_get: [],
blknums_to_get: [],
ife_input_utxos_to_check: [],
ife_input_spends_to_get: [],
piggybacked_blknums_to_get: [],
utxo_exists_result: [],
blocks_result: [],
ife_input_utxo_exists_result: [],
ife_input_spending_blocks_result: [],
se_exiting_pos: nil,
se_creating_blocks_to_get: [],
se_creating_blocks_result: [],
se_spending_blocks_to_get: [],
se_spending_blocks_result: []
]
@type t :: %__MODULE__{
eth_height_now: nil | pos_integer,
blknum_now: nil | pos_integer,
utxos_to_check: list(Utxo.Position.t()),
spends_to_get: list(Utxo.Position.t()),
blknums_to_get: list(pos_integer),
ife_input_utxos_to_check: list(Utxo.Position.t()),
ife_input_spends_to_get: list(Utxo.Position.t()),
piggybacked_blknums_to_get: list(pos_integer),
utxo_exists_result: list(boolean),
blocks_result: list(Block.t()),
ife_input_utxo_exists_result: list(boolean),
ife_input_spending_blocks_result: list(Block.t()),
se_exiting_pos: nil | Utxo.Position.t(),
se_creating_blocks_to_get: list(pos_integer),
se_creating_blocks_result: list(Block.t()),
se_spending_blocks_to_get: list(Utxo.Position.t()),
se_spending_blocks_result: list(Block.t())
}
end
| 39.616438 | 116 | 0.701936 |
ff9eddc5983506dcd6591c11846ec9ec69ed1280 | 3,449 | ex | Elixir | lib/elixir_phoenix_liveview_n_queen_web/live/n_queen_live.ex | aronkst/elixir_phoenix_liveview_n_queen | e23d0c4dad0d16fecdd41b709a4d9830edf8bdee | [
"MIT"
] | 1 | 2020-05-09T02:03:24.000Z | 2020-05-09T02:03:24.000Z | lib/elixir_phoenix_liveview_n_queen_web/live/n_queen_live.ex | aronkst/elixir_phoenix_liveview_n_queen | e23d0c4dad0d16fecdd41b709a4d9830edf8bdee | [
"MIT"
] | null | null | null | lib/elixir_phoenix_liveview_n_queen_web/live/n_queen_live.ex | aronkst/elixir_phoenix_liveview_n_queen | e23d0c4dad0d16fecdd41b709a4d9830edf8bdee | [
"MIT"
] | null | null | null | defmodule ElixirPhoenixLiveviewNQueenWeb.NQueenLive do
use Phoenix.LiveView
def mount(_params, _session, socket) do
{:ok, assign(socket, number: 4, type: "text", one: false, loading: false, chess: queen(4, false))}
end
def handle_event("submit", %{"type" => type, "one" => _, "number" => number}, socket) do
send(self(), %{"one" => true, "number" => number})
{:noreply, assign(socket, form_values(type, true, number, true))}
end
def handle_event("submit", %{"type" => type, "number" => number}, socket) do
send(self(), %{"one" => false, "number" => number})
{:noreply, assign(socket, form_values(type, false, number, true))}
end
def handle_info(%{"one" => one, "number" => number}, socket) do
{:noreply, assign(socket, chess: queen(convert_number(number), one), loading: false)}
end
def render(assigns) do
~L"""
<h1>N Queens</h1>
<form phx-change="submit">
<input type="radio" id="text" name="type" value="text" <%= if @type == "text" do %>checked<% end %> />
<label for="text">text</label>
<input type="radio" id="graphic" name="type" value="graphic" <%= if @type == "graphic" do %>checked<% end %> />
<label for="graphic">graphic</label>
<br />
<input type="checkbox" id="one" name="one" value="true" <%= if @one do %>checked<% end %> />
<label for="one">show only one chessboard?</label>
<br />
<input type="number" min="4" name="number" value="<%= @number %>" />
</form>
<hr />
<%= if @loading do %>
<p>Loading...</p>
<% else %>
<%= if @type == "graphic" do %>
<%= for t <- String.split(@chess, "\n") do %>
<%= case t do %>
<% "<" -> %>
<table class="chessboard">
<% ">" -> %>
</table>
<% _ -> %>
<tr class="chessboard">
<%= for ta <- String.splitter(t, "", trim: true) do %>
<%= if ta == "." do %>
<td class="chessboard"></td>
<% else %>
<td class="chessboard">♕</td>
<% end %>
<% end %>
</tr>
<% end %>
<% end %>
<% else %>
<pre><%= @chess |> String.replace("<", "") |> String.replace(">", "") %></pre>
<% end %>
<% end %>
"""
end
defp form_values(type, one, number, loading) do
%{type: type, one: one, number: convert_number(number), loading: loading}
end
defp convert_number(number) do
number = String.to_integer(number)
if number < 4 do
4
else
number
end
end
defp queen(n, one) do
solve(n, [], [], [], one)
end
defp solve(n, row, _, _, _) when n == length(row) do
solve(n, row)
end
defp solve(n, row, add_list, sub_list, one) do
Enum.reduce_while(Enum.to_list(0..n - 1) -- row, "", fn x, t ->
if one && String.contains?(t, "<") do
{:halt, t}
else
add = x + length(row)
sub = x - length(row)
if (add in add_list) or (sub in sub_list) do
{:cont, t}
else
{:cont, t <> solve(n, [x|row], [add | add_list], [sub | sub_list], one)}
end
end
end)
end
defp solve(n, row) do
"<\n" <> Enum.reduce(row, "", fn x, t ->
line = Enum.map_join(0..n - 1, fn i -> if x == i, do: "Q", else: "." end)
t <> line <> "\n"
end) <> ">\n"
end
end | 31.354545 | 117 | 0.496376 |
ff9ee1d632a18177ccd494b86daebebda77076e9 | 1,117 | exs | Elixir | config/config.exs | lewapkon/eulixir | 990017cdccee7cd508269b7036e290ec777aea3d | [
"MIT"
] | null | null | null | config/config.exs | lewapkon/eulixir | 990017cdccee7cd508269b7036e290ec777aea3d | [
"MIT"
] | null | null | null | config/config.exs | lewapkon/eulixir | 990017cdccee7cd508269b7036e290ec777aea3d | [
"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 :eulixir, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:eulixir, :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"
| 36.032258 | 73 | 0.751119 |
ff9ef81b9c4433ea1bd6a2caf5fe2137a8932041 | 2,290 | ex | Elixir | lib/crypto_exchanges/adapters/bittrex_adapter.ex | sbrink/crypto_exchanges_elixir | 0d500f9129e27b3ab24b59118b88c4d1cbdbec11 | [
"MIT"
] | 12 | 2017-10-01T10:37:11.000Z | 2019-08-09T07:02:02.000Z | lib/crypto_exchanges/adapters/bittrex_adapter.ex | sbrink/crypto_exchanges_elixir | 0d500f9129e27b3ab24b59118b88c4d1cbdbec11 | [
"MIT"
] | 1 | 2017-10-02T21:43:40.000Z | 2017-10-08T18:37:19.000Z | lib/crypto_exchanges/adapters/bittrex_adapter.ex | sbrink/crypto_exchanges_elixir | 0d500f9129e27b3ab24b59118b88c4d1cbdbec11 | [
"MIT"
] | null | null | null | defmodule CryptoExchanges.BittrexAdapter do
@moduledoc """
An Adapter for the Bittrex Exchange
"""
use CryptoExchanges.Adapter
def get_info, do: %CryptoExchange{
name: "Bittrex",
homepage_url: "https://bittrex.com/",
api_docs_url: "https://bittrex.com/home/api",
country: "USA",
intervals: [1, 5, 30, 60, 1440]
}
def get_currencies do
api_get_markets()
|> Enum.map(&transform_bittrex_currency/1)
|> Enum.uniq_by(&(&1.symbol))
end
def transform_bittrex_currency(bittrex_currency) do
%CryptoCurrency{
active: bittrex_currency["IsActive"],
symbol: bittrex_currency["MarketCurrency"]
}
end
def get_markets do
api_get_markets()
|> Enum.map(&transform_bittrex_market/1)
end
def transform_bittrex_market(bittrex_currency) do
%CryptoMarket{
active: bittrex_currency["IsActive"],
symbol: bittrex_currency["MarketCurrency"],
base_symbol: bittrex_currency["BaseCurrency"],
name: bittrex_currency["MarketName"]
}
end
def get_candles(symbol1, symbol2, interval, from) do
candles = api_get_ticks(symbol1, symbol2, interval, from)
candles
|> Enum.map(&transform_bittrex_candle/1)
end
def transform_bittrex_candle(bittrex_candle) do
{:ok, datetime, 0} = DateTime.from_iso8601("#{bittrex_candle["T"]}Z")
%CryptoCandle{
time: datetime,
open: bittrex_candle["O"],
high: bittrex_candle["H"],
close: bittrex_candle["C"],
low: bittrex_candle["L"],
volume: bittrex_candle["BV"]
}
end
# Private functions
@url "https://bittrex.com/api/v1.1/public/getmarkets"
defp api_get_markets do
HTTPoison.get!(@url).body
|> Poison.decode!
|> get_in(["result"])
end
@url "https://bittrex.com/Api/v2.0/pub/market/GetTicks"
defp api_get_ticks(symbol1, symbol2, interval, from) do
params = "marketName=#{symbol1}-#{symbol2}&tickInterval=#{map_interval_param(interval)}&_=#{from}"
HTTPoison.get!("#{@url}?#{params}").body
|> Poison.decode!
|> get_in(["result"])
end
defp map_interval_param(1), do: "oneMin"
defp map_interval_param(5), do: "fiveMin"
defp map_interval_param(30), do: "thirtyMin"
defp map_interval_param(60), do: "hour"
defp map_interval_param(1440), do: "day"
end
| 27.261905 | 102 | 0.678166 |
ff9f403269dc6eac16b18e10a97df7baed0102cb | 2,142 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_telephony_synthesize_speech.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_telephony_synthesize_speech.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_telephony_synthesize_speech.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageTelephonySynthesizeSpeech do
@moduledoc """
Synthesizes speech and plays back the synthesized audio to the caller in Telephony Gateway. Telephony Gateway takes the synthesizer settings from `DetectIntentResponse.output_audio_config` which can either be set at request-level or can come from the agent-level synthesizer config.
## Attributes
- ssml (String.t): The SSML to be synthesized. For more information, see [SSML](https://developers.google.com/actions/reference/ssml). Defaults to: `null`.
- text (String.t): The raw text to be synthesized. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:ssml => any(),
:text => any()
}
field(:ssml)
field(:text)
end
defimpl Poison.Decoder,
for:
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageTelephonySynthesizeSpeech do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageTelephonySynthesizeSpeech.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageTelephonySynthesizeSpeech do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.931034 | 295 | 0.760037 |
ff9f766c4c31d53cbb24407fe0a990f209697b91 | 102 | exs | Elixir | apps/ex_wire/test/ex_wire/message/pong_test.exs | atoulme/ethereum | cebb0756c7292ac266236636d2ab5705cb40a52e | [
"MIT"
] | 14 | 2017-08-21T06:14:49.000Z | 2020-05-15T12:00:52.000Z | apps/ex_wire/test/ex_wire/message/pong_test.exs | atoulme/ethereum | cebb0756c7292ac266236636d2ab5705cb40a52e | [
"MIT"
] | 7 | 2017-08-11T07:50:14.000Z | 2018-08-23T20:42:50.000Z | apps/ex_wire/test/ex_wire/message/pong_test.exs | atoulme/ethereum | cebb0756c7292ac266236636d2ab5705cb40a52e | [
"MIT"
] | 3 | 2017-08-20T17:56:41.000Z | 2018-08-21T00:36:10.000Z | defmodule ExWire.Message.PongTest do
use ExUnit.Case, async: true
doctest ExWire.Message.Pong
end | 20.4 | 36 | 0.794118 |
ff9f998a851f6a5c11189081222e22b23dabb749 | 498 | ex | Elixir | learning/gnome/game/gallows/lib/gallows_web/router.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | 2 | 2020-01-20T20:15:20.000Z | 2020-02-27T11:08:42.000Z | learning/gnome/game/gallows/lib/gallows_web/router.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | null | null | null | learning/gnome/game/gallows/lib/gallows_web/router.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | null | null | null | defmodule GallowsWeb.Router do
use GallowsWeb, :router
pipeline :browser do
plug(:accepts, ["html"])
plug(:fetch_session)
plug(:fetch_flash)
plug(:protect_from_forgery)
plug(:put_secure_browser_headers)
end
pipeline :api do
plug(:accepts, ["json"])
end
scope "/hangman", GallowsWeb do
pipe_through(:browser)
get("/", HangmanController, :new_game)
post("/", HangmanController, :create_game)
put("/", HangmanController, :make_move)
end
end
| 19.153846 | 46 | 0.674699 |
ff9fa560b6671068ad8e06da9fd22e259ac6f30d | 4,329 | ex | Elixir | clients/security_center/lib/google_api/security_center/v1/model/google_cloud_securitycenter_v1p1beta1_asset.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"Apache-2.0"
] | null | null | null | clients/security_center/lib/google_api/security_center/v1/model/google_cloud_securitycenter_v1p1beta1_asset.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"Apache-2.0"
] | null | null | null | clients/security_center/lib/google_api/security_center/v1/model/google_cloud_securitycenter_v1p1beta1_asset.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.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1Asset do
@moduledoc """
Cloud Security Command Center's (Cloud SCC) representation of a Google Cloud
Platform (GCP) resource.
The Asset is a Cloud SCC resource that captures information about a single
GCP resource. All modifications to an Asset are only within the context of
Cloud SCC and don't affect the referenced GCP resource.
## Attributes
* `createTime` (*type:* `DateTime.t`, *default:* `nil`) - The time at which the asset was created in Cloud SCC.
* `iamPolicy` (*type:* `GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1IamPolicy.t`, *default:* `nil`) - IAM Policy information associated with the GCP resource described by the
Cloud SCC asset. This information is managed and defined by the GCP
resource and cannot be modified by the user.
* `name` (*type:* `String.t`, *default:* `nil`) - The relative resource name of this asset. See:
https://cloud.google.com/apis/design/resource_names#relative_resource_name
Example:
"organizations/{organization_id}/assets/{asset_id}".
* `resourceProperties` (*type:* `map()`, *default:* `nil`) - Resource managed properties. These properties are managed and defined by
the GCP resource and cannot be modified by the user.
* `securityCenterProperties` (*type:* `GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1SecurityCenterProperties.t`, *default:* `nil`) - Cloud SCC managed properties. These properties are managed by
Cloud SCC and cannot be modified by the user.
* `securityMarks` (*type:* `GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1SecurityMarks.t`, *default:* `nil`) - User specified security marks. These marks are entirely managed by the user
and come from the SecurityMarks resource that belongs to the asset.
* `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - The time at which the asset was last updated, added, or deleted in Cloud
SCC.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:createTime => DateTime.t(),
:iamPolicy =>
GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1IamPolicy.t(),
:name => String.t(),
:resourceProperties => map(),
:securityCenterProperties =>
GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1SecurityCenterProperties.t(),
:securityMarks =>
GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1SecurityMarks.t(),
:updateTime => DateTime.t()
}
field(:createTime, as: DateTime)
field(:iamPolicy,
as: GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1IamPolicy
)
field(:name)
field(:resourceProperties, type: :map)
field(:securityCenterProperties,
as:
GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1SecurityCenterProperties
)
field(:securityMarks,
as: GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1SecurityMarks
)
field(:updateTime, as: DateTime)
end
defimpl Poison.Decoder,
for: GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1Asset do
def decode(value, options) do
GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1Asset.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.SecurityCenter.V1.Model.GoogleCloudSecuritycenterV1p1beta1Asset do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.727273 | 221 | 0.740818 |
ff9fa7b659ee67855b22a7f410549802978f8cc3 | 2,287 | exs | Elixir | test/ecto/query/builder/select_test.exs | jeregrine/ecto | 98b2dd4bf7b39738ab9a5ae3fa7e48e43a4af39b | [
"Apache-2.0"
] | null | null | null | test/ecto/query/builder/select_test.exs | jeregrine/ecto | 98b2dd4bf7b39738ab9a5ae3fa7e48e43a4af39b | [
"Apache-2.0"
] | null | null | null | test/ecto/query/builder/select_test.exs | jeregrine/ecto | 98b2dd4bf7b39738ab9a5ae3fa7e48e43a4af39b | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Query.Builder.SelectTest do
use ExUnit.Case, async: true
import Ecto.Query
import Ecto.Query.Builder.Select
doctest Ecto.Query.Builder.Select
test "escape" do
assert {Macro.escape(quote do &0 end), {%{}, %{}}} ==
escape(quote do x end, [x: 0], __ENV__)
assert {Macro.escape(quote do &0.y end), {%{}, %{}}} ==
escape(quote do x.y end, [x: 0], __ENV__)
assert {Macro.escape(quote do &0 end), {%{}, %{0 => {:any, [:foo, :bar, baz: :bat]}}}} ==
escape(quote do [:foo, :bar, baz: :bat] end, [x: 0], __ENV__)
assert {Macro.escape(quote do &0 end), {%{}, %{0 => {:struct, [:foo, :bar, baz: :bat]}}}} ==
escape(quote do struct(x, [:foo, :bar, baz: :bat]) end, [x: 0], __ENV__)
assert {Macro.escape(quote do &0 end), {%{}, %{0 => {:map, [:foo, :bar, baz: :bat]}}}} ==
escape(quote do map(x, [:foo, :bar, baz: :bat]) end, [x: 0], __ENV__)
assert {{:{}, [], [:{}, [], [0, 1, 2]]}, {%{}, %{}}} ==
escape(quote do {0, 1, 2} end, [], __ENV__)
assert {{:{}, [], [:%{}, [], [a: {:{}, [], [:&, [], [0]]}]]}, {%{}, %{}}} ==
escape(quote do %{a: a} end, [a: 0], __ENV__)
assert {{:{}, [], [:%{}, [], [{{:{}, [], [:&, [], [0]]}, {:{}, [], [:&, [], [1]]}}]]}, {%{}, %{}}} ==
escape(quote do %{a => b} end, [a: 0, b: 1], __ENV__)
assert {[Macro.escape(quote do &0.y end), Macro.escape(quote do &0.z end)], {%{}, %{}}} ==
escape(quote do [x.y, x.z] end, [x: 0], __ENV__)
assert {[{:{}, [], [{:{}, [], [:., [], [{:{}, [], [:&, [], [0]]}, :y]]}, [], []]},
{:{}, [], [:^, [], [0]]}], {%{0 => {1, :any}}, %{}}} ==
escape(quote do [x.y, ^1] end, [x: 0], __ENV__)
end
test "only one select is allowed" do
message = "only one select expression is allowed in query"
assert_raise Ecto.Query.CompileError, message, fn ->
%Ecto.Query{} |> select([], 1) |> select([], 2)
end
end
test "select interpolation" do
fields = [:foo, :bar, :baz]
assert select("q", ^fields).select.take == %{0 => {:any, fields}}
assert select("q", [q], map(q, ^fields)).select.take == %{0 => {:map, fields}}
assert select("q", [q], struct(q, ^fields)).select.take == %{0 => {:struct, fields}}
end
end
| 41.581818 | 105 | 0.46655 |
ff9fde054f48159abb3c5d90ca786e58779fa122 | 14,427 | ex | Elixir | server/lib/spend_index.ex | bitfeed-project/bitfeed | 48b346ec18fa1be2e09a9e1f36ac10db9c0fab62 | [
"MIT"
] | 27 | 2022-01-01T14:58:22.000Z | 2022-03-22T06:11:18.000Z | server/lib/spend_index.ex | bitfeed-project/bitfeed | 48b346ec18fa1be2e09a9e1f36ac10db9c0fab62 | [
"MIT"
] | 22 | 2022-01-01T04:26:10.000Z | 2022-03-22T00:02:31.000Z | server/lib/spend_index.ex | bitfeed-project/bitfeed | 48b346ec18fa1be2e09a9e1f36ac10db9c0fab62 | [
"MIT"
] | 9 | 2022-01-03T07:34:36.000Z | 2022-03-14T23:19:56.000Z | require Logger
defmodule BitcoinStream.Index.Spend do
use GenServer
alias BitcoinStream.Protocol.Block, as: BitcoinBlock
alias BitcoinStream.Protocol.Transaction, as: BitcoinTx
alias BitcoinStream.RPC, as: RPC
def start_link(opts) do
Logger.info("Starting Spend Index");
{indexed, opts} = Keyword.pop(opts, :indexed);
GenServer.start_link(__MODULE__, [indexed], opts)
end
@impl true
def init([indexed]) do
:ets.new(:spend_cache, [:set, :public, :named_table]);
if (indexed) do
{:ok, dbref} = :rocksdb.open(String.to_charlist("data/index/spend"), [create_if_missing: true]);
Process.send_after(self(), :sync, 2000);
{:ok, [dbref, indexed, false]}
else
{:ok, [nil, indexed, false]}
end
end
@impl true
def terminate(_reason, [dbref, indexed, _done]) do
if (indexed) do
:rocksdb.close(dbref)
end
end
@impl true
def handle_info(:sync, [dbref, indexed, done]) do
if (indexed) do
case sync(dbref) do
true ->
{:noreply, [dbref, indexed, true]}
_ ->
{:noreply, [dbref, indexed, false]}
end
else
{:noreply, [dbref, indexed, done]}
end
end
@impl true
def handle_info(_event, state) do
# if RPC responds after the calling process already timed out, garbled messages get dumped to handle_info
# quietly discard
{:noreply, state}
end
@impl true
def handle_call({:get_tx_spends, txid}, _from, [dbref, indexed, done]) do
case get_transaction_spends(dbref, txid, indexed) do
{:ok, spends} ->
{:reply, {:ok, spends}, [dbref, indexed, done]}
err ->
Logger.error("failed to fetch tx spends");
{:reply, err, [dbref, indexed, done]}
end
end
@impl true
def handle_cast(:new_block, [dbref, indexed, done]) do
if (indexed and done) do
case sync(dbref) do
true ->
{:noreply, [dbref, indexed, true]}
_ ->
{:noreply, [dbref, indexed, false]}
end
else
if (indexed) do
Logger.info("Already building spend index");
end
{:noreply, [dbref, indexed, false]}
end
end
@impl true
def handle_cast({:block_disconnected, hash}, [dbref, indexed, done]) do
Logger.info("block disconnected: #{hash}");
if (indexed and done) do
block_disconnected(dbref, hash)
end
{:noreply, [dbref, indexed, done]}
end
def get_tx_spends(pid, txid) do
GenServer.call(pid, {:get_tx_spends, txid}, 60000)
catch
:exit, reason ->
case reason do
{:timeout, _} -> {:error, :timeout}
_ -> {:error, reason}
end
error -> {:error, error}
end
def notify_block(pid, _hash) do
GenServer.cast(pid, :new_block)
end
def notify_block_disconnect(pid, hash) do
GenServer.cast(pid, {:block_disconnected, hash})
end
defp wait_for_ibd() do
case RPC.get_node_status(:rpc) do
:ok -> true
_ ->
Logger.info("Waiting for node to come online and fully sync before synchronizing spend index");
RPC.notify_on_ready(:rpc)
end
end
defp get_index_height(dbref) do
case :rocksdb.get(dbref, "height", []) do
{:ok, <<height::integer-size(32)>>} ->
height
:not_found ->
-1
_ ->
Logger.error("unexpected leveldb response")
end
end
defp get_chain_height() do
case RPC.request(:rpc, "getblockcount", []) do
{:ok, 200, height} ->
height
_ ->
Logger.error("unexpected RPC response");
:err
end
end
defp get_block(height) do
with {:ok, 200, blockhash} <- RPC.request(:rpc, "getblockhash", [height]),
{:ok, 200, blockdata} <- RPC.request(:rpc, "getblock", [blockhash, 0]),
{:ok, block} <- BitcoinBlock.parse(blockdata) do
block
end
end
defp get_block_by_hash(hash) do
with {:ok, 200, blockdata} <- RPC.request(:rpc, "getblock", [hash, 0]),
{:ok, block} <- BitcoinBlock.parse(blockdata) do
block
end
end
defp index_input(spendkey, input, spends) do
case input do
# coinbase (skip)
%{prev_txid: "0000000000000000000000000000000000000000000000000000000000000000"} ->
spends
%{prev_txid: txid, prev_vout: vout} ->
binid = Base.decode16!(txid, [case: :lower])
case spends[binid] do
nil ->
Map.put(spends, binid, [[vout, spendkey]])
a ->
Map.put(spends, binid, [[vout, spendkey] | a])
end
# unexpected input format (should never happen)
_ ->
spends
end
end
defp index_inputs(_binid, [], _vout, spends) do
spends
end
defp index_inputs(binid, [vin | rest], vout, spends) do
spends = index_input(binid <> <<vout::integer-size(24)>>, vin, spends);
index_inputs(binid, rest, vout+1, spends)
end
defp index_tx(%{id: txid, inputs: inputs}, spends) do
binid = Base.decode16!(txid, [case: :lower]);
index_inputs(binid, inputs, 0, spends)
end
defp index_txs([], spends) do
spends
end
defp index_txs([tx | rest], spends) do
spends = index_tx(tx, spends);
index_txs(rest, spends)
end
defp index_block_inputs(dbref, batch, txns) do
spends = index_txs(txns, %{});
Enum.each(spends, fn {binid, outputs} ->
case get_chain_spends(dbref, binid, true) do
false ->
Logger.error("uninitialised tx in input index: #{Base.encode16(binid, [case: :lower])}")
:ok
prev ->
:rocksdb.batch_put(batch, binid, fillBinarySpends(prev, outputs))
end
end)
end
defp init_block_txs(batch, txns) do
Enum.each(txns, fn tx ->
size = length(tx.outputs) * 35 * 8;
binary_txid = Base.decode16!(tx.id, [case: :lower]);
:rocksdb.batch_put(batch, binary_txid, <<0::integer-size(size)>>)
end)
end
defp index_block(dbref, height) do
with block <- get_block(height),
{:ok, batch} <- :rocksdb.batch(),
:ok <- init_block_txs(batch, block.txns),
:ok <- :rocksdb.write_batch(dbref, batch, []),
{:ok, batch} <- :rocksdb.batch(),
:ok <- index_block_inputs(dbref, batch, block.txns),
:ok <- :rocksdb.write_batch(dbref, batch, []) do
:ok
else
err ->
Logger.error("error indexing block");
IO.inspect(err);
:err
end
end
# insert a 35-byte spend key into a binary spend index
# (not sure how efficient this method is?)
defp fillBinarySpend(bin, index, spendkey) do
a_size = 35 * index;
<<a::binary-size(a_size), _b::binary-size(35), c::binary>> = bin;
<<a::binary, spendkey::binary, c::binary>>
end
defp fillBinarySpends(bin, []) do
bin
end
defp fillBinarySpends(bin, [[index, spendkey] | rest]) do
bin = fillBinarySpend(bin, index, spendkey);
fillBinarySpends(bin, rest)
end
# "erase" a spend by zeroing out the spend key
defp clearBinarySpend(bin, index, _spendkey) do
a_size = 35 * index;
b_size = 35 * 8;
<<a::binary-size(a_size), _b::binary-size(35), c::binary>> = bin;
<<a::binary, <<0::integer-size(b_size)>>, c::binary>>
end
defp clearBinarySpends(bin, []) do
bin
end
defp clearBinarySpends(bin, [[index, spendkey] | rest]) do
bin = clearBinarySpend(bin, index, spendkey);
clearBinarySpends(bin, rest)
end
# On start up, check index height (load from leveldb) vs latest block height (load via rpc)
# Until index height = block height, process next block
defp sync(dbref) do
wait_for_ibd();
with index_height <- get_index_height(dbref),
chain_height <- get_chain_height() do
if index_height < chain_height do
with :ok <- index_block(dbref, index_height + 1),
:ok <- :rocksdb.put(dbref, "height", <<(index_height + 1)::integer-size(32)>>, []) do
Logger.info("Built spend index for block #{index_height + 1}");
Process.send_after(self(), :sync, 0);
else
_ ->
Logger.error("Failed to build spend index");
false
end
else
Logger.info("Spend index fully synced to height #{index_height}");
true
end
end
end
defp batch_spend_status(txid, batch) do
with batch_params <- Enum.map(batch, fn index -> [[txid, index, true], index] end),
{:ok, 200, txouts} <- RPC.batch_request(:rpc, "gettxout", batch_params, false),
utxos <- Enum.map(txouts, fn txout ->
case txout do
%{"error" => nil, "id" => index, "result" => nil} ->
{ index, true }
%{"error" => nil, "id" => index, "result" => _result} ->
{ index, false }
%{"error" => _error, "id" => index } ->
{ index, false }
end
end),
utxoMap <- Enum.into(Enum.filter(utxos, fn utxo ->
case utxo do
{ _index, false } ->
false
{ _index, true } ->
true
_ -> false
end
end), %{})
do
{:ok, utxoMap}
else
_ ->
:error
end
end
defp get_spend_status(_txid, [], results) do
results
end
defp get_spend_status(txid, [next_batch | rest], results) do
case batch_spend_status(txid, next_batch) do
{:ok, result} ->
get_spend_status(txid, rest, Map.merge(results, result))
_ -> :err
end
end
defp get_spend_status(txid, numOutputs) do
index_list = Enum.to_list(0..(numOutputs - 1))
spend_map = get_spend_status(txid, Enum.chunk_every(index_list, 100), %{});
Enum.map(index_list, fn index ->
case Map.get(spend_map, index) do
true -> true
_ -> false
end
end)
end
defp get_spend_status(txid) do
with {:ok, 200, hextx} <- RPC.request(:rpc, "getrawtransaction", [txid]),
rawtx <- Base.decode16!(hextx, case: :lower),
{:ok, tx } <- BitcoinTx.decode(rawtx) do
get_spend_status(txid, length(tx.outputs))
else
_ -> []
end
end
defp get_chain_spends(dbref, binary_txid, use_index) do
case (if use_index do :rocksdb.get(dbref, binary_txid, []) else :unindexed end) do
{:ok, spends} ->
spends
:unindexed ->
# uninitialized, try to construct on-the-fly from RPC data
txid = Base.encode16(binary_txid);
with {:ok, 200, hextx} <- RPC.request(:rpc, "getrawtransaction", [txid]),
rawtx <- Base.decode16!(hextx, case: :lower),
{:ok, tx } <- BitcoinTx.decode(rawtx) do
size = length(tx.outputs) * 35 * 8;
<<0::integer-size(size)>>
else
_ -> false
end
_ ->
Logger.error("unexpected leveldb response");
false
end
end
defp unpack_spends(<<>>, spend_list) do
Enum.reverse(spend_list)
end
# unspent outputs are zeroed out
defp unpack_spends(<<0::integer-size(280), rest::binary>>, spend_list) do
unpack_spends(rest, [false | spend_list])
end
defp unpack_spends(<<binary_txid::binary-size(32), index::integer-size(24), rest::binary>>, spend_list) do
txid = Base.encode16(binary_txid, [case: :lower]);
unpack_spends(rest, [[txid, index] | spend_list])
end
defp unpack_spends(false) do
[]
end
defp unpack_spends(bin) do
unpack_spends(bin, [])
end
defp get_transaction_spends(dbref, txid, use_index) do
if (use_index) do
binary_txid = Base.decode16!(txid, [case: :lower]);
chain_spends = get_chain_spends(dbref, binary_txid, use_index);
spend_list = unpack_spends(chain_spends);
spend_list = add_mempool_spends(txid, spend_list);
{:ok, spend_list}
else
spend_list = get_spend_status(txid);
spend_list = add_mempool_spends(txid, spend_list);
{:ok, spend_list}
end
end
defp add_mempool_spends(_txid, _index, [], added) do
Enum.reverse(added)
end
defp add_mempool_spends(txid, index, [spend | rest], added) when is_boolean(spend) do
case :ets.lookup(:spend_cache, [txid, index]) do
[] ->
add_mempool_spends(txid, index + 1, rest, [spend | added])
[{[_index, _txid], mempool_spend}] ->
add_mempool_spends(txid, index + 1, rest, [mempool_spend | added])
end
end
defp add_mempool_spends(txid, index, [spend | rest], added) do
add_mempool_spends(txid, index + 1, rest, [spend | added])
end
defp add_mempool_spends(txid, spend_list) do
add_mempool_spends(txid, 0, spend_list, [])
end
defp stack_dropped_blocks(dbref, hash, undo_stack, min_height) do
# while we're below the latest processed height
# keep adding blocks to the undo stack until we find an ancestor in the main chain
with {:ok, 200, blockdata} <- RPC.request(:rpc, "getblock", [hash, 1]),
index_height <- get_index_height(dbref),
true <- (blockdata["height"] <= index_height),
true <- (blockdata["confirmations"] < 0) do
stack_dropped_blocks(dbref, blockdata["previousblockhash"], [hash | undo_stack], blockdata["height"])
else
_ -> [undo_stack, min_height]
end
end
defp drop_block_inputs(dbref, batch, txns) do
spends = index_txs(txns, %{});
Enum.each(spends, fn {binid, outputs} ->
case get_chain_spends(dbref, binid, true) do
false ->
Logger.error("uninitialised tx in input index: #{Base.encode16(binid, [case: :lower])}")
:ok
prev ->
:rocksdb.batch_put(batch, binid, clearBinarySpends(prev, outputs))
end
end)
end
defp drop_block(dbref, hash) do
with block <- get_block_by_hash(hash),
{:ok, batch} <- :rocksdb.batch(),
:ok <- drop_block_inputs(dbref, batch, block.txns),
:ok <- :rocksdb.write_batch(dbref, batch, []) do
:ok
else
err ->
Logger.error("error indexing block");
IO.inspect(err);
:err
end
end
defp drop_blocks(_dbref, []) do
:ok
end
defp drop_blocks(dbref, [hash | rest]) do
drop_block(dbref, hash);
drop_blocks(dbref, rest)
end
defp block_disconnected(dbref, hash) do
[undo_stack, min_height] = stack_dropped_blocks(dbref, hash, [], nil);
drop_blocks(dbref, undo_stack);
if (min_height != nil) do
:rocksdb.put(dbref, "height", <<(min_height - 1)::integer-size(32)>>, [])
else
:ok
end
end
end
| 28.681909 | 109 | 0.602343 |
ffa02c36f1d029c36e2dd5911171c978e986da61 | 6,902 | ex | Elixir | lib/distillery/tasks/init.ex | arikai/distillery | 65ddbcc143f2849a6ed5574e8c397a68ca92eb81 | [
"MIT"
] | 3,097 | 2016-07-18T13:59:00.000Z | 2022-03-29T00:27:23.000Z | lib/distillery/tasks/init.ex | arikai/distillery | 65ddbcc143f2849a6ed5574e8c397a68ca92eb81 | [
"MIT"
] | 672 | 2016-07-18T18:25:29.000Z | 2022-02-24T17:39:30.000Z | lib/distillery/tasks/init.ex | arikai/distillery | 65ddbcc143f2849a6ed5574e8c397a68ca92eb81 | [
"MIT"
] | 483 | 2016-07-22T14:08:49.000Z | 2022-03-21T09:35:23.000Z | defmodule Mix.Tasks.Distillery.Init do
@moduledoc """
Prepares a new project for use with releases.
This simply creates a `rel` directory in the project root,
and creates a basic initial configuration file in `rel/config.exs`.
It will also creates a vm.args file in `rel/vm.args` to tweak the
configuration of the BEAM.
After running this, you can build a release right away with `mix distillery.release`,
but it is recommended you review the config file to understand its contents.
## Examples
# Initialize releases, with a fully commented config file
mix distillery.init
# Initialize releases, but with no comments in the config file
mix distillery.init --no-doc
# For umbrella projects, generate a config where each app
# in the umbrella is its own release, rather than all
# apps under a single release
mix distillery.init --release-per-app
# Name the release, by default the current application name
# will be used, or in the case of umbrella projects, the name
# of the directory in which the umbrella project resides, with
# invalid characters replaced or stripped out.
mix distillery.init --name foobar
# Use a custom template for generating the release config.
mix distillery.init --template path/to/template
"""
@shortdoc "initialize a new release configuration"
use Mix.Task
alias Distillery.Releases.Utils
alias Distillery.Releases.Shell
@spec run(OptionParser.argv()) :: no_return
def run(args) do
# make sure loadpaths are updated
Mix.Task.run("loadpaths", [])
# make sure we're compiled too
Mix.Task.run("compile", [])
Shell.configure(:normal)
opts = parse_args(args)
# Generate template bindings based on type of project and task opts
bindings =
if Mix.Project.umbrella?() do
get_umbrella_bindings(opts)
else
get_standard_bindings(opts)
end
# Create /rel
File.mkdir_p!("rel/plugins")
# Generate .gitignore for plugins folder
unless File.exists?("rel/plugins/.gitignore") do
File.write!("rel/plugins/.gitignore", "*.*\n!*.exs\n!.gitignore", [:utf8])
end
# Generate config.exs
{:ok, config} =
case opts[:template] do
nil ->
Utils.template(:example_config, bindings)
template_path ->
Utils.template_path(template_path, bindings)
end
# Save config.exs to /rel
File.write!(Path.join("rel", "config.exs"), config)
# Generate vm.args
vm_args = Path.join("rel", "vm.args")
unless File.exists?(vm_args) do
{:ok, vm} = Utils.template("vm.args.default", bindings)
File.write!(vm_args, vm)
end
IO.puts(
IO.ANSI.cyan() <>
"\nAn example config file has been placed in rel/config.exs, review it,\n" <>
"make edits as needed/desired, and then run `mix distillery.release` to build the release" <>
IO.ANSI.reset()
)
rescue
e in [File.Error] ->
Shell.error("Initialization failed:\n #{Exception.message(e)}")
System.halt(1)
end
@spec parse_args([String.t()]) :: Keyword.t() | no_return
defp parse_args(argv) do
opts = [
strict: [
no_doc: :boolean,
release_per_app: :boolean,
name: :string,
template: :string
]
]
{overrides, _} = OptionParser.parse!(argv, opts)
defaults = [
no_doc: false,
release_per_app: false,
name: nil,
template: nil
]
Keyword.merge(defaults, overrides)
end
@spec get_umbrella_bindings(Keyword.t()) :: Keyword.t() | no_return
defp get_umbrella_bindings(opts) do
apps_path = Keyword.get(Mix.Project.config(), :apps_path)
apps_paths = Path.wildcard("#{apps_path}/*")
apps =
apps_paths
|> Enum.map(fn app_path ->
mixfile = Path.join(app_path, "mix.exs")
app = get_app_name_from_ast(mixfile)
{app, :permanent}
end)
release_per_app? = Keyword.get(opts, :release_per_app, false)
releases =
if release_per_app? do
for {app, start_type} <- apps do
[
release_name: app,
is_umbrella: false,
release_applications: [{app, start_type}]
]
end
else
release_name_from_cwd = String.replace(Path.basename(File.cwd!()), "-", "_")
release_name = Keyword.get(opts, :name, release_name_from_cwd) || release_name_from_cwd
[
[
release_name: String.to_atom(release_name),
is_umbrella: true,
release_applications: apps
]
]
end
[{:releases, releases} | get_common_bindings(opts)]
end
@spec get_standard_bindings(Keyword.t()) :: Keyword.t() | no_return
defp get_standard_bindings(opts) do
app = Keyword.get(Mix.Project.config(), :app)
releases = [
[
# If opts contains the key :name, but its value is nil, we still want to default to app
release_name: Keyword.get(opts, :name, app) || app,
is_umbrella: false,
release_applications: [{app, :permanent}]
]
]
[{:releases, releases} | get_common_bindings(opts)]
end
@spec get_common_bindings(Keyword.t()) :: Keyword.t()
defp get_common_bindings(opts) do
[
no_docs: Keyword.get(opts, :no_doc, false),
cookie: Distillery.Cookies.get(),
get_cookie: &Distillery.Cookies.get/0
]
end
def get_app_name_from_ast(path) do
cwd = File.cwd!()
try do
app_dir = Path.dirname(path)
relative_path = Path.relative_to(path, app_dir)
File.cd!(app_dir)
{{:module, mod, _, _}, _bindings} =
relative_path
|> File.read!()
|> Code.string_to_quoted!()
|> Code.eval_quoted(
[],
aliases: [{Mix, __MODULE__.MixMock}],
requires: [],
macros: [{__MODULE__.MixMock, [defmodule: 2]}]
)
mod.project[:app]
rescue
err ->
raise "Problem reading mix.exs at #{path}:\n\n#{Exception.message(err)}\n" <>
Exception.format_stacktrace()
after
File.cd!(cwd)
end
end
# Used to fake out Mix/Mix.Project when reading mixfiles
defmodule MixMock.Project do
@moduledoc false
defmacro __using__(_) do
quote do
:ok
end
end
end
defmodule MixMock do
@moduledoc false
require MixMock.Project
def env, do: :dev
def compilers, do: []
# We override defmodule so that we can make sure the modules
# don't conflict with any already loaded
defmacro defmodule(name, do: body) do
quote do
conflict_free_name = Module.concat([unquote(__MODULE__), unquote(name)])
require Kernel
Kernel.defmodule conflict_free_name do
import Kernel
unquote(body)
end
end
end
end
end
| 27.608 | 101 | 0.625471 |
ffa047e64a520090cc9663a070dd894747ef65ba | 392 | exs | Elixir | test/test_helper.exs | manukall/phoenix | 5ce19ebb63b1b31e37da5fe6465edb6c4850772e | [
"MIT"
] | 1 | 2019-06-11T20:22:21.000Z | 2019-06-11T20:22:21.000Z | test/test_helper.exs | DavidAlphaFox/phoenix | 560131ab3b48c6b6cf864a3d20b7667e40990237 | [
"MIT"
] | null | null | null | test/test_helper.exs | DavidAlphaFox/phoenix | 560131ab3b48c6b6cf864a3d20b7667e40990237 | [
"MIT"
] | null | null | null | Code.require_file("support/router_helper.exs", __DIR__)
# Starts web server applications
Application.ensure_all_started(:cowboy)
# Used whenever a router fails. We default to simply
# rendering a short string.
defmodule Phoenix.ErrorView do
def render(template, _assigns) do
"#{template} from Phoenix.ErrorView"
end
end
# For mix tests
Mix.shell(Mix.Shell.Process)
ExUnit.start()
| 21.777778 | 55 | 0.772959 |
ffa0542d79ca9df1d0b18400e076d907e8f58842 | 486 | ex | Elixir | lib/secret_grinch/assignment.ex | clorofila-league/secret_grinch | b06ac85ff5f06d5405d190ccc9966b01f0406b87 | [
"Apache-2.0"
] | 3 | 2017-08-03T16:49:18.000Z | 2018-10-03T03:30:26.000Z | lib/secret_grinch/assignment.ex | clorofila-league/secret_grinch | b06ac85ff5f06d5405d190ccc9966b01f0406b87 | [
"Apache-2.0"
] | 18 | 2017-08-04T12:43:08.000Z | 2017-08-05T14:15:41.000Z | lib/secret_grinch/assignment.ex | clorofila-league/secret_grinch | b06ac85ff5f06d5405d190ccc9966b01f0406b87 | [
"Apache-2.0"
] | 1 | 2018-10-03T03:30:29.000Z | 2018-10-03T03:30:29.000Z | defmodule SecretGrinch.Assignment do
@moduledoc """
Represents the relationship between a sender and a recipient for a match
"""
use Ecto.Schema
import Ecto.Changeset
alias SecretGrinch.Assignment
schema "assignments" do
field :match_id, :id
field :sender_id, :id
field :recepient_id, :id
timestamps()
end
@doc false
def changeset(%Assignment{} = assignment, attrs) do
assignment
|> cast(attrs, [])
|> validate_required([])
end
end
| 19.44 | 74 | 0.685185 |
ffa06155a955b7a58d7ec758288aa1adb4b4b787 | 1,700 | ex | Elixir | apps/welcome/lib/welcome_web/endpoint.ex | norbu09/e_no_time | 16a0db136dd91cdcf38d4aab5f11b0684dae289d | [
"BSD-2-Clause"
] | null | null | null | apps/welcome/lib/welcome_web/endpoint.ex | norbu09/e_no_time | 16a0db136dd91cdcf38d4aab5f11b0684dae289d | [
"BSD-2-Clause"
] | null | null | null | apps/welcome/lib/welcome_web/endpoint.ex | norbu09/e_no_time | 16a0db136dd91cdcf38d4aab5f11b0684dae289d | [
"BSD-2-Clause"
] | null | null | null | defmodule WelcomeWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :welcome
socket "/socket", WelcomeWeb.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: :welcome, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
plug Plug.Session,
store: :cookie,
key: "_welcome_key",
signing_salt: "Ds8Med3i"
plug WelcomeWeb.MetricsExporter
plug WelcomeWeb.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.813559 | 95 | 0.710588 |
ffa06bbf732ba6a7c78ddb50da440bf4aee4af40 | 397 | exs | Elixir | test/rubber_band/client/request_error_test.exs | tlux/rubberband | bece85cf8049ba487bba1d5df0906f6fbfa146eb | [
"MIT"
] | null | null | null | test/rubber_band/client/request_error_test.exs | tlux/rubberband | bece85cf8049ba487bba1d5df0906f6fbfa146eb | [
"MIT"
] | null | null | null | test/rubber_band/client/request_error_test.exs | tlux/rubberband | bece85cf8049ba487bba1d5df0906f6fbfa146eb | [
"MIT"
] | null | null | null | defmodule RubberBand.RequestErrorTest do
use ExUnit.Case, async: true
alias RubberBand.Client.RequestError
@error %RequestError{reason: :timeout}
test "raiseable" do
assert_raise RequestError, fn ->
raise @error
end
end
describe "message/1" do
test "get message" do
assert RequestError.message(@error) == "Request error: #{@error.reason}"
end
end
end
| 19.85 | 78 | 0.692695 |
ffa07b2cd4aebb60cd65ae7feb27cce858176ddb | 519 | exs | Elixir | priv/repo/migrations/20140501024735_create_readings.exs | micahyoung/cbstats-importer | a7176b3a25d8a4e919ddda32475c9ecf65e9892a | [
"Unlicense",
"MIT"
] | 1 | 2016-01-06T18:19:35.000Z | 2016-01-06T18:19:35.000Z | priv/repo/migrations/20140501024735_create_readings.exs | micahyoung/cbstats-importer | a7176b3a25d8a4e919ddda32475c9ecf65e9892a | [
"Unlicense",
"MIT"
] | null | null | null | priv/repo/migrations/20140501024735_create_readings.exs | micahyoung/cbstats-importer | a7176b3a25d8a4e919ddda32475c9ecf65e9892a | [
"Unlicense",
"MIT"
] | null | null | null | defmodule CbstatsImporter.Repo.Migrations.CreateReadings do
use Ecto.Migration
def up do
"""
CREATE TABLE readings (
id serial NOT NULL,
station_id integer,
status character varying(255),
available_bikes integer,
available_docks integer,
taken_at timestamp without time zone,
created_at timestamp without time zone,
updated_at timestamp without time zone
);
"""
end
def down do
"""
DROP TABLE readings;
"""
end
end
| 20.76 | 59 | 0.639692 |
ffa0903b81c35050403a4c32b6a651275c8d7939 | 2,080 | exs | Elixir | integration_test/support/models.exs | john-vinters/ecto | 82683a80e865dd0863c08860f609d6910355bfc4 | [
"Apache-2.0"
] | null | null | null | integration_test/support/models.exs | john-vinters/ecto | 82683a80e865dd0863c08860f609d6910355bfc4 | [
"Apache-2.0"
] | null | null | null | integration_test/support/models.exs | john-vinters/ecto | 82683a80e865dd0863c08860f609d6910355bfc4 | [
"Apache-2.0"
] | null | null | null | Code.require_file "types.exs", __DIR__
defmodule Ecto.Integration.Post do
use Ecto.Model
schema "posts" do
field :title, :string
field :counter, :integer, read_after_writes: true
field :text, :binary
field :uuid, :uuid
field :temp, :string, default: "temp", virtual: true
field :public, :boolean, default: true
field :cost, :decimal
field :visits, :integer
field :intensity, :float
has_many :comments, Ecto.Integration.Comment
has_one :permalink, Ecto.Integration.Permalink
has_many :comments_authors, through: [:comments, :author]
timestamps
end
end
defmodule Ecto.Integration.PostUsecTimestamps do
use Ecto.Model
schema "posts" do
field :title, :string
timestamps usec: true
end
end
defmodule Ecto.Integration.Comment do
use Ecto.Model
schema "comments" do
field :text, :string
field :posted, :datetime
belongs_to :post, Ecto.Integration.Post
belongs_to :author, Ecto.Integration.User
has_one :post_permalink, through: [:post, :permalink]
end
end
defmodule Ecto.Integration.Permalink do
use Ecto.Model
@foreign_key_type Custom.Permalink
schema "permalinks" do
field :url, :string
field :lock_version, :integer, default: 1
belongs_to :post, Ecto.Integration.Post
has_many :post_comments_authors, through: [:post, :comments_authors]
end
optimistic_lock :lock_version
end
defmodule Ecto.Integration.User do
use Ecto.Model
schema "users" do
field :name, :string
has_many :comments, Ecto.Integration.Comment, foreign_key: :author_id
belongs_to :custom, Ecto.Integration.Custom, references: :foo, type: :uuid
end
end
defmodule Ecto.Integration.Custom do
use Ecto.Model
@primary_key {:foo, :uuid, []}
schema "customs" do
end
end
defmodule Ecto.Integration.Barebone do
use Ecto.Model
@primary_key false
schema "barebones" do
field :num, :integer
end
end
defmodule Ecto.Integration.Tag do
use Ecto.Model
schema "tags" do
field :ints, {:array, :integer}
field :uuids, {:array, Ecto.UUID}
end
end
| 22.608696 | 78 | 0.715865 |
ffa0c41c28eda8ce734d53b7da398a5a47794448 | 2,338 | ex | Elixir | aoc2019_elixir/apps/day23/lib/nat.ex | mjm/advent-of-code-2019 | a30599c1cba05d574fb30b6de98acdcec1ddc643 | [
"MIT"
] | 1 | 2019-12-09T07:43:02.000Z | 2019-12-09T07:43:02.000Z | aoc2019_elixir/apps/day23/lib/nat.ex | mjm/advent-of-code-2019 | a30599c1cba05d574fb30b6de98acdcec1ddc643 | [
"MIT"
] | null | null | null | aoc2019_elixir/apps/day23/lib/nat.ex | mjm/advent-of-code-2019 | a30599c1cba05d574fb30b6de98acdcec1ddc643 | [
"MIT"
] | null | null | null | require Logger
defmodule Day23.NAT do
@moduledoc """
A process that is responsible for keeping the network active.
The NAT receives packets addressed to address `255` during the course of normal
network traffic. When the router informs the NAT that all addresses are idling,
the NAT may rebroadcast the last packet it received to the computer at address
`0` to restart traffic.
If the NAT would send computer `0` two packets in a row with the same `y` value,
it will instead return the `{x, y}` pair from its task.
"""
@typedoc """
A NAT pid.
"""
@type t() :: pid()
@typedoc """
A mode that the NAT can run in.
"""
@type mode() :: :once | :ongoing
@doc """
Start a new NAT for a router.
The NAT should be created before any computers on the network start sending
traffic. The NAT will not receive any packets from the router until it is added
to the router with `Day23.Router.set_nat/2`.
"""
@spec async(Day23.Router.t(), mode) :: Task.t()
def async(router, mode) do
Task.async(__MODULE__, :run, [router, mode])
end
@doc """
Runs the NAT in the given mode.
If `mode` is `:once`, then the NAT will simply return the first packet it
receives from the router. No restarting of network traffic will occur.
If `mode` is `:ongoing`, then the NAT will perform its normal function of
restarting the network traffic when it idles.
"""
@spec run(Day23.Router.t(), mode) :: {number, number}
def run(router, mode) do
Logger.metadata(mode: mode)
case mode do
:once -> run_once()
:ongoing -> loop(router, nil, nil)
end
end
defp run_once do
receive do
{:packet, {x, y}} ->
Logger.debug("nat received packet", x: x, y: y)
{x, y}
end
end
defp loop(router, last_received, last_broadcast) do
receive do
{:packet, {x, y}} ->
Logger.debug("nat received packet", x: x, y: y)
loop(router, {x, y}, last_broadcast)
:all_idle ->
{x, y} = last_received
{_, y0} = last_broadcast || {nil, nil}
Logger.debug("all queues idle", x: x, y: y, prev_y: y0)
cond do
y == y0 ->
{x, y}
true ->
Day23.Router.route(router, {0, x, y})
loop(router, last_received, last_received)
end
end
end
end
| 26.873563 | 82 | 0.624893 |
ffa0cf64c85032c69c0aada5a2d9f517f23034d1 | 3,292 | ex | Elixir | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_product.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_product.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"Apache-2.0"
] | null | null | null | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_product.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"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.Vision.V1.Model.GoogleCloudVisionV1p1beta1Product do
@moduledoc """
A Product contains ReferenceImages.
## Attributes
* `description` (*type:* `String.t`, *default:* `nil`) - User-provided metadata to be stored with this product. Must be at most 4096
characters long.
* `displayName` (*type:* `String.t`, *default:* `nil`) - The user-provided name for this Product. Must not be empty. Must be at most
4096 characters long.
* `name` (*type:* `String.t`, *default:* `nil`) - The resource name of the product.
Format is:
`projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
This field is ignored when creating a product.
* `productCategory` (*type:* `String.t`, *default:* `nil`) - The category for the product identified by the reference image. This should
be either "homegoods-v2", "apparel-v2", or "toys-v2". The legacy categories
"homegoods", "apparel", and "toys" are still supported, but these should
not be used for new products.
This field is immutable.
* `productLabels` (*type:* `list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1ProductKeyValue.t)`, *default:* `nil`) - Key-value pairs that can be attached to a product. At query time,
constraints can be specified based on the product_labels.
Note that integer values can be provided as strings, e.g. "1199". Only
strings with integer values can match a range-based restriction which is
to be supported soon.
Multiple values can be assigned to the same key. One product may have up to
100 product_labels.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:description => String.t(),
:displayName => String.t(),
:name => String.t(),
:productCategory => String.t(),
:productLabels =>
list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1ProductKeyValue.t())
}
field(:description)
field(:displayName)
field(:name)
field(:productCategory)
field(
:productLabels,
as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1ProductKeyValue,
type: :list
)
end
defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1Product do
def decode(value, options) do
GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1Product.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1Product do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.729412 | 195 | 0.71294 |
ffa0e1c713b34b02819c22fedb8a3ad512aa2dad | 2,031 | ex | Elixir | lib/edgedb/connection/queries_cache.ex | f0lio/edgedb-elixir | b285bd8037b0b951aabfa1d1733889880f8bfd66 | [
"MIT"
] | null | null | null | lib/edgedb/connection/queries_cache.ex | f0lio/edgedb-elixir | b285bd8037b0b951aabfa1d1733889880f8bfd66 | [
"MIT"
] | null | null | null | lib/edgedb/connection/queries_cache.ex | f0lio/edgedb-elixir | b285bd8037b0b951aabfa1d1733889880f8bfd66 | [
"MIT"
] | null | null | null | defmodule EdgeDB.Connection.QueriesCache do
@moduledoc false
use GenServer
alias EdgeDB.Protocol.Enums
defmodule State do
@moduledoc false
defstruct [
:cache
]
@type t() :: %__MODULE__{
cache: :ets.tab()
}
end
@type t() :: GenServer.server()
@spec start_link(list()) :: GenServer.on_start()
def start_link(_opts \\ []) do
GenServer.start_link(__MODULE__, [])
end
@spec get(t(), String.t(), Enums.Cardinality.t(), Enums.IOFormat.t(), boolean()) ::
EdgeDB.Query.t() | nil
def get(cache, statement, cardinality, io_format, required) do
GenServer.call(cache, {:get, statement, cardinality, io_format, required})
end
@spec add(t(), EdgeDB.Query.t()) :: :ok
def add(cache, %EdgeDB.Query{} = query) do
GenServer.cast(cache, {:add, query})
end
@spec clear(t(), EdgeDB.Query.t()) :: :ok
def clear(cache, %EdgeDB.Query{} = query) do
GenServer.cast(cache, {:clear, query})
end
@impl GenServer
def init(_opts \\ []) do
{:ok, %State{cache: new_cache()}}
end
@impl GenServer
def handle_call(
{:get, statement, cardinality, io_format, required},
_from,
%State{cache: cache} = state
) do
key = {statement, cardinality, io_format, required}
query =
case :ets.lookup(cache, key) do
[{^key, query}] ->
query
[] ->
nil
end
{:reply, query, state}
end
@impl GenServer
def handle_cast({:add, query}, %State{cache: cache} = state) do
key = {query.statement, query.cardinality, query.io_format, query.required}
:ets.insert(cache, {key, %EdgeDB.Query{query | cached: true}})
{:noreply, state}
end
@impl GenServer
def handle_cast({:clear, query}, %State{cache: cache} = state) do
key = {query.statement, query.cardinality, query.io_format, query.required}
:ets.delete(cache, key)
{:noreply, state}
end
defp new_cache do
:ets.new(:connection_queries_cache, [:set, :private])
end
end
| 23.079545 | 85 | 0.615953 |
ffa0f31fc0c3d4643bcb88d08d042b27d23ecfcb | 342 | exs | Elixir | day24/test/day24_test.exs | bjorng/advent-of-code-2021 | 82c22dfa0ba7e9134e39b9dbc95227bb99f62c8d | [
"Apache-2.0"
] | 10 | 2021-12-01T08:49:00.000Z | 2022-03-24T13:24:50.000Z | day24/test/day24_test.exs | bjorng/advent-of-code-2021 | 82c22dfa0ba7e9134e39b9dbc95227bb99f62c8d | [
"Apache-2.0"
] | null | null | null | day24/test/day24_test.exs | bjorng/advent-of-code-2021 | 82c22dfa0ba7e9134e39b9dbc95227bb99f62c8d | [
"Apache-2.0"
] | 1 | 2021-12-16T07:09:11.000Z | 2021-12-16T07:09:11.000Z | defmodule Day24Test do
use ExUnit.Case
doctest Day24
test "part 1 with my input data" do
assert Day24.part1(input()) == 51983999947999
end
test "part 2 with my input data" do
assert Day24.part2(input()) == 11211791111365
end
defp input() do
File.read!("input.txt")
|> String.split("\n", trim: true)
end
end
| 19 | 49 | 0.660819 |
ffa108388536e87261e01ead7693d9e330638785 | 510 | exs | Elixir | test/exred_node_aws_iot_daemon_test.exs | exredorg/exred_node_aws_iot_daemon | a48135563d9ba6cc4790be109376c3532a5b3595 | [
"MIT"
] | null | null | null | test/exred_node_aws_iot_daemon_test.exs | exredorg/exred_node_aws_iot_daemon | a48135563d9ba6cc4790be109376c3532a5b3595 | [
"MIT"
] | null | null | null | test/exred_node_aws_iot_daemon_test.exs | exredorg/exred_node_aws_iot_daemon | a48135563d9ba6cc4790be109376c3532a5b3595 | [
"MIT"
] | null | null | null | defmodule Exred.Node.AwsIotDaemonTest do
use ExUnit.Case
doctest Exred.Node.AwsIotDaemon
@config_overrides %{
host: %{value: "test.mosquitto.org"},
port: %{value: 8883}
}
use Exred.NodeTest, module: Exred.Node.AwsIotDaemon, config: @config_overrides
setup_all do
start_node()
end
test "node starts", context do
assert Process.alive?(context.pid)
end
test "mqtt client connected" do
:timer.sleep(5000)
st = AwsIotClient.get_state()
assert st.ready
end
end
| 19.615385 | 80 | 0.696078 |
ffa1396d3722d8a584b3767d08f6741f51a56d6e | 32,405 | ex | Elixir | lib/gringotts/gateways/authorize_net.ex | lyoung83/gringotts | c119a3027e2a313a32f5abeb76a401979e48f7d0 | [
"MIT"
] | null | null | null | lib/gringotts/gateways/authorize_net.ex | lyoung83/gringotts | c119a3027e2a313a32f5abeb76a401979e48f7d0 | [
"MIT"
] | null | null | null | lib/gringotts/gateways/authorize_net.ex | lyoung83/gringotts | c119a3027e2a313a32f5abeb76a401979e48f7d0 | [
"MIT"
] | null | null | null | defmodule Gringotts.Gateways.AuthorizeNet do
@moduledoc """
A module for working with the Authorize.Net payment gateway.
Refer the official Authorize.Net [API docs][docs].
The following set of functions for Authorize.Net have been implemented:
| Action | Method |
| ------ | ------ |
| Authorize a Credit Card | `authorize/3` |
| Capture a previously authorized amount | `capture/3` |
| Charge a Credit Card | `purchase/3` |
| Refund a transaction | `refund/3` |
| Void a transaction | `void/2` |
| Create Customer Profile | `store/2` |
| Create Customer Payment Profile | `store/2` |
| Delete Customer Profile | `unstore/2` |
Most `Gringotts` API calls accept an optional `Keyword` list `opts` to supply
optional arguments for transactions with the Authorize.Net gateway. The
following keys are supported:
| Key |
| ---- |
| `customer` |
| `invoice` |
| `bill_to` |
| `ship_to` |
| `customer_ip` |
| `order` |
| `lineitems` |
| `ref_id` |
| `tax` |
| `duty` |
| `shipping` |
| `po_number` |
| `customer_type` |
| `customer_profile_id` |
| `profile` |
To know more about these keywords check the [Request and Response][req-resp] tabs for each
API method.
[docs]: https://developer.authorize.net/api/reference/index.html
[req-resp]: https://developer.authorize.net/api/reference/index.html#payment-transactions
## Notes
1. Though Authorize.Net supports [multiple currencies][currencies] however,
multiple currencies in one account is not supported. A merchant would need
multiple Authorize.Net accounts, one for each chosen currency. Please refer
the section on "Supported acquirers and currencies" [here][currencies].
2. _You, the merchant needs to be PCI-DSS Compliant if you wish to use this
module. Your server will recieve sensitive card and customer information._
3. The responses of this module include a non-standard field: `:cavv_result`.
- `:cavv_result` is the "cardholder authentication verification response
code". In case of Mastercard transactions, this field will always be
`nil`. Please refer the "Response Format" section in the [docs][docs] for
more details.
[currencies]: https://community.developer.authorize.net/t5/The-Authorize-Net-Developer-Blog/Authorize-Net-UK-Europe-Update/ba-p/35957
## Configuring your AuthorizeNet account at `Gringotts`
To use this module you need to [create an account][dashboard] with the
Authorize.Net gateway and obtain your login secrets: `name` and
`transactionKey`.
Your Application config **must include the `name` and `transaction_key`
fields** and would look something like this:
config :gringotts, Gringotts.Gateways.AuthorizeNet,
name: "name_provided_by_authorize_net",
transaction_key: "transactionKey_provided_by_authorize_net"
## Scope of this module
Although Authorize.Net supports payments from various sources (check your
[dashboard][dashboard]), this library currently accepts payments by
(supported) credit cards only.
[dashboard]: https://www.authorize.net/solutions/merchantsolutions/onlinemerchantaccount/
## Following the examples
1. First, set up a sample application and configure it to work with Authorize.Net.
- You could do that from scratch by following our [Getting Started][gs]
guide.
- To save you time, we recommend [cloning our example repo][example-repo]
that gives you a pre-configured sample app ready-to-go.
+ You could use the same config or update it the with your "secrets"
[above](#module-configuring-your-authorizenet-account-at-gringotts).
2. To save a lot of time, create a [`.iex.exs`][iex-docs] file as shown in
[this gist][authorize_net.iex.exs] to introduce a set of handy bindings and
aliases.
We'll be using these bindings in the examples below.
[example-repo]: https://github.com/aviabird/gringotts_example
[iex-docs]: https://hexdocs.pm/iex/IEx.html#module-the-iex-exs-file
[authorize_net.iex.exs]: https://gist.github.com/oyeb/b1030058bda1fa9a3d81f1cf30723695
[gs]: https://github.com/aviabird/gringotts/wiki
"""
import XmlBuilder
use Gringotts.Gateways.Base
use Gringotts.Adapter, required_config: [:name, :transaction_key]
alias Gringotts.Gateways.AuthorizeNet.ResponseHandler
@test_url "https://apitest.authorize.net/xml/v1/request.api"
@production_url "https://api.authorize.net/xml/v1/request.api"
@headers [{"Content-Type", "text/xml"}]
@transaction_type %{
purchase: "authCaptureTransaction",
authorize: "authOnlyTransaction",
capture: "priorAuthCaptureTransaction",
refund: "refundTransaction",
void: "voidTransaction"
}
@aut_net_namespace "AnetApi/xml/v1/schema/AnetApiSchema.xsd"
alias Gringotts.{CreditCard, Money, Response}
@doc """
Transfers `amount` from the customer to the merchant.
Charges a credit `card` for the specified `amount`. It performs `authorize`
and `capture` at the [same time][auth-cap-same-time].
Authorize.Net returns `transId` (available in the `Response.id` field) which
can be used to:
* `refund/3` a settled transaction.
* `void/2` a transaction.
[auth-cap-same-time]: https://developer.authorize.net/api/reference/index.html#payment-transactions-charge-a-credit-card
## Optional Fields
opts = [
order: %{invoice_number: String, description: String},
ref_id: String,
lineitems: %{
item_id: String, name: String, description: String,
quantity: Integer, unit_price: Gringotts.Money.t()
},
tax: %{amount: Gringotts.Money.t(), name: String, description: String},
duty: %{amount: Gringotts.Money.t(), name: String, description: String},
shipping: %{amount: Gringotts.Money.t(), name: String, description: String},
po_number: String,
customer: %{id: String},
bill_to: %{
first_name: String, last_name: String, company: String,
address: String, city: String, state: String, zip: String,
country: String
},
ship_to: %{
first_name: String, last_name: String, company: String, address: String,
city: String, state: String, zip: String, country: String
},
customer_ip: String
]
## Example
iex> amount = Money.new(20, :USD)
iex> opts = [
ref_id: "123456",
order: %{invoice_number: "INV-12345", description: "Product Description"},
lineitems: %{item_id: "1", name: "vase", description: "Cannes logo", quantity: 1, unit_price: amount},
tax: %{name: "VAT", amount: Money.new("0.1", :EUR), description: "Value Added Tax"},
shipping: %{name: "SAME-DAY-DELIVERY", amount: Money.new("0.56", :EUR), description: "Zen Logistics"},
duty: %{name: "import_duty", amount: Money.new("0.25", :EUR), description: "Upon import of goods"}
]
iex> card = %CreditCard{number: "5424000000000015", year: 2099, month: 12, verification_code: "999"}
iex> result = Gringotts.purchase(Gringotts.Gateways.AuthorizeNet, amount, card, opts)
"""
@spec purchase(Money.t(), CreditCard.t(), Keyword.t()) :: {:ok | :error, Response.t()}
def purchase(amount, payment, opts) do
request_data = add_auth_purchase(amount, payment, opts, @transaction_type[:purchase])
commit(request_data, opts)
end
@doc """
Authorize a credit card transaction.
The authorization validates the `card` details with the banking network,
places a hold on the transaction `amount` in the customer’s issuing bank and
also triggers risk management. Funds are not transferred.
To transfer the funds to merchant's account follow this up with a `capture/3`.
Authorize.Net returns a `transId` (available in the `Response.id` field) which
can be used for:
* `capture/3` an authorized transaction.
* `void/2` a transaction.
## Optional Fields
opts = [
order: %{invoice_number: String, description: String},
ref_id: String,
lineitems: %{
item_id: String, name: String, description: String,
quantity: Integer, unit_price: Gringotts.Money.t()
},
tax: %{amount: Gringotts.Money.t(), name: String, description: String},
duty: %{amount: Gringotts.Money.t(), name: String, description: String},
shipping: %{amount: Gringotts.Money.t(), name: String, description: String},
po_number: String,
customer: %{id: String},
bill_to: %{
first_name: String, last_name: String, company: String,
address: String, city: String, state: String, zip: String,
country: String
},
ship_to: %{
first_name: String, last_name: String, company: String, address: String,
city: String, state: String, zip: String, country: String
},
customer_ip: String
]
## Example
iex> amount = Money.new(20, :USD)
iex> opts = [
ref_id: "123456",
order: %{invoice_number: "INV-12345", description: "Product Description"},
lineitems: %{itemId: "1", name: "vase", description: "Cannes logo", quantity: 1, unit_price: amount},
tax: %{name: "VAT", amount: Money.new("0.1", :EUR), description: "Value Added Tax"},
shipping: %{name: "SAME-DAY-DELIVERY", amount: Money.new("0.56", :EUR), description: "Zen Logistics"},
duty: %{name: "import_duty", amount: Money.new("0.25", :EUR), description: "Upon import of goods"}
]
iex> card = %CreditCard{number: "5424000000000015", year: 2099, month: 12, verification_code: "999"}
iex> result = Gringotts.authorize(Gringotts.Gateways.AuthorizeNet, amount, card, opts)
"""
@spec authorize(Money.t(), CreditCard.t(), Keyword.t()) :: {:ok | :error, Response.t()}
def authorize(amount, payment, opts) do
request_data = add_auth_purchase(amount, payment, opts, @transaction_type[:authorize])
commit(request_data, opts)
end
@doc """
Captures a pre-authorized `amount`.
`amount` is transferred to the merchant account by Authorize.Net when it is smaller or
equal to the amount used in the pre-authorization referenced by `id`.
Authorize.Net returns a `transId` (available in the `Response.id` field) which
can be used to:
* `refund/3` a settled transaction.
* `void/2` a transaction.
## Notes
* Authorize.Net automatically settles authorized transactions after 24
hours. Hence, unnecessary authorizations must be `void/2`ed within this
period!
* Though Authorize.Net supports partial capture of the authorized `amount`, it
is [advised][sound-advice] not to do so.
[sound-advice]: https://support.authorize.net/authkb/index?page=content&id=A1720&actp=LIST
## Optional Fields
opts = [
order: %{invoice_number: String, description: String},
ref_id: String
]
## Example
iex> opts = [
ref_id: "123456"
]
iex> amount = Money.new(20, :USD)
iex> id = "123456"
iex> result = Gringotts.capture(Gringotts.Gateways.AuthorizeNet, id, amount, opts)
"""
@spec capture(String.t(), Money.t(), Keyword.t()) :: {:ok | :error, Response.t()}
def capture(id, amount, opts) do
request_data = normal_capture(amount, id, opts, @transaction_type[:capture])
commit(request_data, opts)
end
@doc """
Refund `amount` for a settled transaction referenced by `id`.
The `payment` field in the `opts` is used to set the instrument/mode of
payment, which could be different from the original one. Currently, we
support only refunds to cards, so put the `card` details in the `payment`.
## Required fields
opts = [
payment: %{card: %{number: String, year: Integer, month: Integer}}
]
## Optional fields
opts = [ref_id: String]
## Example
iex> opts = [
payment: %{card: %{number: "5424000000000015", year: 2099, month: 12}}
ref_id: "123456"
]
iex> id = "123456"
iex> amount = Money.new(20, :USD)
iex> result = Gringotts.refund(Gringotts.Gateways.AuthorizeNet, amount, id, opts)
"""
@spec refund(Money.t(), String.t(), Keyword.t()) :: {:ok | :error, Response.t()}
def refund(amount, id, opts) do
request_data = normal_refund(amount, id, opts, @transaction_type[:refund])
commit(request_data, opts)
end
@doc """
Voids the referenced payment.
This method attempts a reversal of the either a previous `purchase/3` or
`authorize/3` referenced by `id`.
It can cancel either an original transaction that may not be settled or an
entire order composed of more than one transaction.
## Optional fields
opts = [ref_id: String]
## Example
iex> opts = [
ref_id: "123456"
]
iex> id = "123456"
iex> result = Gringotts.void(Gringotts.Gateways.AuthorizeNet, id, opts)
"""
@spec void(String.t(), Keyword.t()) :: {:ok | :error, Response.t()}
def void(id, opts) do
request_data = normal_void(id, opts, @transaction_type[:void])
commit(request_data, opts)
end
@doc """
Store a customer's profile and optionally associate it with a payment profile.
Authorize.Net separates a [customer's profile][cust-profile] from their payment
profile. Thus a customer can have multiple payment profiles.
## Create both profiles
Add `:customer` details in `opts` and also provide `card` details. The response
will contain a `:customer_profile_id`.
## Associate payment profile with existing customer profile
Simply pass the `:customer_profile_id` in the `opts`. This will add the `card`
details to the profile referenced by the supplied `:customer_profile_id`.
## Notes
* Currently only supports `credit card` in the payment profile.
* The supplied `card` details can be validated by supplying a
[`:validation_mode`][cust-profile], available options are `testMode` and
`liveMode`, the deafult is `testMode`.
[cust-profile]: https://developer.authorize.net/api/reference/index.html#customer-profiles-create-customer-profile
## Required Fields
opts = [
profile: %{merchant_customer_id: String, description: String, email: String}
]
## Optional Fields
opts = [
validation_mode: String,
bill_to: %{
first_name: String, last_name: String, company: String, address: String,
city: String, state: String, zip: String, country: String
},
customer_type: String,
customer_profile_id: String
]
## Example
iex> opts = [
profile: %{merchant_customer_id: 123456, description: "test store", email: "test@gmail.com"},
validation_mode: "testMode"
]
iex> card = %CreditCard{number: "5424000000000015", year: 2099, month: 12, verification_code: "999"}
iex> result = Gringotts.store(Gringotts.Gateways.AuthorizeNet, card, opts)
"""
@spec store(CreditCard.t(), Keyword.t()) :: {:ok | :error, Response.t()}
def store(card, opts) do
request_data =
if opts[:customer_profile_id] do
card |> create_customer_payment_profile(opts) |> generate(format: :none)
else
card |> create_customer_profile(opts) |> generate(format: :none)
end
commit(request_data, opts)
end
@doc """
Remove a customer profile from the payment gateway.
Use this function to unstore the customer card information by deleting the customer profile
present. Requires the customer profile id.
## Example
iex> id = "123456"
iex> result = Gringotts.store(Gringotts.Gateways.AuthorizeNet, id)
"""
@spec unstore(String.t(), Keyword.t()) :: {:ok | :error, Response.t()}
def unstore(customer_profile_id, opts) do
request_data = customer_profile_id |> delete_customer_profile(opts) |> generate(format: :none)
commit(request_data, opts)
end
# method to make the API request with params
defp commit(payload, opts) do
opts
|> base_url()
|> HTTPoison.post(payload, @headers)
|> respond()
end
defp respond({:ok, %{body: body, status_code: 200}}), do: ResponseHandler.respond(body)
defp respond({:ok, %{body: body, status_code: code}}) do
{:error, %Response{raw: body, status_code: code}}
end
defp respond({:error, %HTTPoison.Error{} = error}) do
{
:error,
%Response{
reason: "network related failure",
message: "HTTPoison says '#{error.reason}' [ID: #{error.id || "nil"}]"
}
}
end
##############################################################################
# HELPER METHODS #
##############################################################################
# function for formatting the request as an xml for purchase and authorize method
defp add_auth_purchase(amount, payment, opts, transaction_type) do
:createTransactionRequest
|> element(%{xmlns: @aut_net_namespace}, [
add_merchant_auth(opts[:config]),
add_order_id(opts),
add_purchase_transaction_request(amount, transaction_type, payment, opts)
])
|> generate(format: :none)
end
# function for formatting the request for normal capture
defp normal_capture(amount, id, opts, transaction_type) do
:createTransactionRequest
|> element(%{xmlns: @aut_net_namespace}, [
add_merchant_auth(opts[:config]),
add_order_id(opts),
add_capture_transaction_request(amount, id, transaction_type)
])
|> generate(format: :none)
end
# function to format the request for normal refund
defp normal_refund(amount, id, opts, transaction_type) do
:createTransactionRequest
|> element(%{xmlns: @aut_net_namespace}, [
add_merchant_auth(opts[:config]),
add_order_id(opts),
add_refund_transaction_request(amount, id, opts, transaction_type)
])
|> generate(format: :none)
end
# function to format the request for normal void operation
defp normal_void(id, opts, transaction_type) do
:createTransactionRequest
|> element(%{xmlns: @aut_net_namespace}, [
add_merchant_auth(opts[:config]),
add_order_id(opts),
element(:transactionRequest, [
add_transaction_type(transaction_type),
add_ref_trans_id(id)
])
])
|> generate(format: :none)
end
defp create_customer_payment_profile(card, opts) do
element(:createCustomerPaymentProfileRequest, %{xmlns: @aut_net_namespace}, [
add_merchant_auth(opts[:config]),
element(:customerProfileId, opts[:customer_profile_id]),
element(:paymentProfile, [
add_billing_info(opts),
add_payment_source(card)
]),
element(
:validationMode,
if(opts[:validation_mode], do: opts[:validation_mode], else: "testMode")
)
])
end
defp create_customer_profile(card, opts) do
element(:createCustomerProfileRequest, %{xmlns: @aut_net_namespace}, [
add_merchant_auth(opts[:config]),
element(:profile, [
element(:merchantCustomerId, opts[:profile][:merchant_customer_id]),
element(:description, opts[:profile][:description]),
element(:email, opts[:profile][:description]),
element(:paymentProfiles, [
element(
:customerType,
if(opts[:customer_type], do: opts[:customer_type], else: "individual")
),
add_billing_info(opts),
add_payment_source(card)
])
]),
element(
:validationMode,
if(opts[:validation_mode], do: opts[:validation_mode], else: "testMode")
)
])
end
defp delete_customer_profile(id, opts) do
element(:deleteCustomerProfileRequest, %{xmlns: @aut_net_namespace}, [
add_merchant_auth(opts[:config]),
element(:customerProfileId, id)
])
end
##############################################################################
# HELPERS TO ASSIST IN BUILDING AND #
# COMPOSING DIFFERENT XmlBuilder TAGS #
##############################################################################
defp add_merchant_auth(opts) do
element(:merchantAuthentication, [
element(:name, opts[:name]),
element(:transactionKey, opts[:transaction_key])
])
end
defp add_order_id(opts) do
element(:refId, opts[:ref_id])
end
defp add_purchase_transaction_request(amount, transaction_type, payment, opts) do
element(:transactionRequest, [
add_transaction_type(transaction_type),
add_amount(amount),
add_payment_source(payment),
add_invoice(opts),
add_tax_fields(opts),
add_duty_fields(opts),
add_shipping_fields(opts),
add_po_number(opts),
add_customer_info(opts)
])
end
defp add_capture_transaction_request(amount, id, transaction_type) do
element(:transactionRequest, [
add_transaction_type(transaction_type),
add_amount(amount),
add_ref_trans_id(id)
])
end
defp add_refund_transaction_request(amount, id, opts, transaction_type) do
element(:transactionRequest, [
add_transaction_type(transaction_type),
add_amount(amount),
element(:payment, [
element(:creditCard, [
element(:cardNumber, opts[:payment][:card][:number]),
element(
:expirationDate,
join_string([opts[:payment][:card][:year], opts[:payment][:card][:month]], "-")
)
])
]),
add_ref_trans_id(id)
])
end
defp add_ref_trans_id(id) do
element(:refTransId, id)
end
defp add_transaction_type(transaction_type) do
element(:transactionType, transaction_type)
end
defp add_amount(amount) do
if amount do
{_, value} = amount |> Money.to_string()
element(:amount, value)
end
end
defp add_payment_source(source) do
# have to implement for other sources like apple pay
# token payment method and check currently only for credit card
add_credit_card(source)
end
defp add_credit_card(source) do
element(:payment, [
element(:creditCard, [
element(:cardNumber, source.number),
element(:expirationDate, join_string([source.year, source.month], "-")),
element(:cardCode, source.verification_code)
])
])
end
defp add_invoice(opts) do
element([
element(:order, [
element(:invoiceNumber, opts[:order][:invoice_number]),
element(:description, opts[:order][:description])
]),
element(:lineItems, [
element(:lineItem, [
element(:itemId, opts[:lineitems][:item_id]),
element(:name, opts[:lineitems][:name]),
element(:description, opts[:lineitems][:description]),
element(:quantity, opts[:lineitems][:quantity]),
element(
:unitPrice,
opts[:lineitems][:unit_price] |> Money.value() |> Decimal.to_float()
)
])
])
])
end
defp add_tax_fields(opts) do
element(:tax, [
add_amount(opts[:tax][:amount]),
element(:name, opts[:tax][:name]),
element(:description, opts[:tax][:description])
])
end
defp add_duty_fields(opts) do
element(:duty, [
add_amount(opts[:duty][:amount]),
element(:name, opts[:duty][:name]),
element(:description, opts[:duty][:description])
])
end
defp add_shipping_fields(opts) do
element(:shipping, [
add_amount(opts[:shipping][:amount]),
element(:name, opts[:shipping][:name]),
element(:description, opts[:shipping][:description])
])
end
defp add_po_number(opts) do
element(:poNumber, opts[:po_number])
end
defp add_customer_info(opts) do
element([
add_customer_id(opts),
add_billing_info(opts),
add_shipping_info(opts),
add_customer_ip(opts)
])
end
defp add_customer_id(opts) do
element(:customer, [
element(:id, opts[:customer][:id])
])
end
defp add_billing_info(opts) do
element(:billTo, [
element(:firstName, opts[:bill_to][:first_name]),
element(:lastName, opts[:bill_to][:last_name]),
element(:company, opts[:bill_to][:company]),
element(:address, opts[:bill_to][:address]),
element(:city, opts[:bill_to][:city]),
element(:state, opts[:bill_to][:state]),
element(:zip, opts[:bill_to][:zip]),
element(:country, opts[:bill_to][:country])
])
end
defp add_shipping_info(opts) do
element(:shipTo, [
element(:firstName, opts[:ship_to][:first_name]),
element(:lastName, opts[:ship_to][:last_name]),
element(:company, opts[:ship_to][:company]),
element(:address, opts[:ship_to][:address]),
element(:city, opts[:ship_to][:city]),
element(:state, opts[:ship_to][:state]),
element(:zip, opts[:ship_to][:zip]),
element(:country, opts[:ship_to][:country])
])
end
defp add_customer_ip(opts) do
element(:customerIP, opts[:customer_ip])
end
defp join_string(list, symbol) do
Enum.join(list, symbol)
end
defp base_url(opts) do
if opts[:config][:mode] == :prod do
@production_url
else
@test_url
end
end
##################################################################################
# RESPONSE_HANDLER MODULE #
# #
##################################################################################
defmodule ResponseHandler do
@moduledoc false
alias Gringotts.Response
@supported_response_types [
"authenticateTestResponse",
"createTransactionResponse",
"ErrorResponse",
"createCustomerProfileResponse",
"createCustomerPaymentProfileResponse",
"deleteCustomerProfileResponse"
]
@avs_code_translator %{
# The street address matched, but the postal code did not.
"A" => {"pass", "fail"},
# No address information was provided.
"B" => {nil, nil},
# The AVS check returned an error.
"E" => {"fail", nil},
# The card was issued by a bank outside the U.S. and does not support AVS.
"G" => {nil, nil},
# Neither the street address nor postal code matched.
"N" => {"fail", "fail"},
# AVS is not applicable for this transaction.
"P" => {nil, nil},
# Retry — AVS was unavailable or timed out.
"R" => {nil, nil},
# AVS is not supported by card issuer.
"S" => {nil, nil},
# Address information is unavailable.
"U" => {nil, nil},
# The US ZIP+4 code matches, but the street address does not.
"W" => {"fail", "pass"},
# Both the street address and the US ZIP+4 code matched.
"X" => {"pass", "pass"},
# The street address and postal code matched.
"Y" => {"pass", "pass"},
# The postal code matched, but the street address did not.
"Z" => {"fail", "pass"},
# fallback in-case of absence
"" => {nil, nil},
# fallback in-case of absence
nil => {nil, nil}
}
@cvc_code_translator %{
"M" => "CVV matched.",
"N" => "CVV did not match.",
"P" => "CVV was not processed.",
"S" => "CVV should have been present but was not indicated.",
"U" => "The issuer was unable to process the CVV check.",
# fallback in-case of absence
nil => nil
}
@cavv_code_translator %{
"" => "CAVV not validated.",
"0" => "CAVV was not validated because erroneous data was submitted.",
"1" => "CAVV failed validation.",
"2" => "CAVV passed validation.",
"3" => "CAVV validation could not be performed; issuer attempt incomplete.",
"4" => "CAVV validation could not be performed; issuer system error.",
"5" => "Reserved for future use.",
"6" => "Reserved for future use.",
"7" =>
"CAVV failed validation, but the issuer is available. Valid for U.S.-issued card submitted to non-U.S acquirer.",
"8" =>
"CAVV passed validation and the issuer is available. Valid for U.S.-issued card submitted to non-U.S. acquirer.",
"9" =>
"CAVV failed validation and the issuer is unavailable. Valid for U.S.-issued card submitted to non-U.S acquirer.",
"A" =>
"CAVV passed validation but the issuer unavailable. Valid for U.S.-issued card submitted to non-U.S acquirer.",
"B" => "CAVV passed validation, information only, no liability shift.",
# fallback in-case of absence
nil => nil
}
def respond(body) do
response_map = XmlToMap.naive_map(body)
case extract_gateway_response(response_map) do
:undefined_response ->
{
:error,
%Response{
reason: "Undefined response from AunthorizeNet",
raw: body,
message: "You might wish to open an issue with Gringotts."
}
}
result ->
build_response(result, %Response{raw: body, status_code: 200})
end
end
def extract_gateway_response(response_map) do
# The type of the response should be supported
# Find the first non-nil from the above, if all are `nil`...
# We are in trouble!
@supported_response_types
|> Stream.map(&Map.get(response_map, &1, nil))
|> Enum.find(:undefined_response, & &1)
end
defp build_response(%{"messages" => %{"resultCode" => "Ok"}} = result, base_response) do
{:ok, ResponseHandler.parse_gateway_success(result, base_response)}
end
defp build_response(%{"messages" => %{"resultCode" => "Error"}} = result, base_response) do
{:error, ResponseHandler.parse_gateway_error(result, base_response)}
end
def parse_gateway_success(result, base_response) do
id = result["transactionResponse"]["transId"]
message = result["messages"]["message"]["text"]
avs_result = result["transactionResponse"]["avsResultCode"]
cvc_result = result["transactionResponse"]["cvvResultCode"]
cavv_result = result["transactionResponse"]["cavvResultCode"]
gateway_code = result["messages"]["message"]["code"]
base_response
|> set_id(id)
|> set_message(message)
|> set_gateway_code(gateway_code)
|> set_avs_result(avs_result)
|> set_cvc_result(cvc_result)
|> set_cavv_result(cavv_result)
end
def parse_gateway_error(result, base_response) do
message = result["messages"]["message"]["text"]
gateway_code = result["messages"]["message"]["code"]
error_text = result["transactionResponse"]["errors"]["error"]["errorText"]
error_code = result["transactionResponse"]["errors"]["error"]["errorCode"]
reason = "#{error_text} [Error code (#{error_code})]"
base_response
|> set_message(message)
|> set_gateway_code(gateway_code)
|> set_reason(reason)
end
############################################################################
# HELPERS #
############################################################################
defp set_id(response, id), do: %{response | id: id}
defp set_message(response, message), do: %{response | message: message}
defp set_gateway_code(response, code), do: %{response | gateway_code: code}
defp set_reason(response, body), do: %{response | reason: body}
defp set_avs_result(response, avs_code) do
{street, zip_code} = @avs_code_translator[avs_code]
%{response | avs_result: %{street: street, zip_code: zip_code}}
end
defp set_cvc_result(response, cvv_code) do
%{response | cvc_result: @cvc_code_translator[cvv_code]}
end
defp set_cavv_result(response, cavv_code) do
Map.put(response, :cavv_result, @cavv_code_translator[cavv_code])
end
end
end
| 35.885936 | 135 | 0.62478 |
ffa144b0c74fe46f3d4a2cbb67cbfecfebe29273 | 1,027 | ex | Elixir | lib/smartsheet/row/row.ex | kianmeng/smartsheet | ca3f0734fe4bc08811d1726c7dd1072502a60ad2 | [
"MIT"
] | null | null | null | lib/smartsheet/row/row.ex | kianmeng/smartsheet | ca3f0734fe4bc08811d1726c7dd1072502a60ad2 | [
"MIT"
] | 6 | 2020-07-21T17:36:50.000Z | 2021-12-16T00:49:21.000Z | lib/smartsheet/row/row.ex | kianmeng/smartsheet | ca3f0734fe4bc08811d1726c7dd1072502a60ad2 | [
"MIT"
] | 1 | 2020-10-20T13:04:51.000Z | 2020-10-20T13:04:51.000Z | defmodule Smartsheet.Row do
@derive [Poison.Encoder]
defstruct [
:id,
:sheet_id,
:access_level,
:attachments,
:cells,
:columns,
:conditional_format,
:created_at,
:created_by,
:discussions,
:expanded,
:filtered_out,
:format,
:in_critical_path,
:locked,
:locked_for_user,
:modified_at,
:modified_by,
:permalink,
:row_number,
:version
]
@type t :: %__MODULE__{
id: any,
sheet_id: any,
access_level: any,
attachments: any,
cells: any,
columns: any,
conditional_format: any,
created_at: any,
created_by: any,
discussions: any,
expanded: any,
filtered_out: any,
format: any,
in_critical_path: any,
locked: any,
locked_for_user: any,
modified_at: any,
modified_by: any,
permalink: any,
row_number: any,
version: any
}
end
| 19.75 | 34 | 0.528724 |
ffa14b87a14bb2f221f30f87aa2e98ebbb2cf7d4 | 266 | exs | Elixir | test/empty_web/views/layout_view_test.exs | manojsamanta/empty-app-with-auth | e601a7c6ef1b4a992758117e6bf0922a5ce08f04 | [
"MIT"
] | null | null | null | test/empty_web/views/layout_view_test.exs | manojsamanta/empty-app-with-auth | e601a7c6ef1b4a992758117e6bf0922a5ce08f04 | [
"MIT"
] | null | null | null | test/empty_web/views/layout_view_test.exs | manojsamanta/empty-app-with-auth | e601a7c6ef1b4a992758117e6bf0922a5ce08f04 | [
"MIT"
] | null | null | null | defmodule EmptyWeb.LayoutViewTest do
use EmptyWeb.ConnCase, async: true
# When testing helpers, you may want to import Phoenix.HTML and
# use functions such as safe_to_string() to convert the helper
# result into an HTML string.
# import Phoenix.HTML
end
| 29.555556 | 65 | 0.763158 |
ffa187e1182db369f5d04140fee334884aff50c4 | 2,685 | ex | Elixir | lib/retrospectivex/retrospectives/managers/board.ex | dreamingechoes/retrospectivex | cad0df6cfde5376121d841f4a8b36861b6ec5d45 | [
"MIT"
] | 5 | 2018-06-27T17:51:51.000Z | 2020-10-05T09:59:04.000Z | lib/retrospectivex/retrospectives/managers/board.ex | dreamingechoes/retrospectivex | cad0df6cfde5376121d841f4a8b36861b6ec5d45 | [
"MIT"
] | 1 | 2018-10-08T11:33:12.000Z | 2018-10-08T11:33:12.000Z | lib/retrospectivex/retrospectives/managers/board.ex | dreamingechoes/retrospectivex | cad0df6cfde5376121d841f4a8b36861b6ec5d45 | [
"MIT"
] | 2 | 2018-10-08T11:31:55.000Z | 2020-10-05T09:59:05.000Z | defmodule Retrospectivex.Retrospectives.Managers.Board do
import Ecto.Query, warn: false
alias Retrospectivex.Repo
alias Retrospectivex.Retrospectives.Schemas.Board
alias Retrospectivex.Retrospectives.Queries.Card, as: CardQuery
@doc """
Returns the list of boards.
## Examples
iex> list_boards()
[%Board{}, ...]
"""
def list_boards do
Repo.all(Board)
end
@doc """
Gets a single board.
Raises `Ecto.NoResultsError` if the Board does not exist.
## Examples
iex> get_board!(123)
%Board{}
iex> get_board!(456)
** (Ecto.NoResultsError)
"""
def get_board!(id) do
Board
|> Repo.get!(id)
|> Repo.preload(cards: CardQuery.default_order())
end
@doc """
Gets a single board.
Raises `Ecto.NoResultsError` if the Board does not exist.
## Examples
iex> get_board!(123)
%Board{}
iex> get_board!(456)
** (Ecto.NoResultsError)
"""
def get_board!(id, card_filters) do
Board
|> Repo.get!(id)
|> Repo.preload(cards: CardQuery.filter(card_filters))
end
@doc """
Gets a single board by slug and uuid.
Raises `Ecto.NoResultsError` if the Board does not exist.
## Examples
iex> get_board_by_slug_and_uuid!("some-slug", "some-uuid")
%Board{}
iex> get_board_by_slug_and_uuid!("some-slug", "some-uuid")
** (Ecto.NoResultsError)
"""
def get_board_by_slug_and_uuid!(slug, uuid) do
Board
|> Repo.get_by!(slug: slug, uuid: uuid)
|> Repo.preload(cards: CardQuery.default_order())
end
@doc """
Creates a board.
## Examples
iex> create_board(%{field: value})
{:ok, %Board{}}
iex> create_board(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_board(attrs \\ %{}) do
%Board{}
|> Board.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a board.
## Examples
iex> update_board(board, %{field: new_value})
{:ok, %Board{}}
iex> update_board(board, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_board(%Board{} = board, attrs) do
board
|> Board.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a Board.
## Examples
iex> delete_board(board)
{:ok, %Board{}}
iex> delete_board(board)
{:error, %Ecto.Changeset{}}
"""
def delete_board(%Board{} = board) do
Repo.delete(board)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking board changes.
## Examples
iex> change_board(board)
%Ecto.Changeset{source: %Board{}}
"""
def change_board(%Board{} = board) do
Board.changeset(board, %{})
end
end
| 18.390411 | 65 | 0.609683 |
ffa1ac3d1983aebe6c237175745c78eeb5861fda | 351 | ex | Elixir | test/commands/support/aggregate_router.ex | octowombat/commanded | 79a1965e276d3369dcf70ae65ef904d7e59f4a6a | [
"MIT"
] | 1,220 | 2017-10-31T10:56:40.000Z | 2022-03-31T17:40:19.000Z | test/commands/support/aggregate_router.ex | octowombat/commanded | 79a1965e276d3369dcf70ae65ef904d7e59f4a6a | [
"MIT"
] | 294 | 2017-11-03T10:33:41.000Z | 2022-03-24T08:36:42.000Z | test/commands/support/aggregate_router.ex | octowombat/commanded | 79a1965e276d3369dcf70ae65ef904d7e59f4a6a | [
"MIT"
] | 208 | 2017-11-03T10:56:47.000Z | 2022-03-14T05:49:38.000Z | defmodule Commanded.Commands.AggregateRouter do
@moduledoc false
use Commanded.Commands.Router
alias Commanded.Commands.AggregateRoot
alias Commanded.Commands.AggregateRoot.{Command, Command2}
dispatch Command, to: AggregateRoot, identity: :uuid
dispatch Command2, to: AggregateRoot, function: :custom_function_name, identity: :uuid
end
| 31.909091 | 88 | 0.809117 |
ffa1b575631f0927ba3c527bdaa1c1fc7b9a696b | 2,478 | ex | Elixir | clients/iam_credentials/lib/google_api/iam_credentials/v1/model/generate_id_token_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/iam_credentials/lib/google_api/iam_credentials/v1/model/generate_id_token_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/iam_credentials/lib/google_api/iam_credentials/v1/model/generate_id_token_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.IAMCredentials.V1.Model.GenerateIdTokenRequest do
@moduledoc """
## Attributes
* `audience` (*type:* `String.t`, *default:* `nil`) - Required. The audience for the token, such as the API or account that this token
grants access to.
* `delegates` (*type:* `list(String.t)`, *default:* `nil`) - The sequence of service accounts in a delegation chain. Each service
account must be granted the `roles/iam.serviceAccountTokenCreator` role
on its next service account in the chain. The last service account in the
chain must be granted the `roles/iam.serviceAccountTokenCreator` role
on the service account that is specified in the `name` field of the
request.
The delegates must have the following format:
`projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard
character is required; replacing it with a project ID is invalid.
* `includeEmail` (*type:* `boolean()`, *default:* `nil`) - Include the service account email in the token. If set to `true`, the
token will contain `email` and `email_verified` claims.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:audience => String.t(),
:delegates => list(String.t()),
:includeEmail => boolean()
}
field(:audience)
field(:delegates, type: :list)
field(:includeEmail)
end
defimpl Poison.Decoder, for: GoogleApi.IAMCredentials.V1.Model.GenerateIdTokenRequest do
def decode(value, options) do
GoogleApi.IAMCredentials.V1.Model.GenerateIdTokenRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.IAMCredentials.V1.Model.GenerateIdTokenRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.71875 | 138 | 0.721953 |
ffa1ddc46b2e09a4cbd4f802d7fc96c93a69a3ee | 2,591 | exs | Elixir | test/api/scenes_test.exs | connorlay/hue_sdk | f69e038c7f6527277f2ef13c92eb10c5d98b6ba8 | [
"MIT"
] | 4 | 2021-03-22T16:50:55.000Z | 2021-07-09T11:42:08.000Z | test/api/scenes_test.exs | connorlay/hue_sdk | f69e038c7f6527277f2ef13c92eb10c5d98b6ba8 | [
"MIT"
] | null | null | null | test/api/scenes_test.exs | connorlay/hue_sdk | f69e038c7f6527277f2ef13c92eb10c5d98b6ba8 | [
"MIT"
] | null | null | null | defmodule HueSDK.ScenesTest do
alias HueSDK.API.Scenes
use HueSDK.BypassCase, async: true
@json_resp %{"1" => %{"name" => "example"}}
@http_error %Mint.TransportError{reason: :econnrefused}
describe "get_all_scenes/1" do
test "returns parsed JSON if the request succeeds", %{bypass: bypass, bridge: bridge} do
get(bypass, "/api/#{bridge.username}/scenes", @json_resp)
assert {:ok, @json_resp} == Scenes.get_all_scenes(bridge)
end
test "returns a http error if the request fails", %{bypass: bypass, bridge: bridge} do
Bypass.down(bypass)
assert {:error, @http_error} == Scenes.get_all_scenes(bridge)
end
end
describe "get_scene_attributes/2" do
test "returns parsed JSON if the request succeeds", %{bypass: bypass, bridge: bridge} do
get(bypass, "/api/#{bridge.username}/scenes/1", @json_resp)
assert {:ok, @json_resp} == Scenes.get_scene_attributes(bridge, 1)
end
test "returns a http error if the request fails", %{bypass: bypass, bridge: bridge} do
Bypass.down(bypass)
assert {:error, @http_error} == Scenes.get_scene_attributes(bridge, 1)
end
end
describe "create_scene/2" do
test "returns parsed JSON if the request succeeds", %{bypass: bypass, bridge: bridge} do
post(bypass, "/api/#{bridge.username}/scenes", %{}, @json_resp)
assert {:ok, @json_resp} == Scenes.create_scene(bridge, %{})
end
test "returns a http error if the request fails", %{bypass: bypass, bridge: bridge} do
Bypass.down(bypass)
assert {:error, @http_error} == Scenes.create_scene(bridge, %{})
end
end
describe "modify_scene/2" do
test "returns parsed JSON if the request succeeds", %{bypass: bypass, bridge: bridge} do
put(bypass, "/api/#{bridge.username}/scenes/1/lightstates/1", %{}, @json_resp)
assert {:ok, @json_resp} == Scenes.modify_scene(bridge, 1, %{})
end
test "returns a http error if the request fails", %{bypass: bypass, bridge: bridge} do
Bypass.down(bypass)
assert {:error, @http_error} == Scenes.modify_scene(bridge, 1, %{})
end
end
describe "delete_scene/2" do
test "returns parsed JSON if the request succeeds", %{bypass: bypass, bridge: bridge} do
delete(bypass, "/api/#{bridge.username}/scenes/1", @json_resp)
assert {:ok, @json_resp} == Scenes.delete_scene(bridge, 1)
end
test "returns a http error if the request fails", %{bypass: bypass, bridge: bridge} do
Bypass.down(bypass)
assert {:error, @http_error} == Scenes.delete_scene(bridge, 1)
end
end
end
| 37.550725 | 92 | 0.667696 |
ffa1e2f25154e81c486d9ae1b36c9f6214b6ce29 | 1,044 | exs | Elixir | test/type/literal_emptylist/subtype_test.exs | ityonemo/mavis | 6f71c1ff9e12626c1ac5fcd1276c9adb433bfb99 | [
"MIT"
] | 97 | 2020-09-22T01:52:19.000Z | 2022-03-21T17:50:13.000Z | test/type/literal_emptylist/subtype_test.exs | ityonemo/mavis | 6f71c1ff9e12626c1ac5fcd1276c9adb433bfb99 | [
"MIT"
] | 106 | 2020-09-22T18:55:28.000Z | 2021-11-30T01:51:04.000Z | test/type/literal_emptylist/subtype_test.exs | ityonemo/mavis | 6f71c1ff9e12626c1ac5fcd1276c9adb433bfb99 | [
"MIT"
] | 3 | 2020-10-27T22:36:56.000Z | 2022-01-25T21:00:24.000Z | defmodule TypeTest.LiteralEmptylist.SubtypeTest do
use ExUnit.Case, async: true
@moduletag :subtype
import Type, only: :macros
alias Type.List
use Type.Operators
describe "a literal []" do
test "is a subtype of itself" do
assert [] in []
end
test "is a subtype of generic Type.List" do
assert [] in list()
end
test "is a subtype of builtin any()" do
assert [] in any()
end
test "is a subtype of a union with itself or generic list type" do
assert [] in ([] <|> atom())
assert [] in (list() <|> integer())
end
test "is not a subtype of a union with orthogonal types" do
refute [] in (list(...) <|> :infinity)
end
test "is not a subtype of nonempty lists or list with different finals" do
refute [] in list(...)
refute [] in %List{final: :foo}
end
test "is not a subtype of other types" do
TypeTest.Targets.except([[], list()])
|> Enum.each(fn target ->
refute [] in target
end)
end
end
end
| 22.212766 | 78 | 0.595785 |
ffa1f79ad077093a12391e26a0f024f44035085d | 2,055 | exs | Elixir | config/dev.exs | dreamingechoes/diversity-in-tech | 4eb5dadf69f82fd08e1cdd1b125264930d3b4e6f | [
"MIT"
] | 8 | 2018-06-22T05:43:30.000Z | 2020-04-13T20:31:40.000Z | config/dev.exs | dreamingechoes/diversity-in-tech | 4eb5dadf69f82fd08e1cdd1b125264930d3b4e6f | [
"MIT"
] | null | null | null | config/dev.exs | dreamingechoes/diversity-in-tech | 4eb5dadf69f82fd08e1cdd1b125264930d3b4e6f | [
"MIT"
] | null | null | null | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :diversity_in_tech, DiversityInTechWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [npm: ["run", "watch", cd: Path.expand("../assets/", __DIR__)]]
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# command from your terminal:
#
# openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem
#
# The `http:` config above can be replaced with:
#
# https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Watch static and templates for browser reloading.
config :diversity_in_tech, DiversityInTechWeb.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{priv/gettext/.*(po)$},
~r{lib/diversity_in_tech_web/views/.*(ex)$},
~r{lib/diversity_in_tech_web/templates/.*(eex)$}
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Configure your database
config :diversity_in_tech, DiversityInTech.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "",
database: "diversity_in_tech_dev",
hostname: "db",
pool_size: 10
# Finally import the config/dev.secret.exs
# which should be versioned separately.
import_config "dev.secret.exs"
| 33.145161 | 170 | 0.723114 |
ffa1feddd58252ad76cdfde8f035c864f4bc39ca | 1,635 | ex | Elixir | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_session.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_session.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_session.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"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.Apigee.V1.Model.GoogleCloudApigeeV1Session do
@moduledoc """
Session carries the debug session id and its creation time.
## Attributes
* `id` (*type:* `String.t`, *default:* `nil`) - The debug session ID.
* `timestampMs` (*type:* `String.t`, *default:* `nil`) - The first transaction creation timestamp in millisecond, recorded by UAP.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:id => String.t() | nil,
:timestampMs => String.t() | nil
}
field(:id)
field(:timestampMs)
end
defimpl Poison.Decoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1Session do
def decode(value, options) do
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1Session.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1Session do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.7 | 134 | 0.727217 |
ffa21e5ca209e3ba428a2ff0faf6081a390ecd2d | 875 | exs | Elixir | phoenix_example/config/config.exs | Opaala/phoenix_wings | 4cd41769f2450b526bb926ddc6a2531c57ad1e1b | [
"MIT"
] | 1 | 2019-08-31T22:26:40.000Z | 2019-08-31T22:26:40.000Z | phoenix_example/config/config.exs | Opaala/phoenix_wings | 4cd41769f2450b526bb926ddc6a2531c57ad1e1b | [
"MIT"
] | 2 | 2020-07-19T14:16:53.000Z | 2021-03-10T07:44:45.000Z | phoenix_example/config/config.exs | Opaala/phoenix_wings | 4cd41769f2450b526bb926ddc6a2531c57ad1e1b | [
"MIT"
] | 1 | 2019-06-26T08:01:08.000Z | 2019-06-26T08:01:08.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# Configures the endpoint
config :channel_server, ChannelServerWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "LAhjbRyAivhx+ELtcRSKauo8FZtsU0lsaKKo4sarLLY8U/fMACLvgwUypOnivqVQ",
render_errors: [view: ChannelServerWeb.ErrorView, accepts: ~w(html json)],
pubsub: [name: ChannelServer.PubSub,
adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:user_id]
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
| 36.458333 | 86 | 0.766857 |
ffa22cc00906fa97c03760291b2b91109d9a4761 | 1,068 | ex | Elixir | test/support/conn_case.ex | InFact-coop/your-sanctuary | 066e3b99ae52ee0d3fddac80b6aaf65ffef2bd0f | [
"BSD-3-Clause"
] | 2 | 2018-10-23T13:30:00.000Z | 2018-10-24T14:32:52.000Z | test/support/conn_case.ex | InFact-coop/your-sanctuary | 066e3b99ae52ee0d3fddac80b6aaf65ffef2bd0f | [
"BSD-3-Clause"
] | 60 | 2018-10-23T13:39:19.000Z | 2019-02-11T14:18:01.000Z | test/support/conn_case.ex | InFact-coop/your-sanctuary | 066e3b99ae52ee0d3fddac80b6aaf65ffef2bd0f | [
"BSD-3-Clause"
] | null | null | null | defmodule YourSanctuaryWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common datastructures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
import YourSanctuaryWeb.Router.Helpers
# The default endpoint for testing
@endpoint YourSanctuaryWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(YourSanctuary.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(YourSanctuary.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 27.384615 | 75 | 0.727528 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.