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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fff0dad9b8096433089616a0ae0545774080760b | 1,552 | ex | Elixir | lib/honeydew_web/views/error_helpers.ex | elixir-cqrs/honeydew | 888f86c829187eaca28ef1af69a40a337e46630a | [
"MIT"
] | 13 | 2022-02-13T18:43:20.000Z | 2022-03-19T11:53:48.000Z | lib/honeydew_web/views/error_helpers.ex | elixir-cqrs/honeydew | 888f86c829187eaca28ef1af69a40a337e46630a | [
"MIT"
] | 1 | 2022-02-23T13:57:19.000Z | 2022-02-23T13:57:19.000Z | lib/honeydew_web/views/error_helpers.ex | elixir-cqrs/honeydew | 888f86c829187eaca28ef1af69a40a337e46630a | [
"MIT"
] | 3 | 2022-02-13T19:25:19.000Z | 2022-02-22T17:56:52.000Z | defmodule HoneydewWeb.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
content_tag(:span, translate_error(error),
class: "invalid-feedback",
phx_feedback_for: input_name(form, field)
)
end)
end
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# When using gettext, we typically pass the strings we want
# to translate as a static argument:
#
# # Translate "is invalid" in the "errors" domain
# dgettext("errors", "is invalid")
#
# # Translate the number of files with plural rules
# dngettext("errors", "1 file", "%{count} files", count)
#
# Because the error messages we show in our forms and APIs
# are defined inside Ecto, we need to translate them dynamically.
# This requires us to call the Gettext module passing our gettext
# backend as first argument.
#
# Note we use the "errors" domain, which means translations
# should be written to the errors.po file. The :count option is
# set by Ecto and indicates we should also apply plural rules.
if count = opts[:count] do
Gettext.dngettext(HoneydewWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(HoneydewWeb.Gettext, "errors", msg, opts)
end
end
end
| 32.333333 | 77 | 0.666237 |
fff0f8bc57b009c6a493dfe87763e25369fc5532 | 196 | exs | Elixir | priv/repo/migrations/20170730220520_add_stats_to_items.exs | stevegrossi/ex_venture | e02d5a63fdb882d92cfb4af3e15f7b48ad7054aa | [
"MIT"
] | 2 | 2019-05-14T11:36:44.000Z | 2020-07-01T08:54:04.000Z | priv/repo/migrations/20170730220520_add_stats_to_items.exs | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | null | null | null | priv/repo/migrations/20170730220520_add_stats_to_items.exs | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | 1 | 2021-01-29T14:12:40.000Z | 2021-01-29T14:12:40.000Z | defmodule Data.Repo.Migrations.AddStatsToItems do
use Ecto.Migration
def change do
alter table(:items) do
add :stats, :map, default: fragment("'{}'"), null: false
end
end
end
| 19.6 | 62 | 0.673469 |
fff0fe5e515b73f0229746fe58ee7ae21b36fec6 | 3,200 | exs | Elixir | test/behaviour/handle_request_test.exs | elcritch/ExDhcp | 7c2641eaf86b1e1e0cbbaef67908a8e1829c45a8 | [
"MIT"
] | null | null | null | test/behaviour/handle_request_test.exs | elcritch/ExDhcp | 7c2641eaf86b1e1e0cbbaef67908a8e1829c45a8 | [
"MIT"
] | null | null | null | test/behaviour/handle_request_test.exs | elcritch/ExDhcp | 7c2641eaf86b1e1e0cbbaef67908a8e1829c45a8 | [
"MIT"
] | 1 | 2019-12-16T04:53:17.000Z | 2019-12-16T04:53:17.000Z | defmodule DhcpTest.Behaviour.HandleRequestTest do
@moduledoc false
use ExUnit.Case, async: true
alias ExDhcp.Packet
@moduletag [handle_request: true, behaviour: true]
# packet request example taken from wikipedia:
# https://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol#Request
@dhcp_request %Packet{
op: 1, xid: 0x3903_F326, chaddr: {0x00, 0x05, 0x3C, 0x04, 0x8D, 0x59},
siaddr: {192, 168, 1, 1},
options: %{message_type: :request, requested_address: {192, 168, 1, 100},
server: {192, 168, 1, 1}}
}
defmodule ReqSrvNoRespond do
use ExDhcp
def init(test_pid), do: {:ok, test_pid}
def handle_discover(_, _, _, _), do: :error
def handle_decline(_, _, _, _), do: :error
def handle_request(pack, xid, chaddr, test_pid) do
send(test_pid, {:request, xid, pack, chaddr})
{:norespond, :new_state}
end
end
test "a dhcp request message gets sent to handle_request" do
ReqSrvNoRespond.start_link(self(), port: 6752)
{:ok, sock} = :gen_udp.open(0, [:binary])
disc_pack = Packet.encode(@dhcp_request)
:gen_udp.send(sock, {127, 0, 0, 1}, 6752, disc_pack)
assert_receive {:request, xid, pack, chaddr}
assert pack == @dhcp_request
assert xid == @dhcp_request.xid
assert chaddr == @dhcp_request.chaddr
end
defmodule ReqSrvRespond do
use ExDhcp
def init(test_pid), do: {:ok, test_pid}
def handle_discover(_, _, _, _), do: :error
def handle_decline(_, _, _, _), do: :error
def handle_request(pack, _, _, _) do
# for simplicity, just send back the same packet.
{:respond, pack, :new_state}
end
end
@localhost {127, 0, 0, 1}
test "a dhcp request message can respond to the caller" do
ReqSrvRespond.start_link(self(), port: 6753, client_port: 6754, broadcast_addr: @localhost)
{:ok, sock} = :gen_udp.open(6754, [:binary, active: true])
disc_pack = Packet.encode(@dhcp_request)
:gen_udp.send(sock, {127, 0, 0, 1}, 6753, disc_pack)
assert_receive {:udp, _, _, _, binary}
assert @dhcp_request == Packet.decode(binary)
end
defmodule ReqParserlessSrv do
use ExDhcp, dhcp_options: []
def init(test_pid), do: {:ok, test_pid}
def handle_discover(_, _, _, _), do: :error
def handle_decline(_, _, _, _), do: :error
def handle_request(pack, xid, chaddr, test_pid) do
send(test_pid, {:request, pack, xid, chaddr})
{:respond, pack, :new_state}
end
end
test "dhcp will respond to request without options parsers" do
ReqParserlessSrv.start_link(self(), port: 6755, client_port: 6756, broadcast_addr: @localhost)
{:ok, sock} = :gen_udp.open(6756, [:binary, active: true])
disc_pack = Packet.encode(@dhcp_request)
:gen_udp.send(sock, {127, 0, 0, 1}, 6755, disc_pack)
assert_receive {:request, pack, xid, chaddr}
# make sure that the inner contents are truly unencoded.
assert %{50 => <<192, 168, 1, 100>>, 53 => <<3>>, 54 => <<192, 168, 1, 1>>}
== pack.options
assert xid == @dhcp_request.xid
assert chaddr == @dhcp_request.chaddr
assert_receive {:udp, _, _, _, packet}
assert @dhcp_request == Packet.decode(packet)
end
end
| 32.653061 | 98 | 0.658125 |
fff1061e6fe9e0353adfc8787fc7f3c010e4dcca | 989 | ex | Elixir | apps/core/lib/core/declaration_requests/api/v2/mpi_search.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 8 | 2019-06-14T11:34:49.000Z | 2021-08-05T19:14:24.000Z | apps/core/lib/core/declaration_requests/api/v2/mpi_search.ex | edenlabllc/ehealth.api.public | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 1 | 2019-07-08T15:20:22.000Z | 2019-07-08T15:20:22.000Z | apps/core/lib/core/declaration_requests/api/v2/mpi_search.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 6 | 2018-05-11T13:59:32.000Z | 2022-01-19T20:15:22.000Z | defmodule Core.DeclarationRequests.API.V2.MpiSearch do
@moduledoc """
Provides mpi search
"""
@rpc_worker Application.get_env(:core, :rpc_worker)
def search(%{"auth_phone_number" => _} = search_params) do
"mpi"
|> @rpc_worker.run(MPI.Rpc, :search_persons, [search_params])
|> search_result(:all)
end
def search(person_search_params) when is_list(person_search_params) do
Enum.reduce_while(person_search_params, {:ok, nil}, fn search_params_set, acc ->
case "mpi"
|> @rpc_worker.run(MPI.Rpc, :search_persons, [search_params_set])
|> search_result(:one) do
{:ok, nil} -> {:cont, acc}
{:ok, person} -> {:halt, {:ok, person}}
err -> {:halt, err}
end
end)
end
defp search_result({:ok, entries}, :all), do: {:ok, entries}
defp search_result({:ok, [%{} = person | _]}, :one), do: {:ok, person}
defp search_result({:ok, []}, :one), do: {:ok, nil}
defp search_result(error, _), do: error
end
| 31.903226 | 84 | 0.624874 |
fff12bc4be2b088f956ee7dab02e9a4934206319 | 1,953 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v3alpha1_delete_document_operation_metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v3alpha1_delete_document_operation_metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v3alpha1_delete_document_operation_metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV3alpha1DeleteDocumentOperationMetadata do
@moduledoc """
Metadata for DeleteDocument operation.
## Attributes
* `genericMetadata` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV3alpha1GenericKnowledgeOperationMetadata.t`, *default:* `nil`) - The generic information of the operation.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:genericMetadata =>
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV3alpha1GenericKnowledgeOperationMetadata.t()
| nil
}
field(:genericMetadata,
as:
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV3alpha1GenericKnowledgeOperationMetadata
)
end
defimpl Poison.Decoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV3alpha1DeleteDocumentOperationMetadata do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV3alpha1DeleteDocumentOperationMetadata.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV3alpha1DeleteDocumentOperationMetadata do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.263158 | 192 | 0.771121 |
fff1349fc42bb984ef646895df9f4a33448108d7 | 822 | ex | Elixir | lib/webhooks.ex | TheDragonProject/webhooks | 5e0fc3fd53e439321ab65a99f06b31596ddce8ed | [
"MIT"
] | null | null | null | lib/webhooks.ex | TheDragonProject/webhooks | 5e0fc3fd53e439321ab65a99f06b31596ddce8ed | [
"MIT"
] | null | null | null | lib/webhooks.ex | TheDragonProject/webhooks | 5e0fc3fd53e439321ab65a99f06b31596ddce8ed | [
"MIT"
] | null | null | null | defmodule Webhooks.Application do
@moduledoc """
Small application listening for webhooks notifications
You can specify a custom redis url by setting the `REDIS_URL` environment variable.
> Defaults to "redis://localhost:6379"
You can specify the port under which Cowboy will listen to by setting the `PORT` environment variable.
> Defaults to `8080`
"""
use Application
def start(_type, _args) do
redis_opts = System.get_env("REDIS_URL") || "redis://localhost:6379"
port = System.get_env("PORT") || 8080
children = [
{Redix, [redis_opts, [name: :redix]]},
Plug.Adapters.Cowboy.child_spec(
:http,
Webhooks.Routers,
[],
port: port
)
]
opts = [strategy: :one_for_one]
Supervisor.start_link(children, opts)
end
end
| 25.6875 | 106 | 0.654501 |
fff13cad03c4bf537ef3d1ae06a0e4de35e13ddf | 10,624 | ex | Elixir | web/controllers/invoice_controller.ex | mindsigns/soroban | c56962e1164a51cb5e383bbbfda880f098f181f1 | [
"MIT"
] | 1 | 2020-02-09T03:03:04.000Z | 2020-02-09T03:03:04.000Z | web/controllers/invoice_controller.ex | mindsigns/soroban | c56962e1164a51cb5e383bbbfda880f098f181f1 | [
"MIT"
] | null | null | null | web/controllers/invoice_controller.ex | mindsigns/soroban | c56962e1164a51cb5e383bbbfda880f098f181f1 | [
"MIT"
] | null | null | null | defmodule Soroban.InvoiceController do
@moduledoc """
Invoice Controller Route: /invoices
"""
use Soroban.Web, :controller
import Soroban.Authorize
alias Soroban.{Invoice, Job, Client, Email, Mailer, Pdf}
alias Soroban.InvoiceUtils
plug :user_check
plug :load_clients when action in [:new, :edit, :create, :generate]
plug :load_today when action in [:new, :show, :edit, :create, :send_email]
plug :scrub_params, "id" when action in [:send_pdf, :show, :edit, :update, :delete, :view]
plug :scrub_params, "invoice_id" when action in [:send_email, :show_invoice]
plug :scrub_params, "invoice" when action in [:create, :update]
plug :scrub_params, "type" when action in [:clear_cache]
@doc """
Route: GET /invoices
Shows a list of Invoices by unique invoice IDs.
"""
def index(conn, _params) do
invoices = Invoice
|> distinct(:number)
|> Repo.all
render(conn, "index.html", invoices: invoices)
end
@doc """
Route: GET /invoices/sendpdf/<id>
Sends a pdf to the browser.
"""
def send_pdf(conn, %{"id" => id}) do
Pdf.send_pdf(conn, id)
end
@doc """
Route: GET /invoices/<id>/send_email
Sends an email to the client email address.
"""
def send_email(conn, %{"invoice_id" => id}) do
{invoice, jobs, total, company} = InvoiceUtils.generate(id, true)
Email.invoice_html_email(invoice.client.email, invoice, jobs, total, company)
|> Mailer.deliver_later
msg =
if invoice.client.cc_email do
Enum.join(["Invoice mailed to : ", invoice.client.contact, " <", invoice.client.email, "> and CC'd ", invoice.client.cc_email])
else
Enum.join(["Invoice mailed to : ", invoice.client.contact, " <", invoice.client.email, ">"])
end
conn
|> put_flash(:info, msg)
|> render("show.html", invoice: invoice, jobs: jobs)
end
@doc """
Route: GET /invoices/new
Creates a new invoice
"""
def new(conn, _params) do
changeset = Invoice.changeset(%Invoice{})
render(conn, "new.html", changeset: changeset)
end
@doc """
Route: POST /invoices/
Inserts data into the database
"""
def create(conn, %{"invoice" => invoice_params}) do
changeset = Invoice.changeset(%Invoice{}, invoice_params)
case changeset.valid? do
false -> conn
|> put_flash(:error, "Missing info")
|> render("new.html", changeset: changeset)
true ->
client_id = Ecto.Changeset.get_field(changeset, :client_id)
start_date = Ecto.Changeset.get_field(changeset, :start)
end_date = Ecto.Changeset.get_field(changeset, :end)
invtotal = total(client_id, start_date, end_date)
advtotal = total_adv(client_id, start_date, end_date)
if to_string(invtotal) == "$0.00" do
conn
|> put_flash(:error, "There are no jobs in that range.")
|> render("new.html", changeset: changeset)
else
newchangeset = Ecto.Changeset.put_change(changeset, :total, invtotal)
newchangeset2 = Ecto.Changeset.put_change(newchangeset, :fees_advanced, advtotal)
case Repo.insert(newchangeset2) do
{:ok, _invoice} ->
conn
|> put_flash(:info, "Invoice created successfully.")
|> redirect(to: invoice_path(conn, :index))
{:error, newchangeset2} ->
render(conn, "new.html", changeset: changeset)
end
end
end
end
@doc """
Route: GET /invoices/<id>
Displays a single invoice
"""
def show(conn, %{"id" => id}) do
invoice = Repo.get!(Invoice, id) |> Repo.preload(:client)
query = (from j in Job,
where: j.date >= ^invoice.start,
where: j.date <= ^invoice.end,
where: j.client_id == ^invoice.client_id,
order_by: j.date,
select: j)
jobs = Repo.all(query) |> Repo.preload(:client)
render(conn, "show.html", invoice: invoice, jobs: jobs)
end
@doc """
Route: GET /invoices/<invoice_id>/show
Displays a list of invoices with the same Invoice ID
"""
def show_invoice(conn, %{"invoice_id" => id}) do
query = (from i in Invoice,
where: i.number == ^id,
order_by: i.paid_on)
invoices = Repo.all(query) |> Repo.preload([client: (from c in Client, order_by: c.name)])
case Enum.count(invoices) do
0 -> conn
|> put_status(:not_found)
|> render(Soroban.ErrorView, "error_msg.html")
_ ->
total = InvoiceUtils.total(invoices)
total_adv = InvoiceUtils.total_advanced(invoices)
total_net =
if total > total_adv do
Money.subtract(total, total_adv)
else
Money.subtract(total_adv, total)
end
invoice_count = Enum.count(invoices)
render(conn, "invoicelist.html", invoices: invoices, invoice_id: id, invoice_count: invoice_count, total: total, total_adv: total_adv, total_net: total_net)
end
end
@doc """
Route: GET /invoices/view/<invoice_id_number>
Shows the HTML version of the rendered invoice using the Email/PDF template.
"""
def view(conn, %{"id" => id}) do
{invoice, jobs, total, company} = InvoiceUtils.generate(id, false)
render(conn, invoice: invoice, jobs: jobs, total: total,
company: company, layout: {Soroban.LayoutView, "invoice.html"})
end
@doc """
Route: POST /invoices/paid/
Mark an Invoice 'Paid'
"""
def paid(conn, %{"paid" => %{"date" => paid_on, "invoice_id" => invoice_id}}) do
{:ok, date_paid} = Ecto.Date.cast({paid_on["year"], paid_on["month"], paid_on["day"]})
invoice = Repo.get!(Invoice, invoice_id) |> Repo.preload(:client)
changeset = Invoice.changeset(invoice)
paidchangeset = Ecto.Changeset.put_change(changeset, :paid, true)
newchangeset = Ecto.Changeset.put_change(paidchangeset, :paid_on, date_paid)
case Repo.update(newchangeset) do
{:ok, invoice} ->
conn
|> put_flash(:info, "Invoice updated successfully.")
|> redirect(to: invoice_path(conn, :show, invoice_id))
{:error, paidchangeset} ->
conn
|> put_flash(:error, "Error.")
|> redirect(to: invoice_path(conn, :show, invoice_id))
end
end
@doc """
Route: POST /invoices/multipay/
Mark an Invoice 'Paid'
"""
def multipay(conn, %{"paid" => ids, "invoice_id" => %{"invoice_name" => invoice_id}}) do
idlist = for {id, "true"} <- ids, do: id
paid_on = DateTime.utc_now()
{:ok, date_paid} = Ecto.Date.cast({paid_on.year, paid_on.month, paid_on.day})
for invoiceid <- idlist do
invoice = Repo.get!(Invoice, invoiceid) |> Repo.preload(:client)
changeset = Invoice.changeset(invoice)
paidchangeset = Ecto.Changeset.put_change(changeset, :paid, true)
newchangeset = Ecto.Changeset.put_change(paidchangeset, :paid_on, date_paid)
Repo.update(newchangeset)
end
conn
|> put_flash(:info, "Invoices marked 'Paid'.")
|> redirect(to: invoice_invoice_path(conn, :show_invoice, invoice_id))
end
@doc """
Route: GET /invoices/<id>/edit
Edit an invoice
"""
def edit(conn, %{"id" => id}) do
invoice = Repo.get!(Invoice, id) |> Repo.preload(:client)
changeset = Invoice.changeset(invoice)
render(conn, "edit.html", invoice: invoice, changeset: changeset)
end
@doc """
Route: PATCH/PUT /invoices/<id>
Updates an invoice after editing
"""
def update(conn, %{"id" => id, "invoice" => invoice_params}) do
invoice = Repo.get!(Invoice, id) |> Repo.preload(:client)
changeset = Invoice.changeset(invoice, invoice_params)
# Remove any PDF's that might be cached. Remove Zips
InvoiceUtils.cleanup(invoice.client.name, invoice.number)
case Repo.update(changeset) do
{:ok, invoice} ->
conn
|> put_flash(:info, "Invoice updated successfully.")
|> redirect(to: invoice_path(conn, :show, invoice))
{:error, changeset} ->
render(conn, "edit.html", invoice: invoice, changeset: changeset)
end
end
@doc """
ROUTE: DELETE /invoices/<id>
Deletes an invoice
"""
def delete(conn, %{"id" => id}) do
invoice = Repo.get!(Invoice, id)
Repo.delete!(invoice)
conn
|> put_flash(:info, "Invoice deleted successfully.")
|> redirect(to: invoice_path(conn, :index))
end
@doc """
ROUTE: GET /invoices/outstanding
display outstanding invoices
def index(conn, _params) do
query = (from i in Invoice,
where: i.paid == false,
order_by: i.date,
select: i)
invoices = Repo.all(query)
render(conn, "index.html", invoices: invoices)
end
"""
@doc """
ROUTE: GET /clear_cache/<zip|pdf|all>
Deletes Zip and PDF files from the file system
"""
def clear_cache(conn, %{"type" => type}) do
res = case type do
"zip" -> Enum.join([Soroban.Pdf.pdf_path, "*.zip"])
"pdf" -> Enum.join([Soroban.Pdf.pdf_path, "*.pdf"])
"all" -> Enum.join([Soroban.Pdf.pdf_path, "*"])
_ -> "error"
end
files = Path.wildcard(res)
for f <- files do
File.rm(f)
end
conn
|> put_flash(:info, "Cache deleted successfully.")
|> redirect(to: admin_path(conn, :index))
end
#
# Private functions
#
#Totals dollar amount from jobs within a date range for a client
def total(client, startdate, enddate) do
query = (from j in Job,
where: j.date >= ^startdate,
where: j.date <= ^enddate,
where: j.client_id == ^client,
order_by: j.date,
select: j)
jobs = Repo.all(query) |> Repo.preload(:client)
jtotal = for n <- jobs, do: Map.get(n, :total)
ftotal = for n <- jtotal, do: Map.get(n, :amount)
total = Money.new(Enum.sum(ftotal))
total
end
def total_adv(client, startdate, enddate) do
query = (from j in Job,
where: j.date >= ^startdate,
where: j.date <= ^enddate,
where: j.client_id == ^client,
order_by: j.date,
select: j)
jobs = Repo.all(query) |> Repo.preload(:client)
jtotal = for n <- jobs, do: Map.get(n, :fees_advanced)
ftotal = for n <- jtotal, do: Map.get(n, :amount)
total = Money.new(Enum.sum(ftotal))
total
end
defp load_clients(conn, _) do
clients = Repo.all from c in Client, order_by: c.name, select: {c.name, c.id}
assign(conn, :clients, clients)
end
defp load_today(conn, _) do
today = Date.utc_today()
assign(conn, :today, today)
end
end
| 29.675978 | 162 | 0.61474 |
fff179c4b3cd38bbd534f0a2ab32a98b549cb254 | 757 | exs | Elixir | priv/repo/migrations/20211203161255_create_users_auth_tables.exs | karolsluszniak/clustered_queue_and_pool-phoenix1.6 | cbf8f51a3c72cb7a5bde31839c1de056775af4f3 | [
"MIT"
] | null | null | null | priv/repo/migrations/20211203161255_create_users_auth_tables.exs | karolsluszniak/clustered_queue_and_pool-phoenix1.6 | cbf8f51a3c72cb7a5bde31839c1de056775af4f3 | [
"MIT"
] | null | null | null | priv/repo/migrations/20211203161255_create_users_auth_tables.exs | karolsluszniak/clustered_queue_and_pool-phoenix1.6 | cbf8f51a3c72cb7a5bde31839c1de056775af4f3 | [
"MIT"
] | null | null | null | defmodule Outer.Repo.Migrations.CreateUsersAuthTables do
use Ecto.Migration
def change do
execute "CREATE EXTENSION IF NOT EXISTS citext", ""
create table(:users) do
add :email, :citext, null: false
add :hashed_password, :string, null: false
add :confirmed_at, :naive_datetime
timestamps()
end
create unique_index(:users, [:email])
create table(:users_tokens) do
add :user_id, references(:users, on_delete: :delete_all), null: false
add :token, :binary, null: false
add :context, :string, null: false
add :sent_to, :string
timestamps(updated_at: false)
end
create index(:users_tokens, [:user_id])
create unique_index(:users_tokens, [:context, :token])
end
end
| 27.035714 | 75 | 0.672391 |
fff189755cdcd9892134b59649dbcd4e2ae18808 | 679 | exs | Elixir | test/conceal_test.exs | thiamsantos/conceal | 3d636d3f043314afd6565c2f67ad2781063c87e0 | [
"Apache-2.0"
] | 2 | 2020-03-02T00:48:45.000Z | 2020-03-05T17:58:19.000Z | test/conceal_test.exs | thiamsantos/conceal | 3d636d3f043314afd6565c2f67ad2781063c87e0 | [
"Apache-2.0"
] | null | null | null | test/conceal_test.exs | thiamsantos/conceal | 3d636d3f043314afd6565c2f67ad2781063c87e0 | [
"Apache-2.0"
] | null | null | null | defmodule ConcealTest do
use ExUnit.Case
test "encrypts and decrypts" do
input = "data"
{:ok, result} =
input
|> Conceal.encrypt("key")
|> Conceal.decrypt("key")
assert result == input
end
describe "decrypt/2" do
test "different key" do
input = "data"
digest = Conceal.encrypt(input, "key")
assert Conceal.decrypt(digest, "different_key") == :error
end
test "not a encrypted digest" do
input = Base.encode64("data")
assert Conceal.decrypt(input, "key") == :error
end
test "not base 64" do
input = "data"
assert Conceal.decrypt(input, "key") == :error
end
end
end
| 18.351351 | 63 | 0.594993 |
fff1a46566f1dd002402b3d6c5b12efe7f5a74fd | 1,389 | ex | Elixir | lib/resty/serializer.ex | kkvesper/resty | a7680b9b10487b5ffb02bfa2a5c89b67312a2411 | [
"MIT"
] | null | null | null | lib/resty/serializer.ex | kkvesper/resty | a7680b9b10487b5ffb02bfa2a5c89b67312a2411 | [
"MIT"
] | null | null | null | lib/resty/serializer.ex | kkvesper/resty | a7680b9b10487b5ffb02bfa2a5c89b67312a2411 | [
"MIT"
] | 1 | 2019-01-10T13:15:23.000Z | 2019-01-10T13:15:23.000Z | defmodule Resty.Serializer do
alias Resty.Resource
@moduledoc """
This module is used by `Resty.Repo` in order to serialize and deserialize
data sent and received from the web API.
It will use the serializer implementation configured on the resource. By
default it is `Resty.Serializer.Json` but if you want to use another format
you'll have to write your own implementation.
Once that's done you'll be able to use it on a per resource basis by calling
the appropriate `Resty.Resource.Base` macro or globally by setting it in the
config.
"""
@doc false
def deserialize(serialized, resource_module) do
{implementation, params} = resource_module.serializer()
data = implementation.decode(serialized, params)
build(resource_module, data)
end
@doc false
def serialize(resource), do: serialize(resource, resource.__struct__)
defp serialize(resource, resource_module) do
{implementation, params} = resource_module.serializer()
implementation.encode(
resource,
resource_module.known_attributes(),
params ++ [include_root: resource_module.include_root()]
)
end
defp build(resource_module, data) when is_list(data) do
Enum.map(data, &build(resource_module, &1))
end
defp build(resource_module, data) do
Resource.Builder.build(resource_module, data)
|> Resource.mark_as_persisted()
end
end
| 28.9375 | 78 | 0.737941 |
fff22aabc17581b74d6826c7842f3ed0d5089b04 | 1,747 | ex | Elixir | lib/esi.ex | johnschultz/esi | 6bc69c39e21baa8655523e71755a65516b68e60c | [
"MIT"
] | null | null | null | lib/esi.ex | johnschultz/esi | 6bc69c39e21baa8655523e71755a65516b68e60c | [
"MIT"
] | null | null | null | lib/esi.ex | johnschultz/esi | 6bc69c39e21baa8655523e71755a65516b68e60c | [
"MIT"
] | null | null | null | defmodule ESI do
@doc """
Execute a request.
## Arguments
- `request` -- the request
- `opts` -- any additional options to set on the request
"""
@spec request!(req :: ESI.Request.t(), opts :: ESI.Request.request_opts()) ::
{:ok, any} | {:error, any}
def request(req, opts \\ []) do
req
|> ESI.Request.options(opts)
|> ESI.Request.run()
end
@doc """
Execute a request and raise an error if it is not successful.
"""
@spec request!(req :: ESI.Request.t(), opts :: ESI.Request.request_opts()) :: any
def request!(req, opts \\ []) do
case request(req, opts) do
{:ok, result} ->
result
{:error, err} ->
raise "Request failed: #{err}"
end
end
@doc """
Generate a stream from a request, supporting automatic pagination.
## Examples
Paginating, without `stream!`; you need to manually handle incrementing the
`:page` option:
iex> ESI.API.Universe.groups() |> ESI.request! |> length
1000
iex> ESI.API.Universe.groups(page: 2) |> ESI.request! |> length
423
Paginating with `stream!`, you don't have to care about `:page`:
iex> ESI.API.Universe.groups() |> ESI.stream! |> Enum.take(1020) |> length
1020
Like any stream, you can use `Enum.to_list/1` to get all the items:
iex> ESI.API.Universe.groups() |> ESI.stream! |> Enum.to_list |> length
1423
It even works for requests that don't paginate:
iex> ESI.API.Universe.bloodlines() |> ESI.stream! |> Enum.to_list |> length
18
"""
@spec stream!(req :: ESI.Request.t(), opts :: ESI.Request.request_opts()) :: any
def stream!(req, opts \\ []) do
req
|> ESI.Request.options(opts)
|> ESI.Request.stream!()
end
end
| 25.691176 | 83 | 0.605037 |
fff22b5bdc59f9fc93067933765c4bf24b92f53e | 1,790 | exs | Elixir | clients/vault/mix.exs | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/vault/mix.exs | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/vault/mix.exs | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Vault.Mixfile do
use Mix.Project
@version "0.16.1"
def project() do
[
app: :google_api_vault,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/vault"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.4"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
G Suite Vault API client library. Archiving and eDiscovery for G Suite.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching", "Daniel Azuma"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/vault",
"Homepage" => "https://developers.google.com/vault"
}
]
end
end
| 26.716418 | 96 | 0.648603 |
fff2542923e619550f1ce0fced0423608d403f12 | 2,805 | exs | Elixir | priv/templates/brando.install/config/prod.exs | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 4 | 2020-10-30T08:40:38.000Z | 2022-01-07T22:21:37.000Z | priv/templates/brando.install/config/prod.exs | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 1,162 | 2020-07-05T11:20:15.000Z | 2022-03-31T06:01:49.000Z | priv/templates/brando.install/config/prod.exs | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | null | null | null | import Config
# For production, we configure the host to read the PORT
# from the system environment. Therefore, you will need
# to set PORT=80 before running your server.
#
# You should also configure the url host to something
# meaningful, we use this information when generating URLs.
#
# Finally, we also include the path to a manifest
# containing the digested version of static files. This
# manifest is generated by the mix phoenix.digest task
# which you typically run after static files are built.
config :<%= application_name %>, <%= application_module %>Web.Endpoint,
http: [:inet6, port: {:system, "PORT"}],
# http: [:inet6, port: {:system, "PORT"}, protocol_options: [idle_timeout: 360_000]],
# force_ssl: [hsts: true, rewrite_on: [:x_forwarded_proto]],
check_origin: [
"//<%= application_name %>.com",
"//*.<%= application_name %>.com",
"//*.univers.agency",
"//*.b-y.no",
"//localhost:4000"
],
server: true,
render_errors: [accepts: ~w(html json), view: Brando.ErrorView, default_format: "html"],
cache_static_manifest: "priv/static/cache_manifest.json"
# Ensure no HMR in prod :)
config :<%= application_name %>, hmr: false
# Show breakpoint debug in frontend
config :<%= application_name %>, show_breakpoint_debug: false
# Do not print debug messages in production
config :logger, level: :error
# Handle SASL reports
config :logger, handle_sasl_reports: true
# Path to your media directory.
config :brando, media_path: "./media"
# Path to your log directory.
config :brando, log_dir: "./log"
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :<%= application_name %>, <%= application_module %>Web.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [:inet6, port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :<%= application_name %>, <%= application_module %>Web.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :<%= application_name %>, <%= application_module %>Web.Endpoint,
# server: true
#
| 33 | 90 | 0.691622 |
fff26b4c8a626ab31ce02e4b7281e4a10de79112 | 3,613 | ex | Elixir | lib/absinthe/type/scalar.ex | podium/absinthe | 7d14fab0282a3987e124f4d5dc3009bc94eb884c | [
"MIT"
] | null | null | null | lib/absinthe/type/scalar.ex | podium/absinthe | 7d14fab0282a3987e124f4d5dc3009bc94eb884c | [
"MIT"
] | 2 | 2019-03-07T00:26:03.000Z | 2019-08-19T17:30:30.000Z | lib/absinthe/type/scalar.ex | podium/absinthe | 7d14fab0282a3987e124f4d5dc3009bc94eb884c | [
"MIT"
] | 1 | 2019-01-18T20:49:03.000Z | 2019-01-18T20:49:03.000Z | defmodule Absinthe.Type.Scalar do
@moduledoc """
Represents a primitive value.
GraphQL responses take the form of a hierarchical tree; the leaves on these
trees are scalars.
Also see `Absinthe.Type.Object`.
## Built-In Scalars
The following built-in scalar types are defined:
* `:boolean` - Represents `true` or `false`. See the [GraphQL Specification](https://www.graphql.org/learn/schema/#scalar-types).
* `:float` - Represents signed double‐precision fractional values as specified by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). See the [GraphQL Specification](https://www.graphql.org/learn/schema/#scalar-types).
* `:id` - Represents a unique identifier, often used to refetch an object or as key for a cache. The ID type is serialized in the same way as a String; however, it is not intended to be human‐readable. See the [GraphQL Specification](https://www.graphql.org/learn/schema/#scalar-types).
* `:integer` - Represents a signed 32‐bit numeric non‐fractional value, greater than or equal to -2^31 and less than 2^31. Note that Absinthe uses the full word `:integer` to identify this type, but its `name` (used by variables, for instance), is `"Int"`. See the [GraphQL Specification](https://www.graphql.org/learn/schema/#scalar-types).
* `:string` - Represents textual data, represented as UTF‐8 character sequences. The String type is most often used by GraphQL to represent free‐form human‐readable text. See the [GraphQL Specification](https://www.graphql.org/learn/schema/#scalar-types).
## Examples
Supporting a time format in ISOz format, using [Timex](http://hexdocs.pm/timex):
```
scalar :time do
description "Time (in ISOz format)"
parse &Timex.DateFormat.parse(&1, "{ISOz}")
serialize &Timex.DateFormat.format!(&1, "{ISOz}")
end
```
"""
use Absinthe.Introspection.TypeKind, :scalar
alias Absinthe.Type
@doc false
defdelegate functions(), to: Absinthe.Blueprint.Schema.ScalarTypeDefinition
def serialize(type, value) do
Type.function(type, :serialize).(value)
end
def parse(type, value, context \\ %{}) do
case Type.function(type, :parse) do
parser when is_function(parser, 1) ->
parser.(value)
parser when is_function(parser, 2) ->
parser.(value, context)
end
end
@typedoc """
A defined scalar type.
Note new scalars should be defined using `Absinthe.Schema.Notation.scalar`.
* `:name` - The name of scalar. Should be a TitleCased `binary`. Set Automatically by `Absinthe.Schema.Notation.scalar`.
* `:description` - A nice description for introspection.
* `:serialize` - A function used to convert a value to a form suitable for JSON serialization
* `:parse` - A function used to convert the raw, incoming form of a scalar to the canonical internal format.
The `:__private__` and `:__reference__` keys are for internal use.
"""
@type t :: %__MODULE__{
name: binary,
description: binary,
identifier: atom,
__private__: Keyword.t(),
definition: module,
__reference__: Type.Reference.t()
}
defstruct name: nil,
description: nil,
identifier: nil,
__private__: [],
definition: nil,
__reference__: nil,
parse: nil,
serialize: nil
@typedoc "The internal, canonical representation of a scalar value"
@type value_t :: any
if System.get_env("DEBUG_INSPECT") do
defimpl Inspect do
def inspect(scalar, _) do
"#<Scalar:#{scalar.name}>"
end
end
end
end
| 38.43617 | 343 | 0.68558 |
fff26de8f20cce35915876cf535704b05541275b | 20,871 | ex | Elixir | lib/elixir/lib/task.ex | diogovk/elixir | 7b8213affaad38b50afaa3dfc3a43717f35ba4e7 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/task.ex | diogovk/elixir | 7b8213affaad38b50afaa3dfc3a43717f35ba4e7 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/task.ex | diogovk/elixir | 7b8213affaad38b50afaa3dfc3a43717f35ba4e7 | [
"Apache-2.0"
] | null | null | null | defmodule Task do
@moduledoc """
Conveniences for spawning and awaiting tasks.
Tasks are processes meant to execute one particular
action throughout their lifetime, often with little or no
communication with other processes. The most common use case
for tasks is to convert sequential code into concurrent code
by computing a value asynchronously:
task = Task.async(fn -> do_some_work() end)
res = do_some_other_work()
res + Task.await(task)
Tasks spawned with `async` can be awaited on by their caller
process (and only their caller) as shown in the example above.
They are implemented by spawning a process that sends a message
to the caller once the given computation is performed.
Besides `async/1` and `await/2`, tasks can also be
started as part of a supervision tree and dynamically spawned
on remote nodes. We will explore all three scenarios next.
## async and await
One of the common uses of tasks is to convert sequential code
into concurrent code with `Task.async/1` while keeping its semantics.
When invoked, a new process will be created, linked and monitored
by the caller. Once the task action finishes, a message will be sent
to the caller with the result.
`Task.await/2` is used to read the message sent by the task.
There are two important things to consider when using `async`:
1. If you are using async tasks, you must await a reply
as they are *always* sent. If you are not expecting a reply,
consider using `Task.start_link/1` detailed below.
2. async tasks link the caller and the spawned process. This
means that, if the caller crashes, the task will crash
too and vice-versa. This is on purpose: if the process
meant to receive the result no longer exists, there is
no purpose in completing the computation.
If this is not desired, use `Task.start/1` or consider starting
the task under a `Task.Supervisor` using `async_nolink` or
`start_child`.
`Task.yield/2` is an alternative to `await/2` where the caller will
temporarily block, waiting until the task replies or crashes. If the
result does not arrive within the timeout, it can be called again at a
later moment. This allows checking for the result of a task multiple
times. If a reply does not arrive within the desired time,
`Task.shutdown/2` can be used to stop the task.
## Supervised tasks
It is also possible to spawn a task under a supervisor
with `start_link/1` and `start_link/3`:
Task.start_link(fn -> IO.puts "ok" end)
Such tasks can be mounted in your supervision tree as:
import Supervisor.Spec
children = [
worker(Task, [fn -> IO.puts "ok" end])
]
Since these tasks are supervised and not directly linked to
the caller, they cannot be awaited on. Note `start_link/1`,
unlike `async/1`, returns `{:ok, pid}` (which is
the result expected by supervision trees).
By default, most supervision strategies will try to restart
a worker after it exits regardless of the reason. If you design the
task to terminate normally (as in the example with `IO.puts/2` above),
consider passing `restart: :transient` in the options to `worker/3`.
## Dynamically supervised tasks
The `Task.Supervisor` module allows developers to dynamically
create multiple supervised tasks.
A short example is:
{:ok, pid} = Task.Supervisor.start_link()
task = Task.Supervisor.async(pid, fn ->
# Do something
end)
Task.await(task)
However, in the majority of cases, you want to add the task supervisor
to your supervision tree:
import Supervisor.Spec
children = [
supervisor(Task.Supervisor, [[name: MyApp.TaskSupervisor]])
]
Now you can dynamically start supervised tasks:
Task.Supervisor.start_child(MyApp.TaskSupervisor, fn ->
# Do something
end)
Or even use the async/await pattern:
Task.Supervisor.async(MyApp.TaskSupervisor, fn ->
# Do something
end) |> Task.await()
Finally, check `Task.Supervisor` for other supported operations.
## Distributed tasks
Since Elixir provides a Task supervisor, it is easy to use one
to dynamically spawn tasks across nodes:
# On the remote node
Task.Supervisor.start_link(name: MyApp.DistSupervisor)
# On the client
Task.Supervisor.async({MyApp.DistSupervisor, :remote@local},
MyMod, :my_fun, [arg1, arg2, arg3])
Note that, when working with distributed tasks, one should use the `async/4` function
that expects explicit module, function and arguments, instead of `async/2` that
works with anonymous functions. That's because anonymous functions expect
the same module version to exist on all involved nodes. Check the `Agent` module
documentation for more information on distributed processes as the limitations
described there apply to the whole ecosystem.
"""
@doc """
The Task struct.
It contains these fields:
* `:pid` - the PID of the task process; `nil` if the task does
not use a task process
* `:ref` - the task monitor reference
* `:owner` - the PID of the process that started the task
"""
defstruct pid: nil, ref: nil, owner: nil
@type t :: %__MODULE__{}
@doc """
Starts a task as part of a supervision tree.
"""
@spec start_link(fun) :: {:ok, pid}
def start_link(fun) do
start_link(:erlang, :apply, [fun, []])
end
@doc """
Starts a task as part of a supervision tree.
"""
@spec start_link(module, atom, [term]) :: {:ok, pid}
def start_link(mod, fun, args) do
Task.Supervised.start_link(get_info(self), {mod, fun, args})
end
@doc """
Starts a task.
This is only used when the task is used for side-effects
(i.e. no interest in the returned result) and it should not
be linked to the current process.
"""
@spec start(fun) :: {:ok, pid}
def start(fun) do
start(:erlang, :apply, [fun, []])
end
@doc """
Starts a task.
This is only used when the task is used for side-effects
(i.e. no interest in the returned result) and it should not
be linked to the current process.
"""
@spec start(module, atom, [term]) :: {:ok, pid}
def start(mod, fun, args) do
Task.Supervised.start(get_info(self), {mod, fun, args})
end
@doc """
Starts a task that must be awaited on.
This function spawns a process that is linked to and monitored
by the caller process. A `Task` struct is returned containing
the relevant information.
Read the `Task` module documentation for more info on general
usage of `async/1` and `async/3`.
See also `async/3`.
"""
@spec async(fun) :: t
def async(fun) do
async(:erlang, :apply, [fun, []])
end
@doc """
Starts a task that must be awaited on.
A `Task` struct is returned containing the relevant information.
Developers must eventually call `Task.await/2` or `Task.yield/2`
followed by `Task.shutdown/2` on the returned task.
Read the `Task` module documentation for more info on general
usage of `async/1` and `async/3`.
## Linking
This function spawns a process that is linked to and monitored
by the caller process. The linking part is important because it
aborts the task if the parent process dies. It also guarantees
the code before async/await has the same properties after you
add the async call. For example, imagine you have this:
x = heavy_fun()
y = some_fun()
x + y
Now you want to make the `heavy_fun()` async:
x = Task.async(&heavy_fun/0)
y = some_fun()
Task.await(x) + y
As before, if `heavy_fun/0` fails, the whole computation will
fail, including the parent process. If you don't want the task
to fail then you must change the `heavy_fun/0` code in the
same way you would achieve it if you didn't have the async call.
For example, to either return `{:ok, val} | :error` results or,
in more extreme cases, by using `try/rescue`. In other words,
an asynchronous task should be thought of as an extension of a
process rather than a mechanism to isolate it from all errors.
If you don't want to link the caller to the task, then you
must use a supervised task with `Task.Supervisor` and call
`Task.Supervisor.async_nolink/2`.
In any case, avoid any of the following:
* Setting `:trap_exit` to `true` - trapping exits should be
used only in special circumstances as it would make your
process immune to not only exits from the task but from
any other processes.
Moreover, even when trapping exists, calling `await` will
still exit if the task has terminated without sending its
result back.
* Unlinking the task process started with `async`/`await`.
If you unlink the processes and the task does not belong
to any supervisor, you may leave dangling tasks in case
the parent dies.
## Message format
The reply sent by the task will be in the format `{ref, result}`,
where `ref` is the monitor reference held by the task struct
and `result` is the return value of the task function.
"""
@spec async(module, atom, [term]) :: t
def async(mod, fun, args) do
mfa = {mod, fun, args}
owner = self()
pid = Task.Supervised.spawn_link(owner, get_info(owner), mfa)
ref = Process.monitor(pid)
send(pid, {owner, ref})
%Task{pid: pid, ref: ref, owner: owner}
end
defp get_info(self) do
{node(),
case Process.info(self, :registered_name) do
{:registered_name, []} -> self()
{:registered_name, name} -> name
end}
end
@doc """
Awaits a task reply.
A timeout, in milliseconds, can be given with default value
of `5000`. In case the task process dies, this function will
exit with the same reason as the task.
If the timeout is exceeded, `await` will exit; however,
the task will continue to run. When the calling process exits, its
exit signal will terminate the task if it is not trapping exits.
This function assumes the task's monitor is still active or the monitor's
`:DOWN` message is in the message queue. If it has been demonitored, or the
message already received, this function will wait for the duration of the
timeout awaiting the message.
This function can only be called once for any given task. If you want
to be able to check multiple times if a long-running task has finished
its computation, use `yield/2` instead.
## Compatibility with OTP behaviours
It is not recommended to `await` a long-running task inside an OTP
behaviour such as `GenServer`. Instead, you should match on the message
coming from a task inside your `handle_info` callback.
"""
@spec await(t, timeout) :: term | no_return
def await(task, timeout \\ 5000)
def await(%Task{owner: owner} = task, _) when owner != self() do
raise ArgumentError, invalid_owner_error(task)
end
def await(%Task{ref: ref} = task, timeout) do
receive do
{^ref, reply} ->
Process.demonitor(ref, [:flush])
reply
{:DOWN, ^ref, _, proc, reason} ->
exit({reason(reason, proc), {__MODULE__, :await, [task, timeout]}})
after
timeout ->
Process.demonitor(ref, [:flush])
exit({:timeout, {__MODULE__, :await, [task, timeout]}})
end
end
@doc false
def find(tasks, msg) do
IO.write :stderr, "warning: Task.find/2 is deprecated, please match on the message directly\n" <>
Exception.format_stacktrace
do_find(tasks, msg)
end
defp do_find(tasks, {ref, reply}) when is_reference(ref) do
Enum.find_value tasks, fn
%Task{ref: ^ref} = task ->
Process.demonitor(ref, [:flush])
{reply, task}
%Task{} ->
nil
end
end
defp do_find(tasks, {:DOWN, ref, _, proc, reason} = msg) when is_reference(ref) do
find = fn %Task{ref: task_ref} -> task_ref == ref end
if Enum.find(tasks, find) do
exit({reason(reason, proc), {__MODULE__, :find, [tasks, msg]}})
end
end
defp do_find(_tasks, _msg) do
nil
end
@doc """
Temporarily blocks the current process waiting for a task reply.
Returns `{:ok, reply}` if the reply is received, `nil` if
no reply has arrived, or `{:exit, reason}` if the task has already
exited. Keep in mind that normally a task failure also causes
the process owning the task to exit. Therefore this function can
return `{:exit, reason}` only if
* the task process exited with the reason `:normal`
* it isn't linked to the caller
* the caller is trapping exits
A timeout, in milliseconds, can be given with default value
of `5000`. If the time runs out before a message from
the task is received, this function will return `nil`
and the monitor will remain active. Therefore `yield/2` can be
called multiple times on the same task.
This function assumes the task's monitor is still active or the
monitor's `:DOWN` message is in the message queue. If it has been
demonitored or the message already received, this function will wait
for the duration of the timeout awaiting the message.
"""
@spec yield(t, timeout) :: {:ok, term} | {:exit, term} | nil
def yield(task, timeout \\ 5_000)
def yield(%Task{owner: owner} = task, _) when owner != self() do
raise ArgumentError, invalid_owner_error(task)
end
def yield(%Task{ref: ref} = task, timeout) do
receive do
{^ref, reply} ->
Process.demonitor(ref, [:flush])
{:ok, reply}
{:DOWN, ^ref, _, proc, :noconnection} ->
exit({reason(:noconnection, proc), {__MODULE__, :yield, [task, timeout]}})
{:DOWN, ^ref, _, _, reason} ->
{:exit, reason}
after
timeout ->
nil
end
end
@doc """
Yields to multiple tasks in the given time interval.
This function receives a list of tasks and waits for their
replies in the given time interval. It returns a list
of tuples of two elements, with the task as the first element
and the yielded result as the second.
Similarly to `yield/2`, each task's result will be
* `{:ok, term}` if the task has successfully reported its
result back in the given time interval
* `{:exit, reason}` if the task has died
* `nil` if the task keeps running past the timeout
Check `yield/2` for more information.
## Example
`Task.yield_many/2` allows developers to spawn multiple tasks
and retrieve the results received in a given timeframe.
If we combine it with `Task.shutdown/2`, it allows us to gather
those results and cancel the tasks that have not replied in time.
Let's see an example.
tasks =
for i <- 1..10 do
Task.async(fn ->
:timer.sleep(i * 1000)
i
end)
end
tasks_with_results = Task.yield_many(tasks, 5000)
results = Enum.map(tasks_with_results, fn {task, res} ->
# Shutdown the tasks that did not reply nor exit
res || Task.shutdown(task, :brutal_kill)
end)
# Here we are matching only on {:ok, value} and
# ignoring {:exit, _} (crashed tasks) and `nil` (no replies)
for {:ok, value} <- results do
IO.inspect value
end
In the example above, we create tasks that sleep from 1
up to 10 seconds and return the amount of seconds they slept.
If you execute the code all at once, you should see 1 up to 5
printed, as those were the tasks that have replied in the
given time. All other tasks will have been shut down using
the `Task.shutdown/2` call.
"""
@spec yield_many([t], timeout) :: [{t, {:ok, term} | {:exit, term} | nil}]
def yield_many(tasks, timeout \\ 5000) do
timeout_ref = make_ref()
timer_ref = Process.send_after(self(), timeout_ref, timeout)
try do
yield_many(tasks, timeout_ref, :infinity)
catch
{:noconnection, reason} ->
exit({reason, {__MODULE__, :yield_many, [tasks, timeout]}})
after
Process.cancel_timer(timer_ref)
receive do: (^timeout_ref -> :ok), after: (0 -> :ok)
end
end
defp yield_many([%Task{ref: ref, owner: owner}=task | rest], timeout_ref, timeout) do
if owner != self() do
raise ArgumentError, invalid_owner_error(task)
end
receive do
{^ref, reply} ->
Process.demonitor(ref, [:flush])
[{task, {:ok, reply}} | yield_many(rest, timeout_ref, timeout)]
{:DOWN, ^ref, _, proc, :noconnection} ->
throw({:noconnection, reason(:noconnection, proc)})
{:DOWN, ^ref, _, _, reason} ->
[{task, {:exit, reason}} | yield_many(rest, timeout_ref, timeout)]
^timeout_ref ->
[{task, nil} | yield_many(rest, timeout_ref, 0)]
after
timeout ->
[{task, nil} | yield_many(rest, timeout_ref, 0)]
end
end
defp yield_many([], _timeout_ref, _timeout) do
[]
end
@doc """
Unlinks and shuts down the task, and then checks for a reply.
Returns `{:ok, reply}` if the reply is received while shutting down the task,
`{:exit, reason}` if the task died, otherwise `nil`.
The shutdown method is either a timeout or `:brutal_kill`. In case
of a `timeout`, a `:shutdown` exit signal is sent to the task process
and if it does not exit within the timeout, it is killed. With `:brutal_kill`
the task is killed straight away. In case the task terminates abnormally
(possibly killed by another process), this function will exit with the same reason.
It is not required to call this function when terminating the caller, unless
exiting with reason `:normal` or if the task is trapping exits. If the caller is
exiting with a reason other than `:normal` and the task is not trapping exits, the
caller's exit signal will stop the task. The caller can exit with reason
`:shutdown` to shutdown all of its linked processes, including tasks, that
are not trapping exits without generating any log messages.
This function assumes the task's monitor is still active or the monitor's
`:DOWN` message is in the message queue. If it has been demonitored, or the
message already received, this function will block forever awaiting the message.
"""
@spec shutdown(t, timeout | :brutal_kill) :: {:ok, term} | {:exit, term} | nil
def shutdown(task, shutdown \\ 5_000)
def shutdown(%Task{pid: nil} = task, _) do
raise ArgumentError, "task #{inspect task} does not have an associated task process"
end
def shutdown(%Task{owner: owner} = task, _) when owner != self() do
raise ArgumentError, invalid_owner_error(task)
end
def shutdown(%Task{pid: pid} = task, :brutal_kill) do
exit(pid, :kill)
case shutdown_receive(task, :brutal_kill, :infinity) do
{:down, proc, :noconnection} ->
exit({reason(:noconnection, proc), {__MODULE__, :shutdown, [task, :brutal_kill]}})
{:down, _, reason} ->
{:exit, reason}
result ->
result
end
end
def shutdown(%Task{pid: pid} = task, timeout) do
exit(pid, :shutdown)
case shutdown_receive(task, :shutdown, timeout) do
{:down, proc, :noconnection} ->
exit({reason(:noconnection, proc), {__MODULE__, :shutdown, [task, timeout]}})
{:down, _, reason} ->
{:exit, reason}
result ->
result
end
end
## Helpers
defp reason(:noconnection, proc), do: {:nodedown, monitor_node(proc)}
defp reason(reason, _), do: reason
defp monitor_node(pid) when is_pid(pid), do: node(pid)
defp monitor_node({_, node}), do: node
# spawn a process to ensure task gets exit signal if process dies from exit signal
# between unlink and exit.
defp exit(task, reason) do
caller = self()
ref = make_ref()
enforcer = spawn(fn() -> enforce_exit(task, reason, caller, ref) end)
Process.unlink(task)
Process.exit(task, reason)
send(enforcer, {:done, ref})
:ok
end
defp enforce_exit(pid, reason, caller, ref) do
mon = Process.monitor(caller)
receive do
{:done, ^ref} -> :ok
{:DOWN, ^mon, _, _, _} -> Process.exit(pid, reason)
end
end
defp shutdown_receive(%{ref: ref} = task, type, timeout) do
receive do
{:DOWN, ^ref, _, _, :shutdown} when type in [:shutdown, :timeout_kill] ->
flush_reply(ref)
{:DOWN, ^ref, _, _, :killed} when type == :brutal_kill ->
flush_reply(ref)
{:DOWN, ^ref, _, proc, reason} ->
flush_reply(ref) || {:down, proc, reason}
after
timeout ->
Process.exit(task.pid, :kill)
shutdown_receive(task, :timeout_kill, :infinity)
end
end
defp flush_reply(ref) do
receive do
{^ref, reply} -> {:ok, reply}
after
0 -> nil
end
end
defp invalid_owner_error(task) do
"task #{inspect task} must be queried from the owner but was queried from #{inspect self()}"
end
end
| 33.287081 | 101 | 0.671698 |
fff26e3d4b89065f93dd6a8e62e1bbbfbf9fabb0 | 2,002 | exs | Elixir | test/game_scoring_test.exs | Philpenhas/bowlingkata-phil | 7391aa7197bebb59a17ede5d7464caead7db1861 | [
"MIT"
] | null | null | null | test/game_scoring_test.exs | Philpenhas/bowlingkata-phil | 7391aa7197bebb59a17ede5d7464caead7db1861 | [
"MIT"
] | null | null | null | test/game_scoring_test.exs | Philpenhas/bowlingkata-phil | 7391aa7197bebb59a17ede5d7464caead7db1861 | [
"MIT"
] | null | null | null | defmodule GameScoringTest do
use ExUnit.Case
test "it only scores a list of frames" do
assert_raise FunctionClauseError, fn ->
GameScoring.score(%Frame{})
end
end
test "it returns an error tuple if given a partial game" do
assert {:error, :full_game_required} = GameScoring.score([])
end
test "it scores a :scored frame as the sum of rolls" do
frame = %Frame{type: :scored, rolls: [0, 5]}
assert {:ok, 5} = GameScoring.score_frame(frame, [])
end
test "it scores a :spare frame as 10 plus the next roll" do
frame = %Frame{type: :spare, rolls: [0, 10]}
rest = [%Frame{type: :scored, rolls: [3,5]}]
assert {:ok, 13} = GameScoring.score_frame(frame, rest)
end
test "it returns an error tuple if scoring a spare without any additional frames" do
frame = %Frame{type: :spare, rolls: [0, 10]}
assert {:error, :partial_game} = GameScoring.score_frame(frame, [])
end
test "it scores a :strike frame as 10 plus the next two rolls" do
frame = %Frame{type: :strike, rolls: [10]}
rest = [%Frame{type: :scored, rolls: [3,5]}]
assert {:ok, 18} = GameScoring.score_frame(frame, rest)
end
test "it scores three :strike frames in a row as a 30" do
frame = %Frame{type: :strike, rolls: [10]}
rest = [
%Frame{type: :strike, rolls: [10]},
%Frame{type: :strike, rolls: [10]}
]
assert {:ok, 30} = GameScoring.score_frame(frame, rest)
end
test "it scores a tenth frame of :strike as sum of it's rolls" do
frame = %Frame{type: :strike, rolls: [10, 3, 7]}
rest = []
assert {:ok, 20} = GameScoring.score_frame(frame, rest)
end
test "it scores a tenth frame of :spare as sum of it's rolls" do
frame = %Frame{type: :strike, rolls: [7, 3, 7]}
rest = []
assert {:ok, 17} = GameScoring.score_frame(frame, rest)
end
test "it scores a perfect game" do
frames = BowlingKata.parse_input("XXXXXXXXXXXX")
assert {:ok, 300} = GameScoring.score(frames)
end
end
| 29.014493 | 86 | 0.639361 |
fff2ad291a13344ce62ac4bf0b4f1d16d17fb885 | 1,707 | ex | Elixir | lib/mix/tasks/ecto.migrate.ex | ashneyderman/ecto | 16f27f64c5ca2480568fad10e40c26522ffbf793 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/ecto.migrate.ex | ashneyderman/ecto | 16f27f64c5ca2480568fad10e40c26522ffbf793 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/ecto.migrate.ex | ashneyderman/ecto | 16f27f64c5ca2480568fad10e40c26522ffbf793 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Ecto.Migrate do
use Mix.Task
import Mix.Ecto
@shortdoc "Run migrations up on a repo"
@moduledoc """
Runs the pending migrations for the given repository.
By default, migrations are expected at "priv/YOUR_REPO/migrations"
directory of the current application but it can be configured
by specify the `:priv` key under the repository configuration.
Runs all pending migrations by default. To migrate up
to a version number, supply `--to version_number`.
To migrate up a specific number of times, use `--step n`.
## Examples
mix ecto.migrate
mix ecto.migrate -r Custom.Repo
mix ecto.migrate -n 3
mix ecto.migrate --step 3
mix ecto.migrate -v 20080906120000
mix ecto.migrate --to 20080906120000
## Command line options
* `-r`, `--repo` - the repo to migrate (defaults to `YourApp.Repo`)
* `--all` - run all pending migrations
* `--step` / `-n` - run n number of pending migrations
* `--to` / `-v` - run all migrations up to and including version
"""
@doc false
def run(args, migrator \\ &Ecto.Migrator.run/4) do
Mix.Task.run "app.start", ["--no-start"|args]
{:ok, _} = Application.ensure_all_started(:ecto)
repo = parse_repo(args)
{opts, _, _} = OptionParser.parse args,
switches: [all: :boolean, step: :integer, to: :integer, quiet: :boolean],
aliases: [n: :step, v: :to]
ensure_repo(repo)
ensure_started(repo)
unless opts[:to] || opts[:step] || opts[:all] do
opts = Keyword.put(opts, :all, true)
end
if opts[:quiet] do
opts = Keyword.put(opts, :log, false)
end
migrator.(repo, migrations_path(repo), :up, opts)
end
end
| 27.532258 | 79 | 0.652607 |
fff2b515c3beece25bcdeeef498d48d83d790657 | 2,498 | ex | Elixir | lib/chat_api/conversations/conversation.ex | wmnnd/papercups | 1e6fdfaf343b95b8bd6853d1327d6123180d0ac7 | [
"MIT"
] | null | null | null | lib/chat_api/conversations/conversation.ex | wmnnd/papercups | 1e6fdfaf343b95b8bd6853d1327d6123180d0ac7 | [
"MIT"
] | 1 | 2021-01-17T10:42:34.000Z | 2021-01-17T10:42:34.000Z | lib/chat_api/conversations/conversation.ex | BotCart/papercups | 7e7533ac8a8becc114060ab5033376c6aab4b369 | [
"MIT"
] | null | null | null | defmodule ChatApi.Conversations.Conversation do
use Ecto.Schema
import Ecto.Changeset
alias ChatApi.{
Accounts.Account,
Customers.Customer,
Messages.Message,
Tags.ConversationTag,
Users.User
}
@type t :: %__MODULE__{
status: String.t(),
priority: String.t(),
source: String.t() | nil,
read: boolean(),
archived_at: any(),
closed_at: any(),
metadata: any(),
# Relations
assignee_id: any(),
assignee: any(),
account_id: any(),
account: any(),
customer_id: any(),
customer: any(),
messages: any(),
conversation_tags: any(),
tags: any(),
# Timestamps
inserted_at: any(),
updated_at: any()
}
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "conversations" do
field(:status, :string, default: "open")
field(:priority, :string, default: "not_priority")
field(:source, :string, default: "chat")
field(:read, :boolean, default: false)
field(:archived_at, :utc_datetime)
field(:first_replied_at, :utc_datetime)
field(:closed_at, :utc_datetime)
field(:metadata, :map)
has_many(:messages, Message)
belongs_to(:assignee, User, foreign_key: :assignee_id, references: :id, type: :integer)
belongs_to(:account, Account)
belongs_to(:customer, Customer)
has_many(:conversation_tags, ConversationTag)
has_many(:tags, through: [:conversation_tags, :tag])
timestamps()
end
@doc false
def changeset(conversation, attrs) do
conversation
|> cast(attrs, [
:status,
:priority,
:read,
:assignee_id,
:account_id,
:customer_id,
:archived_at,
:first_replied_at,
:closed_at,
:source,
:metadata
])
|> validate_required([:status, :account_id, :customer_id])
|> validate_inclusion(:source, ["chat", "slack", "email"])
|> put_closed_at()
|> foreign_key_constraint(:account_id)
|> foreign_key_constraint(:customer_id)
end
defp put_closed_at(%Ecto.Changeset{valid?: true, changes: %{status: status}} = changeset) do
case status do
"closed" ->
put_change(changeset, :closed_at, DateTime.utc_now() |> DateTime.truncate(:second))
"open" ->
put_change(changeset, :closed_at, nil)
end
end
defp put_closed_at(changeset), do: changeset
end
| 26.294737 | 94 | 0.609688 |
fff2eaf3af5f2535336080f14997efe65c22848b | 1,910 | exs | Elixir | clients/secret_manager/mix.exs | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/secret_manager/mix.exs | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/secret_manager/mix.exs | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.SecretManager.Mixfile do
use Mix.Project
@version "0.17.1"
def project() do
[
app: :google_api_secret_manager,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/secret_manager"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.4"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
Secret Manager API client library. Stores sensitive data such as API keys, passwords, and certificates. Provides convenience while improving security.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching", "Daniel Azuma"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/secret_manager",
"Homepage" => "https://cloud.google.com/secret-manager/"
}
]
end
end
| 28.507463 | 155 | 0.663351 |
fff31262ca7120ef282f20fb64364ba39563057d | 860 | ex | Elixir | lib/online_editor_web/views/folder_view.ex | zzats/online-editor | 2532315b40c974fe766e960e0b0933773907906d | [
"MIT"
] | null | null | null | lib/online_editor_web/views/folder_view.ex | zzats/online-editor | 2532315b40c974fe766e960e0b0933773907906d | [
"MIT"
] | null | null | null | lib/online_editor_web/views/folder_view.ex | zzats/online-editor | 2532315b40c974fe766e960e0b0933773907906d | [
"MIT"
] | null | null | null | defmodule OnlineEditorWeb.FolderView do
use OnlineEditorWeb, :view
def render("index.json", %{folders: folders}) do
render_many(folders, __MODULE__, "folder.json")
end
def render("show.json", %{folder: folder}) do
render_one(folder, __MODULE__, "folder.json")
end
def render("folder.json", %{folder: folder}) do
json = %{
id: folder.id,
name: folder.name,
parent: folder.parent_id,
inserted_at: folder.inserted_at,
updated_at: folder.updated_at,
}
|> add_ids(folder, :children)
|> add_ids(folder, :documents)
end
defp add_ids(json, folder, key) do
case Map.get(folder, key) do
value when is_list(value) ->
ids = value
|> Enum.filter(fn e -> !e.deleted end)
|> Enum.map(fn e -> e.id end)
Map.put(json, key, ids)
_ -> json
end
end
end
| 23.888889 | 51 | 0.617442 |
fff33550713c5e080829c44b6cefbd04f3d5b2d6 | 541 | exs | Elixir | test/models/sale_detaill_test.exs | GoberInfinity/ExamplePhoenix | 4f2e016000a55dd4dbc28409dd214f0923e38e32 | [
"MIT"
] | null | null | null | test/models/sale_detaill_test.exs | GoberInfinity/ExamplePhoenix | 4f2e016000a55dd4dbc28409dd214f0923e38e32 | [
"MIT"
] | null | null | null | test/models/sale_detaill_test.exs | GoberInfinity/ExamplePhoenix | 4f2e016000a55dd4dbc28409dd214f0923e38e32 | [
"MIT"
] | null | null | null | defmodule Otherpool.SaleDetaillTest do
use Otherpool.ModelCase
alias Otherpool.SaleDetaill
@valid_attrs %{due_date: %{day: 17, month: 4, year: 2010}, order_date: %{day: 17, month: 4, year: 2010}, subtotal: 42}
@invalid_attrs %{}
test "changeset with valid attributes" do
changeset = SaleDetaill.changeset(%SaleDetaill{}, @valid_attrs)
assert changeset.valid?
end
test "changeset with invalid attributes" do
changeset = SaleDetaill.changeset(%SaleDetaill{}, @invalid_attrs)
refute changeset.valid?
end
end
| 28.473684 | 120 | 0.728281 |
fff345283e71f479907811c0b37148a70b62cf75 | 686 | ex | Elixir | lib/myApi_web/controllers/fallback_controller.ex | njwest/Phoenix_API | 61002c0e5566d0ab68d4a2fd0e93e3b9c20f1beb | [
"MIT"
] | 40 | 2018-05-20T21:30:30.000Z | 2021-09-10T07:25:44.000Z | Elixir-Phoenix-API/lib/myApi_web/controllers/fallback_controller.ex | eibay/React-Native-Elixir-Phoenix-JWT | 1d3c622c7cf19d5a7dbf3c618a291188e33166c4 | [
"MIT"
] | 3 | 2020-09-07T10:53:53.000Z | 2022-02-12T21:45:34.000Z | Elixir-Phoenix-API/lib/myApi_web/controllers/fallback_controller.ex | trinhdinhphuong/React-Native-Elixir-Phoenix-JWT | 4af4900787ea272b0c1dd3ee7ef039b579e162ba | [
"MIT"
] | 15 | 2018-06-07T08:16:20.000Z | 2020-04-12T07:38:05.000Z | defmodule MyApiWeb.FallbackController do
@moduledoc """
Translates controller action results into valid `Plug.Conn` responses.
See `Phoenix.Controller.action_fallback/1` for more details.
"""
use MyApiWeb, :controller
def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
conn
|> put_status(:unprocessable_entity)
|> render(MyApiWeb.ChangesetView, "error.json", changeset: changeset)
end
def call(conn, {:error, :not_found}) do
conn
|> put_status(:not_found)
|> render(MyApiWeb.ErrorView, :"404")
end
def call(conn, {:error, :unauthorized}) do
conn
|> put_status(:unauthorized)
|> json(%{error: "Login error"})
end
end
| 25.407407 | 73 | 0.680758 |
fff36c86151dac2c7d313c747e60f796bde079fd | 6,365 | ex | Elixir | lib/broadway_sqs/ex_aws_client.ex | maartenvanvliet/broadway_sqs | aea664c9de0c0af016fa420a50f7a51f1c0fbcd8 | [
"Apache-2.0"
] | null | null | null | lib/broadway_sqs/ex_aws_client.ex | maartenvanvliet/broadway_sqs | aea664c9de0c0af016fa420a50f7a51f1c0fbcd8 | [
"Apache-2.0"
] | null | null | null | lib/broadway_sqs/ex_aws_client.ex | maartenvanvliet/broadway_sqs | aea664c9de0c0af016fa420a50f7a51f1c0fbcd8 | [
"Apache-2.0"
] | null | null | null | defmodule BroadwaySQS.ExAwsClient do
@moduledoc """
Default SQS client used by `BroadwaySQS.Producer` to communicate with AWS
SQS service. This client uses the `ExAws.SQS` library and implements the
`BroadwaySQS.SQSClient` and `Broadway.Acknowledger` behaviours which define
callbacks for receiving and acknowledging messages.
"""
alias Broadway.{Message, Acknowledger}
require Logger
@behaviour BroadwaySQS.SQSClient
@behaviour Acknowledger
@default_max_number_of_messages 10
@max_num_messages_allowed_by_aws 10
@max_visibility_timeout_allowed_by_aws_in_seconds 12 * 60 * 60
@supported_attributes [
:sender_id,
:sent_timestamp,
:approximate_receive_count,
:approximate_first_receive_timestamp,
:wait_time_seconds,
:receive_message_wait_time_seconds
]
@impl true
def init(opts) do
with {:ok, queue_name} <- validate(opts, :queue_name, required: true),
{:ok, receive_messages_opts} <- validate_receive_messages_opts(opts),
{:ok, config} <- validate(opts, :config, default: []) do
ack_ref = Broadway.TermStorage.put(%{queue_name: queue_name, config: config})
{:ok,
%{
queue_name: queue_name,
receive_messages_opts: receive_messages_opts,
config: config,
ack_ref: ack_ref
}}
end
end
@impl true
def receive_messages(demand, opts) do
receive_messages_opts = put_max_number_of_messages(opts.receive_messages_opts, demand)
opts.queue_name
|> ExAws.SQS.receive_message(receive_messages_opts)
|> ExAws.request(opts.config)
|> wrap_received_messages(opts.ack_ref)
end
@impl true
def ack(ack_ref, successful, _failed) do
successful
|> Enum.chunk_every(@max_num_messages_allowed_by_aws)
|> Enum.each(fn messages -> delete_messages(messages, ack_ref) end)
end
defp delete_messages(messages, ack_ref) do
receipts = Enum.map(messages, &extract_message_receipt/1)
opts = Broadway.TermStorage.get!(ack_ref)
opts.queue_name
|> ExAws.SQS.delete_message_batch(receipts)
|> ExAws.request(opts.config)
end
defp wrap_received_messages({:ok, %{body: body}}, ack_ref) do
Enum.map(body.messages, fn message ->
metadata = Map.delete(message, :body)
acknowledger = build_acknowledger(message, ack_ref)
%Message{data: message.body, metadata: metadata, acknowledger: acknowledger}
end)
end
defp wrap_received_messages({:error, reason}, _) do
Logger.error("Unable to fetch events from AWS. Reason: #{inspect(reason)}")
[]
end
defp build_acknowledger(message, ack_ref) do
receipt = %{id: message.message_id, receipt_handle: message.receipt_handle}
{__MODULE__, ack_ref, %{receipt: receipt}}
end
defp put_max_number_of_messages(receive_messages_opts, demand) do
max_number_of_messages = min(demand, receive_messages_opts[:max_number_of_messages])
Keyword.put(receive_messages_opts, :max_number_of_messages, max_number_of_messages)
end
defp extract_message_receipt(message) do
{_, _, %{receipt: receipt}} = message.acknowledger
receipt
end
defp validate(opts, key, options \\ []) when is_list(opts) do
has_key = Keyword.has_key?(opts, key)
required = Keyword.get(options, :required, false)
default = Keyword.get(options, :default)
cond do
has_key ->
validate_option(key, opts[key])
required ->
{:error, "#{inspect(key)} is required"}
default != nil ->
validate_option(key, default)
true ->
{:ok, nil}
end
end
defp validate_option(:config, value) when not is_list(value),
do: validation_error(:config, "a keyword list", value)
defp validate_option(:queue_name, value) when not is_binary(value) or value == "",
do: validation_error(:queue_name, "a non empty string", value)
defp validate_option(:wait_time_seconds, value) when not is_integer(value) or value < 0,
do: validation_error(:wait_time_seconds, "a non negative integer", value)
defp validate_option(:max_number_of_messages, value)
when value not in 1..@max_num_messages_allowed_by_aws do
validation_error(
:max_number_of_messages,
"an integer between 1 and #{@max_num_messages_allowed_by_aws}",
value
)
end
defp validate_option(:visibility_timeout, value)
when value not in 0..@max_visibility_timeout_allowed_by_aws_in_seconds do
validation_error(
:visibility_timeout,
"an integer between 0 and #{@max_visibility_timeout_allowed_by_aws_in_seconds}",
value
)
end
defp validate_option(:attribute_names, value) do
supported? = fn name -> name in @supported_attributes end
if value == :all || (is_list(value) && Enum.all?(value, supported?)) do
{:ok, value}
else
validation_error(
:attribute_names,
":all or a list containing any of #{inspect(@supported_attributes)}",
value
)
end
end
defp validate_option(:message_attribute_names, value) do
non_empty_string? = fn name -> is_binary(name) && name != "" end
if value == :all || (is_list(value) && Enum.all?(value, non_empty_string?)) do
{:ok, value}
else
validation_error(:message_attribute_names, ":all or a list of non empty strings", value)
end
end
defp validate_option(_, value), do: {:ok, value}
defp validation_error(option, expected, value) do
{:error, "expected #{inspect(option)} to be #{expected}, got: #{inspect(value)}"}
end
defp validate_receive_messages_opts(opts) do
with {:ok, wait_time_seconds} <- validate(opts, :wait_time_seconds),
{:ok, attribute_names} <- validate(opts, :attribute_names),
{:ok, message_attribute_names} <- validate(opts, :message_attribute_names),
{:ok, max_number_of_messages} <-
validate(opts, :max_number_of_messages, default: @default_max_number_of_messages),
{:ok, visibility_timeout} <- validate(opts, :visibility_timeout) do
validated_opts = [
max_number_of_messages: max_number_of_messages,
wait_time_seconds: wait_time_seconds,
visibility_timeout: visibility_timeout,
attribute_names: attribute_names,
message_attribute_names: message_attribute_names
]
{:ok, Enum.filter(validated_opts, fn {_, value} -> value end)}
end
end
end
| 32.641026 | 94 | 0.701021 |
fff3704b962d48efa8adbf598908e72b9825606a | 593 | ex | Elixir | server/lib/project_web/views/user_view.ex | lemartin19/cs4550-project | bd7baf279021543db33fe52beb3e0d5413dbe405 | [
"Xnet",
"X11"
] | null | null | null | server/lib/project_web/views/user_view.ex | lemartin19/cs4550-project | bd7baf279021543db33fe52beb3e0d5413dbe405 | [
"Xnet",
"X11"
] | null | null | null | server/lib/project_web/views/user_view.ex | lemartin19/cs4550-project | bd7baf279021543db33fe52beb3e0d5413dbe405 | [
"Xnet",
"X11"
] | null | null | null | defmodule ProjectWeb.UserView do
use ProjectWeb, :view
alias ProjectWeb.UserView
alias ProjectWeb.ChangesetView
def render("index.json", %{users: users}) do
%{data: render_many(users, UserView, "user.json")}
end
def render("show.json", %{user: user}) do
%{data: render_one(user, UserView, "user.json")}
end
def render("user.json", %{user: user}) do
%{id: user.id, name: user.name, email: user.email, password_hash: user.password_hash}
end
def render("error.json", %{changeset: changeset}) do
render_one(changeset, ChangesetView, "error.json")
end
end
| 26.954545 | 89 | 0.689713 |
fff375a081ec8f50193f2372ae2137c67826f495 | 1,700 | ex | Elixir | lib/commodity/request.ex | akdilsiz/commodity-cloud | 08c366c9fc95fbb3565131672db4cc52f8b870c9 | [
"Apache-2.0"
] | 7 | 2019-04-11T21:12:49.000Z | 2021-04-14T12:56:42.000Z | lib/commodity/request.ex | akdilsiz/commodity-cloud | 08c366c9fc95fbb3565131672db4cc52f8b870c9 | [
"Apache-2.0"
] | null | null | null | lib/commodity/request.ex | akdilsiz/commodity-cloud | 08c366c9fc95fbb3565131672db4cc52f8b870c9 | [
"Apache-2.0"
] | 2 | 2019-06-06T18:05:33.000Z | 2019-07-16T08:49:45.000Z | ##
# Copyright 2018 Abdulkadir DILSIZ
#
# 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 Commodity.Request do
@moduledoc """
Http Client method for Commodity API
"""
@spec get(binary, map, binary) :: tuple
def get(url, headers, body) do
request(:get, url, headers, body)
end
@spec get(binary, map) :: tuple
def get(url, headers) do
request(:get, url, headers, [])
end
@spec post(binary, map, binary) :: tuple
def post(url, headers, body) do
request(:post, url, headers, body)
end
@spec put(binary, map, binary) :: tuple
def put(url, headers, body) do
request(:put, url, headers, body)
end
@spec delete(binary, map, binary) :: tuple
def delete(url, headers, body) do
request(:delete, url, headers, body)
end
@spec request(atom, binary, map, binary) :: tuple
defp request(method, url, headers, body) when is_atom(method) do
case HTTPoison.request(method, url, body, headers, [:ssl]) do
{:ok, %HTTPoison.Response{body: body, status_code: status_code}} ->
{:ok, status_code, body}
{:error, %HTTPoison.Error{id: nil, reason: error}} ->
{:error, error}
end
end
end
| 30.357143 | 77 | 0.670588 |
fff38b5aea89dfeb8a900a7acba6d7bdcf0b9b93 | 131 | ex | Elixir | lib/utils/mock_center.ex | BailianBlockchain/Bailian_Supply_Chain | 8341e974b133c86f48488cb52ec4b3b281a99eb5 | [
"MIT"
] | 5 | 2020-12-10T07:24:18.000Z | 2021-12-15T08:26:05.000Z | lib/utils/mock_center.ex | BailianBlockchain/Bailian_Supply_Chain | 8341e974b133c86f48488cb52ec4b3b281a99eb5 | [
"MIT"
] | 4 | 2021-02-22T08:53:43.000Z | 2021-06-09T09:24:46.000Z | lib/utils/mock_center.ex | WeLightProject/WeLight-Portal | 6e701469423e3a62affdc415c4e8c186d603d324 | [
"MIT"
] | 2 | 2020-12-12T17:06:13.000Z | 2021-04-09T02:12:31.000Z | defmodule MockCenter do
def create_weid_result() do
{:ok, "did:weid:1:0xd497f242b141089e30c59e92d56929e9ad9dbc63"}
end
end
| 21.833333 | 66 | 0.778626 |
fff396352b3305dc6fdbd050ae4c83abe809dfea | 3,767 | ex | Elixir | lib/ambry/media/chapters/utils.ex | doughsay/ambry | c04e855bf06a6b00b8053c6eacb2eac14a56a37c | [
"MIT"
] | 12 | 2021-09-30T20:51:49.000Z | 2022-01-27T04:09:32.000Z | lib/ambry/media/chapters/utils.ex | doughsay/ambry | c04e855bf06a6b00b8053c6eacb2eac14a56a37c | [
"MIT"
] | 76 | 2021-10-01T05:45:11.000Z | 2022-03-28T04:12:39.000Z | lib/ambry/media/chapters/utils.ex | doughsay/ambry | c04e855bf06a6b00b8053c6eacb2eac14a56a37c | [
"MIT"
] | 2 | 2021-10-04T19:27:28.000Z | 2022-01-13T22:36:38.000Z | defmodule Ambry.Media.Chapters.Utils do
@moduledoc """
Utility functions for chapter strategies.
"""
alias Ambry.Media.Media
require Logger
def adapt_ffmpeg_chapters(map) do
case map do
%{"chapters" => [_ | _] = chapters} ->
map_chapters(chapters)
%{"chapters" => []} ->
{:error, :no_chapters}
unexpected ->
Logger.warn(fn -> "Unexpected chapters format: #{inspect(unexpected)}" end)
{:error, :unexpected_format}
end
end
defp map_chapters(chapters, acc \\ [])
defp map_chapters([], acc), do: {:ok, Enum.reverse(acc)}
defp map_chapters([chapter | rest], acc) do
case chapter do
%{
"start_time" => start_time_string,
"tags" => %{"title" => title}
} ->
map_chapters(rest, [
%{
time:
start_time_string
|> Decimal.new()
|> Decimal.round(2),
title: title
}
| acc
])
unexpected ->
Logger.warn(fn -> "Unexpected chapter format: #{inspect(unexpected)}" end)
{:error, :unexpected_format}
end
end
@doc """
Get json metadata from a media file.
"""
def get_metadata_json(media, file) do
command = "ffprobe"
args = [
"-i",
file,
"-print_format",
"json",
"-show_entries",
"format",
"-v",
"quiet"
]
case System.cmd(command, args, cd: Media.source_path(media), parallelism: true) do
{output, 0} ->
{:ok, output}
{output, code} ->
Logger.warn(fn -> "ffmpeg metadata probe failed. Code: #{code}, Output: #{output}" end)
{:error, :probe_failed}
end
end
@doc """
Slow but accurate duration of a given file.
"""
def get_accurate_duration(media, file) do
command = "ffmpeg"
args = [
"-i",
file,
"-vn",
"-stats",
"-v",
"quiet",
"-f",
"null",
"-"
]
try do
{output, 0} =
System.cmd(command, args,
cd: Media.source_path(media),
parallelism: true,
stderr_to_stdout: true
)
timecode =
output
|> String.split("\r")
|> List.last()
|> String.trim()
|> String.split(" ")
|> Enum.at(1)
|> String.split("=")
|> Enum.at(1)
{:ok, timecode_to_decimal(timecode)}
rescue
error in RuntimeError ->
Logger.warn(fn -> "Couldn't get duration:" end)
Logger.error(Exception.format(:error, error, __STACKTRACE__))
{:error, :no_duration}
end
end
@doc """
Converts timecodes, e.g. `00:29:22.24` into a Decimal number of seconds.
"""
def timecode_to_decimal(timecode) do
case String.split(timecode, ":") do
[minutes, seconds] ->
seconds_of_minutes = minutes |> Decimal.new() |> Decimal.mult(60)
seconds = Decimal.new(seconds)
Decimal.add(seconds_of_minutes, seconds)
[hours, minutes, seconds] ->
seconds_of_hours = hours |> Decimal.new() |> Decimal.mult(3600)
seconds_of_minutes = minutes |> Decimal.new() |> Decimal.mult(60)
seconds = Decimal.new(seconds)
seconds_of_hours |> Decimal.add(seconds_of_minutes) |> Decimal.add(seconds)
end
end
def mp4_chapter_probe(media, mp4_file) do
command = "ffprobe"
args = ["-i", mp4_file, "-print_format", "json", "-show_chapters", "-loglevel", "error"]
case System.cmd(command, args, cd: Media.source_path(media), parallelism: true) do
{output, 0} ->
{:ok, output}
{output, code} ->
Logger.warn(fn -> "MP4 chapter probe failed. Code: #{code}, Output: #{output}" end)
{:error, :probe_failed}
end
end
end
| 24.147436 | 95 | 0.551102 |
fff39d08251b4f9361e30484d59e6c061f4c57b6 | 259 | ex | Elixir | lib/media_server.ex | MNDL-27/midarr-server | b749707a1777205cea2d93349cde2ef922e527ec | [
"MIT"
] | 538 | 2022-02-02T21:46:52.000Z | 2022-03-29T20:50:34.000Z | lib/media_server.ex | MNDL-27/midarr-server | b749707a1777205cea2d93349cde2ef922e527ec | [
"MIT"
] | 48 | 2022-02-03T11:46:09.000Z | 2022-03-31T04:44:53.000Z | lib/media_server.ex | MNDL-27/midarr-server | b749707a1777205cea2d93349cde2ef922e527ec | [
"MIT"
] | 15 | 2022-02-03T05:55:14.000Z | 2022-02-28T11:09:03.000Z | defmodule MediaServer do
@moduledoc """
MediaServer keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end
| 25.9 | 66 | 0.760618 |
fff3a89ce43a45e424cc65274c0e51ba184730f7 | 1,736 | exs | Elixir | apps/blunt_ddd/mix.exs | blunt-elixir/blunt | a88b88984022db7ba2110204248fdb541121e3a0 | [
"MIT"
] | 1 | 2022-03-07T11:54:47.000Z | 2022-03-07T11:54:47.000Z | apps/blunt_ddd/mix.exs | elixir-cqrs/cqrs_tools | afbf82da522a10d2413547a46f316ed3aadebba5 | [
"MIT"
] | null | null | null | apps/blunt_ddd/mix.exs | elixir-cqrs/cqrs_tools | afbf82da522a10d2413547a46f316ed3aadebba5 | [
"MIT"
] | null | null | null | defmodule CqrsToolsDdd.MixProject do
use Mix.Project
@version "0.1.0-rc1"
def project do
[
version: @version,
app: :blunt_ddd,
elixir: "~> 1.12",
#
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
#
start_permanent: Mix.env() == :prod,
deps: deps(),
package: [
description: "DDD semantics for blunt",
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/blunt-elixir/blunt_ddd"}
],
source_url: "https://github.com/blunt-elixir/blunt_ddd",
elixirc_paths: elixirc_paths(Mix.env())
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# 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
env = System.get_env("MIX_LOCAL") || Mix.env()
blunt(env) ++
[
# For testing
{:etso, "~> 0.1.6", only: [:test]},
{:faker, "~> 0.17.0", optional: true, only: [:test]},
{:ex_machina, "~> 2.7", optional: true, only: [:test]},
{:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false},
{:elixir_uuid, "~> 1.6", only: [:dev, :test], override: true, hex: :uuid_utils},
# generate docs
{:ex_doc, "~> 0.28", only: :dev, runtime: false}
]
end
defp blunt(:prod) do
[
{:blunt, "~> 0.1"},
{:blunt_data, "~> 0.1"}
]
end
defp blunt(_env) do
[
{:blunt, in_umbrella: true},
{:blunt_data, in_umbrella: true}
]
end
end
| 24.450704 | 88 | 0.535714 |
fff3b5a6a57bdcdc0a98a62667f8d464cdcb9870 | 1,437 | ex | Elixir | clients/datastore/lib/google_api/datastore/v1/model/property_reference.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/datastore/lib/google_api/datastore/v1/model/property_reference.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/datastore/lib/google_api/datastore/v1/model/property_reference.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.Datastore.V1.Model.PropertyReference do
@moduledoc """
A reference to a property relative to the kind expressions.
## Attributes
- name (String): The name of the property. If name includes \".\"s, it may be interpreted as a property name path. Defaults to: `null`.
"""
defstruct [
:"name"
]
end
defimpl Poison.Decoder, for: GoogleApi.Datastore.V1.Model.PropertyReference do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.Datastore.V1.Model.PropertyReference do
def encode(value, options) do
GoogleApi.Datastore.V1.Deserializer.serialize_non_nil(value, options)
end
end
| 31.23913 | 147 | 0.751566 |
fff3c80c96060976ec0fbb635d402f3699d3a489 | 1,930 | ex | Elixir | lib/coherence/plugs/authorization/basic.ex | remigijusj/coherence | 36fe35b0bfe7ac63b44b4046f3ba62f2fe69603a | [
"MIT"
] | null | null | null | lib/coherence/plugs/authorization/basic.ex | remigijusj/coherence | 36fe35b0bfe7ac63b44b4046f3ba62f2fe69603a | [
"MIT"
] | null | null | null | lib/coherence/plugs/authorization/basic.ex | remigijusj/coherence | 36fe35b0bfe7ac63b44b4046f3ba62f2fe69603a | [
"MIT"
] | null | null | null | defmodule Coherence.Authentication.Basic do
@moduledoc """
Implements basic HTTP authentication. To use add:
plug Coherence.Authentication.Basic, realm: "Secret world"
to your pipeline.
This module is derived from https://github.com/bitgamma/plug_auth which is derived from https://github.com/lexmag/blaguth
"""
@behaviour Plug
import Plug.Conn
import Coherence.Authentication.Utils
alias Coherence.Config
import Coherence.Authentication.Utils
@doc """
Returns the encoded form for the given `user` and `password` combination.
"""
def encode_credentials(user, password), do: Base.encode64("#{user}:#{password}")
def create_login(email, password, user_data, _opts \\ []) do
creds = encode_credentials(email, password)
store = get_credential_store
store.put_credentials(creds, user_data)
end
def init(opts) do
%{
realm: Keyword.get(opts, :realm, "Restricted Area"),
error: Keyword.get(opts, :error, "HTTP Authentication Required"),
store: Keyword.get(opts, :store, Coherence.CredentialStore.Agent),
assigns_key: Keyword.get(opts, :assigns_key, :current_user),
}
end
def call(conn, opts) do
conn
|> get_auth_header
|> verify_creds(opts[:store])
|> assert_creds(opts[:realm], opts[:error], opts[:assigns_key])
end
defp get_auth_header(conn), do: {conn, get_first_req_header(conn, "authorization")}
defp verify_creds({conn, << "Basic ", creds::binary >>}, store), do: {conn, store.get_user_data(creds)}
defp verify_creds({conn, _}, _), do: {conn, nil}
defp assert_creds({conn, nil}, realm, error, _), do: halt_with_login(conn, realm, error)
defp assert_creds({conn, user_data}, _, _, key), do: assign_user_data(conn, user_data, key)
defp halt_with_login(conn, realm, error) do
conn
|> put_resp_header("www-authenticate", ~s{Basic realm="#{realm}"})
|> halt_with_error(error)
end
end
| 32.711864 | 125 | 0.698446 |
fff3c8913435fac31a6da88ab7baafeebf9cfa41 | 134 | exs | Elixir | spec/spec_helper.exs | FabienHenon/jsonapi-deserializer | db6f7201e6b6b04201f9bcbe42888635133e655a | [
"MIT"
] | 1 | 2019-06-05T18:33:31.000Z | 2019-06-05T18:33:31.000Z | spec/spec_helper.exs | FabienHenon/jsonapi-deserializer | db6f7201e6b6b04201f9bcbe42888635133e655a | [
"MIT"
] | null | null | null | spec/spec_helper.exs | FabienHenon/jsonapi-deserializer | db6f7201e6b6b04201f9bcbe42888635133e655a | [
"MIT"
] | null | null | null | ESpec.configure(fn config ->
config.before(fn _tags ->
{:shared, []}
end)
config.finally(fn _shared ->
:ok
end)
end)
| 13.4 | 30 | 0.597015 |
fff4096e8524046298b48d5249c92efff37d436a | 8,699 | ex | Elixir | lib/ditto/cache_strategy/eviction.ex | mogorman/ditto | 6c19a0c3f2bc3cf243ea46d5eae0087850045a82 | [
"MIT"
] | 1 | 2020-08-29T08:29:14.000Z | 2020-08-29T08:29:14.000Z | lib/ditto/cache_strategy/eviction.ex | mogorman/ditto | 6c19a0c3f2bc3cf243ea46d5eae0087850045a82 | [
"MIT"
] | null | null | null | lib/ditto/cache_strategy/eviction.ex | mogorman/ditto | 6c19a0c3f2bc3cf243ea46d5eae0087850045a82 | [
"MIT"
] | null | null | null | if Ditto.CacheStrategy.configured?(Ditto.CacheStrategy.Eviction) do
defmodule Ditto.CacheStrategy.Eviction do
@behaviour Ditto.CacheStrategy
@moduledoc """
The eviction version has tools for removing things from cache based on size
"""
@ets_tab __MODULE__
@read_history_tab Module.concat(__MODULE__, "ReadHistory")
@expiration_tab Module.concat(__MODULE__, "Expiration")
@opts Application.fetch_env!(:ditto, __MODULE__)
@max_threshold Keyword.fetch!(@opts, :max_threshold)
if @max_threshold != :infinity do
@min_threshold Keyword.fetch!(@opts, :min_threshold)
end
def init(opts) do
case Keyword.get(opts, :caches) do
nil ->
:ets.new(tab(nil), [:public, :set, :named_table, {:read_concurrency, true}])
:ets.new(history_tab(nil), [:public, :set, :named_table, {:write_concurrency, true}])
:ets.new(expiration_tab(nil), [:public, :ordered_set, :named_table])
caches ->
Enum.each(caches, fn cache ->
:ets.new(tab(cache), [:public, :set, :named_table, {:read_concurrency, true}])
:ets.new(history_tab(cache), [:public, :set, :named_table, {:write_concurrency, true}])
:ets.new(expiration_tab(cache), [:public, :ordered_set, :named_table])
end)
end
end
defp history_tab(cache) do
Module.concat(tab(cache), ReadHistory)
end
defp expiration_tab(cache) do
Module.concat(tab(cache), Expiration)
end
def tab(_module, _key \\ nil)
def tab(nil, _key) do
@ets_tab
end
def tab(module, _key) do
Module.concat(@ets_tab, module)
end
def used_bytes(cache) do
words = 0
words = words + :ets.info(tab(cache), :memory)
words = words + :ets.info(history_tab(cache), :memory)
words * :erlang.system_info(:wordsize)
end
if @max_threshold == :infinity do
def cache(cache, key, value, opts) do
do_cache(cache, key, value, opts)
end
else
def cache(cache, key, value, opts) do
if used_bytes(cache) > @max_threshold do
garbage_collect(cache)
end
do_cache(cache, key, value, opts)
end
end
defp do_cache(cache, key, _value, opts) do
case Keyword.fetch(opts, :expires_in) do
{:ok, expires_in} ->
expired_at = System.monotonic_time(:millisecond) + expires_in
counter = System.unique_integer()
:ets.insert(expiration_tab(cache), {{expired_at, counter}, key})
:error ->
:ok
end
%{permanent: Keyword.get(opts, :permanent, false)}
end
def read(cache, key, _value, context) do
expired? = clear_expired_cache(cache, key)
unless context.permanent do
counter = System.unique_integer([:monotonic, :positive])
:ets.insert(history_tab(cache), {key, counter})
end
if expired?, do: :retry, else: :ok
end
def invalidate do
case Application.get_env(:ditto, :caches) do
nil ->
num_deleted = :ets.select_delete(tab(nil), [{{:_, {:completed, :_, :_}}, [], [true]}])
:ets.delete_all_objects(history_tab(nil))
num_deleted
modules ->
Enum.reduce(modules, 0, fn module, acc ->
num_deleted =
:ets.select_delete(tab(module), [{{:_, {:completed, :_, :_}}, [], [true]}]) + acc
:ets.delete_all_objects(history_tab(module))
num_deleted
end)
end
end
def invalidate(module) do
cache_name = Cache.cache_name(module)
num_deleted =
cache_name
|> tab()
|> :ets.select_delete([{{key(cache_name, module), {:completed, :_, :_}}, [], [true]}])
:ets.select_delete(history_tab(cache_name), [{key(cache_name, module), [], [true]}])
num_deleted
end
def invalidate(module, function) do
cache_name = Cache.cache_name(module)
num_deleted =
cache_name
|> tab()
|> :ets.select_delete([
{{key(cache_name, module, function), {:completed, :_, :_}}, [], [true]}
])
:ets.select_delete(history_tab(cache_name), [
{key(cache_name, module, function), [], [true]}
])
num_deleted
end
def invalidate(module, function, args) do
cache_name = Cache.cache_name(module)
num_deleted =
cache_name
|> tab()
|> :ets.select_delete([
{{key(cache_name, module, function, args), {:completed, :_, :_}}, [], [true]}
])
:ets.select_delete(history_tab(cache_name), [
{key(cache_name, module, function, args), [], [true]}
])
num_deleted
end
def garbage_collect do
do_garbage_collect_all(@max_threshold)
end
def garbage_collect(module) do
do_garbage_collect(@max_threshold, module)
end
def do_garbage_collect(:infinity, _) do
0
end
def do_garbage_collect(_, module) do
cache = Cache.cache_name(module)
if used_bytes(cache) <= @min_threshold do
# still don't collect
0
else
# remove values ordered by last accessed time until used bytes less than @min_threshold.
values = :lists.keysort(2, :ets.tab2list(history_tab(cache)))
stream = values |> Stream.filter(fn n -> n != :permanent end) |> Stream.with_index(1)
try do
for {{key, _}, num_deleted} <- stream do
case is_our_key?(key, module) do
true ->
:ets.select_delete(tab(cache), [{{key, {:completed, :_, :_}}, [], [true]}])
:ets.delete(history_tab(cache), key)
false ->
0
end
if used_bytes(cache) <= @min_threshold do
throw({:break, num_deleted})
end
end
else
_ -> length(values)
catch
{:break, num_deleted} -> num_deleted
end
end
end
defp is_our_key?({_, _}, _), do: true
defp is_our_key?({module, _, _}, module), do: true
defp is_our_key?(_, _), do: false
def do_garbage_collect_all(:infinity) do
0
end
def do_garbage_collect_all(_) do
Application.get_env(:ditto, :caches, [nil])
|> Enum.reduce(0, fn cache, acc ->
if used_bytes(cache) <= @min_threshold do
# still don't collect
0 + acc
else
# remove values ordered by last accessed time until used bytes less than @min_threshold.
values = :lists.keysort(2, :ets.tab2list(history_tab(cache)))
stream = values |> Stream.filter(fn n -> n != :permanent end) |> Stream.with_index(1)
try do
for {{key, _}, num_deleted} <- stream do
:ets.select_delete(tab(cache), [{{key, {:completed, :_, :_}}, [], [true]}])
:ets.delete(history_tab(cache), key)
if used_bytes(cache) <= @min_threshold do
throw({:break, num_deleted})
end
end
else
_ -> length(values) + acc
catch
{:break, num_deleted} -> num_deleted + acc
end
end
end)
end
def clear_expired_cache(cache, read_key \\ nil, expired? \\ false) do
case :ets.first(expiration_tab(cache)) do
:"$end_of_table" ->
expired?
{expired_at, _counter} = key ->
case :ets.lookup(expiration_tab(cache), key) do
[] ->
# retry
clear_expired_cache(cache, read_key, expired?)
[{^key, cache_key}] ->
now = System.monotonic_time(:millisecond)
if now > expired_at do
invalidate(cache_key)
:ets.delete(expiration_tab(cache), key)
expired? = expired? || cache_key == read_key
# next
clear_expired_cache(cache, read_key, expired?)
else
# completed
expired?
end
end
end
end
# ets per module
defp key(module_name, module_name) do
{:_, :_}
end
defp key(_cache_name, module_name) do
{module_name, :_, :_}
end
# ets per module
defp key(module_name, module_name, function_name) do
{function_name, :_}
end
defp key(_cache_name, module_name, function_name) do
{module_name, function_name, :_}
end
# ets per module
defp key(module_name, module_name, function_name, args) do
{function_name, args}
end
defp key(_cache_name, module_name, function_name, args) do
{module_name, function_name, args}
end
end
end
| 28.615132 | 99 | 0.573859 |
fff41fcd5275bb1a41770e6c0c46c9db583c415f | 1,093 | ex | Elixir | lib/otto/application.ex | juvet/otto | aee3b34029da0f8c232bc79e0febb5339fd3e22b | [
"MIT"
] | 1 | 2019-11-05T06:07:56.000Z | 2019-11-05T06:07:56.000Z | lib/otto/application.ex | juvet/otto | aee3b34029da0f8c232bc79e0febb5339fd3e22b | [
"MIT"
] | 2 | 2019-01-06T18:32:53.000Z | 2019-01-06T18:47:02.000Z | lib/otto/application.ex | juvet/otto | aee3b34029da0f8c232bc79e0febb5339fd3e22b | [
"MIT"
] | null | null | null | defmodule Otto.Application do
use Application
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec
unless Mix.env() == :prod do
Envy.auto_load()
Envy.reload_config()
end
# Define workers and child supervisors to be supervised
children = [
# Start the Ecto repository
supervisor(Otto.Repo, []),
# Start the endpoint when the application starts
supervisor(OttoWeb.Endpoint, [])
# Start your own worker by calling: Otto.Worker.start_link(arg1, arg2, arg3)
# worker(Otto.Worker, [arg1, arg2, arg3]),
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Otto.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
OttoWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 29.540541 | 82 | 0.695334 |
fff425888ffd86b2184f867585cb7b291a3c3c84 | 100 | ex | Elixir | apps/gapi/lib/gapi/repo.ex | rolandolucio/gapi_umbrella | b1e690804d7d2a79d3ece7ca12edf65197ca7145 | [
"MIT"
] | null | null | null | apps/gapi/lib/gapi/repo.ex | rolandolucio/gapi_umbrella | b1e690804d7d2a79d3ece7ca12edf65197ca7145 | [
"MIT"
] | null | null | null | apps/gapi/lib/gapi/repo.ex | rolandolucio/gapi_umbrella | b1e690804d7d2a79d3ece7ca12edf65197ca7145 | [
"MIT"
] | null | null | null | defmodule Gapi.Repo do
use Ecto.Repo,
otp_app: :gapi,
adapter: Ecto.Adapters.Postgres
end
| 16.666667 | 35 | 0.71 |
fff4537a8ea4534d3440290fbf114000aa932f81 | 3,467 | ex | Elixir | lib/grizzly/zwave/commands/schedule_entry_lock_daily_repeating_set.ex | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 76 | 2019-09-04T16:56:58.000Z | 2022-03-29T06:54:36.000Z | lib/grizzly/zwave/commands/schedule_entry_lock_daily_repeating_set.ex | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 124 | 2019-09-05T14:01:24.000Z | 2022-02-28T22:58:14.000Z | lib/grizzly/zwave/commands/schedule_entry_lock_daily_repeating_set.ex | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 10 | 2019-10-23T19:25:45.000Z | 2021-11-17T13:21:20.000Z | defmodule Grizzly.ZWave.Commands.ScheduleEntryLockDailyRepeatingSet do
@moduledoc """
This command is used to set or erase a daily repeating schedule for an
identified user who already has valid user access code.
Params:
* `:set_action` - Indicates whether to erase or modify
* `:user_identifier` - The User Identifier is used to recognize the user
identity. A valid User Identifier MUST be a value starting from 1 to the
maximum number of users supported by the device
* `:schedule_slot_id` - A value from 1 to Number of Slots Daily Repeating
Supported
* `:week_days` - a list of scheduled week day's names
* `:start_hour` - A value from 0 to 23 representing the starting hour of the
time fence.
* `:start_minute` - A value from 0 to 59 representing the starting minute of
the time fence.
* `:duration_hour` - A value from 0 to 23 representing how many hours the
time fence will last
* `:duration_minute` - A value from 0 to 59 representing how many minutes
the time fence will last past the Duration Hour field.
"""
@behaviour Grizzly.ZWave.Command
alias Grizzly.ZWave.Command
alias Grizzly.ZWave.CommandClasses.ScheduleEntryLock
@type param ::
{:set_action, :erase | :modify}
| {:user_identifier, byte()}
| {:schedule_slot_id, byte()}
| {:week_days, [ScheduleEntryLock.week_day()]}
| {:start_hour, 0..23}
| {:start_minute, 0..59}
| {:duration_hour, 0..23}
| {:duration_minute, 0..59}
@impl true
@spec new([param()]) :: {:ok, Command.t()}
def new(params) do
command = %Command{
name: :schedule_entry_lock_daily_repeating_set,
command_byte: 0x10,
command_class: ScheduleEntryLock,
params: params,
impl: __MODULE__
}
{:ok, command}
end
@impl true
@spec encode_params(Command.t()) :: binary()
def encode_params(command) do
set_action = Command.param!(command, :set_action)
user_identifier = Command.param!(command, :user_identifier)
schedule_slot_id = Command.param!(command, :schedule_slot_id)
week_days = Command.param!(command, :week_days)
start_hour = Command.param!(command, :start_hour)
start_minute = Command.param!(command, :start_minute)
duration_hour = Command.param!(command, :duration_hour)
duration_minute = Command.param!(command, :duration_minute)
week_day_bitmask = ScheduleEntryLock.weekdays_to_bitmask(week_days)
action_byte = action_to_byte(set_action)
<<action_byte, user_identifier, schedule_slot_id>> <>
week_day_bitmask <> <<start_hour, start_minute, duration_hour, duration_minute>>
end
@impl true
def decode_params(
<<action_byte, user_identifier, schedule_slot_id, week_day_bitmask, start_hour,
start_minute, duration_hour, duration_minute>>
) do
week_days = ScheduleEntryLock.bitmask_to_weekdays(week_day_bitmask)
{:ok,
[
set_action: byte_to_action(action_byte),
user_identifier: user_identifier,
schedule_slot_id: schedule_slot_id,
week_days: week_days,
start_hour: start_hour,
start_minute: start_minute,
duration_hour: duration_hour,
duration_minute: duration_minute
]}
end
defp action_to_byte(:erase), do: 0x00
defp action_to_byte(:modify), do: 0x01
defp byte_to_action(0x00), do: :erase
defp byte_to_action(0x01), do: :modify
end
| 35.020202 | 87 | 0.691664 |
fff46e1dc2496bdb982106d64ac474a53ca8c279 | 1,080 | exs | Elixir | test/json_schema_test_suite/draft7/default_test.exs | hrzndhrn/json_xema | 955eab7b0919d144b38364164d90275201c89474 | [
"MIT"
] | 54 | 2019-03-10T19:51:07.000Z | 2021-12-23T07:31:09.000Z | test/json_schema_test_suite/draft7/default_test.exs | hrzndhrn/json_xema | 955eab7b0919d144b38364164d90275201c89474 | [
"MIT"
] | 36 | 2018-05-20T09:13:20.000Z | 2021-03-14T15:22:03.000Z | test/json_schema_test_suite/draft7/default_test.exs | hrzndhrn/json_xema | 955eab7b0919d144b38364164d90275201c89474 | [
"MIT"
] | 3 | 2019-04-12T09:08:51.000Z | 2019-12-04T01:23:56.000Z | defmodule JsonSchemaTestSuite.Draft7.DefaultTest do
use ExUnit.Case
import JsonXema, only: [valid?: 2]
describe ~s|invalid type for default| do
setup do
%{
schema:
JsonXema.new(%{"properties" => %{"foo" => %{"default" => [], "type" => "integer"}}})
}
end
test ~s|valid when property is specified|, %{schema: schema} do
assert valid?(schema, %{"foo" => 13})
end
test ~s|still valid when the invalid default is used|, %{schema: schema} do
assert valid?(schema, %{})
end
end
describe ~s|invalid string value for default| do
setup do
%{
schema:
JsonXema.new(%{
"properties" => %{
"bar" => %{"default" => "bad", "minLength" => 4, "type" => "string"}
}
})
}
end
test ~s|valid when property is specified|, %{schema: schema} do
assert valid?(schema, %{"bar" => "good"})
end
test ~s|still valid when the invalid default is used|, %{schema: schema} do
assert valid?(schema, %{})
end
end
end
| 24.545455 | 94 | 0.546296 |
fff48f2bb440d8fdfb656b9adf3f83579e75645b | 459 | ex | Elixir | elixir_libs/elixir_example/lib/otp.ex | tyalt1/elixir_example | 043e75039bea992613be88f6a4d26c5032e6b57f | [
"Apache-2.0"
] | 1 | 2018-01-25T11:08:17.000Z | 2018-01-25T11:08:17.000Z | elixir_libs/elixir_example/lib/otp.ex | tyalt1/elixir_rebar_example | 043e75039bea992613be88f6a4d26c5032e6b57f | [
"Apache-2.0"
] | null | null | null | elixir_libs/elixir_example/lib/otp.ex | tyalt1/elixir_rebar_example | 043e75039bea992613be88f6a4d26c5032e6b57f | [
"Apache-2.0"
] | null | null | null | defmodule MyApp do
use Application
@moduledoc """
Example of OTP application starting counter servers from alt_server.ex.
"""
def start(_type, _args) do
import Supervisor.Spec
children = [
worker(AltServer.Server, [], [name: MyApp.Counter.Server]),
worker(AltServer.Agent, [], [name: MyApp.Counter.Agent]),
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 22.95 | 73 | 0.679739 |
fff49ce0927b12c7106adf5a4b1d0094eeedddb5 | 1,653 | ex | Elixir | clients/admin/lib/google_api/admin/reports_v1/model/usage_report_entity.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/admin/lib/google_api/admin/reports_v1/model/usage_report_entity.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/admin/lib/google_api/admin/reports_v1/model/usage_report_entity.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.Admin.Reports_v1.Model.UsageReportEntity do
@moduledoc """
Information about the type of the item.
## Attributes
- customerId (String): Obfuscated customer id for the record. Defaults to: `null`.
- profileId (String): Obfuscated user id for the record. Defaults to: `null`.
- type (String): The type of item, can be a customer or user. Defaults to: `null`.
- userEmail (String): user's email. Defaults to: `null`.
"""
defstruct [
:"customerId",
:"profileId",
:"type",
:"userEmail"
]
end
defimpl Poison.Decoder, for: GoogleApi.Admin.Reports_v1.Model.UsageReportEntity do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.Admin.Reports_v1.Model.UsageReportEntity do
def encode(value, options) do
GoogleApi.Admin.Reports_v1.Deserializer.serialize_non_nil(value, options)
end
end
| 31.788462 | 84 | 0.738052 |
fff49ea9705bee94e0a61137d9d8e4b5f63a5ca5 | 1,191 | ex | Elixir | lib/contraq/endpoint.ex | marnen/contraq-elixir | 69798c1b92a08c76a63e200eadeeb19986d56d91 | [
"MIT"
] | null | null | null | lib/contraq/endpoint.ex | marnen/contraq-elixir | 69798c1b92a08c76a63e200eadeeb19986d56d91 | [
"MIT"
] | 3 | 2016-11-25T20:35:54.000Z | 2016-11-26T19:45:35.000Z | lib/contraq/endpoint.ex | marnen/contraq-elixir | 69798c1b92a08c76a63e200eadeeb19986d56d91 | [
"MIT"
] | null | null | null | defmodule Contraq.Endpoint do
use Phoenix.Endpoint, otp_app: :contraq
socket "/socket", Contraq.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: :contraq, 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: "_contraq_key",
signing_salt: "qWlh98Pk"
plug Contraq.Router
end
| 27.697674 | 69 | 0.714526 |
fff4a9a293ba09f3a8655e051bf00c45f431e160 | 4,839 | ex | Elixir | lib/cpfcnpj.ex | soteras/Brcpfcnpj | 8d3394ff8a84898d6f403ce2025e934be6af45fe | [
"MIT"
] | 62 | 2016-03-02T12:05:35.000Z | 2022-01-19T00:23:36.000Z | lib/cpfcnpj.ex | soteras/Brcpfcnpj | 8d3394ff8a84898d6f403ce2025e934be6af45fe | [
"MIT"
] | 24 | 2015-03-15T19:30:19.000Z | 2022-03-21T15:31:23.000Z | lib/cpfcnpj.ex | soteras/Brcpfcnpj | 8d3394ff8a84898d6f403ce2025e934be6af45fe | [
"MIT"
] | 20 | 2015-03-09T22:35:42.000Z | 2022-03-21T14:23:19.000Z | defmodule Cpfcnpj do
@moduledoc """
Módulo responsável por realizar todos os cálculos de validação.
## Examples
iex>Cpfcnpj.valid?({:cnpj,"69.103.604/0001-60"})
true
iex>Cpfcnpj.valid?({:cpf,"111.444.777-35"})
true
Com ou sem os caracteres especiais os mesmos serão validados
"""
@division 11
@cpf_length 11
@cpf_algs_1 [10, 9, 8, 7, 6, 5, 4, 3, 2, 0, 0]
@cpf_algs_2 [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 0]
@cpf_regex ~r/(\d{3})?(\d{3})?(\d{3})?(\d{2})/
@cnpj_length 14
@cnpj_algs_1 [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2, 0, 0]
@cnpj_algs_2 [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2, 0]
@cnpj_regex ~r/(\d{2})?(\d{3})?(\d{3})?(\d{4})?(\d{2})/
@doc """
Valida cpf/cnpj caracteres especias não são levados em consideração.
## Examples
iex>Cpfcnpj.valid?({:cnpj,"69.103.604/0001-60"})
true
"""
@spec valid?({:cpf | :cnpj, String.t()}) :: boolean()
def valid?(number_in) do
check_number(number_in) and type_checker(number_in) and special_checker(number_in)
end
defp check_number({_, nil}) do
false
end
# Checks length and if all are equal
defp check_number(tp_cpfcnpj) do
cpfcnpj = String.replace(elem(tp_cpfcnpj, 1), ~r/[\.\/-]/, "")
all_equal? =
cpfcnpj
|> String.replace(String.at(cpfcnpj, 0), "")
|> String.length()
|> Kernel.==(0)
correct_length? =
case tp_cpfcnpj do
{:cpf, _} ->
String.length(cpfcnpj) == @cpf_length
{:cnpj, _} ->
String.length(cpfcnpj) == @cnpj_length
end
correct_length? and not all_equal?
end
# Checks validation digits
defp type_checker(tp_cpfcnpj) do
cpfcnpj = String.replace(elem(tp_cpfcnpj, 1), ~r/[^0-9]/, "")
first_char_valid = character_valid(cpfcnpj, {elem(tp_cpfcnpj, 0), :first})
second_char_valid = character_valid(cpfcnpj, {elem(tp_cpfcnpj, 0), :second})
verif = first_char_valid <> second_char_valid
verif == String.slice(cpfcnpj, -2, 2)
end
# Checks special cases
defp special_checker({:cpf, _}) do
true
end
defp special_checker(tp_cpfcnpj = {:cnpj, _}) do
cnpj = String.replace(elem(tp_cpfcnpj, 1), ~r/[\.\/-]/, "")
order = String.slice(cnpj, 8..11)
first_three_digits = String.slice(cnpj, 0..2)
basic = String.slice(cnpj, 0..7)
cond do
order == "0000" ->
false
String.to_integer(order) > 300 and first_three_digits == "000" and basic != "00000000" ->
false
true ->
true
end
end
defp mult_sum(algs, cpfcnpj) do
mult =
cpfcnpj
|> String.codepoints()
|> Enum.with_index()
|> Enum.map(fn {k, v} -> String.to_integer(k) * Enum.at(algs, v) end)
Enum.reduce(mult, 0, &+/2)
end
defp character_calc(remainder) do
if remainder < 2, do: 0, else: @division - remainder
end
defp character_valid(cpfcnpj, valid_type) do
array =
case valid_type do
{:cpf, :first} -> @cpf_algs_1
{:cnpj, :first} -> @cnpj_algs_1
{:cpf, :second} -> @cpf_algs_2
{:cnpj, :second} -> @cnpj_algs_2
end
mult_sum(array, cpfcnpj)
|> rem(@division)
|> character_calc
|> Integer.to_string()
end
@doc """
Valida o Cpf/Cnpj e retorna uma String com o mesmo formatado.
Caso seja inválido retorna `nil`
## Examples
iex> Cpfcnpj.format_number({:cnpj,"69.103.604/0001-60"})
"69.103.604/0001-60"
"""
@spec format_number({:cpf | :cnpj, String.t()}) :: String.t() | nil
def format_number(number_in) do
if valid?(number_in) do
tp_cpfcnpj = {elem(number_in, 0), String.replace(elem(number_in, 1), ~r/[^0-9]/, "")}
case tp_cpfcnpj do
{:cpf, cpf} ->
Regex.replace(@cpf_regex, cpf, "\\1.\\2.\\3-\\4")
{:cnpj, cnpj} ->
Regex.replace(@cnpj_regex, cnpj, "\\1.\\2.\\3/\\4-\\5")
end
else
nil
end
end
@doc """
Gerador de cpf/cnpj concatenado com o dígito verificador.
"""
@spec generate(:cpf | :cnpj) :: String.t()
def generate(tp_cpfcnpj) do
numbers = random_numbers(tp_cpfcnpj)
first_valid_char = character_valid(numbers, {tp_cpfcnpj, :first})
second_valid_char = character_valid(numbers <> first_valid_char, {tp_cpfcnpj, :second})
result = numbers <> first_valid_char <> second_valid_char
# Chance de gerar um inválido seguindo esse algoritmo é baixa o suficiente que
# vale a pena simplesmente retentar caso o resultado for inválido
if valid?({tp_cpfcnpj, result}) do
result
else
generate(tp_cpfcnpj)
end
end
defp random_numbers(tp_cpfcnpj) do
random_digit_generator = fn -> Enum.random(0..9) end
random_digit_generator
|> Stream.repeatedly()
|> Enum.take(if(tp_cpfcnpj == :cpf, do: @cpf_length, else: @cnpj_length) - 2)
|> Enum.join()
end
end
| 26.156757 | 95 | 0.606944 |
fff4ada16f7a2168f8371d16ee8344cac10bd7cb | 925 | exs | Elixir | test/currency_conversion_test.exs | strzibny/currency-conversion | 057ad0f4a6e9169db55ae52a06dc22675644d467 | [
"MIT"
] | null | null | null | test/currency_conversion_test.exs | strzibny/currency-conversion | 057ad0f4a6e9169db55ae52a06dc22675644d467 | [
"MIT"
] | null | null | null | test/currency_conversion_test.exs | strzibny/currency-conversion | 057ad0f4a6e9169db55ae52a06dc22675644d467 | [
"MIT"
] | null | null | null | defmodule CurrencyConversionTest do
use ExUnit.Case, async: true
doctest CurrencyConversion
describe "get_currencies/0" do
test "fetches all currencies" do
assert CurrencyConversion.get_currencies() == [
:EUR,
:AUD,
:BGN,
:BRL,
:CAD,
:CHF,
:CNY,
:CZK,
:DKK,
:GBP,
:HKD,
:HRK,
:HUF,
:IDR,
:ILS,
:INR,
:JPY,
:KRW,
:MXN,
:MYR,
:NOK,
:NZD,
:PHP,
:PLN,
:RON,
:RUB,
:SEK,
:SGD,
:THB,
:TRY,
:USD,
:ZAR
]
end
end
end
| 21.022727 | 53 | 0.296216 |
fff4b7d080d94e94ed9f81f86bd310ea920b82d2 | 175 | exs | Elixir | .formatter.exs | blatyo/injex | 9f28a5897c9ee6bff6c6fddc60110103d608e88e | [
"MIT"
] | 10 | 2016-11-14T23:20:10.000Z | 2022-03-16T13:36:30.000Z | .formatter.exs | blatyo/injex | 9f28a5897c9ee6bff6c6fddc60110103d608e88e | [
"MIT"
] | null | null | null | .formatter.exs | blatyo/injex | 9f28a5897c9ee6bff6c6fddc60110103d608e88e | [
"MIT"
] | 2 | 2016-11-14T23:38:11.000Z | 2016-11-15T15:15:30.000Z | [
inputs: ["mix.exs", "{config,lib,test}/**/*.{ex,exs}"],
locals_without_parens: [
inject: 2
],
export: [
locals_without_parens: [
inject: 2
]
]
]
| 14.583333 | 57 | 0.525714 |
fff4b85c10ba088cf320c2a97301079f4311b5d7 | 3,781 | ex | Elixir | lib/phoenix.ex | samkenxstream/phoenix | 18433f95a90fc948e1d6d0f5606dfa339fdc6d61 | [
"MIT"
] | null | null | null | lib/phoenix.ex | samkenxstream/phoenix | 18433f95a90fc948e1d6d0f5606dfa339fdc6d61 | [
"MIT"
] | null | null | null | lib/phoenix.ex | samkenxstream/phoenix | 18433f95a90fc948e1d6d0f5606dfa339fdc6d61 | [
"MIT"
] | 1 | 2018-10-01T19:42:35.000Z | 2018-10-01T19:42:35.000Z | defmodule Phoenix do
@moduledoc """
This is the documentation for the Phoenix project.
By default, Phoenix applications depend on the following packages
across these categories.
## General
* [Ecto](https://hexdocs.pm/ecto) - a language integrated query and
database wrapper
* [ExUnit](https://hexdocs.pm/ex_unit) - Elixir's built-in test framework
* [Gettext](https://hexdocs.pm/gettext) - Internationalization and
localization through [`gettext`](https://www.gnu.org/software/gettext/)
* [Phoenix](https://hexdocs.pm/phoenix) - the Phoenix web framework
(these docs)
* [Phoenix PubSub](https://hexdocs.pm/phoenix_pubsub) - a distributed
pub/sub system with presence support
* [Phoenix HTML](https://hexdocs.pm/phoenix_html) - conveniences for
working with HTML in Phoenix
* [Phoenix View](https://hexdocs.pm/phoenix_view) - a set of functions
for building `Phoenix.View` and working with template languages such
as Elixir's own `EEx`
* [Phoenix LiveView](https://hexdocs.pm/phoenix_live_view) - rich,
real-time user experiences with server-rendered HTML
* [Phoenix LiveDashboard](https://hexdocs.pm/phoenix_live_dashboard) -
real-time performance monitoring and debugging tools for Phoenix
developers
* [Plug](https://hexdocs.pm/plug) - a specification and conveniences
for composable modules in between web applications
* [Swoosh](https://hexdocs.pm/swoosh) - a library for composing,
delivering and testing emails, also used by `mix phx.gen.auth`
* [Telemetry Metrics](https://hexdocs.pm/telemetry_metrics) - common
interface for defining metrics based on Telemetry events
To get started, see our [overview guides](overview.html).
"""
use Application
@doc false
def start(_type, _args) do
# Warm up caches
_ = Phoenix.Template.engines()
_ = Phoenix.Template.format_encoder("index.html")
warn_on_missing_json_library()
# Configure proper system flags from Phoenix only
if stacktrace_depth = Application.get_env(:phoenix, :stacktrace_depth) do
:erlang.system_flag(:backtrace_depth, stacktrace_depth)
end
if Application.fetch_env!(:phoenix, :logger) do
Phoenix.Logger.install()
end
children = [
# Code reloading must be serial across all Phoenix apps
Phoenix.CodeReloader.Server,
{DynamicSupervisor, name: Phoenix.Transports.LongPoll.Supervisor, strategy: :one_for_one}
]
Supervisor.start_link(children, strategy: :one_for_one, name: Phoenix.Supervisor)
end
@doc """
Returns the configured JSON encoding library for Phoenix.
To customize the JSON library, including the following
in your `config/config.exs`:
config :phoenix, :json_library, AlternativeJsonLibrary
"""
def json_library do
Application.get_env(:phoenix, :json_library, Jason)
end
@doc """
Returns the `:plug_init_mode` that controls when plugs are
initialized.
We recommend to set it to `:runtime` in development for
compilation time improvements. It must be `:compile` in
production (the default).
This option is passed as the `:init_mode` to `Plug.Builder.compile/3`.
"""
def plug_init_mode do
Application.get_env(:phoenix, :plug_init_mode, :compile)
end
defp warn_on_missing_json_library do
configured_lib = Application.get_env(:phoenix, :json_library)
if configured_lib && not Code.ensure_loaded?(configured_lib) do
IO.warn """
found #{inspect(configured_lib)} in your application configuration
for Phoenix JSON encoding, but module #{inspect(configured_lib)} is not available.
Ensure #{inspect(configured_lib)} is listed as a dependency in mix.exs.
"""
end
end
end
| 32.878261 | 95 | 0.714626 |
fff4cd3c2a2b1679149da31b5e23378356bfec6c | 538 | ex | Elixir | tests/dummy/web/models/truck.ex | autoxjs/autox-phoenix | 6446f4487e3af28955f6560973cff6add34be4d4 | [
"MIT"
] | null | null | null | tests/dummy/web/models/truck.ex | autoxjs/autox-phoenix | 6446f4487e3af28955f6560973cff6add34be4d4 | [
"MIT"
] | null | null | null | tests/dummy/web/models/truck.ex | autoxjs/autox-phoenix | 6446f4487e3af28955f6560973cff6add34be4d4 | [
"MIT"
] | null | null | null | defmodule Dummy.Truck do
use Dummy.Web, :model
schema "trucks" do
field :name, :string
field :status, :string
belongs_to :dock, Dummy.Dock
timestamps
end
@create_fields ~w()
@update_fields @create_fields
@optional_fields ~w(name status dock_id)
def create_changeset(model, params\\%{}) do
model
|> cast(params, @create_fields, @optional_fields)
end
def update_changeset(model, params\\%{}) do
create_changeset(model, params)
end
def delete_changeset(model, _) do
model
end
end | 19.925926 | 53 | 0.687732 |
fff4ea0bdc8ffc677c4c7a5e0c6104377038f6dd | 1,750 | ex | Elixir | clients/firestore/lib/google_api/firestore/v1/model/composite_filter.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/firestore/lib/google_api/firestore/v1/model/composite_filter.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/firestore/lib/google_api/firestore/v1/model/composite_filter.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.Firestore.V1.Model.CompositeFilter do
@moduledoc """
A filter that merges multiple other filters using the given operator.
## Attributes
* `filters` (*type:* `list(GoogleApi.Firestore.V1.Model.Filter.t)`, *default:* `nil`) - The list of filters to combine. Requires: * At least one filter is present.
* `op` (*type:* `String.t`, *default:* `nil`) - The operator for combining multiple filters.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:filters => list(GoogleApi.Firestore.V1.Model.Filter.t()) | nil,
:op => String.t() | nil
}
field(:filters, as: GoogleApi.Firestore.V1.Model.Filter, type: :list)
field(:op)
end
defimpl Poison.Decoder, for: GoogleApi.Firestore.V1.Model.CompositeFilter do
def decode(value, options) do
GoogleApi.Firestore.V1.Model.CompositeFilter.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Firestore.V1.Model.CompositeFilter do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35 | 167 | 0.725714 |
fff4f55f42684b5e6301f4130e9463473b6b2370 | 3,683 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/interconnect_outage_notification.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/interconnect_outage_notification.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/interconnect_outage_notification.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.InterconnectOutageNotification do
@moduledoc """
Description of a planned outage on this Interconnect. Next id: 9
## Attributes
* `affectedCircuits` (*type:* `list(String.t)`, *default:* `nil`) - If issue_type is IT_PARTIAL_OUTAGE, a list of the Google-side circuit IDs that will be affected.
* `description` (*type:* `String.t`, *default:* `nil`) - A description about the purpose of the outage.
* `endTime` (*type:* `String.t`, *default:* `nil`) - Scheduled end time for the outage (milliseconds since Unix epoch).
* `issueType` (*type:* `String.t`, *default:* `nil`) - Form this outage is expected to take, which can take one of the following values:
- OUTAGE: The Interconnect may be completely out of service for some or all of the specified window.
- PARTIAL_OUTAGE: Some circuits comprising the Interconnect as a whole should remain up, but with reduced bandwidth. Note that the versions of this enum prefixed with "IT_" have been deprecated in favor of the unprefixed values.
* `name` (*type:* `String.t`, *default:* `nil`) - Unique identifier for this outage notification.
* `source` (*type:* `String.t`, *default:* `nil`) - The party that generated this notification, which can take the following value:
- GOOGLE: this notification as generated by Google. Note that the value of NSRC_GOOGLE has been deprecated in favor of GOOGLE.
* `startTime` (*type:* `String.t`, *default:* `nil`) - Scheduled start time for the outage (milliseconds since Unix epoch).
* `state` (*type:* `String.t`, *default:* `nil`) - State of this notification, which can take one of the following values:
- ACTIVE: This outage notification is active. The event could be in the past, present, or future. See start_time and end_time for scheduling.
- CANCELLED: The outage associated with this notification was cancelled before the outage was due to start. Note that the versions of this enum prefixed with "NS_" have been deprecated in favor of the unprefixed values.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:affectedCircuits => list(String.t()),
:description => String.t(),
:endTime => String.t(),
:issueType => String.t(),
:name => String.t(),
:source => String.t(),
:startTime => String.t(),
:state => String.t()
}
field(:affectedCircuits, type: :list)
field(:description)
field(:endTime)
field(:issueType)
field(:name)
field(:source)
field(:startTime)
field(:state)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.InterconnectOutageNotification do
def decode(value, options) do
GoogleApi.Compute.V1.Model.InterconnectOutageNotification.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.InterconnectOutageNotification do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 50.452055 | 234 | 0.710834 |
fff4fb4b4feb8cd3131d2ff0a51a8fff20fec60a | 5,266 | ex | Elixir | lib/stripe/subscriptions/plan.ex | mmmries/stripity_stripe | 7bfaa2316f24a86fbbfc3cf140b1caff05f5ef9d | [
"BSD-3-Clause"
] | null | null | null | lib/stripe/subscriptions/plan.ex | mmmries/stripity_stripe | 7bfaa2316f24a86fbbfc3cf140b1caff05f5ef9d | [
"BSD-3-Clause"
] | null | null | null | lib/stripe/subscriptions/plan.ex | mmmries/stripity_stripe | 7bfaa2316f24a86fbbfc3cf140b1caff05f5ef9d | [
"BSD-3-Clause"
] | null | null | null | defmodule Stripe.Plan do
@moduledoc """
Work with Stripe plan objects.
You can:
- Create a plan
- Retrieve a plan
- Update a plan
- Delete a plan
Does not yet render lists or take options.
Stripe API reference: https://stripe.com/docs/api#plan
Example:
```
{
"id": "ivory-extended-580",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 999,
"billing_scheme": "per_unit",
"created": 1531234812,
"currency": "usd",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {
},
"nickname": null,
"product": "prod_DCmtkptv7qHXGE",
"tiers": null,
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
}
```
"""
use Stripe.Entity
import Stripe.Request
@type t :: %__MODULE__{
id: Stripe.id(),
object: String.t(),
active: boolean,
aggregate_usage: String.t() | nil,
amount: non_neg_integer | nil,
billing_scheme: String.t() | nil,
created: Stripe.timestamp(),
currency: String.t(),
deleted: boolean | nil,
interval: String.t(),
interval_count: pos_integer,
livemode: boolean,
metadata: Stripe.Types.metadata(),
name: String.t(),
nickname: String.t() | nil,
product: Stripe.id() | Stripe.Product.t(),
tiers: Stripe.List.t(map) | nil,
tiers_mode: boolean | nil,
transform_usage: map | nil,
trial_period_days: non_neg_integer | nil,
usage_type: String.t() | nil,
}
defstruct [
:id,
:object,
:active,
:aggregate_usage,
:amount,
:billing_scheme,
:created,
:currency,
:deleted,
:interval,
:interval_count,
:livemode,
:metadata,
:name,
:nickname,
:product,
:tiers,
:tiers_mode,
:transform_usage,
:trial_period_days,
:usage_type,
]
@plural_endpoint "plans"
@doc """
Create a plan.
"""
@spec create(params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params: %{
:currency => String.t(),
:interval => String.t(),
:product => Stripe.id() | Stripe.Product.t(),
optional(:id) => String.t(),
optional(:amount) => non_neg_integer,
optional(:active) => boolean,
optional(:billing_scheme) => String.t(),
optional(:interval_count) => pos_integer,
optional(:metadata) => Stripe.Types.metadata(),
optional(:nickname) => String.t(),
optional(:tiers) => Stripe.List.t(),
optional(:tiers_mode) => String.t(),
optional(:transform_usage) => map,
optional(:trial_period_days) => non_neg_integer,
optional(:usage_type) => String.t(),
} | %{}
def create(%{currency: _, interval: _, product: _} = params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint)
|> put_params(params)
|> put_method(:post)
|> make_request()
end
@doc """
Retrieve a plan.
"""
@spec retrieve(Stripe.id() | t, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
def retrieve(id, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:get)
|> make_request()
end
@doc """
Update a plan.
Takes the `id` and a map of changes.
"""
@spec update(Stripe.id() | t, params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params: %{
optional(:active) => boolean,
optional(:metadata) => Stripe.Types.metadata(),
optional(:nickname) => String.t(),
optional(:product) => Stripe.id() | Stripe.Product.t(),
optional(:trial_period_days) => non_neg_integer,
} | %{}
def update(id, params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:post)
|> put_params(params)
|> make_request()
end
@doc """
Delete a plan.
"""
@spec delete(Stripe.id() | t, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
def delete(id, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:delete)
|> make_request()
end
@doc """
List all plans.
"""
@spec list(params, Stripe.options()) :: {:ok, Stripe.List.t(t)} | {:error, Stripe.Error.t()}
when params: %{
optional(:active) => boolean,
optional(:created) => Stripe.date_query(),
optional(:ending_before) => t | Stripe.id(),
optional(:limit) => 1..100,
optional(:product) => Stripe.Product.t() | Stripe.id(),
optional(:starting_after) => t | Stripe.id(),
} | %{}
def list(params \\ %{}, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint)
|> put_method(:get)
|> put_params(params)
|> cast_to_id([:ending_before, :starting_after])
|> make_request()
end
end
| 27.715789 | 98 | 0.543107 |
fff5379829cef419c953113183e99c650ce7aaec | 74 | exs | Elixir | test/loom_web/views/page_view_test.exs | simonfraserduncan/my-copy | 03c618035a06a63d8fcf9f6511ef59d3e4cf2da9 | [
"Apache-2.0"
] | 4 | 2021-02-20T02:47:36.000Z | 2021-06-08T18:42:40.000Z | test/loom_web/views/page_view_test.exs | DataStax-Examples/astra-loom | 767c55200d08a6c592773d7af7da95873c4c3445 | [
"Apache-2.0"
] | null | null | null | test/loom_web/views/page_view_test.exs | DataStax-Examples/astra-loom | 767c55200d08a6c592773d7af7da95873c4c3445 | [
"Apache-2.0"
] | 1 | 2021-02-17T18:28:35.000Z | 2021-02-17T18:28:35.000Z | defmodule LoomWeb.PageViewTest do
use LoomWeb.ConnCase, async: true
end
| 18.5 | 35 | 0.810811 |
fff5387831f52a54168ca8d5932bb1b0c6bbc046 | 816 | exs | Elixir | mix.exs | evuez/leekbot | f75fa513000dbeab8a340f169dc303327b81d890 | [
"MIT"
] | null | null | null | mix.exs | evuez/leekbot | f75fa513000dbeab8a340f169dc303327b81d890 | [
"MIT"
] | null | null | null | mix.exs | evuez/leekbot | f75fa513000dbeab8a340f169dc303327b81d890 | [
"MIT"
] | null | null | null | defmodule Leekbot.Mixfile do
use Mix.Project
def project do
[app: :leekbot,
version: "0.0.1",
elixir: "~> 1.0",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[applications: [:logger, :nadia, :httpoison],
mod: {Leekbot, []}]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# Type `mix help deps` for more examples and options
defp deps do
[
{:nadia, "~> 0.3"},
{:httpoison, "~> 0.9"},
{:poison, "~> 2.0", override: true},
]
end
end
| 21.473684 | 77 | 0.573529 |
fff54fad19b29dae98caf49c43db2242b4122281 | 2,792 | ex | Elixir | clients/civic_info/lib/google_api/civic_info/v2/model/candidate.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/civic_info/lib/google_api/civic_info/v2/model/candidate.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/civic_info/lib/google_api/civic_info/v2/model/candidate.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.CivicInfo.V2.Model.Candidate do
@moduledoc """
Information about a candidate running for elected office.
## Attributes
- candidateUrl (String.t): The URL for the candidate's campaign web site. Defaults to: `null`.
- channels ([Channel]): A list of known (social) media channels for this candidate. Defaults to: `null`.
- email (String.t): The email address for the candidate's campaign. Defaults to: `null`.
- name (String.t): The candidate's name. If this is a joint ticket it will indicate the name of the candidate at the top of a ticket followed by a / and that name of candidate at the bottom of the ticket. e.g. \"Mitt Romney / Paul Ryan\" Defaults to: `null`.
- orderOnBallot (String.t): The order the candidate appears on the ballot for this contest. Defaults to: `null`.
- party (String.t): The full name of the party the candidate is a member of. Defaults to: `null`.
- phone (String.t): The voice phone number for the candidate's campaign office. Defaults to: `null`.
- photoUrl (String.t): A URL for a photo of the candidate. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:candidateUrl => any(),
:channels => list(GoogleApi.CivicInfo.V2.Model.Channel.t()),
:email => any(),
:name => any(),
:orderOnBallot => any(),
:party => any(),
:phone => any(),
:photoUrl => any()
}
field(:candidateUrl)
field(:channels, as: GoogleApi.CivicInfo.V2.Model.Channel, type: :list)
field(:email)
field(:name)
field(:orderOnBallot)
field(:party)
field(:phone)
field(:photoUrl)
end
defimpl Poison.Decoder, for: GoogleApi.CivicInfo.V2.Model.Candidate do
def decode(value, options) do
GoogleApi.CivicInfo.V2.Model.Candidate.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CivicInfo.V2.Model.Candidate do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.463768 | 274 | 0.703797 |
fff5c3383c1b8ea9a9dcce17eb9ba76f6f05d6b7 | 1,464 | exs | Elixir | mix.exs | Tmw/ecto_ranked | 8791c88b157f09dfba8cfa9556cedaa8a53da9b7 | [
"MIT"
] | null | null | null | mix.exs | Tmw/ecto_ranked | 8791c88b157f09dfba8cfa9556cedaa8a53da9b7 | [
"MIT"
] | null | null | null | mix.exs | Tmw/ecto_ranked | 8791c88b157f09dfba8cfa9556cedaa8a53da9b7 | [
"MIT"
] | null | null | null | defmodule EctoRanked.Mixfile do
use Mix.Project
def project do
[app: :ecto_ranked,
version: "0.4.1",
elixir: "~> 1.4",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
elixirc_paths: elixirc_paths(Mix.env),
docs: [main: "readme", extras: ["README.md"]],
aliases: aliases(),
package: package(),
deps: deps()]
end
defp package do
[description: "Add and maintain rankings to sort your data with Ecto",
files: ["lib", "mix.exs", "README*"],
maintainers: ["Dylan Markow"],
licenses: ["MIT"],
links: %{github: "https://github.com/dmarkow/ecto_ranked"}
]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
# Specify extra applications you'll use from Erlang/Elixir
[extra_applications: [:logger]]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp aliases do
[test: ["ecto.create --quiet", "ecto.migrate", "test"]]
end
# Dependencies can be Hex packages:
#
# {:my_dep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
#
# Type "mix help deps" for more examples and options
defp deps do
[{:ecto_sql, "~> 3.0"},
{:postgrex, "~> 0.14", only: :test},
{:ex_doc, "~> 0.14", only: :dev, runtime: false}]
end
end
| 26.618182 | 79 | 0.60929 |
fff5c7b86a1b548bbf85f258ba118889dfa5adc0 | 1,078 | ex | Elixir | lib/hl7/2.4/segments/rxa.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.4/segments/rxa.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.4/segments/rxa.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | defmodule HL7.V2_4.Segments.RXA do
@moduledoc false
require Logger
alias HL7.V2_4.{DataTypes}
use HL7.Segment,
fields: [
segment: nil,
give_sub_id_counter: nil,
administration_sub_id_counter: nil,
date_time_start_of_administration: DataTypes.Ts,
date_time_end_of_administration: DataTypes.Ts,
administered_code: DataTypes.Ce,
administered_amount: nil,
administered_units: DataTypes.Ce,
administered_dosage_form: DataTypes.Ce,
administration_notes: DataTypes.Ce,
administering_provider: DataTypes.Xcn,
administered_at_location: DataTypes.La2,
administered_per_time_unit: nil,
administered_strength: nil,
administered_strength_units: DataTypes.Ce,
substance_lot_number: nil,
substance_expiration_date: DataTypes.Ts,
substance_manufacturer_name: DataTypes.Ce,
substance_treatment_refusal_reason: DataTypes.Ce,
indication: DataTypes.Ce,
completion_status: nil,
action_code_rxa: nil,
system_entry_date_time: DataTypes.Ts
]
end
| 31.705882 | 55 | 0.731911 |
fff5edf5a9518695c52856264eabe6b1e85e9c85 | 26,357 | ex | Elixir | lib/logger/lib/logger.ex | allansson/elixir | 3db086a51eb48d4fef05c7f9b698a7da97128a2d | [
"Apache-2.0"
] | null | null | null | lib/logger/lib/logger.ex | allansson/elixir | 3db086a51eb48d4fef05c7f9b698a7da97128a2d | [
"Apache-2.0"
] | null | null | null | lib/logger/lib/logger.ex | allansson/elixir | 3db086a51eb48d4fef05c7f9b698a7da97128a2d | [
"Apache-2.0"
] | null | null | null | defmodule Logger do
@moduledoc ~S"""
A logger for Elixir applications.
It includes many features:
* Provides debug, info, warn, and error levels.
* Supports multiple backends which are automatically
supervised when plugged into `Logger`.
* Formats and truncates messages on the client
to avoid clogging `Logger` backends.
* Alternates between sync and async modes to remain
performant when required but also apply backpressure
when under stress.
* Wraps OTP's [`:error_logger`](http://erlang.org/doc/man/error_logger.html)
to prevent it from overflowing.
Logging is useful for tracking when an event of interest happens in your
system. For example, it may be helpful to log whenever a user is deleted.
def delete_user(user) do
Logger.info fn ->
"Deleting user from the system: #{inspect(user)}"
end
# ...
end
The `Logger.info/2` macro emits the provided message at the `:info`
level. There are additional macros for other levels. Notice the argument
passed to `Logger.info/2` in the above example is a zero argument function.
The `Logger` macros also accept messages as strings, but keep in mind that
strings are **always** evaluated regardless of log-level. As such, it is
recommended to use a function whenever the message is expensive to compute.
Another option that does not depend on the message type is to purge the log
calls at compile-time using the `:compile_time_purge_level` option (see
below).
## Levels
The supported levels are:
* `:debug` - for debug-related messages
* `:info` - for information of any kind
* `:warn` - for warnings
* `:error` - for errors
## Configuration
`Logger` supports a wide range of configurations.
This configuration is split in three categories:
* Application configuration - must be set before the `:logger`
application is started
* Runtime configuration - can be set before the `:logger`
application is started, but may be changed during runtime
* Error logger configuration - configuration for the
wrapper around OTP's [`:error_logger`](http://erlang.org/doc/man/error_logger.html)
### Application configuration
The following configuration must be set via config files (such as
`config/config.exs`) before the `:logger` application is started.
* `:backends` - the backends to be used. Defaults to `[:console]`.
See the "Backends" section for more information.
* `:compile_time_purge_level` - purges *at compilation time* all calls that
have log level lower than the value of this option. This means that
`Logger` calls with level lower than this option will be completely
removed at compile time, accruing no overhead at runtime. Defaults to
`:debug` and only applies to the `Logger.debug/2`, `Logger.info/2`,
`Logger.warn/2`, and `Logger.error/2` macros (for example, it doesn't apply to
`Logger.log/3`). Note that arguments passed to `Logger` calls that are
removed from the AST at compilation time are never evaluated, thus any
function call that occurs in these arguments is never executed. As a
consequence, avoid code that looks like `Logger.debug("Cleanup:
#{perform_cleanup()}")` as in the example `perform_cleanup/0` won't be
executed if the `:compile_time_purge_level` is `:info` or higher.
* `:compile_time_application` - sets the `:application` metadata value
to the configured value at compilation time. This configuration is
usually only useful for build tools to automatically add the
application to the metadata for `Logger.debug/2`, `Logger.info/2`, etc.
style of calls.
For example, to configure the `:backends` and `compile_time_purge_level`
options in a `config/config.exs` file:
config :logger,
backends: [:console],
compile_time_purge_level: :info
### Runtime Configuration
All configuration below can be set via config files (such as
`config/config.exs`) but also changed dynamically during runtime via
`Logger.configure/1`.
* `:level` - the logging level. Attempting to log any message
with severity less than the configured level will simply
cause the message to be ignored. Keep in mind that each backend
may have its specific level, too. Note that, unlike what happens with the
`:compile_time_purge_level` option, the argument passed to `Logger` calls
is evaluated even if the level of the call is lower than
`:level`. For this reason, messages that are expensive to
compute should be wrapped in 0-arity anonymous functions that are
evaluated only when the `:level` option demands it.
* `:utc_log` - when `true`, uses UTC in logs. By default it uses
local time (i.e., it defaults to `false`).
* `:truncate` - the maximum message size to be logged (in bytes). Defaults
to 8192 bytes. Note this configuration is approximate. Truncated messages
will have `" (truncated)"` at the end. The atom `:infinity` can be passed
to disable this behavior.
* `:sync_threshold` - if the `Logger` manager has more than
`:sync_threshold` messages in its queue, `Logger` will change
to *sync mode*, to apply backpressure to the clients.
`Logger` will return to *async mode* once the number of messages
in the queue is reduced to `sync_threshold * 0.75` messages.
Defaults to 20 messages. `:sync_threshold` can be set to `0` to force *sync mode*.
* `:discard_threshold` - if the `Logger` manager has more than
`:discard_threshold` messages in its queue, `Logger` will change
to *discard mode* and messages will be discarded directly in the
clients. `Logger` will return to *sync mode* once the number of
messages in the queue is reduced to `discard_threshold * 0.75`
messages. Defaults to 500 messages.
* `:translator_inspect_opts` - when translating OTP reports and
errors, the last message and state must be inspected in the
error reports. This configuration allow developers to change
how much and how the data should be inspected.
For example, to configure the `:level` and `:truncate` options in a
`config/config.exs` file:
config :logger,
level: :warn,
truncate: 4096
### Error logger configuration
The following configuration applies to `Logger`'s wrapper around
OTP's [`:error_logger`](http://erlang.org/doc/man/error_logger.html).
All the configurations below must be set before the `:logger` application starts.
* `:handle_otp_reports` - redirects OTP reports to `Logger` so
they are formatted in Elixir terms. This uninstalls OTP's
logger that prints terms to terminal. Defaults to `true`.
* `:handle_sasl_reports` - redirects supervisor, crash and
progress reports to `Logger` so they are formatted in Elixir
terms. Your application must guarantee `:sasl` is started before
`:logger`. This means you may see some initial reports written
in Erlang syntax until the Logger application kicks in and
uninstalls SASL's logger in favor of its own. Defaults to `false`.
* `:discard_threshold_for_error_logger` - if `:error_logger` has more than
`discard_threshold` messages in its inbox, messages will be dropped
until the message queue goes down to `discard_threshold * 0.75`
entries. The threshold will be checked once again after 10% of threshold
messages are processed, to avoid messages from being constantly dropped.
For exmaple, if the threshold is 500 (the default) and the inbox has
600 messages, 250 messages will dropped, bringing the inbox down to
350 (0.75 * threshold) entries and 50 (0.1 * threshold) messages will
be processed before the threshold is checked once again.
For example, to configure `Logger` to redirect all
[`:error_logger`](http://erlang.org/doc/man/error_logger.html) messages
using a `config/config.exs` file:
config :logger,
handle_otp_reports: true,
handle_sasl_reports: true
Furthermore, `Logger` allows messages sent by OTP's `:error_logger`
to be translated into an Elixir format via translators. Translators
can be dynamically added at any time with the `add_translator/1`
and `remove_translator/1` APIs. Check `Logger.Translator` for more
information.
## Backends
`Logger` supports different backends where log messages are written to.
The available backends by default are:
* `:console` - logs messages to the console (enabled by default)
Developers may also implement their own backends, an option that
is explored in more detail below.
The initial backends are loaded via the `:backends` configuration,
which must be set before the `:logger` application is started.
### Console backend
The console backend logs messages by printing them to the console. It supports
the following options:
* `:level` - the level to be logged by this backend.
Note that messages are filtered by the general
`:level` configuration for the `:logger` application first.
* `:format` - the format message used to print logs.
Defaults to: `"\n$time $metadata[$level] $levelpad$message\n"`.
It may also be a `{module, function}` tuple that is invoked
with the log level, the message, the current timestamp and
the metadata.
* `:metadata` - the metadata to be printed by `$metadata`.
Defaults to an empty list (no metadata).
Setting `:metadata` to `:all` prints all metadata.
* `:colors` - a keyword list of coloring options.
* `:device` - the device to log error messages to. Defaults to
`:user` but can be changed to something else such as `:standard_error`.
* `:max_buffer` - maximum events to buffer while waiting
for a confirmation from the IO device (default: 32).
Once the buffer is full, the backend will block until
a confirmation is received.
In addition to the keys provided by the user via `Logger.metadata/1`,
the following extra keys are available to the `:metadata` list:
* `:application` - the current application
* `:module` - the current module
* `:function` - the current function
* `:file` - the current file
* `:line` - the current line
* `:pid` - the current process ID
The supported keys in the `:colors` keyword list are:
* `:enabled` - boolean value that allows for switching the
coloring on and off. Defaults to: `IO.ANSI.enabled?/0`
* `:debug` - color for debug messages. Defaults to: `:cyan`
* `:info` - color for info messages. Defaults to: `:normal`
* `:warn` - color for warn messages. Defaults to: `:yellow`
* `:error` - color for error messages. Defaults to: `:red`
See the `IO.ANSI` module for a list of colors and attributes.
Here is an example of how to configure the `:console` backend in a
`config/config.exs` file:
config :logger, :console,
format: "\n$time $metadata[$level] $levelpad$message\n",
metadata: [:user_id]
### Custom formatting
The console backend allows you to customize the format of your log messages
with the `:format` option.
You may set `:format` to either a string or a `{module, function}` tuple if
you wish to provide your own format function. The `{module, function}` will be
invoked with the log level, the message, the current timestamp and the
metadata.
Here is an example of how to configure the `:console` backend in a
`config/config.exs` file:
config :logger, :console,
format: {MyConsoleLogger, :format}
And here is an example of how you can define `MyConsoleLogger.format/4` from the
above configuration:
defmodule MyConsoleLogger do
def format(level, message, timestamp, metadata) do
# Custom formatting logic...
end
end
It is extremely important that **the formatting function does not fail**, as
it will bring that particular logger instance down, causing your system to
temporarily lose messages. If necessary, wrap the function in a "rescue" and
log a default message instead:
defmodule MyConsoleLogger do
def format(level, message, timestamp, metadata) do
# Custom formatting logic...
rescue
_ -> "could not format: #{inspect {level, message, metadata}}"
end
end
You can read more about formatting in `Logger.Formatter`.
### Custom backends
Any developer can create their own `Logger` backend.
Since `Logger` is an event manager powered by `:gen_event`,
writing a new backend is a matter of creating an event
handler, as described in the [`:gen_event`](http://erlang.org/doc/man/gen_event.html)
documentation.
From now on, we will be using the term "event handler" to refer
to your custom backend, as we head into implementation details.
Once the `:logger` application starts, it installs all event handlers listed under
the `:backends` configuration into the `Logger` event manager. The event
manager and all added event handlers are automatically supervised by `Logger`.
Once initialized, the handler should be designed to handle events
in the following format:
{level, group_leader, {Logger, message, timestamp, metadata}} | :flush
where:
* `level` is one of `:debug`, `:info`, `:warn`, or `:error`, as previously
described
* `group_leader` is the group leader of the process which logged the message
* `{Logger, message, timestamp, metadata}` is a tuple containing information
about the logged message:
* the first element is always the atom `Logger`
* `message` is the actual message (as chardata)
* `timestamp` is the timestamp for when the message was logged, as a
`{{year, month, day}, {hour, minute, second, millisecond}}` tuple
* `metadata` is a keyword list of metadata used when logging the message
It is recommended that handlers ignore messages where
the group leader is in a different node than the one where
the handler is installed. For example:
def handle_event({_level, gl, {Logger, _, _, _}}, state)
when node(gl) != node() do
{:ok, state}
end
In the case of the event `:flush` handlers should flush any pending data. This
event is triggered by `flush/0`.
Furthermore, backends can be configured via the
`configure_backend/2` function which requires event handlers
to handle calls of the following format:
{:configure, options}
where `options` is a keyword list. The result of the call is
the result returned by `configure_backend/2`. The recommended
return value for successful configuration is `:ok`.
It is recommended that backends support at least the following
configuration options:
* `:level` - the logging level for that backend
* `:format` - the logging format for that backend
* `:metadata` - the metadata to include in that backend
Check the implementation for `Logger.Backends.Console`, for
examples on how to handle the recommendations in this section
and how to process the existing options.
"""
@type backend :: :gen_event.handler()
@type message :: IO.chardata() | String.Chars.t()
@type level :: :error | :info | :warn | :debug
@type metadata :: keyword(String.Chars.t())
@levels [:error, :info, :warn, :debug]
@metadata :logger_metadata
@compile {:inline, __metadata__: 0}
defp __metadata__ do
Process.get(@metadata) || {true, []}
end
@doc """
Alters the current process metadata according the given keyword list.
This function will merge the given keyword list into the existing metadata,
with the exception of setting a key to `nil`, which will remove that key
from the metadata.
"""
@spec metadata(metadata) :: :ok
def metadata(keyword) do
{enabled?, metadata} = __metadata__()
metadata =
Enum.reduce(keyword, metadata, fn
{key, nil}, acc -> Keyword.delete(acc, key)
{key, val}, acc -> Keyword.put(acc, key, val)
end)
Process.put(@metadata, {enabled?, metadata})
:ok
end
@doc """
Reads the current process metadata.
"""
@spec metadata() :: metadata
def metadata() do
__metadata__() |> elem(1)
end
@doc """
Resets the current process metadata to the given keyword list.
"""
@spec reset_metadata(metadata) :: :ok
def reset_metadata(keywords \\ []) do
{enabled?, _metadata} = __metadata__()
Process.put(@metadata, {enabled?, []})
metadata(keywords)
end
@doc """
Enables logging for the current process.
Currently the only accepted PID is `self()`.
"""
@spec enable(pid) :: :ok
def enable(pid) when pid == self() do
Process.put(@metadata, {true, metadata()})
:ok
end
@doc """
Disables logging for the current process.
Currently the only accepted PID is `self()`.
"""
@spec disable(pid) :: :ok
def disable(pid) when pid == self() do
Process.put(@metadata, {false, metadata()})
:ok
end
@doc """
Retrieves the `Logger` level.
The `Logger` level can be changed via `configure/1`.
"""
@spec level() :: level
def level() do
%{level: level} = Logger.Config.__data__()
level
end
@doc """
Compares log levels.
Receives two log levels and compares the `left` level
against the `right` level and returns
* `:lt` if `left` is less than `right`
* `:eq` if `left` and `right` are equal
* `:gt` if `left` is greater than `right`
## Examples
iex> Logger.compare_levels(:debug, :warn)
:lt
iex> Logger.compare_levels(:error, :info)
:gt
"""
@spec compare_levels(level, level) :: :lt | :eq | :gt
def compare_levels(level, level) do
:eq
end
def compare_levels(left, right) do
if level_to_number(left) > level_to_number(right), do: :gt, else: :lt
end
defp level_to_number(:debug), do: 0
defp level_to_number(:info), do: 1
defp level_to_number(:warn), do: 2
defp level_to_number(:error), do: 3
@doc """
Configures the logger.
See the "Runtime Configuration" section in the `Logger` module
documentation for the available options.
"""
@valid_options [
:compile_time_purge_level,
:compile_time_application,
:sync_threshold,
:truncate,
:level,
:utc_log
]
@spec configure(keyword) :: :ok
def configure(options) do
Logger.Config.configure(Keyword.take(options, @valid_options))
end
@doc """
Flushes the logger.
This guarantees all messages sent to `Logger` prior to this call will
be processed. This is useful for testing and it should not be called
in production code.
"""
@spec flush :: :ok
def flush do
_ = :gen_event.which_handlers(:error_logger)
:gen_event.sync_notify(Logger, :flush)
end
@doc """
Adds a new backend.
## Options
* `:flush` - when `true`, guarantees all messages currently sent
to both Logger and OTP's [`:error_logger`](http://erlang.org/doc/man/error_logger.html)
are processed before the backend is added
"""
@spec add_backend(atom, keyword) :: Supervisor.on_start_child()
def add_backend(backend, opts \\ []) do
_ = if opts[:flush], do: flush()
case Logger.WatcherSupervisor.watch(Logger, Logger.Config.translate_backend(backend), backend) do
{:ok, _} = ok ->
Logger.Config.add_backend(backend)
ok
{:error, {:already_started, _pid}} ->
{:error, :already_present}
{:error, _} = error ->
error
end
end
@doc """
Removes a backend.
## Options
* `:flush` - when `true`, guarantees all messages currently sent
to both Logger and OTP's [`:error_logger`](http://erlang.org/doc/man/error_logger.html)
are processed before the backend is removed
"""
@spec remove_backend(atom, keyword) :: :ok | {:error, term}
def remove_backend(backend, opts \\ []) do
_ = if opts[:flush], do: flush()
Logger.Config.remove_backend(backend)
Logger.WatcherSupervisor.unwatch(Logger, Logger.Config.translate_backend(backend))
end
@doc """
Adds a new translator.
"""
@spec add_translator({module, function :: atom}) :: :ok
def add_translator({mod, fun} = translator) when is_atom(mod) and is_atom(fun) do
Logger.Config.add_translator(translator)
end
@doc """
Removes a translator.
"""
@spec remove_translator({module, function :: atom}) :: :ok
def remove_translator({mod, fun} = translator) when is_atom(mod) and is_atom(fun) do
Logger.Config.remove_translator(translator)
end
@doc """
Configures the given backend.
The backend needs to be started and running in order to
be configured at runtime.
"""
@spec configure_backend(backend, keyword) :: term
def configure_backend(backend, options) when is_list(options) do
:gen_event.call(Logger, Logger.Config.translate_backend(backend), {:configure, options})
end
@doc """
Logs a message dynamically.
Use this function only when there is a need to
explicitly avoid embedding metadata.
"""
@spec bare_log(level, message | (() -> message | {message, keyword}), keyword) ::
:ok | {:error, :noproc} | {:error, term}
def bare_log(level, chardata_or_fun, metadata \\ [])
when level in @levels and is_list(metadata) do
case __metadata__() do
{true, pdict} ->
%{mode: mode, truncate: truncate, level: min_level, utc_log: utc_log?} =
Logger.Config.__data__()
if compare_levels(level, min_level) != :lt and mode != :discard do
metadata = [pid: self()] ++ Keyword.merge(pdict, metadata)
{message, metadata} = normalize_message(chardata_or_fun, metadata)
truncated = truncate(message, truncate)
tuple = {Logger, truncated, Logger.Utils.timestamp(utc_log?), metadata}
try do
notify(mode, {level, Process.group_leader(), tuple})
:ok
rescue
ArgumentError -> {:error, :noproc}
catch
:exit, reason -> {:error, reason}
end
else
:ok
end
{false, _} ->
:ok
end
end
@doc """
Logs a warning message.
Returns `:ok` or an `{:error, reason}` tuple.
## Examples
Logger.warn "knob turned too far to the right"
Logger.warn fn -> "expensive to calculate warning" end
Logger.warn fn -> {"expensive to calculate warning", [additional: :metadata]} end
"""
defmacro warn(chardata_or_fun, metadata \\ []) do
maybe_log(:warn, chardata_or_fun, metadata, __CALLER__)
end
@doc """
Logs an info message.
Returns `:ok` or an `{:error, reason}` tuple.
## Examples
Logger.info "mission accomplished"
Logger.info fn -> "expensive to calculate info" end
Logger.info fn -> {"expensive to calculate info", [additional: :metadata]} end
"""
defmacro info(chardata_or_fun, metadata \\ []) do
maybe_log(:info, chardata_or_fun, metadata, __CALLER__)
end
@doc """
Logs an error message.
Returns `:ok` or an `{:error, reason}` tuple.
## Examples
Logger.error "oops"
Logger.error fn -> "expensive to calculate error" end
Logger.error fn -> {"expensive to calculate error", [additional: :metadata]} end
"""
defmacro error(chardata_or_fun, metadata \\ []) do
maybe_log(:error, chardata_or_fun, metadata, __CALLER__)
end
@doc """
Logs a debug message.
Returns `:ok` or an `{:error, reason}` tuple.
## Examples
Logger.debug "hello?"
Logger.debug fn -> "expensive to calculate debug" end
Logger.debug fn -> {"expensive to calculate debug", [additional: :metadata]} end
"""
defmacro debug(chardata_or_fun, metadata \\ []) do
maybe_log(:debug, chardata_or_fun, metadata, __CALLER__)
end
@doc """
Logs a message with the given `level`.
Returns `:ok` or an `{:error, reason}` tuple.
The macros `debug/2`, `warn/2`, `info/2`, and `error/2` are
preferred over this macro as they can automatically eliminate
the call to `Logger` altogether at compile time if desired
(see the documentation for the `Logger` module).
"""
defmacro log(level, chardata_or_fun, metadata \\ []) do
macro_log(level, chardata_or_fun, metadata, __CALLER__)
end
defp macro_log(level, data, metadata, caller) do
%{module: module, function: fun, file: file, line: line} = caller
caller =
compile_time_application_and_file(file) ++
[module: module, function: form_fa(fun), line: line]
metadata =
if Keyword.keyword?(metadata) do
Keyword.merge(caller, metadata)
else
quote do
Keyword.merge(unquote(caller), unquote(metadata))
end
end
quote do
Logger.bare_log(unquote(level), unquote(data), unquote(metadata))
end
end
defp compile_time_application_and_file(file) do
if app = Application.get_env(:logger, :compile_time_application) do
[application: app, file: Path.relative_to_cwd(file)]
else
[file: file]
end
end
defp maybe_log(level, data, metadata, caller) do
min_level = Application.get_env(:logger, :compile_time_purge_level, :debug)
if compare_levels(level, min_level) != :lt do
macro_log(level, data, metadata, caller)
else
# We wrap the contents in an anonymous function
# to avoid unused variable warnings.
quote do
_ = fn -> {unquote(data), unquote(metadata)} end
:ok
end
end
end
defp normalize_message(fun, metadata) when is_function(fun, 0) do
normalize_message(fun.(), metadata)
end
defp normalize_message({message, fun_metadata}, metadata) when is_list(fun_metadata) do
{message, Keyword.merge(metadata, fun_metadata)}
end
defp normalize_message(message, metadata), do: {message, metadata}
defp truncate(data, n) when is_list(data) or is_binary(data), do: Logger.Utils.truncate(data, n)
defp truncate(data, n), do: Logger.Utils.truncate(to_string(data), n)
defp form_fa({name, arity}) do
Atom.to_string(name) <> "/" <> Integer.to_string(arity)
end
defp form_fa(nil), do: nil
defp notify(:sync, msg), do: :gen_event.sync_notify(Logger, msg)
defp notify(:async, msg), do: :gen_event.notify(Logger, msg)
end
| 33.661558 | 101 | 0.68202 |
fff6060e7fc9f32b96a9527f551be9dfe12a3b68 | 501 | ex | Elixir | lib/flamelex/fluxus/supervision_tree/fluxus_supervisor_top.ex | JediLuke/franklin | 8eb77a342547de3eb43d28dcf9f835ff443ad489 | [
"Apache-2.0"
] | 1 | 2020-02-09T23:04:33.000Z | 2020-02-09T23:04:33.000Z | lib/flamelex/fluxus/supervision_tree/fluxus_supervisor_top.ex | JediLuke/franklin | 8eb77a342547de3eb43d28dcf9f835ff443ad489 | [
"Apache-2.0"
] | null | null | null | lib/flamelex/fluxus/supervision_tree/fluxus_supervisor_top.ex | JediLuke/franklin | 8eb77a342547de3eb43d28dcf9f835ff443ad489 | [
"Apache-2.0"
] | null | null | null | defmodule Flamelex.Fluxus.TopLevelSupervisor do
@moduledoc false
use Supervisor
require Logger
def start_link(params) do
Supervisor.start_link(__MODULE__, params, name: __MODULE__)
end
def init(_params) do
Logger.debug "#{__MODULE__} initializing..."
children = [
Flamelex.Fluxus.RadixStore,
Flamelex.Fluxus.ActionListener,
Flamelex.Fluxus.InputListener
]
Supervisor.init(children, strategy: :one_for_all) #TODO make this :rest_for_one?
end
end
| 22.772727 | 84 | 0.726547 |
fff61643c04b676886f3f957f463eb06a8fe2b0e | 646 | exs | Elixir | components/notifications-service/server/test/config_test.exs | mmci2468/automate | dbe8bfaae91169861f7ea1d2a66cff5c7ca83ddf | [
"Apache-2.0"
] | 191 | 2019-04-16T15:04:53.000Z | 2022-03-21T14:10:44.000Z | components/notifications-service/server/test/config_test.exs | mmci2468/automate | dbe8bfaae91169861f7ea1d2a66cff5c7ca83ddf | [
"Apache-2.0"
] | 4,882 | 2019-04-16T16:16:01.000Z | 2022-03-31T15:39:35.000Z | components/notifications-service/server/test/config_test.exs | mmci2468/automate | dbe8bfaae91169861f7ea1d2a66cff5c7ca83ddf | [
"Apache-2.0"
] | 114 | 2019-04-16T15:21:27.000Z | 2022-03-26T09:50:08.000Z | defmodule Notifications.Config.Test do
use ExUnit.Case
alias Notifications.Config
@env_var "NOTIF_CONFIG_TEST"
setup do
System.delete_env(@env_var)
end
test "#get/2 returns the value of the env var when present" do
System.put_env(@env_var, "hello")
assert Config.get(@env_var) == {:ok, "hello"}
end
test "#get/2 returns the default value when the env var is not present" do
assert Config.get(@env_var, "goodbye") == {:ok, "goodbye"}
end
test "#get/2 returns an error tuple when env var is missing and no default provided" do
assert Config.get(@env_var) == {:error, {:missing_env_var, @env_var}}
end
end
| 34 | 89 | 0.701238 |
fff626a34e82e792183e766a1fc30e6596074bf3 | 690 | exs | Elixir | test/webhooks_emitter/emitter/json_safe_encoder_test.exs | davec82/webhooks_emitter | 57cfb2a90c8a6ec17093c36bada88d356fb7ce8a | [
"Apache-2.0"
] | 3 | 2020-03-19T07:37:18.000Z | 2020-03-30T11:45:31.000Z | test/webhooks_emitter/emitter/json_safe_encoder_test.exs | davec82/webhooks_emitter | 57cfb2a90c8a6ec17093c36bada88d356fb7ce8a | [
"Apache-2.0"
] | 2 | 2020-10-06T11:03:37.000Z | 2020-11-17T13:44:50.000Z | test/webhooks_emitter/emitter/json_safe_encoder_test.exs | davec82/webhooks_emitter | 57cfb2a90c8a6ec17093c36bada88d356fb7ce8a | [
"Apache-2.0"
] | 2 | 2020-10-06T10:17:11.000Z | 2020-10-06T12:13:39.000Z | defmodule WebhooksEmitter.Emitter.JsonSafeEncoderTest do
@moduledoc false
use ExUnit.Case
use ExUnitProperties
alias WebhooksEmitter.Emitter.JsonSafeEncoder
property "can encode any term" do
check all(term <- terms()) do
ret =
term
|> JsonSafeEncoder.encode()
|> Jason.encode()
assert {:ok, _} = ret
end
end
defp terms do
StreamData.one_of([
term(),
StreamData.list_of(term()),
StreamData.map_of(keys(), term())
])
end
defp keys do
StreamData.one_of([
StreamData.string(:ascii),
StreamData.atom(:alphanumeric),
StreamData.float(),
StreamData.integer()
])
end
end
| 19.166667 | 56 | 0.626087 |
fff6499e84778eb2e54ff667cd937728a1d4ec89 | 905 | ex | Elixir | lib/ex_oneroster/results/result.ex | jrissler/ex_oneroster | cec492117bffc14aec91e2448643682ceeb449e9 | [
"Apache-2.0"
] | 3 | 2018-09-06T11:15:07.000Z | 2021-12-27T15:36:51.000Z | lib/ex_oneroster/results/result.ex | jrissler/ex_oneroster | cec492117bffc14aec91e2448643682ceeb449e9 | [
"Apache-2.0"
] | null | null | null | lib/ex_oneroster/results/result.ex | jrissler/ex_oneroster | cec492117bffc14aec91e2448643682ceeb449e9 | [
"Apache-2.0"
] | null | null | null | defmodule ExOneroster.Results.Result do
use Ecto.Schema
import Ecto.Changeset
alias ExOneroster.Results.Result
alias ExOneroster.Users.User
alias ExOneroster.Lineitems.Lineitem
schema "results" do
belongs_to :user, User
belongs_to :lineitem, Lineitem
field :comment, :string
field :dateLastModified, :utc_datetime
field :metadata, :map
field :score, :decimal
field :scoreDate, :date
field :scoreStatus, :string
field :sourcedId, :string
field :status, :string
timestamps()
end
@doc false
def changeset(%Result{} = result, attrs) do
result
|> cast(attrs, [:sourcedId, :status, :dateLastModified, :metadata, :lineitem_id, :user_id, :scoreStatus, :score, :scoreDate, :comment])
|> validate_required([:sourcedId, :status, :dateLastModified, :metadata, :lineitem_id, :user_id, :scoreStatus, :score, :scoreDate, :comment])
end
end
| 29.193548 | 145 | 0.709392 |
fff6b16ab79d7840ef7f72a225af0fc63a7f5f13 | 2,832 | ex | Elixir | lib/secure_random.ex | agatheblues/secure_random.ex | 0b2cda59a7bb0f1a1ff668fa16296e7cc321f010 | [
"Apache-2.0"
] | null | null | null | lib/secure_random.ex | agatheblues/secure_random.ex | 0b2cda59a7bb0f1a1ff668fa16296e7cc321f010 | [
"Apache-2.0"
] | null | null | null | lib/secure_random.ex | agatheblues/secure_random.ex | 0b2cda59a7bb0f1a1ff668fa16296e7cc321f010 | [
"Apache-2.0"
] | 1 | 2022-02-26T10:21:26.000Z | 2022-02-26T10:21:26.000Z | defmodule SecureRandom do
use Bitwise
@moduledoc """
Takes my favorite hits from Ruby's SecureRandom and brings em to elixir.
Mostly a convienance wrapper around Erlangs Crypto library, converting
Crypto.strong_rand_bytes/1 into a string.
## Examples
iex> SecureRandom.base64
"xhTcitKZI8YiLGzUNLD+HQ=="
iex> SecureRandom.urlsafe_base64(4)
"pLSVJw"
iex> SecureRandom.uuid
"a18e8302-c417-076d-196a-71dfbd5b1e03"
"""
@default_length 16
@doc """
Returns random Base64 encoded string.
## Examples
iex> SecureRandom.base64
"rm/JfqH8Y+Jd7m5SHTHJoA=="
iex> SecureRandom.base64(8)
"2yDtUyQ5Xws="
"""
def base64(n \\ @default_length) do
random_bytes(n)
|> Base.encode64()
end
@doc """
Generates a random hexadecimal string.
The argument n specifies the length, in bytes, of the random number to be generated. The length of the resulting hexadecimal string is twice n.
If n is not specified, 16 is assumed. It may be larger in future.
The result may contain 0-9 and a-f.
## Examples
iex> SecureRandom.hex(6)
"34fb5655a231"
"""
def hex(n \\ @default_length) do
random_bytes(n)
|> Base.encode16(case: :lower)
end
@doc """
Returns random urlsafe Base64 encoded string.
## Examples
iex> SecureRandom.urlsafe_base64
"xYQcVfWuq6THMY_ZVmG0mA"
iex> SecureRandom.urlsafe_base64(8)
"8cN__l-6wNw"
"""
def urlsafe_base64(n \\ @default_length) do
base64(n)
|> Base.url_encode64(padding: true)
end
@doc """
Returns UUID v4 string. I have lifted most of this straight from Ecto's implementation.
## Examples
iex> SecureRandom.uuid
"e1d87f6e-fbd5-6801-9528-a1d568c1fd02"
"""
def uuid do
bigenerate() |> encode
end
@doc """
Returns random bytes.
## Examples
iex> SecureRandom.random_bytes
<<202, 104, 227, 197, 25, 7, 132, 73, 92, 186, 242, 13, 170, 115, 135, 7>>
iex> SecureRandom.random_bytes(8)
<<231, 123, 252, 174, 156, 112, 15, 29>>
"""
def random_bytes(n \\ @default_length) do
:crypto.strong_rand_bytes(n)
end
defp bigenerate do
<<u0::48, _::4, u1::12, _::2, u2::62>> = random_bytes(16)
<<u0::48, 4::4, u1::12, 2::2, u2::62>>
end
defp encode(<<u0::32, u1::16, u2::16, u3::16, u4::48>>) do
hex_pad(u0, 8) <> "-" <>
hex_pad(u1, 4) <> "-" <>
hex_pad(u2, 4) <> "-" <>
hex_pad(u3, 4) <> "-" <>
hex_pad(u4, 12)
end
defp hex_pad(hex, count) do
hex = Integer.to_string(hex, 16)
lower(hex, :binary.copy("0", count - byte_size(hex)))
end
defp lower(<<h, t::binary>>, acc) when h in ?A..?F,
do: lower(t, acc <> <<h + 32>>)
defp lower(<<h, t::binary>>, acc),
do: lower(t, acc <> <<h>>)
defp lower(<<>>, acc),
do: acc
end
| 21.784615 | 145 | 0.61935 |
fff6d2d88e476981d774ef66b68b6d038361066b | 2,775 | exs | Elixir | apps/omg_eth/test/omg_eth/application_test.exs | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 177 | 2018-08-24T03:51:02.000Z | 2020-05-30T13:29:25.000Z | apps/omg_eth/test/omg_eth/application_test.exs | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 1,042 | 2018-08-25T00:52:39.000Z | 2020-06-01T05:15:17.000Z | apps/omg_eth/test/omg_eth/application_test.exs | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 47 | 2018-08-24T12:06:33.000Z | 2020-04-28T11:49:25.000Z | # Copyright 2019-2020 OMG Network Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule OMG.Eth.ApplicationTest do
use ExUnit.Case, async: false
import ExUnit.CaptureLog, only: [capture_log: 1]
alias OMG.DB
alias OMG.Eth.Configuration
setup do
db_path = Briefly.create!(directory: true)
Application.put_env(:omg_db, :path, db_path, persistent: true)
:ok = DB.init()
{:ok, apps} = Application.ensure_all_started(:omg_eth)
on_exit(fn ->
contracts_hash = DB.get_single_value(:omg_eth_contracts)
:ok = DB.multi_update([{:delete, :omg_eth_contracts, contracts_hash}])
apps |> Enum.reverse() |> Enum.each(&Application.stop/1)
end)
{:ok, %{apps: apps}}
end
describe "valid_contracts/0" do
test "if contracts hash is persisted when application starts" do
contracts_hash =
Configuration.contracts()
|> Map.put(:txhash_contract, Configuration.txhash_contract())
# authority_addr to keep backwards compatibility
|> Map.put(:authority_addr, Configuration.authority_address())
|> :erlang.phash2()
assert DB.get_single_value(:omg_eth_contracts) == {:ok, contracts_hash}
end
test "that if contracts change boot is not permitted", %{apps: apps} do
contracts_hash =
Configuration.contracts()
|> Map.put(:txhash_contract, Configuration.txhash_contract())
# authority_addr to keep backwards compatibility
|> Map.put(:authority_addr, Configuration.authority_address())
|> :erlang.phash2()
assert DB.get_single_value(:omg_eth_contracts) == {:ok, contracts_hash}
apps |> Enum.reverse() |> Enum.each(&Application.stop/1)
contracts = Configuration.contracts()
Application.put_env(:omg_eth, :contract_addr, %{"test" => "test"})
assert capture_log(fn ->
assert Application.ensure_all_started(:omg_eth) ==
{:error,
{:omg_eth,
{:bad_return, {{OMG.Eth.Application, :start, [:normal, []]}, {:EXIT, :contracts_missmatch}}}}}
end) =~ "[error]"
Application.put_env(:omg_eth, :contract_addr, contracts)
{:ok, _} = Application.ensure_all_started(:omg_eth)
end
end
end
| 37.5 | 120 | 0.670631 |
fff6e30712887b047d59eced4415f0cbc7226d19 | 1,720 | ex | Elixir | apps/core/lib/core/tile.ex | joshnuss/ornia | 6a4c69a761b41ba0bcfd1c30f54dd2ccc92e5ead | [
"MIT"
] | 1 | 2020-01-14T23:19:25.000Z | 2020-01-14T23:19:25.000Z | apps/core/lib/core/tile.ex | joshnuss/ornia | 6a4c69a761b41ba0bcfd1c30f54dd2ccc92e5ead | [
"MIT"
] | null | null | null | apps/core/lib/core/tile.ex | joshnuss/ornia | 6a4c69a761b41ba0bcfd1c30f54dd2ccc92e5ead | [
"MIT"
] | null | null | null | defmodule Ornia.Core.Tile do
use GenServer
alias Ornia.Core.{Geometry, Grid}
@tile_size Application.get_env(:core, :tile_size)
def start_link(name, coordinates={lat, lng}) do
state = %{
jurisdiction: {coordinates, {lat + @tile_size, lng + @tile_size}},
pids: %{},
}
GenServer.start_link(__MODULE__, state, name: name)
end
def init(state) do
{:ok, state}
end
def handle_call({:join, pid, coordinates, traits}, _from, state) do
record = %{
position: coordinates,
traits: traits,
ref: Process.monitor(pid)
}
{:reply, :ok, put_in(state[:pids][pid], record)}
end
def handle_call({:leave, pid}, _from, state) do
{:reply, :ok, remove(state, pid)}
end
def handle_call({:update, pid, coordinates}, _from, state) do
if Geometry.outside?(state.jurisdiction, coordinates) do
Grid.join(pid, coordinates)
{:reply, :ok, remove(state, pid)}
else
{:reply, :ok, put_in(state[:pids][pid][:position], coordinates)}
end
end
def handle_call({:nearby, from, radius, filters}, _from, state) do
results = state.pids
|> Enum.into([])
|> Enum.filter(fn {_pid, %{traits: traits}} -> (filters -- traits) == [] end)
|> Enum.map(fn {pid, %{position: to}} -> {pid, to, Geometry.distance(from, to)} end)
|> Enum.filter(fn {_pid, _position, distance} -> distance < radius end)
{:reply, {:ok, results}, state}
end
def handle_info({:DOWN, _ref, :process, pid, _reason}, state) do
{:noreply, remove(state, pid)}
end
defp remove(state, pid) do
Process.demonitor(state.pids[pid].ref)
%{state | pids: Map.delete(state.pids, pid)}
end
end
| 26.461538 | 98 | 0.610465 |
fff6e345abe29a8daf9e01af7da8bafb2e77fde3 | 2,023 | ex | Elixir | lib/ecto_schema_store/factory.ex | onboardingsystems/ecto_schema_store | 120c929faecb686e3da685f411da66c80d7d0127 | [
"Apache-2.0"
] | null | null | null | lib/ecto_schema_store/factory.ex | onboardingsystems/ecto_schema_store | 120c929faecb686e3da685f411da66c80d7d0127 | [
"Apache-2.0"
] | null | null | null | lib/ecto_schema_store/factory.ex | onboardingsystems/ecto_schema_store | 120c929faecb686e3da685f411da66c80d7d0127 | [
"Apache-2.0"
] | null | null | null | defmodule EctoSchemaStore.Factory do
@moduledoc false
defmacro build do
quote do
def generate(keys \\ []) do
generate(keys, %{})
end
def generate(keys, fields) when is_atom(keys) do
generate([keys], fields)
end
def generate(keys, fields) when is_list(keys) do
# Default always applies first.
keys = [:default | keys]
params_list =
Enum.map(keys, fn key ->
try do
generate_prepare_fields(apply(__MODULE__, :generate_params, [key]))
rescue
_ ->
if key != :default do
Logger.warn("Factory '#{key}' not found in '#{__MODULE__}'.")
end
%{}
end
end)
params =
Enum.reduce(params_list, %{}, fn params, acc ->
Map.merge(acc, params)
end)
fields = generate_prepare_fields(fields)
params = Map.merge(params, fields)
insert_fields(params)
end
def generate_default(fields \\ %{}) do
generate([], fields)
end
def generate_default!(fields \\ %{}) do
generate!([], fields)
end
def generate!(keys \\ []) do
generate!(keys, %{})
end
def generate!(keys, fields) do
case generate(keys, fields) do
{:ok, response} -> response
{:error, message} -> throw(message)
end
end
defp generate_prepare_fields(fields) when is_list(fields) do
generate_prepare_fields(Enum.into(fields, %{}))
end
defp generate_prepare_fields(fields) when is_map(fields) do
alias_filters(fields)
end
end
end
defmacro factory(function, do: block) do
name = elem(function, 0)
quote do
def generate_params(unquote(name)) do
unquote(block)
end
end
end
defmacro factory(do: block) do
quote do
factory default do
unquote(block)
end
end
end
end
| 22.477778 | 81 | 0.544736 |
fff6f0da45f0401e08fef05d53aab03d9be576a0 | 2,150 | ex | Elixir | clients/gmail/lib/google_api/gmail/v1/model/message_part_body.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/gmail/lib/google_api/gmail/v1/model/message_part_body.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/gmail/lib/google_api/gmail/v1/model/message_part_body.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.Gmail.V1.Model.MessagePartBody do
@moduledoc """
The body of a single MIME message part.
## Attributes
* `attachmentId` (*type:* `String.t`, *default:* `nil`) - When present, contains the ID of an external attachment that can be retrieved in a separate `messages.attachments.get` request. When not present, the entire content of the message part body is contained in the data field.
* `data` (*type:* `String.t`, *default:* `nil`) - The body data of a MIME message part as a base64url encoded string. May be empty for MIME container types that have no message body or when the body data is sent as a separate attachment. An attachment ID is present if the body data is contained in a separate attachment.
* `size` (*type:* `integer()`, *default:* `nil`) - Number of bytes for the message part data (encoding notwithstanding).
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:attachmentId => String.t() | nil,
:data => String.t() | nil,
:size => integer() | nil
}
field(:attachmentId)
field(:data)
field(:size)
end
defimpl Poison.Decoder, for: GoogleApi.Gmail.V1.Model.MessagePartBody do
def decode(value, options) do
GoogleApi.Gmail.V1.Model.MessagePartBody.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Gmail.V1.Model.MessagePartBody do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.566038 | 325 | 0.723256 |
fff6ff501d4b64f9ee76927e44ad687b9310ff5a | 2,744 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/model/job.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/model/job.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/model/job.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.BigQuery.V2.Model.Job do
@moduledoc """
## Attributes
- configuration (JobConfiguration): [Required] Describes the job configuration. Defaults to: `null`.
- etag (String.t): [Output-only] A hash of this resource. Defaults to: `null`.
- id (String.t): [Output-only] Opaque ID field of the job Defaults to: `null`.
- jobReference (JobReference): [Optional] Reference describing the unique-per-user name of the job. Defaults to: `null`.
- kind (String.t): [Output-only] The type of the resource. Defaults to: `null`.
- selfLink (String.t): [Output-only] A URL that can be used to access this resource again. Defaults to: `null`.
- statistics (JobStatistics): [Output-only] Information about the job, including starting time and ending time of the job. Defaults to: `null`.
- status (JobStatus): [Output-only] The status of this job. Examine this value when polling an asynchronous job to see if the job is complete. Defaults to: `null`.
- user_email (String.t): [Output-only] Email address of the user who ran the job. Defaults to: `null`.
"""
defstruct [
:"configuration",
:"etag",
:"id",
:"jobReference",
:"kind",
:"selfLink",
:"statistics",
:"status",
:"user_email"
]
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.Job do
import GoogleApi.BigQuery.V2.Deserializer
def decode(value, options) do
value
|> deserialize(:"configuration", :struct, GoogleApi.BigQuery.V2.Model.JobConfiguration, options)
|> deserialize(:"jobReference", :struct, GoogleApi.BigQuery.V2.Model.JobReference, options)
|> deserialize(:"statistics", :struct, GoogleApi.BigQuery.V2.Model.JobStatistics, options)
|> deserialize(:"status", :struct, GoogleApi.BigQuery.V2.Model.JobStatus, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.Job do
def encode(value, options) do
GoogleApi.BigQuery.V2.Deserializer.serialize_non_nil(value, options)
end
end
| 40.955224 | 165 | 0.725219 |
fff70ec27d2c6e929ebdfdee11e3296ec270cdfb | 1,636 | ex | Elixir | test/support/conn_case.ex | jeffgrunewald/goose | 6b4f90d7c6e2c83d9967248312b96abde05f4d05 | [
"Apache-2.0"
] | 16 | 2020-11-13T01:01:05.000Z | 2021-09-13T10:38:36.000Z | test/support/conn_case.ex | jeffgrunewald/goose | 6b4f90d7c6e2c83d9967248312b96abde05f4d05 | [
"Apache-2.0"
] | 9 | 2020-11-22T21:26:30.000Z | 2021-11-22T02:15:26.000Z | test/support/conn_case.ex | jeffgrunewald/goose | 6b4f90d7c6e2c83d9967248312b96abde05f4d05 | [
"Apache-2.0"
] | 1 | 2020-11-13T06:43:51.000Z | 2020-11-13T06:43:51.000Z | defmodule Maverick.ConnCase do
use ExUnit.CaseTemplate
using do
quote do
import Maverick.Test.Helpers
end
end
end
defmodule Maverick.Test.Helpers do
require ExUnit.Assertions
def response(%Plug.Conn{status: status, resp_body: body}, given) do
given = Plug.Conn.Status.code(given)
if given == status do
body
else
raise "expected response with status #{given}, got: #{status}, with body:\n#{inspect(body)}"
end
end
def json_response(conn, status) do
body = response(conn, status)
_ = response_content_type(conn, :json)
Jason.decode!(body)
end
def response_content_type(conn, format) when is_atom(format) do
case Plug.Conn.get_resp_header(conn, "content-type") do
[] ->
raise "no content-type was set, expected a #{format} response"
[h] ->
if response_content_type?(h, format) do
h
else
raise "expected content-type for #{format}, got: #{inspect(h)}"
end
[_ | _] ->
raise "more than one content-type was set, expected a #{format} response"
end
end
def response_content_type?(header, format) do
case parse_content_type(header) do
{part, subpart} ->
format = Atom.to_string(format)
format in MIME.extensions(part <> "/" <> subpart) or
format == subpart or String.ends_with?(subpart, "+" <> format)
_ ->
false
end
end
defp parse_content_type(header) do
case Plug.Conn.Utils.content_type(header) do
{:ok, part, subpart, _params} ->
{part, subpart}
_ ->
false
end
end
end
| 23.042254 | 98 | 0.623472 |
fff70fc543a0f7813d9c986bf1f2ae3b3f089629 | 1,672 | ex | Elixir | lib/elixir_groups/signup/signup.ex | moxley/elixir_groups | cb37e0cec44316c17c60a0d12cfb0231d6b11eea | [
"Apache-2.0"
] | 2 | 2018-02-24T18:38:29.000Z | 2018-02-25T22:32:55.000Z | lib/elixir_groups/signup/signup.ex | moxley/elixir_groups | cb37e0cec44316c17c60a0d12cfb0231d6b11eea | [
"Apache-2.0"
] | 2 | 2018-03-25T02:01:08.000Z | 2019-10-23T20:00:57.000Z | lib/elixir_groups/signup/signup.ex | moxley/elixir_groups | cb37e0cec44316c17c60a0d12cfb0231d6b11eea | [
"Apache-2.0"
] | 1 | 2018-03-17T19:07:34.000Z | 2018-03-17T19:07:34.000Z | defmodule ElixirGroups.Signup do
@moduledoc """
The Signup context.
"""
import Ecto.Query, warn: false
alias ElixirGroups.Repo
alias ElixirGroups.Signup.User
@doc """
Returns the list of users.
## Examples
iex> list_users()
[%User{}, ...]
"""
def list_users do
Repo.all(User)
end
@doc """
Gets a single user.
Raises `Ecto.NoResultsError` if the User does not exist.
## Examples
iex> get_user!(123)
%User{}
iex> get_user!(456)
** (Ecto.NoResultsError)
"""
def get_user!(id), do: Repo.get!(User, id)
@doc """
Creates a user.
## Examples
iex> create_user(%{field: value})
{:ok, %User{}}
iex> create_user(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_user(attrs \\ %{}) do
%User{}
|> User.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a user.
## Examples
iex> update_user(user, %{field: new_value})
{:ok, %User{}}
iex> update_user(user, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_user(%User{} = user, attrs) do
user
|> User.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a User.
## Examples
iex> delete_user(user)
{:ok, %User{}}
iex> delete_user(user)
{:error, %Ecto.Changeset{}}
"""
def delete_user(%User{} = user) do
Repo.delete(user)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking user changes.
## Examples
iex> change_user(user)
%Ecto.Changeset{source: %User{}}
"""
def change_user(%User{} = user) do
User.changeset(user, %{})
end
end
| 15.92381 | 59 | 0.568182 |
fff746d8a2bf0b98f3b4d2ac9c8f5d3df0c18291 | 4,504 | ex | Elixir | lib/surgex/data_pipe/foreign_data_wrapper.ex | surgeventures/surgex | b3acdd6a9a010c26f0081b9cb23aeb072459be30 | [
"MIT"
] | 10 | 2017-09-15T08:55:48.000Z | 2021-07-08T09:26:24.000Z | lib/surgex/data_pipe/foreign_data_wrapper.ex | surgeventures/surgex | b3acdd6a9a010c26f0081b9cb23aeb072459be30 | [
"MIT"
] | 17 | 2017-07-24T11:27:22.000Z | 2022-01-24T22:28:18.000Z | lib/surgex/data_pipe/foreign_data_wrapper.ex | surgeventures/surgex | b3acdd6a9a010c26f0081b9cb23aeb072459be30 | [
"MIT"
] | 2 | 2018-04-12T15:01:00.000Z | 2018-05-27T12:14:34.000Z | case Code.ensure_loaded(Ecto) do
{:module, _} ->
defmodule Surgex.DataPipe.ForeignDataWrapper do
@moduledoc """
Configures a PostgreSQL Foreign Data Wrapper linkage between two repos.
Specifically, it executes the following steps:
- adds postgres_fdw extension to local repo
- (re)creates server and user mapping based on current remote repo's config
- copies remote repo's schema to local repo (named with underscored repo module name)
Everything is executed in one transaction, so it's safe to use while existing transactions that
depend on connection to foreign repo and its schema are running in the system (based on
https://robots.thoughtbot.com/postgres-foreign-data-wrapper).
## Usage
Refer to `Surgex.DataPipe` for a complete data pipe example.
"""
require Logger
alias Ecto.Adapters.SQL
@doc """
Links source repo to a given foreign repo.
"""
def init(source_repo, foreign_repo) do
local_name = source_repo |> Module.split() |> List.last()
server = schema = build_foreign_alias(foreign_repo)
config = foreign_repo.config
Logger.info(fn -> "Preparing foreign data wrapper at #{local_name}.#{server}..." end)
servers_count =
SQL.query!(
source_repo,
"select 1 from pg_foreign_server where srvname = '#{server}'"
)
script =
case servers_count.num_rows do
0 -> init_script(server, schema, config)
_ -> update_script(server, schema, config)
end
{:ok, _} =
apply(source_repo, :transaction, [
fn ->
Enum.each(script, fn command ->
SQL.query!(source_repo, command)
end)
end
])
end
def update_script(server, schema, config) do
server_opts = build_server_opts(config, "SET")
user_opts = build_user_opts(config, "SET")
[
"ALTER SERVER #{server}" <> server_opts,
"ALTER USER MAPPING FOR CURRENT_USER SERVER #{server}" <> user_opts,
"DROP SCHEMA IF EXISTS #{schema} CASCADE",
"CREATE SCHEMA #{schema}",
"IMPORT FOREIGN SCHEMA public FROM SERVER #{server} INTO #{schema}"
]
end
def init_script(server, schema, config) do
server_opts = build_server_opts(config)
user_opts = build_user_opts(config)
[
"CREATE EXTENSION IF NOT EXISTS postgres_fdw",
"DROP SERVER IF EXISTS #{server} CASCADE",
"CREATE SERVER #{server} FOREIGN DATA WRAPPER postgres_fdw" <> server_opts,
"CREATE USER MAPPING FOR CURRENT_USER SERVER #{server}" <> user_opts,
"DROP SCHEMA IF EXISTS #{schema}",
"CREATE SCHEMA #{schema}",
"IMPORT FOREIGN SCHEMA public FROM SERVER #{server} INTO #{schema}"
]
end
@doc """
Puts a foreign repo prefix (aka. schema) in a given Repo query.
After calling this function, a given query will target tables from the previously linked repo
instead of Repo.
"""
def prefix(query = %{}, foreign_repo) do
Map.put(query, :prefix, build_foreign_alias(foreign_repo))
end
def prefix(schema, foreign_repo) do
import Ecto.Query, only: [from: 1]
prefix(from(schema), foreign_repo)
end
defp build_server_opts(config, command \\ "") do
build_opts(
[
{"host", Keyword.get(config, :hostname)},
{"dbname", Keyword.get(config, :database)},
{"port", Keyword.get(config, :port)}
],
command
)
end
defp build_user_opts(config, command \\ "") do
build_opts(
[
{"user", Keyword.get(config, :username)},
{"password", Keyword.get(config, :password)}
],
command
)
end
defp build_opts(mapping, command) do
opts_string =
mapping
|> Enum.filter(fn {_, value} -> value end)
|> Enum.map(fn {option, value} -> "#{command} #{option} '#{value}'" end)
|> Enum.join(", ")
case opts_string do
"" -> ""
_ -> " OPTIONS (#{opts_string})"
end
end
defp build_foreign_alias(repo) do
repo
|> Module.split()
|> List.last()
|> Macro.underscore()
end
end
_ ->
nil
end
| 30.849315 | 101 | 0.578153 |
fff76e7bf953acba101ca8942e490c4ea66c955f | 922 | exs | Elixir | apps/amf0/mix.exs | tiensonqin/elixir-media-libs | 87f17e2b23bf8380e785423652910bfa7d3bb47c | [
"MIT"
] | null | null | null | apps/amf0/mix.exs | tiensonqin/elixir-media-libs | 87f17e2b23bf8380e785423652910bfa7d3bb47c | [
"MIT"
] | null | null | null | apps/amf0/mix.exs | tiensonqin/elixir-media-libs | 87f17e2b23bf8380e785423652910bfa7d3bb47c | [
"MIT"
] | null | null | null | defmodule Amf0.Mixfile do
use Mix.Project
def project do
[
app: :amf0,
version: "1.0.1",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.2",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
description: description(),
package: package(),
deps: deps()
]
end
def application do
[applications: [:logger]]
end
defp deps do
[{:ex_doc, "~> 0.14", only: :dev}]
end
defp package do
[
name: :eml_amf0,
maintainers: ["Matthew Shapiro"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/KallDrexx/elixir-media-libs/tree/master/apps/amf0"}
]
end
defp description do
"Provides functions to serialize and deserialize data encoded in the AMF0 data format"
end
end
| 21.952381 | 98 | 0.574837 |
fff77e8b849cdf2e4f86e4d63aef9a44e74752bb | 1,042 | exs | Elixir | config/web/releases.exs | paulanthonywilson/mcam | df9c5aaae00b568749dff22613636f5cb92f905a | [
"MIT"
] | null | null | null | config/web/releases.exs | paulanthonywilson/mcam | df9c5aaae00b568749dff22613636f5cb92f905a | [
"MIT"
] | 8 | 2020-11-16T09:59:12.000Z | 2020-11-16T10:13:07.000Z | config/web/releases.exs | paulanthonywilson/mcam | df9c5aaae00b568749dff22613636f5cb92f905a | [
"MIT"
] | null | null | null | import Config
env_int = fn key ->
key
|> System.fetch_env!()
|> String.to_integer()
end
config :mcam_server, :camera_token,
secret: System.fetch_env!("MCAM_CAMERA_SECRET"),
salt: System.fetch_env!("MCAM_CAMERA_SALT")
config :mcam_server, :browser_token,
secret: System.fetch_env!("MCAM_BROWSER_SECRET"),
salt: System.fetch_env!("MCAM_BROWSER_SALT")
config :mcam_server_web, McamServerWeb.Endpoint,
secret_key_base: System.fetch_env!("MCAM_SECRET_KEY_BASE"),
live_view: [signing_salt: System.fetch_env!("MCAM_LIVE_SALT")],
https: [keyfile: System.fetch_env!("MCAM_SSL_KEY_PATH"),
certfile: System.fetch_env!("MCAM_SSL_CERT_PATH"),
cacertfile: System.fetch_env!("MCAM_SSL_CACERT_PATH")]
config :mcam_server, McamServer.Repo,
url: System.get_env("MCAM_DATABASE_URL"),
pool_size: String.to_integer(System.fetch_env!("MCAM_POOL_SIZE") || "10")
config :mcam_server, McamServer.Mailing.Mailer,
api_key: System.fetch_env!("MCAM_MAILGUN_API_KEY"),
domain: System.fetch_env!("MCAM_MAILGUN_DOMAIN")
| 33.612903 | 75 | 0.752399 |
fff783b3630d7251716ec3c11aee73887895bc42 | 1,947 | exs | Elixir | config/dev.exs | ritou/elixir-oauth-xyz | 110d4eadb16fa5c106ae0f6fad49c0424bdbf477 | [
"MIT"
] | 2 | 2020-04-22T13:22:25.000Z | 2020-12-01T12:01:30.000Z | config/dev.exs | ritou/elixir-oauth-xyz | 110d4eadb16fa5c106ae0f6fad49c0424bdbf477 | [
"MIT"
] | 3 | 2019-12-05T01:32:09.000Z | 2019-12-09T01:15:32.000Z | config/dev.exs | ritou/elixir-oauth-xyz-web | 110d4eadb16fa5c106ae0f6fad49c0424bdbf477 | [
"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 :oauth_xyz, OAuthXYZWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"node_modules/brunch/bin/brunch",
"watch",
"--stdin",
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 :oauth_xyz, OAuthXYZWeb.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{priv/gettext/.*(po)$},
~r{lib/oauth_xyz_web/views/.*(ex)$},
~r{lib/oauth_xyz_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 :oauth_xyz, OAuthXYZ.Repo,
adapter: Ecto.Adapters.MySQL,
username: "root",
password: "",
database: "oauth_xyz_dev",
hostname: "localhost",
pool_size: 10
| 29.953846 | 170 | 0.696456 |
fff7952dc22d0e0a6019feb5244ea8a250e734d5 | 3,120 | ex | Elixir | lib/ecto/exceptions.ex | timgestson/ecto | 1c1eb6d322db04cfa48a4fc81da1332e91adbc1f | [
"Apache-2.0"
] | null | null | null | lib/ecto/exceptions.ex | timgestson/ecto | 1c1eb6d322db04cfa48a4fc81da1332e91adbc1f | [
"Apache-2.0"
] | null | null | null | lib/ecto/exceptions.ex | timgestson/ecto | 1c1eb6d322db04cfa48a4fc81da1332e91adbc1f | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Query.CompileError do
@moduledoc """
Raised at compilation time when the query cannot be compiled.
"""
defexception [:message]
end
defmodule Ecto.QueryError do
@moduledoc """
Raised at runtime when the query is invalid.
"""
defexception [:message]
def exception(opts) do
message = Keyword.fetch!(opts, :message)
query = Keyword.fetch!(opts, :query)
message = """
#{message} in query:
#{Inspect.Ecto.Query.to_string(query)}
"""
if (file = opts[:file]) && (line = opts[:line]) do
relative = Path.relative_to_cwd(file)
message = Exception.format_file_line(relative, line) <> " " <> message
end
%__MODULE__{message: message}
end
end
defmodule Ecto.CastError do
@moduledoc """
Raised at runtime when a value cannot be cast.
"""
defexception [:model, :field, :type, :value, :message]
def exception(opts) do
model = Keyword.fetch!(opts, :model)
field = Keyword.fetch!(opts, :field)
value = Keyword.fetch!(opts, :value)
type = Keyword.fetch!(opts, :type)
msg = Keyword.fetch!(opts, :message)
%__MODULE__{model: model, field: field, value: value, type: type, message: msg}
end
end
defmodule Ecto.InvalidURLError do
defexception [:message, :url]
def exception(opts) do
url = Keyword.fetch!(opts, :url)
msg = Keyword.fetch!(opts, :message)
msg = "invalid url #{url}, #{msg}"
%__MODULE__{message: msg, url: url}
end
end
defmodule Ecto.NoPrimaryKeyError do
defexception [:message, :model]
def exception(opts) do
model = Keyword.fetch!(opts, :model)
message = "model `#{inspect model}` has no primary key"
%__MODULE__{message: message, model: model}
end
end
defmodule Ecto.MissingPrimaryKeyError do
defexception [:message, :struct]
def exception(opts) do
struct = Keyword.fetch!(opts, :struct)
message = "struct `#{inspect struct}` is missing primary key value"
%__MODULE__{message: message, struct: struct}
end
end
defmodule Ecto.ChangeError do
defexception [:message]
end
defmodule Ecto.NoResultsError do
defexception [:message]
def exception(opts) do
query = Keyword.fetch!(opts, :queryable) |> Ecto.Queryable.to_query
msg = """
expected at least one result but got none in query:
#{Inspect.Ecto.Query.to_string(query)}
"""
%__MODULE__{message: msg}
end
end
defmodule Ecto.MultipleResultsError do
defexception [:message]
def exception(opts) do
query = Keyword.fetch!(opts, :queryable) |> Ecto.Queryable.to_query
count = Keyword.fetch!(opts, :count)
msg = """
expected at most one result but got #{count} in query:
#{Inspect.Ecto.Query.to_string(query)}
"""
%__MODULE__{message: msg}
end
end
defmodule Ecto.MigrationError do
defexception [:message]
end
defmodule Ecto.StaleModelError do
defexception [:message]
def exception(opts) do
action = Keyword.fetch!(opts, :action)
model = Keyword.fetch!(opts, :model)
msg = """
attempted to #{action} a stale model:
#{inspect model}
"""
%__MODULE__{message: msg}
end
end
| 22.773723 | 83 | 0.670513 |
fff795f81f753b6cec8658593ab38a495c787b5e | 1,908 | ex | Elixir | lib/erlef/twitter.ex | joaquinalcerro/website | 52dc89c70cd0b42127ab233a4c0d10f626d2b698 | [
"Apache-2.0"
] | 71 | 2019-07-02T18:06:15.000Z | 2022-03-09T15:30:08.000Z | lib/erlef/twitter.ex | joaquinalcerro/website | 52dc89c70cd0b42127ab233a4c0d10f626d2b698 | [
"Apache-2.0"
] | 157 | 2019-07-02T01:21:16.000Z | 2022-03-30T16:08:12.000Z | lib/erlef/twitter.ex | joaquinalcerro/website | 52dc89c70cd0b42127ab233a4c0d10f626d2b698 | [
"Apache-2.0"
] | 45 | 2019-07-04T05:51:11.000Z | 2022-02-27T11:56:02.000Z | defmodule Erlef.Twitter do
@moduledoc """
Wrapper around the ExTwitter library
"""
defmodule Tweet do
@moduledoc "Struct for tweets"
@type t :: %__MODULE__{
id: String.t(),
name: String.t(),
screen_name: String.t(),
avatar: String.t(),
posted_date: String.t(),
text: String.t()
}
defstruct [:id, :name, :screen_name, :avatar, :posted_date, :text]
end
@screen_name "TheErlef"
@doc """
Returns the 3 most recent tweets for the EEF twitter account
"""
@spec latest_tweets(client :: Atom.t()) :: [Tweet.t()]
def latest_tweets(client \\ nil) do
client = client || Application.get_env(:erlef, :twitter_client, ExTwitter)
[
screen_name: @screen_name,
count: 3
]
|> client.user_timeline()
|> Enum.map(&format_tweet/1)
end
if Erlef.is_env?(:dev) do
def user_timeline(_) do
tweet = %{
id_str: "1326232249054818305",
user: %{
name: "Erlang Ecosystem Foundation",
screen_name: "TheErlef",
profile_image_url_https:
"https://pbs.twimg.com/profile_images/1099510098701910017/RSwfpAGg_normal.png"
},
text: "It's adventure time! https://t.co/5FTnyXb8AE",
created_at: "Tue Nov 10 18:36:23 +0000 2020"
}
[tweet, tweet, tweet]
end
end
defp format_tweet(tweet) do
%Tweet{
id: tweet.id_str,
name: tweet.user.name,
screen_name: tweet.user.screen_name,
avatar: tweet.user.profile_image_url_https,
posted_date: format_date(tweet.created_at),
text: tweet.text
}
end
defp format_date(
<<_::binary-size(4), month::binary-size(3), " ", day::binary-size(2), _::binary-size(16),
year::binary>>
) do
"#{month} #{day}, #{year}"
end
defp format_date(date_string), do: date_string
end
| 25.105263 | 98 | 0.591719 |
fff7b553021e5e511e719b3587eded8d32e8e403 | 1,100 | exs | Elixir | mix.exs | theocodes/monetized | bc742c5be8e435681daa35a2edddf55337a2d12f | [
"MIT"
] | 42 | 2015-12-21T00:16:49.000Z | 2019-02-25T10:19:26.000Z | mix.exs | theocodes/monetized | bc742c5be8e435681daa35a2edddf55337a2d12f | [
"MIT"
] | 23 | 2015-12-31T19:36:14.000Z | 2020-08-18T19:25:53.000Z | mix.exs | tfelippe/monetized | bc742c5be8e435681daa35a2edddf55337a2d12f | [
"MIT"
] | 21 | 2016-01-27T17:44:50.000Z | 2020-09-21T16:46:12.000Z | defmodule Monetized.Mixfile do
use Mix.Project
def project do
[app: :monetized,
name: "Monetized",
source_url: "https://github.com/theocodes/monetized",
version: "0.5.1",
elixir: "~> 1.3",
description: description(),
package: package(),
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps()]
end
def application do
[extra_applications: [:logger]]
end
defp deps do
[
{:ex_doc, "~> 0.11.5", only: :dev},
{:earmark, "~> 0.2.1", only: :dev},
{:inch_ex, "~> 0.5.1", only: :docs},
{:decimal, "~> 1.3"},
{:ecto, "~> 2.1.3"},
{:benchfella, "~> 0.3.2", only: :bench},
{:poison, "~> 1.5 or ~> 2.0", optional: true},
]
end
defp package do
[
maintainers: ["Theo Felippe"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/theocodes/monetized",
"Docs" => "http://hexdocs.pm/monetized"}
]
end
defp description do
"""
A lightweight solution for handling and storing money.
"""
end
end
| 21.568627 | 68 | 0.536364 |
fff7d127defd9fa7d98f7d6c57d2b139b79b6c47 | 795 | ex | Elixir | Microsoft.Azure.Management.Storage/lib/microsoft/azure/management/storage/model/endpoints.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | 4 | 2018-09-29T03:43:15.000Z | 2021-04-01T18:30:46.000Z | Microsoft.Azure.Management.Storage/lib/microsoft/azure/management/storage/model/endpoints.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | Microsoft.Azure.Management.Storage/lib/microsoft/azure/management/storage/model/endpoints.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | # NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule Microsoft.Azure.Management.Storage.Model.Endpoints do
@moduledoc """
The URIs that are used to perform a retrieval of a public blob, queue, table, web or dfs object.
"""
@derive [Poison.Encoder]
defstruct [
:"blob",
:"queue",
:"table",
:"file",
:"web",
:"dfs"
]
@type t :: %__MODULE__{
:"blob" => String.t,
:"queue" => String.t,
:"table" => String.t,
:"file" => String.t,
:"web" => String.t,
:"dfs" => String.t
}
end
defimpl Poison.Decoder, for: Microsoft.Azure.Management.Storage.Model.Endpoints do
def decode(value, _options) do
value
end
end
| 22.083333 | 98 | 0.636478 |
fff7ec1e4224e426f25d3ad4102f777a5cbbff74 | 1,942 | exs | Elixir | lib/elixir/test/elixir/calendar_test.exs | kevsmith/elixir | 74825645e8cac770708f45139e651fd9d4e4264c | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/calendar_test.exs | kevsmith/elixir | 74825645e8cac770708f45139e651fd9d4e4264c | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/calendar_test.exs | kevsmith/elixir | 74825645e8cac770708f45139e651fd9d4e4264c | [
"Apache-2.0"
] | null | null | null | Code.require_file "test_helper.exs", __DIR__
defmodule FakeCalendar do
def to_string(_), do: "boom"
end
defmodule DateTest do
use ExUnit.Case, async: true
doctest Date
test "to_string/1" do
assert to_string(~D[2000-01-01]) == "2000-01-01"
date = Map.put(~D[2000-01-01], :calendar, FakeCalendar)
assert to_string(date) == "boom"
end
test "inspect/1" do
assert inspect(~D[2000-01-01]) == "~D[2000-01-01]"
date = Map.put(~D[2000-01-01], :calendar, FakeCalendar)
assert inspect(date) == "%Date{calendar: FakeCalendar, day: 1, month: 1, year: 2000}"
end
end
defmodule TimeTest do
use ExUnit.Case, async: true
doctest Time
test "to_string/1" do
assert to_string(~T[23:00:07.005]) == "23:00:07.005"
end
test "inspect/1" do
assert inspect(~T[23:00:07.005]) == "~T[23:00:07.005]"
end
end
defmodule NaiveDateTimeTest do
use ExUnit.Case, async: true
doctest NaiveDateTime
test "to_string/1" do
assert to_string(~N[2000-01-01 23:00:07.005]) == "2000-01-01 23:00:07.005"
date = Map.put(~N[2000-01-01 23:00:07.005], :calendar, FakeCalendar)
assert to_string(date) == "boom"
end
test "inspect/1" do
assert inspect(~N[2000-01-01 23:00:07.005]) == "~N[2000-01-01 23:00:07.005]"
date = Map.put(~N[2000-01-01 23:00:07.005], :calendar, FakeCalendar)
assert inspect(date) == "%NaiveDateTime{calendar: FakeCalendar, day: 1, hour: 23, " <>
"microsecond: {5000, 3}, minute: 0, month: 1, second: 7, year: 2000}"
end
end
defmodule DateTimeTest do
use ExUnit.Case, async: true
doctest DateTime
test "to_string/1" do
dt = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "BRM",
hour: 23, minute: 0, second: 7, microsecond: {0, 0},
utc_offset: -12600, std_offset: 3600, time_zone: "Brazil/Manaus"}
assert to_string(dt) == "2000-02-29 23:00:07-02:30 BRM Brazil/Manaus"
end
end
| 27.742857 | 97 | 0.639032 |
fff7ed6778db54096913b240d294dfddb63243a9 | 120 | exs | Elixir | test/std_json_io_test.exs | plandela/std_json_io | ade74982dd9edfea2a13e42addb71b68679c241f | [
"MIT"
] | 26 | 2016-01-03T01:30:36.000Z | 2019-06-01T14:30:28.000Z | test/std_json_io_test.exs | plandela/std_json_io | ade74982dd9edfea2a13e42addb71b68679c241f | [
"MIT"
] | 10 | 2016-04-20T06:20:14.000Z | 2017-07-19T17:55:14.000Z | test/std_json_io_test.exs | plandela/std_json_io | ade74982dd9edfea2a13e42addb71b68679c241f | [
"MIT"
] | 26 | 2016-04-26T18:41:02.000Z | 2020-03-03T21:39:29.000Z | defmodule StdJsonIoTest do
use ExUnit.Case
doctest StdJsonIo
test "the truth" do
assert 1 + 1 == 2
end
end
| 13.333333 | 26 | 0.683333 |
fff7f0438f6a559ce912ebb47ac29e13bfcc21c2 | 1,283 | ex | Elixir | lib/changelog_web/controllers/github_controller.ex | PsOverflow/changelog.com | 53f4ecfc39b021c6b8cfcc0fa11f29aff8038a7f | [
"MIT"
] | 1 | 2021-03-14T21:12:49.000Z | 2021-03-14T21:12:49.000Z | lib/changelog_web/controllers/github_controller.ex | type1fool/changelog.com | fbec3528cc3f5adfdc75b008bb92b17efc4f248f | [
"MIT"
] | null | null | null | lib/changelog_web/controllers/github_controller.ex | type1fool/changelog.com | fbec3528cc3f5adfdc75b008bb92b17efc4f248f | [
"MIT"
] | 1 | 2018-10-03T20:55:52.000Z | 2018-10-03T20:55:52.000Z | defmodule ChangelogWeb.GithubController do
use ChangelogWeb, :controller
alias Changelog.Github
require Logger
def event(conn, params) do
case get_req_header(conn, "x-github-event") do
["push"] -> push_event(conn, params)
[event] -> unsupported_event(conn, params, event)
end
end
defp push_event(conn, params = %{"repository" => %{"full_name" => full_name}, "commits" => commits}) do
case extract_supported_repository_from(full_name) do
%{"repo" => repo} ->
update_list = added_or_modified_files(commits)
Github.Puller.update(repo, update_list)
json(conn, %{})
nil -> unsupported_event(conn, params, "push #{full_name}")
end
end
defp push_event(conn, params) do
unsupported_event(conn, params, "push fail")
end
defp added_or_modified_files(commits) do
commits
|> Enum.map(&(Map.take(&1, ["added", "modified"])))
|> Enum.map(&Map.values/1)
|> List.flatten
end
defp extract_supported_repository_from(full_name) do
Regex.named_captures(Github.Source.repo_regex(), full_name)
end
defp unsupported_event(conn, params, event) do
Logger.info("GitHub: Unhandled event '#{event}' params: #{inspect(params)}")
send_resp(conn, :method_not_allowed, "")
end
end
| 28.511111 | 105 | 0.678878 |
fff7f7f73b41aa2c73de2674d8ae6cfde9dfe1c1 | 5,740 | ex | Elixir | lib/glfw.ex | lafilipo/scenic_driver_glfw | 7d61e31c73ea3acc3ead98a9819630e73f47d57c | [
"Apache-2.0"
] | 27 | 2018-09-09T00:25:58.000Z | 2022-03-13T17:01:29.000Z | lib/glfw.ex | lafilipo/scenic_driver_glfw | 7d61e31c73ea3acc3ead98a9819630e73f47d57c | [
"Apache-2.0"
] | 26 | 2018-09-09T09:06:15.000Z | 2022-02-13T08:31:12.000Z | lib/glfw.ex | lafilipo/scenic_driver_glfw | 7d61e31c73ea3acc3ead98a9819630e73f47d57c | [
"Apache-2.0"
] | 22 | 2018-09-08T15:28:47.000Z | 2022-01-14T11:33:17.000Z | #
# Created by Boyd Multerer on 05/31/18.
# Copyright © 2018 Kry10 Industries. All rights reserved.
#
# sends data to a Glfw port app
#
defmodule Scenic.Driver.Glfw do
@moduledoc """
"""
use Scenic.ViewPort.Driver
alias Scenic.Cache
alias Scenic.Driver.Glfw
# import IEx
require Logger
@driver_ext if elem(:os.type(), 0) == :win32, do: '.exe', else: ''
@port '/' ++ to_charlist(Mix.env()) ++ '/scenic_driver_glfw' ++ @driver_ext
@default_title "Driver Glfw"
@default_resizeable false
@default_block_size 512
@default_clear_color {0, 0, 0, 0xFF}
@default_sync 15
# ============================================================================
# client callable api
def query_stats(pid), do: GenServer.call(pid, :query_stats)
def reshape(pid, width, height), do: GenServer.cast(pid, {:reshape, width, height})
def position(pid, x, y), do: GenServer.cast(pid, {:position, x, y})
def focus(pid), do: GenServer.cast(pid, :focus)
def iconify(pid), do: GenServer.cast(pid, :iconify)
def maximize(pid), do: GenServer.cast(pid, :maximize)
def restore(pid), do: GenServer.cast(pid, :restore)
def show(pid), do: GenServer.cast(pid, :show)
def hide(pid), do: GenServer.cast(pid, :hide)
def close(pid), do: GenServer.cast(pid, :close)
if Mix.env() == :dev do
def crash(pid), do: GenServer.cast(pid, :crash)
end
# ============================================================================
# startup
def init(viewport, {width, height}, config) do
title =
cond do
is_bitstring(config[:title]) -> config[:title]
true -> @default_title
end
resizeable =
cond do
is_boolean(config[:resizeable]) -> config[:resizeable]
true -> @default_resizeable
end
sync_interval =
cond do
is_integer(config[:sync]) -> config[:sync]
true -> @default_sync
end
dl_block_size =
cond do
is_integer(config[:block_size]) -> config[:block_size]
true -> @default_block_size
end
port_args =
to_charlist(" #{width} #{height} #{inspect(title)} #{resizeable} #{dl_block_size}")
# request put and delete notifications from the cache
Cache.Static.Font.subscribe(:all)
Cache.Static.Texture.subscribe(:all)
# open and initialize the window
Process.flag(:trap_exit, true)
executable = :code.priv_dir(:scenic_driver_glfw) ++ @port ++ port_args
port = Port.open({:spawn, executable}, [:binary, {:packet, 4}])
state = %{
inputs: 0x0000,
port: port,
closing: false,
ready: false,
debounce: %{},
root_ref: nil,
dl_block_size: dl_block_size,
start_dl: nil,
end_dl: nil,
last_used_dl: nil,
dl_map: %{},
used_dls: %{},
clear_color: @default_clear_color,
textures: %{},
fonts: %{},
dirty_graphs: [],
sync_interval: sync_interval,
draw_busy: false,
pending_flush: false,
currently_drawing: [],
window: {width, height},
frame: {width, height},
screen_factor: 1.0,
viewport: viewport
}
# mark this rendering process has high priority
# Process.flag(:priority, :high)
{:ok, state}
end
# ============================================================================
# farm out handle_cast and handle_info to the supporting modules.
# this module just got too long and complicated, so this cleans things up.
# --------------------------------------------------------
def handle_call(msg, from, state) do
Glfw.Port.handle_call(msg, from, state)
end
# --------------------------------------------------------
# %{ready: true} =
def handle_cast(msg, state) do
msg
|> do_handle(&Glfw.Graph.handle_cast(&1, state))
|> do_handle(&Glfw.Cache.handle_cast(&1, state))
|> do_handle(&Glfw.Port.handle_cast(&1, state))
# |> do_handle( &Glfw.Font.handle_cast( &1, state ) )
|> case do
{:noreply, state} ->
{:noreply, state}
_ ->
{:noreply, state}
end
end
# def handle_cast( {:request_input, input_flags}, state ) do
# {:noreply, Map.put(state, :inputs, input_flags)}
# end
# def handle_cast( {:cache_put, _}, state ), do: {:noreply, state}
# def handle_cast( {:cache_delete, _}, state ), do: {:noreply, state}
# def handle_cast( msg, %{ready: false} = state ) do
# {:noreply, state}
# end
# --------------------------------------------------------
def handle_info(:flush_dirty, %{ready: true} = state) do
Glfw.Graph.handle_flush_dirty(state)
end
# --------------------------------------------------------
def handle_info({:debounce, type}, %{ready: true} = state) do
Glfw.Input.handle_debounce(type, state)
end
# --------------------------------------------------------
def handle_info({msg_port, {:data, msg}}, %{port: port} = state) when msg_port == port do
msg
|> do_handle(&Glfw.Input.handle_port_message(&1, state))
end
# deal with the app exiting normally
def handle_info({:EXIT, port_id, :normal} = msg, %{port: port, closing: closing} = state)
when port_id == port do
if closing do
Logger.info("clean close")
# we are closing cleanly, let it happen.
GenServer.stop(self())
{:noreply, state}
else
Logger.error("dirty close")
# we are not closing cleanly. Let the supervisor recover.
super(msg, state)
end
end
def handle_info(msg, state) do
super(msg, state)
end
# --------------------------------------------------------
defp do_handle({:noreply, _} = msg, _), do: msg
defp do_handle(msg, handler) when is_function(handler) do
handler.(msg)
end
end
| 28.557214 | 91 | 0.56324 |
fff814f5222033e912e41863d5f416fd1e927f75 | 12,870 | ex | Elixir | lib/mix/lib/mix/dep/converger.ex | lytedev/elixir | dc25bb8e1484e2328eef819402d268dec7bb908a | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/dep/converger.ex | lytedev/elixir | dc25bb8e1484e2328eef819402d268dec7bb908a | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/dep/converger.ex | lytedev/elixir | dc25bb8e1484e2328eef819402d268dec7bb908a | [
"Apache-2.0"
] | null | null | null | # This module is the one responsible for converging
# dependencies in a recursive fashion. This
# module and its functions are private to Mix.
defmodule Mix.Dep.Converger do
@moduledoc false
@doc """
Topologically sorts the given dependencies.
"""
def topological_sort(deps) do
graph = :digraph.new()
try do
Enum.each(deps, fn %Mix.Dep{app: app} ->
:digraph.add_vertex(graph, app)
end)
Enum.each(deps, fn %Mix.Dep{app: app, deps: other_deps} ->
Enum.each(other_deps, fn
%Mix.Dep{app: ^app} ->
Mix.raise("App #{app} lists itself as a dependency")
%Mix.Dep{app: other_app} ->
:digraph.add_edge(graph, other_app, app)
end)
end)
if apps = :digraph_utils.topsort(graph) do
Enum.map(apps, fn app ->
Enum.find(deps, fn %Mix.Dep{app: other_app} -> app == other_app end)
end)
else
Mix.raise("Could not sort dependencies. There are cycles in the dependency graph")
end
after
:digraph.delete(graph)
end
end
@doc """
Converges all dependencies from the current project,
including nested dependencies.
There is a callback that is invoked for each dependency and
must return an updated dependency in case some processing
is done.
See `Mix.Dep.Loader.children/1` for options.
"""
def converge(acc, lock, opts, callback) do
{deps, acc, lock} = all(acc, lock, opts, callback)
if remote = Mix.RemoteConverger.get(), do: remote.post_converge
{topological_sort(deps), acc, lock}
end
defp all(acc, lock, opts, callback) do
main = Mix.Dep.Loader.children()
main = Enum.map(main, &%{&1 | top_level: true})
apps = Enum.map(main, & &1.app)
lock_given? = !!lock
env = opts[:env]
# If no lock was given, let's read one to fill in the deps
lock = lock || Mix.Dep.Lock.read()
# Run converger for all dependencies, except remote
# dependencies. Since the remote converger may be
# lazily loaded, we need to check for it on every
# iteration.
{deps, acc, lock} =
all(main, apps, callback, acc, lock, env, fn dep ->
if (remote = Mix.RemoteConverger.get()) && remote.remote?(dep) do
{:loaded, dep}
else
{:unloaded, dep, nil}
end
end)
# Run remote converger and rerun Mix's converger with the new information.
# Don't run the remote if deps didn't converge, if the remote is not
# available or if none of the deps are handled by the remote.
remote = Mix.RemoteConverger.get()
diverged? = Enum.any?(deps, &Mix.Dep.diverged?/1)
use_remote? = !!remote and Enum.any?(deps, &remote.remote?/1)
if not diverged? and use_remote? do
# Make sure there are no cycles before calling remote converge
topological_sort(deps)
# If there is a lock, it means we are doing a get/update
# and we need to hit the remote converger which do external
# requests and what not. In case of deps.loadpaths, deps and so
# on, there is no lock, so we won't hit this branch.
lock = if lock_given?, do: remote.converge(deps, lock), else: lock
# Build a cache using both dep_name and dep_scm to ensure we only
# return :loaded for deps which have been loaded from the same source.
cache =
deps
|> Enum.reject(&remote.remote?(&1))
|> Enum.into(%{}, &{{&1.app, &1.scm}, &1})
# In case no lock was given, we will use the local lock
# which is potentially stale. So remote.deps/2 needs to always
# check if the data it finds in the lock is actually valid.
{deps, acc, lock} =
all(main, apps, callback, acc, lock, env, fn dep ->
if cached = cache[{dep.app, dep.scm}] do
{:loaded, cached}
else
{:unloaded, dep, remote.deps(dep, lock)}
end
end)
{reject_non_fulfilled_optional(deps), acc, lock}
else
{reject_non_fulfilled_optional(deps), acc, lock}
end
end
defp all(main, apps, callback, rest, lock, env, cache) do
{deps, rest, lock} = all(main, [], [], apps, callback, rest, lock, env, cache)
deps = Enum.reverse(deps)
# When traversing dependencies, we keep skipped ones to
# find conflicts. We remove them now after traversal.
{deps, _} = Mix.Dep.Loader.partition_by_env(deps, env)
{deps, rest, lock}
end
# We traverse the tree of dependencies in a breadth-first
# fashion. The reason for this is that we converge
# dependencies, but allow the parent to override any
# dependency in the child. Consider this tree with
# dependencies "a", "b", etc and the order they are
# converged:
#
# * project
# 1) a
# 2) b
# 4) d
# 3) c
# 5) e
# 6) f
# 7) d
#
# Notice that the "d" dependency exists as a child of "b"
# and child of "f". In case the dependency is the same,
# we proceed. However, if there is a conflict, for instance
# different Git repositories are used as source in each, we
# raise an exception.
#
# In order to solve such dependencies, we allow the project
# to specify the same dependency, but it will be considered
# to have higher priority:
#
# * project
# 1) a
# 2) b
# 5) d
# 3) c
# 6) e
# 7) f
# 8) d
# 4) d
#
# Now, since "d" was specified in a parent project, no
# exception is going to be raised since d is considered
# to be the authoritative source.
defp all([dep | t], acc, upper_breadths, current_breadths, callback, rest, lock, env, cache) do
case match_deps(acc, upper_breadths, dep, env) do
{:replace, dep, acc} ->
all([dep | t], acc, upper_breadths, current_breadths, callback, rest, lock, env, cache)
{:match, acc} ->
all(t, acc, upper_breadths, current_breadths, callback, rest, lock, env, cache)
:skip ->
# We still keep skipped dependencies around to detect conflicts.
# They must be rejected after every all iteration.
all(t, [dep | acc], upper_breadths, current_breadths, callback, rest, lock, env, cache)
:nomatch ->
{dep, rest, lock} =
case cache.(dep) do
{:loaded, cached_dep} ->
{cached_dep, rest, lock}
{:unloaded, dep, children} ->
{dep, rest, lock} = callback.(put_lock(dep, lock), rest, lock)
Mix.Dep.Loader.with_system_env(dep, fn ->
# After we invoke the callback (which may actually check out the
# dependency), we load the dependency including its latest info
# and children information.
{Mix.Dep.Loader.load(dep, children), rest, lock}
end)
end
{acc, rest, lock} =
all(t, [dep | acc], upper_breadths, current_breadths, callback, rest, lock, env, cache)
umbrella? = dep.opts[:from_umbrella]
deps = reject_non_fulfilled_optional(dep.deps, Enum.map(acc, & &1.app), umbrella?)
new_breadths = Enum.map(deps, & &1.app) ++ current_breadths
all(deps, acc, current_breadths, new_breadths, callback, rest, lock, env, cache)
end
end
defp all([], acc, _upper, _current, _callback, rest, lock, _env, _cache) do
{acc, rest, lock}
end
defp put_lock(%Mix.Dep{app: app} = dep, lock) do
put_in(dep.opts[:lock], lock[app])
end
# Look for matching and divergence in dependencies.
#
# If the same dependency is specified more than once,
# we need to guarantee they converge. If they don't
# converge, we mark them as diverged.
#
# The only exception is when the dependency that
# diverges is in the upper breadth, in those cases we
# also check for the override option and mark the dependency
# as overridden instead of diverged.
defp match_deps(list, upper_breadths, %Mix.Dep{app: app} = dep, env) do
case Enum.split_while(list, &(&1.app != app)) do
{_, []} ->
if Mix.Dep.Loader.skip?(dep, env) do
:skip
else
:nomatch
end
{pre, [%Mix.Dep{opts: other_opts} = other | pos]} ->
in_upper? = app in upper_breadths
if other.top_level and dep.top_level do
Mix.shell().error(
"warning: the dependency #{inspect(dep.app)} is " <>
"duplicated at the top level, please remove one of them"
)
end
cond do
in_upper? && other_opts[:override] ->
{:match, list}
not converge?(other, dep) ->
tag = if in_upper?, do: :overridden, else: :diverged
other = %{other | status: {tag, dep}}
{:match, pre ++ [other | pos]}
vsn = req_mismatch(other, dep) ->
other = %{other | status: {:divergedreq, vsn, dep}}
{:match, pre ++ [other | pos]}
not in_upper? and Mix.Dep.Loader.skip?(other, env) and
not Mix.Dep.Loader.skip?(dep, env) ->
dep =
dep
|> with_matching_only(other, in_upper?)
|> merge_manager(other, in_upper?)
{:replace, dep, pre ++ pos}
true ->
other =
other
|> with_matching_only(dep, in_upper?)
|> merge_manager(dep, in_upper?)
{:match, pre ++ [other | pos]}
end
end
end
defp with_matching_only(%{opts: other_opts} = other, %{opts: opts} = dep, in_upper?) do
if opts[:optional] do
other
else
with_matching_only(other, other_opts, dep, opts, in_upper?)
end
end
# When in_upper is true
#
# When a parent dependency specifies :only that is a subset
# of a child dependency, we are going to abort as the parent
# dependency must explicitly outline a superset of child
# dependencies.
#
# We could resolve such conflicts automatically but, since
# the user has likely written only: :env in their mix.exs
# file, we decided to go with a more explicit approach of
# asking them to change it to avoid later surprises and
# headaches.
defp with_matching_only(other, other_opts, dep, opts, true) do
case Keyword.fetch(other_opts, :only) do
{:ok, other_only} ->
case Keyword.fetch(opts, :only) do
{:ok, only} ->
case List.wrap(only) -- List.wrap(other_only) do
[] -> other
_ -> %{other | status: {:divergedonly, dep}}
end
:error ->
%{other | status: {:divergedonly, dep}}
end
:error ->
other
end
end
# When in_upper is false
#
# In this case, the two dependencies do not have a common path and
# only solution is to merge the environments. We have decided to
# perform it explicitly as, opposite to in_upper above, the
# dependencies are never really laid out in the parent tree.
defp with_matching_only(other, other_opts, _dep, opts, false) do
other_only = Keyword.get(other_opts, :only)
only = Keyword.get(opts, :only)
if other_only && only do
put_in(other.opts[:only], Enum.uniq(List.wrap(other_only) ++ List.wrap(only)))
else
%{other | opts: Keyword.delete(other_opts, :only)}
end
end
defp converge?(%Mix.Dep{scm: scm1, opts: opts1}, %Mix.Dep{scm: scm2, opts: opts2}) do
scm1 == scm2 and opts_equal?(opts1, opts2) and scm1.equal?(opts1, opts2)
end
defp opts_equal?(opts1, opts2) do
keys = ~w(app env compile)a
Enum.all?(keys, &(Keyword.fetch(opts1, &1) == Keyword.fetch(opts2, &1)))
end
defp reject_non_fulfilled_optional(deps) do
apps = Enum.map(deps, & &1.app)
for dep <- deps do
update_in(dep.deps, &reject_non_fulfilled_optional(&1, apps, dep.opts[:from_umbrella]))
end
end
defp reject_non_fulfilled_optional(children, upper_breadths, umbrella?) do
Enum.reject(children, fn %Mix.Dep{app: app, opts: opts} ->
opts[:optional] && app not in upper_breadths && !umbrella?
end)
end
defp merge_manager(%{manager: other_manager} = other, %{manager: manager}, in_upper?) do
%{other | manager: sort_manager(other_manager, manager, in_upper?)}
end
@managers [:mix, :rebar3, :rebar, :make]
defp sort_manager(other_manager, manager, true) do
other_manager || manager
end
defp sort_manager(other_manager, manager, false) do
to_exclude = @managers -- (List.wrap(other_manager) ++ List.wrap(manager))
List.first(@managers -- to_exclude) || other_manager || manager
end
defp req_mismatch(%Mix.Dep{status: status}, %Mix.Dep{app: app, requirement: requirement}) do
with {:ok, vsn} when not is_nil(vsn) <- status,
true <- Mix.Dep.Loader.vsn_match(requirement, vsn, app) != {:ok, true} do
vsn
else
_ -> nil
end
end
end
| 33.603133 | 97 | 0.613598 |
fff834e7a5c7667be093df92978b2ecc4b524d22 | 2,036 | ex | Elixir | clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1__person_detection_annotation.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1__person_detection_annotation.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1__person_detection_annotation.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.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1_PersonDetectionAnnotation do
@moduledoc """
Person detection annotation per video.
## Attributes
* `tracks` (*type:* `list(GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1_Track.t)`, *default:* `nil`) - The detected tracks of a person.
* `version` (*type:* `String.t`, *default:* `nil`) - Feature version.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:tracks =>
list(GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1_Track.t())
| nil,
:version => String.t() | nil
}
field(:tracks,
as: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1_Track,
type: :list
)
field(:version)
end
defimpl Poison.Decoder,
for:
GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1_PersonDetectionAnnotation do
def decode(value, options) do
GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1_PersonDetectionAnnotation.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1_PersonDetectionAnnotation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.31746 | 161 | 0.742141 |
fff842285d8982cf60f0e3ffbeacfa8572449ab5 | 589 | exs | Elixir | test/kepler_web/live/page_live_test.exs | SAAF-Alex-and-Ashton-Forces/kepler | 06cea361e5972b5ebe4e19f70793d921aca25664 | [
"MIT"
] | null | null | null | test/kepler_web/live/page_live_test.exs | SAAF-Alex-and-Ashton-Forces/kepler | 06cea361e5972b5ebe4e19f70793d921aca25664 | [
"MIT"
] | null | null | null | test/kepler_web/live/page_live_test.exs | SAAF-Alex-and-Ashton-Forces/kepler | 06cea361e5972b5ebe4e19f70793d921aca25664 | [
"MIT"
] | null | null | null | defmodule KeplerWeb.PageLiveTest do
use KeplerWeb.ConnCase
alias Kepler.Users.User
import Phoenix.LiveViewTest
setup %{conn: conn} do
# Add user to conn so we know we've got some authentication
user = %User{email: "test@example.com"}
conn = Pow.Plug.assign_current_user(conn, user, otp_app: :my_app)
{:ok, conn: conn}
end
test "disconnected and connected render", %{conn: conn} do
{:ok, page_live, disconnected_html} = live(conn, "/")
assert disconnected_html =~ "Welcome to Phoenix!"
assert render(page_live) =~ "Welcome to Phoenix!"
end
end
| 28.047619 | 69 | 0.697793 |
fff88f4c0ce68de1c58e270db4b11f1992daaa42 | 111,652 | ex | Elixir | clients/compute/lib/google_api/compute/v1/api/instances.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/instances.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/instances.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Compute.V1.Api.Instances do
@moduledoc """
API calls for all endpoints tagged `Instances`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Adds an access config to an instance's network interface.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): The instance name for this request.
- network_interface (String.t): The name of the network interface to add to this instance.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (AccessConfig):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_add_access_config(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_add_access_config(
connection,
project,
zone,
instance,
network_interface,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/addAccessConfig", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :networkInterface, network_interface)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Retrieves aggregated list of all of the instances in your project across all regions and zones.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :filter (String.t): A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel Broadwell\") AND (scheduling.automaticRestart = true).
- :maxResults (integer()): The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
- :orderBy (String.t): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy=\"creationTimestamp desc\". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported.
- :pageToken (String.t): Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.InstanceAggregatedList{}} on success
{:error, info} on failure
"""
@spec compute_instances_aggregated_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.InstanceAggregatedList.t()} | {:error, Tesla.Env.t()}
def compute_instances_aggregated_list(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/aggregated/instances", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.InstanceAggregatedList{}])
end
@doc """
Attaches an existing Disk resource to an instance. You must first create the disk before you can attach it. It is not possible to create and attach a disk at the same time. For more information, read Adding a persistent disk to your instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): The instance name for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :forceAttach (boolean()): Whether to force attach the disk even if it's currently attached to another instance.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (AttachedDisk):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_attach_disk(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_attach_disk(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:forceAttach => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/attachDisk", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Deletes the specified Instance resource. For more information, see Stopping or Deleting an Instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance resource to delete.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_delete(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/{project}/zones/{zone}/instances/{instance}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Deletes an access config from an instance's network interface.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): The instance name for this request.
- access_config (String.t): The name of the access config to delete.
- network_interface (String.t): The name of the network interface.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_delete_access_config(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_delete_access_config(
connection,
project,
zone,
instance,
access_config,
network_interface,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/deleteAccessConfig", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :accessConfig, access_config)
|> Request.add_param(:query, :networkInterface, network_interface)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Detaches a disk from an instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Instance name for this request.
- device_name (String.t): The device name of the disk to detach. Make a get() request on the instance to view currently attached disks and device names.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_detach_disk(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_detach_disk(
connection,
project,
zone,
instance,
device_name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/detachDisk", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :deviceName, device_name)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Returns the specified Instance resource. Gets a list of available instances by making a list() request.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance resource to return.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Instance{}} on success
{:error, info} on failure
"""
@spec compute_instances_get(Tesla.Env.client(), String.t(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Instance.t()} | {:error, Tesla.Env.t()}
def compute_instances_get(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/zones/{zone}/instances/{instance}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Instance{}])
end
@doc """
Gets the access control policy for a resource. May be empty if no such policy or resource exists.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- resource (String.t): Name or id of the resource for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Policy{}} on success
{:error, info} on failure
"""
@spec compute_instances_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def compute_instances_get_iam_policy(
connection,
project,
zone,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/zones/{zone}/instances/{resource}/getIamPolicy", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Policy{}])
end
@doc """
Returns the last 1 MB of serial port output from the specified instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :port (integer()): Specifies which COM or serial port to retrieve data from.
- :start (String.t): Returns output starting from a specific byte position. Use this to page through output when the output is too large to return in a single request. For the initial request, leave this field unspecified. For subsequent calls, this field should be set to the next value returned in the previous call.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.SerialPortOutput{}} on success
{:error, info} on failure
"""
@spec compute_instances_get_serial_port_output(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.SerialPortOutput.t()} | {:error, Tesla.Env.t()}
def compute_instances_get_serial_port_output(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:port => :query,
:start => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/serialPort", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.SerialPortOutput{}])
end
@doc """
Returns the Shielded Instance Identity of an instance
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name or id of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.ShieldedInstanceIdentity{}} on success
{:error, info} on failure
"""
@spec compute_instances_get_shielded_instance_identity(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.ShieldedInstanceIdentity.t()} | {:error, Tesla.Env.t()}
def compute_instances_get_shielded_instance_identity(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/{project}/zones/{zone}/instances/{instance}/getShieldedInstanceIdentity",
%{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.ShieldedInstanceIdentity{}])
end
@doc """
Creates an instance resource in the specified project using the data included in the request.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :sourceInstanceTemplate (String.t): Specifies instance template to create the instance. This field is optional. It can be a full or partial URL. For example, the following are all valid URLs to an instance template: - https://www.googleapis.com/compute/v1/projects/project/global/instanceTemplates/instanceTemplate - projects/project/global/instanceTemplates/instanceTemplate - global/instanceTemplates/instanceTemplate
- :body (Instance):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_insert(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_insert(connection, project, zone, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:sourceInstanceTemplate => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Retrieves the list of instances contained within the specified zone.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :filter (String.t): A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel Broadwell\") AND (scheduling.automaticRestart = true).
- :maxResults (integer()): The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
- :orderBy (String.t): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy=\"creationTimestamp desc\". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported.
- :pageToken (String.t): Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.InstanceList{}} on success
{:error, info} on failure
"""
@spec compute_instances_list(Tesla.Env.client(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.InstanceList.t()} | {:error, Tesla.Env.t()}
def compute_instances_list(connection, project, zone, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/zones/{zone}/instances", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.InstanceList{}])
end
@doc """
Retrieves the list of referrers to instances contained within the specified zone. For more information, read Viewing Referrers to VM Instances.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the target instance scoping this request, or '-' if the request should span over all instances in the container.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :filter (String.t): A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel Broadwell\") AND (scheduling.automaticRestart = true).
- :maxResults (integer()): The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
- :orderBy (String.t): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy=\"creationTimestamp desc\". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported.
- :pageToken (String.t): Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.InstanceListReferrers{}} on success
{:error, info} on failure
"""
@spec compute_instances_list_referrers(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.InstanceListReferrers.t()} | {:error, Tesla.Env.t()}
def compute_instances_list_referrers(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/referrers", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.InstanceListReferrers{}])
end
@doc """
Performs a reset on the instance. This is a hard reset the VM does not do a graceful shutdown. For more information, see Resetting an instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_reset(Tesla.Env.client(), String.t(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_reset(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/reset", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Sets deletion protection on the instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- resource (String.t): Name or id of the resource for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :deletionProtection (boolean()): Whether the resource should be protected against deletion.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_deletion_protection(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_deletion_protection(
connection,
project,
zone,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:deletionProtection => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{resource}/setDeletionProtection", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Sets the auto-delete flag for a disk attached to an instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): The instance name for this request.
- auto_delete (boolean()): Whether to auto-delete the disk when the instance is deleted.
- device_name (String.t): The device name of the disk to modify. Make a get() request on the instance to view currently attached disks and device names.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_disk_auto_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
boolean(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_disk_auto_delete(
connection,
project,
zone,
instance,
auto_delete,
device_name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/setDiskAutoDelete", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :autoDelete, auto_delete)
|> Request.add_param(:query, :deviceName, device_name)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- resource (String.t): Name or id of the resource for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (ZoneSetPolicyRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Policy{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_iam_policy(
connection,
project,
zone,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{resource}/setIamPolicy", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Policy{}])
end
@doc """
Sets labels on an instance. To learn more about labels, read the Labeling Resources documentation.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstancesSetLabelsRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_labels(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_labels(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/setLabels", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Changes the number and/or type of accelerator for a stopped instance to the values specified in the request.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstancesSetMachineResourcesRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_machine_resources(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_machine_resources(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/setMachineResources", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Changes the machine type for a stopped instance to the machine type specified in the request.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstancesSetMachineTypeRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_machine_type(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_machine_type(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/setMachineType", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Sets metadata for the specified instance to the data included in the request.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (Metadata):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_metadata(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_metadata(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/setMetadata", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Changes the minimum CPU platform that this instance should use. This method can only be called on a stopped instance. For more information, read Specifying a Minimum CPU Platform.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstancesSetMinCpuPlatformRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_min_cpu_platform(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_min_cpu_platform(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/setMinCpuPlatform", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Sets an instance's scheduling options.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Instance name for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (Scheduling):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_scheduling(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_scheduling(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/setScheduling", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Sets the service account on the instance. For more information, read Changing the service account and access scopes for an instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance resource to start.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstancesSetServiceAccountRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_service_account(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_service_account(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/setServiceAccount", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Sets the Shielded Instance integrity policy for an instance. You can only use this method on a running instance. This method supports PATCH semantics and uses the JSON merge patch format and processing rules.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name or id of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (ShieldedInstanceIntegrityPolicy):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_shielded_instance_integrity_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_shielded_instance_integrity_policy(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url(
"/{project}/zones/{zone}/instances/{instance}/setShieldedInstanceIntegrityPolicy",
%{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Sets network tags for the specified instance to the data included in the request.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (Tags):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_set_tags(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_set_tags(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/setTags", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Simulates a maintenance event on the instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_simulate_maintenance_event(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_simulate_maintenance_event(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/simulateMaintenanceEvent", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Starts an instance that was stopped using the instances().stop method. For more information, see Restart an instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance resource to start.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_start(Tesla.Env.client(), String.t(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_start(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/start", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Starts an instance that was stopped using the instances().stop method. For more information, see Restart an instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance resource to start.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstancesStartWithEncryptionKeyRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_start_with_encryption_key(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_start_with_encryption_key(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/startWithEncryptionKey", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Stops a running instance, shutting it down cleanly, and allows you to restart the instance at a later time. Stopped instances do not incur VM usage charges while they are stopped. However, resources that the VM is using, such as persistent disks and static IP addresses, will continue to be charged until they are deleted. For more information, see Stopping an instance.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name of the instance resource to stop.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_stop(Tesla.Env.client(), String.t(), String.t(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_stop(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/stop", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Returns permissions that a caller has on the specified resource.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- resource (String.t): Name or id of the resource for this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (TestPermissionsRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.TestPermissionsResponse{}} on success
{:error, info} on failure
"""
@spec compute_instances_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.TestPermissionsResponse.t()} | {:error, Tesla.Env.t()}
def compute_instances_test_iam_permissions(
connection,
project,
zone,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{resource}/testIamPermissions", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.TestPermissionsResponse{}])
end
@doc """
Updates the specified access config from an instance's network interface with the data included in the request. This method supports PATCH semantics and uses the JSON merge patch format and processing rules.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): The instance name for this request.
- network_interface (String.t): The name of the network interface where the access config is attached.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (AccessConfig):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_update_access_config(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_update_access_config(
connection,
project,
zone,
instance,
network_interface,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/updateAccessConfig", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :networkInterface, network_interface)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Updates an instance's network interface. This method follows PATCH semantics.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): The instance name for this request.
- network_interface (String.t): The name of the network interface to update.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (NetworkInterface):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_update_network_interface(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_update_network_interface(
connection,
project,
zone,
instance,
network_interface,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/{project}/zones/{zone}/instances/{instance}/updateNetworkInterface", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :networkInterface, network_interface)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Updates the Shielded Instance config for an instance. You can only use this method on a stopped instance. This method supports PATCH semantics and uses the JSON merge patch format and processing rules.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone for this request.
- instance (String.t): Name or id of the instance scoping this request.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (ShieldedInstanceConfig):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instances_update_shielded_instance_config(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instances_update_shielded_instance_config(
connection,
project,
zone,
instance,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url(
"/{project}/zones/{zone}/instances/{instance}/updateShieldedInstanceConfig",
%{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"instance" => URI.encode(instance, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
end
| 49.272727 | 1,213 | 0.679549 |
fff8a6da43ddfaf6749ffcbb1fafe95f6312e284 | 987 | ex | Elixir | lib/ingram_marketplace/model/subscription.ex | fbettag/ingram_marketplace.ex | 1c63d391707058fb8cf58fdefd54e2ade97acf4b | [
"MIT"
] | null | null | null | lib/ingram_marketplace/model/subscription.ex | fbettag/ingram_marketplace.ex | 1c63d391707058fb8cf58fdefd54e2ade97acf4b | [
"MIT"
] | null | null | null | lib/ingram_marketplace/model/subscription.ex | fbettag/ingram_marketplace.ex | 1c63d391707058fb8cf58fdefd54e2ade97acf4b | [
"MIT"
] | null | null | null | defmodule Ingram.Marketplace.Model.Subscription do
@moduledoc """
The representation of a subscription created when an order to a product is processed.
"""
@derive [Poison.Encoder]
defstruct [
:id,
:customerId,
:status,
:renewalStatus,
:creationDate,
:renewalDate,
:lastModifiedDate
]
@type t :: %__MODULE__{
:id => String.t(),
:customerId => String.t() | nil,
:status => String.t() | nil,
:renewalStatus => boolean() | nil,
:creationDate => Date.t() | nil,
:renewalDate => Date.t() | nil,
:lastModifiedDate => Date.t() | nil
}
end
defimpl Poison.Decoder, for: Ingram.Marketplace.Model.Subscription do
import Ingram.Marketplace.Deserializer
def decode(value, options) do
value
|> deserialize(:creationDate, :date, nil, options)
|> deserialize(:renewalDate, :date, nil, options)
|> deserialize(:lastModifiedDate, :date, nil, options)
end
end
| 25.973684 | 87 | 0.622087 |
fff8c90b824bae97006c025542d8979ebd3dc9e0 | 523 | ex | Elixir | lib/lakeland/handler/supervisor.ex | nonsense2020/lakeland | f7f928562ef8f81193f07d80e5d5c79cc919422c | [
"MIT"
] | 3 | 2016-04-27T14:42:30.000Z | 2016-05-11T13:05:46.000Z | lib/lakeland/handler/supervisor.ex | lerencao/lakeland | f7f928562ef8f81193f07d80e5d5c79cc919422c | [
"MIT"
] | 5 | 2016-02-28T08:15:40.000Z | 2020-02-10T21:16:52.000Z | lib/lakeland/handler/supervisor.ex | nonsense2020/lakeland | f7f928562ef8f81193f07d80e5d5c79cc919422c | [
"MIT"
] | null | null | null | defmodule Lakeland.Handler.Supervisor do
use Supervisor
def start_link(handler, conn_type) do
Supervisor.start_link(__MODULE__, {handler, conn_type})
end
def init({handler, conn_type}) do
children = [
case conn_type do
:worker ->
worker(handler, [], restart: :temporary)
:supervisor ->
supervisor(handler, [], restart: :temporary)
end
]
supervise_opts = [
strategy: :simple_one_for_one
]
supervise(children, supervise_opts)
end
end
| 21.791667 | 59 | 0.640535 |
fff91abf2d10075f16382ddf99b7986d00c38830 | 10,159 | exs | Elixir | lib/elixir/test/elixir/version_test.exs | IvanRublev/elixir | 1ce201aa1ebbfc1666c4e4bde64f706a89629d59 | [
"Apache-2.0"
] | 2 | 2020-06-02T18:00:28.000Z | 2021-12-10T03:21:42.000Z | lib/elixir/test/elixir/version_test.exs | IvanRublev/elixir | 1ce201aa1ebbfc1666c4e4bde64f706a89629d59 | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/version_test.exs | IvanRublev/elixir | 1ce201aa1ebbfc1666c4e4bde64f706a89629d59 | [
"Apache-2.0"
] | null | null | null | Code.require_file("test_helper.exs", __DIR__)
defmodule VersionTest do
use ExUnit.Case, async: true
doctest Version
alias Version.Parser
test "compare/2 with valid versions" do
assert Version.compare("1.0.1", "1.0.0") == :gt
assert Version.compare("1.1.0", "1.0.1") == :gt
assert Version.compare("2.1.1", "1.2.2") == :gt
assert Version.compare("1.0.0", "1.0.0-dev") == :gt
assert Version.compare("1.2.3-dev", "0.1.2") == :gt
assert Version.compare("1.0.0-a.b", "1.0.0-a") == :gt
assert Version.compare("1.0.0-b", "1.0.0-a.b") == :gt
assert Version.compare("1.0.0-a", "1.0.0-0") == :gt
assert Version.compare("1.0.0-a.b", "1.0.0-a.a") == :gt
assert Version.compare("1.0.0", "1.0.1") == :lt
assert Version.compare("1.0.1", "1.1.0") == :lt
assert Version.compare("1.2.2", "2.1.1") == :lt
assert Version.compare("1.0.0-dev", "1.0.0") == :lt
assert Version.compare("0.1.2", "1.2.3-dev") == :lt
assert Version.compare("1.0.0-a", "1.0.0-a.b") == :lt
assert Version.compare("1.0.0-a.b", "1.0.0-b") == :lt
assert Version.compare("1.0.0-0", "1.0.0-a") == :lt
assert Version.compare("1.0.0-a.a", "1.0.0-a.b") == :lt
assert Version.compare("1.0.0", "1.0.0") == :eq
assert Version.compare("1.0.0-dev", "1.0.0-dev") == :eq
assert Version.compare("1.0.0-a", "1.0.0-a") == :eq
end
test "compare/2 with invalid versions" do
assert_raise Version.InvalidVersionError, fn ->
Version.compare("1.0", "1.0.0")
end
assert_raise Version.InvalidVersionError, fn ->
Version.compare("1.0.0-dev", "1.0")
end
assert_raise Version.InvalidVersionError, fn ->
Version.compare("foo", "1.0.0-a")
end
end
test "lexes specifications properly" do
assert Parser.lexer("== != > >= < <= ~>", []) == [:==, :!=, :>, :>=, :<, :<=, :~>]
assert Parser.lexer("2.3.0", []) == [:==, {2, 3, 0, [], []}]
assert Parser.lexer("!2.3.0", []) == [:!=, {2, 3, 0, [], []}]
assert Parser.lexer(">>=", []) == [:>, :>=]
assert Parser.lexer(">2.4.0", []) == [:>, {2, 4, 0, [], []}]
assert Parser.lexer("> 2.4.0", []) == [:>, {2, 4, 0, [], []}]
assert Parser.lexer(" > 2.4.0", []) == [:>, {2, 4, 0, [], []}]
assert Parser.lexer(" or 2.1.0", []) == [:||, :==, {2, 1, 0, [], []}]
assert Parser.lexer(" and 2.1.0", []) == [:&&, :==, {2, 1, 0, [], []}]
assert Parser.lexer(">= 2.0.0 and < 2.1.0", []) == [
:>=,
{2, 0, 0, [], []},
:&&,
:<,
{2, 1, 0, [], []}
]
assert Parser.lexer(">= 2.0.0 or < 2.1.0", []) == [
:>=,
{2, 0, 0, [], []},
:||,
:<,
{2, 1, 0, [], []}
]
end
test "parse/1" do
assert {:ok, %Version{major: 1, minor: 2, patch: 3}} = Version.parse("1.2.3")
assert {:ok, %Version{major: 1, minor: 4, patch: 5}} = Version.parse("1.4.5+ignore")
assert {:ok, %Version{major: 0, minor: 0, patch: 1}} = Version.parse("0.0.1+sha.0702245")
assert {:ok, %Version{major: 1, minor: 4, patch: 5, pre: ["6-g3318bd5"]}} =
Version.parse("1.4.5-6-g3318bd5")
assert {:ok, %Version{major: 1, minor: 4, patch: 5, pre: [6, 7, "eight"]}} =
Version.parse("1.4.5-6.7.eight")
assert {:ok, %Version{major: 1, minor: 4, patch: 5, pre: ["6-g3318bd5"]}} =
Version.parse("1.4.5-6-g3318bd5+ignore")
assert Version.parse("foobar") == :error
assert Version.parse("2") == :error
assert Version.parse("2.") == :error
assert Version.parse("2.3") == :error
assert Version.parse("2.3.") == :error
assert Version.parse("2.3.0-") == :error
assert Version.parse("2.3.0+") == :error
assert Version.parse("2.3.0.") == :error
assert Version.parse("2.3.0.4") == :error
assert Version.parse("2.3.-rc.1") == :error
assert Version.parse("2.3.+rc.1") == :error
assert Version.parse("2.3.0-01") == :error
assert Version.parse("2.3.00-1") == :error
assert Version.parse("2.3.00") == :error
assert Version.parse("2.03.0") == :error
assert Version.parse("02.3.0") == :error
assert Version.parse("0. 0.0") == :error
assert Version.parse("0.1.0-&&pre") == :error
end
test "Kernel.to_string/1" do
assert Version.parse!("1.0.0") |> to_string == "1.0.0"
assert Version.parse!("1.0.0-dev") |> to_string == "1.0.0-dev"
assert Version.parse!("1.0.0+lol") |> to_string == "1.0.0+lol"
assert Version.parse!("1.0.0-dev+lol") |> to_string == "1.0.0-dev+lol"
assert Version.parse!("1.0.0-0") |> to_string == "1.0.0-0"
assert Version.parse!("1.0.0-rc.0") |> to_string == "1.0.0-rc.0"
assert %Version{major: 1, minor: 0, patch: 0} |> to_string() == "1.0.0"
end
test "match?/2 with invalid versions" do
assert_raise Version.InvalidVersionError, fn ->
Version.match?("foo", "2.3.0")
end
assert_raise Version.InvalidVersionError, fn ->
Version.match?("2.3", "2.3.0")
end
assert_raise Version.InvalidRequirementError, fn ->
Version.match?("2.3.0", "foo")
end
assert_raise Version.InvalidRequirementError, fn ->
Version.match?("2.3.0", "2.3")
end
end
test "==" do
assert Version.match?("2.3.0", "2.3.0")
refute Version.match?("2.4.0", "2.3.0")
assert Version.match?("2.3.0", "== 2.3.0")
refute Version.match?("2.4.0", "== 2.3.0")
assert Version.match?("1.0.0", "1.0.0")
assert Version.match?("1.0.0", "1.0.0")
assert Version.match?("1.2.3-alpha", "1.2.3-alpha")
assert Version.match?("0.9.3", "== 0.9.3+dev")
{:ok, vsn} = Version.parse("2.3.0")
assert Version.match?(vsn, "2.3.0")
end
test "!=" do
assert Version.match?("2.4.0", "!2.3.0")
refute Version.match?("2.3.0", "!2.3.0")
assert Version.match?("2.4.0", "!= 2.3.0")
refute Version.match?("2.3.0", "!= 2.3.0")
end
test ">" do
assert Version.match?("2.4.0", "> 2.3.0")
refute Version.match?("2.2.0", "> 2.3.0")
refute Version.match?("2.3.0", "> 2.3.0")
assert Version.match?("1.2.3", "> 1.2.3-alpha")
assert Version.match?("1.2.3-alpha.1", "> 1.2.3-alpha")
assert Version.match?("1.2.3-alpha.beta.sigma", "> 1.2.3-alpha.beta")
refute Version.match?("1.2.3-alpha.10", "< 1.2.3-alpha.1")
refute Version.match?("0.10.2-dev", "> 0.10.2")
end
test ">=" do
assert Version.match?("2.4.0", ">= 2.3.0")
refute Version.match?("2.2.0", ">= 2.3.0")
assert Version.match?("2.3.0", ">= 2.3.0")
assert Version.match?("2.0.0", ">= 1.0.0")
assert Version.match?("1.0.0", ">= 1.0.0")
end
test "<" do
assert Version.match?("2.2.0", "< 2.3.0")
refute Version.match?("2.4.0", "< 2.3.0")
refute Version.match?("2.3.0", "< 2.3.0")
assert Version.match?("0.10.2-dev", "< 0.10.2")
refute Version.match?("1.0.0", "< 1.0.0-dev")
refute Version.match?("1.2.3-dev", "< 0.1.2")
end
test "<=" do
assert Version.match?("2.2.0", "<= 2.3.0")
refute Version.match?("2.4.0", "<= 2.3.0")
assert Version.match?("2.3.0", "<= 2.3.0")
end
describe "~>" do
test "regular cases" do
assert Version.match?("3.0.0", "~> 3.0")
assert Version.match?("3.2.0", "~> 3.0")
refute Version.match?("4.0.0", "~> 3.0")
refute Version.match?("4.4.0", "~> 3.0")
assert Version.match?("3.0.2", "~> 3.0.0")
assert Version.match?("3.0.0", "~> 3.0.0")
refute Version.match?("3.1.0", "~> 3.0.0")
refute Version.match?("3.4.0", "~> 3.0.0")
assert Version.match?("3.6.0", "~> 3.5")
assert Version.match?("3.5.0", "~> 3.5")
refute Version.match?("4.0.0", "~> 3.5")
refute Version.match?("5.0.0", "~> 3.5")
assert Version.match?("3.5.2", "~> 3.5.0")
assert Version.match?("3.5.4", "~> 3.5.0")
refute Version.match?("3.6.0", "~> 3.5.0")
refute Version.match?("3.6.3", "~> 3.5.0")
assert Version.match?("0.9.3", "~> 0.9.3-dev")
refute Version.match?("0.10.0", "~> 0.9.3-dev")
refute Version.match?("0.3.0-dev", "~> 0.2.0")
assert Version.match?("1.11.0-dev", "~> 1.11-dev")
assert Version.match?("1.11.0", "~> 1.11-dev")
assert Version.match?("1.12.0", "~> 1.11-dev")
refute Version.match?("1.10.0", "~> 1.11-dev")
refute Version.match?("2.0.0", "~> 1.11-dev")
assert_raise Version.InvalidRequirementError, fn ->
Version.match?("3.0.0", "~> 3")
end
end
test "~> will never include pre-release versions of its upper bound" do
refute Version.match?("2.2.0-dev", "~> 2.1.0")
refute Version.match?("2.2.0-dev", "~> 2.1.0", allow_pre: false)
refute Version.match?("2.2.0-dev", "~> 2.1.0-dev")
refute Version.match?("2.2.0-dev", "~> 2.1.0-dev", allow_pre: false)
end
end
test "allow_pre" do
assert Version.match?("1.1.0", "~> 1.0", allow_pre: true)
assert Version.match?("1.1.0", "~> 1.0", allow_pre: false)
assert Version.match?("1.1.0-beta", "~> 1.0", allow_pre: true)
refute Version.match?("1.1.0-beta", "~> 1.0", allow_pre: false)
assert Version.match?("1.0.1-beta", "~> 1.0.0-beta", allow_pre: false)
assert Version.match?("1.1.0", ">= 1.0.0", allow_pre: true)
assert Version.match?("1.1.0", ">= 1.0.0", allow_pre: false)
assert Version.match?("1.1.0-beta", ">= 1.0.0", allow_pre: true)
refute Version.match?("1.1.0-beta", ">= 1.0.0", allow_pre: false)
assert Version.match?("1.1.0-beta", ">= 1.0.0-beta", allow_pre: false)
end
test "and" do
assert Version.match?("0.9.3", "> 0.9.0 and < 0.10.0")
refute Version.match?("0.10.2", "> 0.9.0 and < 0.10.0")
end
test "or" do
assert Version.match?("0.9.1", "0.9.1 or 0.9.3 or 0.9.5")
assert Version.match?("0.9.3", "0.9.1 or 0.9.3 or 0.9.5")
assert Version.match?("0.9.5", "0.9.1 or 0.9.3 or 0.9.5")
refute Version.match?("0.9.6", "0.9.1 or 0.9.3 or 0.9.5")
end
test "compile requirement" do
{:ok, req} = Version.parse_requirement("1.2.3")
req = Version.compile_requirement(req)
assert Version.match?("1.2.3", req)
refute Version.match?("1.2.4", req)
end
end
| 35.645614 | 93 | 0.534403 |
fff91af22c79888daf2a9990182e8bc91150b836 | 1,245 | ex | Elixir | lib/splitwise/oauth2/behaviour.ex | nathanbegbie/ex_splitwise | 6de8b9f59db9834b342b86dfcd5c41354f349e5d | [
"MIT"
] | 3 | 2019-09-29T04:15:29.000Z | 2021-04-02T14:52:04.000Z | lib/splitwise/oauth2/behaviour.ex | nathanbegbie/ex_splitwise | 6de8b9f59db9834b342b86dfcd5c41354f349e5d | [
"MIT"
] | null | null | null | lib/splitwise/oauth2/behaviour.ex | nathanbegbie/ex_splitwise | 6de8b9f59db9834b342b86dfcd5c41354f349e5d | [
"MIT"
] | 1 | 2022-02-22T15:32:16.000Z | 2022-02-22T15:32:16.000Z | defmodule ExSplitwise.OAuth2.Behaviour do
@moduledoc false
@type authorize_url :: binary
@type body :: any
@type client_id :: binary
@type client_secret :: binary
@type headers :: [{binary, binary}]
@type param :: binary | %{binary => param} | [param]
@type params :: %{binary => param} | Keyword.t()
@type redirect_uri :: binary
@type ref :: reference | nil
@type request_opts :: Keyword.t()
@type serializers :: %{binary => module}
@type site :: binary
@type strategy :: module
@type token :: AccessToken.t() | nil
@type token_method :: :post | :get | atom
@type token_url :: binary
@typep client :: %{
authorize_url: authorize_url,
client_id: client_id,
client_secret: client_secret,
headers: headers,
params: params,
redirect_uri: redirect_uri,
ref: ref,
request_opts: request_opts,
serializers: serializers,
site: site,
strategy: strategy,
token: token,
token_method: token_method,
token_url: token_url
}
@callback authorize_url!(client) :: binary
@callback get_token!(client, list) :: client
@callback new(Keyword.t) :: client
end
| 29.642857 | 54 | 0.608032 |
fff91f8e52e477129fb885912aa80a695a82231d | 1,816 | exs | Elixir | mix.exs | palm86/hex_flora | 26dc95f948763507b4d7cb643d98696936b45e07 | [
"CC-BY-3.0"
] | null | null | null | mix.exs | palm86/hex_flora | 26dc95f948763507b4d7cb643d98696936b45e07 | [
"CC-BY-3.0"
] | 8 | 2021-06-04T18:50:28.000Z | 2021-08-08T19:43:46.000Z | mix.exs | palm86/hex_flora | 26dc95f948763507b4d7cb643d98696936b45e07 | [
"CC-BY-3.0"
] | null | null | null | defmodule HexFlora.MixProject do
use Mix.Project
def project do
[
app: :hex_flora,
version: "0.1.0",
elixir: "~> 1.11",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix, :gettext] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
aliases: aliases(),
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {HexFlora.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:phoenix, "~> 1.6.0"},
{:phoenix_html, "~> 3.0.4"},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:phoenix_live_dashboard, "~> 0.5"},
{:telemetry_metrics, "~> 0.6"},
{:telemetry_poller, "~> 0.5"},
{:gettext, "~> 0.11"},
{:jason, "~> 1.0"},
{:plug_cowboy, "~> 2.0"},
{:nimble_publisher, "~> 0.1.1"},
{:esbuild, "~> 0.2", runtime: Mix.env() == :dev},
{:dart_sass, "~> 0.2", runtime: Mix.env() == :dev}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to install project dependencies and perform other setup tasks, run:
#
# $ mix setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
setup: ["deps.get"],
"assets.deploy": [
"esbuild default --minify --loader:.jpg=file",
"sass default --no-source-map --style=compressed",
"phx.digest"
]
]
end
end
| 26.705882 | 84 | 0.57489 |
fff926ebce03856188158dde1ee1e92b29baa021 | 22,596 | ex | Elixir | clients/compute/lib/google_api/compute/v1/api/ssl_policies.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/compute/lib/google_api/compute/v1/api/ssl_policies.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/ssl_policies.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Compute.V1.Api.SslPolicies do
@moduledoc """
API calls for all endpoints tagged `SslPolicies`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Deletes the specified SSL policy. The SSL policy resource can be deleted only if it is not in use by any TargetHttpsProxy or TargetSslProxy resources.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `ssl_policy` (*type:* `String.t`) - Name of the SSL policy to delete. The name must be 1-63 characters long, and comply with RFC1035.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_ssl_policies_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_ssl_policies_delete(
connection,
project,
ssl_policy,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/{project}/global/sslPolicies/{sslPolicy}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"sslPolicy" => URI.encode(ssl_policy, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Lists all of the ordered rules present in a single specified policy.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `ssl_policy` (*type:* `String.t`) - Name of the SSL policy to update. The name must be 1-63 characters long, and comply with RFC1035.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.SslPolicy{}}` on success
* `{:error, info}` on failure
"""
@spec compute_ssl_policies_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.SslPolicy.t()} | {:error, Tesla.Env.t()}
def compute_ssl_policies_get(connection, project, ssl_policy, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/sslPolicies/{sslPolicy}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"sslPolicy" => URI.encode(ssl_policy, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.SslPolicy{}])
end
@doc """
Returns the specified SSL policy resource. Gets a list of available SSL policies by making a list() request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.Compute.V1.Model.SslPolicy.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_ssl_policies_insert(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_ssl_policies_insert(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/global/sslPolicies", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Lists all the SSL policies that have been configured for the specified project.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <.
For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance.
You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true).
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by name or creationTimestamp desc is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.SslPoliciesList{}}` on success
* `{:error, info}` on failure
"""
@spec compute_ssl_policies_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.SslPoliciesList.t()} | {:error, Tesla.Env.t()}
def compute_ssl_policies_list(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/sslPolicies", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.SslPoliciesList{}])
end
@doc """
Lists all features that can be specified in the SSL policy when using custom profile.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <.
For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance.
You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true).
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by name or creationTimestamp desc is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.SslPoliciesListAvailableFeaturesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec compute_ssl_policies_list_available_features(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.SslPoliciesListAvailableFeaturesResponse.t()}
| {:error, Tesla.Env.t()}
def compute_ssl_policies_list_available_features(
connection,
project,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/sslPolicies/listAvailableFeatures", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Compute.V1.Model.SslPoliciesListAvailableFeaturesResponse{}]
)
end
@doc """
Patches the specified SSL policy with the data included in the request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `ssl_policy` (*type:* `String.t`) - Name of the SSL policy to update. The name must be 1-63 characters long, and comply with RFC1035.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.Compute.V1.Model.SslPolicy.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_ssl_policies_patch(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_ssl_policies_patch(
connection,
project,
ssl_policy,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/{project}/global/sslPolicies/{sslPolicy}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"sslPolicy" => URI.encode(ssl_policy, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
end
| 54.711864 | 414 | 0.667242 |
fff97456f4b36099f332147a4c542acfff79d3b0 | 6,528 | ex | Elixir | lib/kinesis_client/stream/shard/lease.ex | knocklabs/kcl_ex | d032744cb037cea351af1fad826923253bced2b4 | [
"Apache-2.0"
] | null | null | null | lib/kinesis_client/stream/shard/lease.ex | knocklabs/kcl_ex | d032744cb037cea351af1fad826923253bced2b4 | [
"Apache-2.0"
] | null | null | null | lib/kinesis_client/stream/shard/lease.ex | knocklabs/kcl_ex | d032744cb037cea351af1fad826923253bced2b4 | [
"Apache-2.0"
] | null | null | null | defmodule KinesisClient.Stream.Shard.Lease do
@moduledoc false
require Logger
use GenServer
alias KinesisClient.Stream.AppState
alias KinesisClient.Stream.AppState.ShardLease
alias KinesisClient.Stream.Shard.Pipeline
@default_renew_interval 30_000
# The amount of time that must have elapsed since the least_count was incremented in order to
# consider the lease expired.
@default_lease_expiry 90_001
def start_link(opts) do
name = name(opts[:app_name], opts[:shard_id])
GenServer.start_link(__MODULE__, opts, name: name)
end
defstruct [
:app_name,
:shard_id,
:lease_owner,
:lease_count,
:lease_count_increment_time,
:app_state_opts,
:renew_interval,
:notify,
:lease_expiry,
:lease_holder
]
@type t :: %__MODULE__{}
@impl GenServer
def init(opts) do
state = %__MODULE__{
app_name: opts[:app_name],
shard_id: opts[:shard_id],
lease_owner: opts[:lease_owner],
app_state_opts: Keyword.get(opts, :app_state_opts, []),
renew_interval: Keyword.get(opts, :renew_interval, @default_renew_interval),
lease_expiry: Keyword.get(opts, :lease_expiry, @default_lease_expiry),
lease_count_increment_time: current_time(),
notify: Keyword.get(opts, :notify)
}
Process.send_after(self(), :take_or_renew_lease, state.renew_interval)
Logger.debug("Starting KinesisClient.Stream.Lease: #{inspect(state)}")
{:ok, state, {:continue, :initialize}}
end
@impl GenServer
def handle_continue(:initialize, state) do
new_state =
case get_lease(state) do
:not_found ->
Logger.debug(
"No existing lease record found in AppState: " <>
"[app_name: #{state.app_name}, shard_id: #{state.shard_id}]"
)
create_lease(state)
%ShardLease{} = s ->
take_or_renew_lease(s, state)
end
if new_state.lease_holder do
:ok = Pipeline.start(state.app_name, state.shard_id)
end
notify({:initialized, new_state}, state)
{:noreply, new_state}
end
@impl GenServer
def handle_info(:take_or_renew_lease, state) do
Process.send_after(self(), :take_or_renew_lease, state.renew_interval)
reply =
case get_lease(state) do
%ShardLease{} = s ->
{:noreply, take_or_renew_lease(s, state)}
{:error, e} ->
Logger.error("Error fetching shard #{state.share_id}: #{inspect(e)}")
{:noreply, state}
end
reply
end
@spec take_or_renew_lease(shard_lease :: ShardLease.t(), state :: t()) :: t()
defp take_or_renew_lease(shard_lease, %{lease_expiry: lease_expiry} = state) do
cond do
shard_lease.lease_owner == state.lease_owner ->
renew_lease(shard_lease, state)
current_time() - state.lease_count_increment_time > lease_expiry ->
take_lease(shard_lease, state)
true ->
state =
case shard_lease.lease_count != state.lease_count do
true ->
set_lease_count(shard_lease.lease_count, false, state)
false ->
%{state | lease_holder: false}
end
Logger.debug(
"Lease is owned by another node, and could not be taken: [shard_id: #{state.shard_id}, " <>
"lease_owner: #{state.lease_owner}, lease_count: #{state.lease_count}]"
)
notify({:tracking_lease, state}, state)
state
end
end
defp set_lease_count(lease_count, is_lease_holder, %__MODULE__{} = state) do
%{
state
| lease_count: lease_count,
lease_count_increment_time: current_time(),
lease_holder: is_lease_holder
}
end
defp get_lease(state) do
AppState.get_lease(state.app_name, state.shard_id, state.app_state_opts)
end
@spec create_lease(state :: t()) :: t()
defp create_lease(%{app_state_opts: opts, app_name: app_name, lease_owner: lease_owner} = state) do
Logger.debug(
"Creating lease: [app_name: #{app_name}, shard_id: #{state.shard_id}, lease_owner: " <>
"#{lease_owner}]"
)
case AppState.create_lease(app_name, state.shard_id, lease_owner, opts) do
:ok -> %{state | lease_holder: true, lease_count: 1}
:already_exists -> %{state | lease_holder: false}
end
end
@spec renew_lease(shard_lease :: ShardLease.t(), state :: t()) :: t()
defp renew_lease(shard_lease, %{app_state_opts: opts, app_name: app_name} = state) do
expected = shard_lease.lease_count + 1
Logger.debug(
"Renewing lease: [app_name: #{app_name}, shard_id: #{state.shard_id}, lease_owner: " <>
"#{state.lease_owner}]"
)
case AppState.renew_lease(app_name, shard_lease, opts) do
{:ok, ^expected} ->
state = set_lease_count(expected, true, state)
notify({:lease_renewed, state}, state)
state
{:error, :lease_renew_failed} ->
Logger.debug(
"Failed to renew lease, stopping producer: [app_name: #{app_name}, " <>
"shard_id: #{state.shard_id}, lease_owner: #{state.lease_owner}]"
)
:ok = Pipeline.stop(app_name, state.shard_id)
%{state | lease_holder: false, lease_count_increment_time: current_time()}
{:error, e} ->
Logger.error("Error trying to renew lease for #{state.shard_id}: #{inspect(e)}")
state
end
end
defp take_lease(_shard_lease, %{app_state_opts: opts, app_name: app_name} = state) do
expected = state.lease_count + 1
Logger.debug(
"Attempting to take lease: [lease_owner: #{state.lease_owner}, shard_id: #{state.shard_id}]"
)
case AppState.take_lease(app_name, state.shard_id, state.lease_owner, state.lease_count, opts) do
{:ok, ^expected} ->
state = %{
state
| lease_holder: true,
lease_count: expected,
lease_count_increment_time: current_time()
}
notify({:lease_taken, state}, state)
:ok = Pipeline.start(app_name, state.shard_id)
state
{:error, :lease_take_failed} ->
# TODO
# :ok = Processor.ensure_halted(state)
%{state | lease_holder: false, lease_count_increment_time: current_time()}
end
end
defp notify(_msg, %{notify: nil}) do
:ok
end
defp notify(msg, %{notify: notify}) do
send(notify, msg)
:ok
end
defp current_time do
System.monotonic_time(:millisecond)
end
def name(app_name, shard_id) do
Module.concat([__MODULE__, app_name, shard_id])
end
end
| 28.884956 | 101 | 0.643536 |
fff9d59ea07cb258a286dff597ee0e9585f74980 | 204 | exs | Elixir | ros/ros_ui_admin/test/ros_ui_admin_web/controllers/page_controller_test.exs | kujua/elixir-handbook | 4185ad8da7f652fdb59c799dc58bcb33fda10475 | [
"Apache-2.0"
] | 1 | 2019-07-01T18:47:28.000Z | 2019-07-01T18:47:28.000Z | ros/ros_ui_admin/test/ros_ui_admin_web/controllers/page_controller_test.exs | kujua/elixir-handbook | 4185ad8da7f652fdb59c799dc58bcb33fda10475 | [
"Apache-2.0"
] | 4 | 2020-07-17T16:57:18.000Z | 2021-05-09T23:50:52.000Z | ros/ros_ui_admin/test/ros_ui_admin_web/controllers/page_controller_test.exs | kujua/elixir-handbook | 4185ad8da7f652fdb59c799dc58bcb33fda10475 | [
"Apache-2.0"
] | null | null | null | defmodule Ros.AdminWeb.PageControllerTest do
use Ros.AdminWeb.ConnCase
test "GET /", %{conn: conn} do
conn = get(conn, "/")
assert html_response(conn, 200) =~ "Welcome to Phoenix!"
end
end
| 22.666667 | 60 | 0.676471 |
fff9d7a948b27ef5799df0028b36936e58d211d4 | 1,731 | ex | Elixir | apps/ui/lib/ui/pin.ex | joshuawscott/led_control | e7851442b70dfb9940d5bd81463cc05e619b4faa | [
"MIT"
] | null | null | null | apps/ui/lib/ui/pin.ex | joshuawscott/led_control | e7851442b70dfb9940d5bd81463cc05e619b4faa | [
"MIT"
] | null | null | null | apps/ui/lib/ui/pin.ex | joshuawscott/led_control | e7851442b70dfb9940d5bd81463cc05e619b4faa | [
"MIT"
] | null | null | null | defmodule Ui.Pin do
@moduledoc """
A Ui.Pin describes a physical pin on a device. This is mainly for displaying information
about the physical pins, not for controlling them (e.g. in the case of a GPIO pin.
"""
alias Ui.Pin
defmodule GPIO do
@type t :: %GPIO{}
defstruct [:gpio_number]
@spec description(t) :: String.t
def description(%GPIO{gpio_number: gpio_number}) do
"GPIO pin ##{gpio_number}"
end
end
defmodule Power do
@type t :: %Power{}
defstruct [:voltage]
@spec description(t) :: String.t
def description(%Power{voltage: voltage}) do
"#{voltage} Power pin"
end
end
defmodule Ground do
@type t :: %Ground{}
defstruct []
@spec description(t) :: String.t
def description(%Ground{}) do
"Ground pin"
end
end
defmodule Other do
defstruct [:description]
@type t :: %Other{}
@spec description(t) :: String.t
def description(%Other{description: description}) do
description
end
end
@type pin_number :: non_neg_integer()
def description(%type{} = pin) do
type.description(pin)
end
## Factory Functions
@doc "Creates a power pin with voltage"
@spec power(number()) :: Power.t
def power(voltage), do: %Pin.Power{voltage: voltage}
@doc "Creates a GPIO pin with GPIO number"
@spec gpio(number()) :: GPIO.t
def gpio(gpio_number), do: %Pin.GPIO{gpio_number: gpio_number}
@doc "Creates a ground pin"
@spec ground() :: Ground.t
def ground(), do: %Pin.Ground{}
@doc """
creates an "other" pin - e.g. anything else. Will display with the data passed.
"""
@spec other(term()) :: Other.t
def other(description), do: %Pin.Other{description: description}
end
| 23.08 | 90 | 0.647025 |
fff9ed8a62ccc58129297c305d8e62912a4401a5 | 195 | ex | Elixir | lib/pushex/apns.ex | mauricionr/pushex-1 | a096335bd4b92da152cf9fe5f99c824433a6af41 | [
"MIT"
] | 69 | 2016-03-29T15:35:29.000Z | 2018-06-27T14:57:23.000Z | lib/pushex/apns.ex | mauricionr/pushex-1 | a096335bd4b92da152cf9fe5f99c824433a6af41 | [
"MIT"
] | 9 | 2016-04-29T09:14:49.000Z | 2017-10-31T02:08:14.000Z | lib/pushex/apns.ex | mauricionr/pushex-1 | a096335bd4b92da152cf9fe5f99c824433a6af41 | [
"MIT"
] | 6 | 2016-08-26T12:56:05.000Z | 2018-06-21T23:51:00.000Z | defmodule Pushex.APNS do
@moduledoc "This module defines types to work with APNS"
@type response :: {:ok, Pushex.APNS.Response} | {:error, atom}
@type request :: Pushex.APNS.Request.t
end
| 27.857143 | 64 | 0.712821 |
fff9f2ecb0f20a0129aea0f4bc3c022faf4b03e9 | 283 | exs | Elixir | test/tablestore_protos_test.exs | hou8/tablestore_protos | 1a3223326b92bbe196d57ce4dd19b5a8db1c728d | [
"MIT"
] | null | null | null | test/tablestore_protos_test.exs | hou8/tablestore_protos | 1a3223326b92bbe196d57ce4dd19b5a8db1c728d | [
"MIT"
] | 1 | 2022-02-08T06:37:02.000Z | 2022-02-08T06:37:02.000Z | test/tablestore_protos_test.exs | hou8/tablestore_protos | 1a3223326b92bbe196d57ce4dd19b5a8db1c728d | [
"MIT"
] | 2 | 2022-01-24T06:13:03.000Z | 2022-01-24T08:33:41.000Z | defmodule TablestoreProtosTest do
use ExUnit.Case
alias ExAliyunOts.TableStoreSearch.RowCountSort
test "encode with default enum" do
encoded = RowCountSort.encode!(%RowCountSort{order: :'SORT_ORDER_ASC'}) |> IO.iodata_to_binary()
assert encoded == <<8, 0>>
end
end
| 25.727273 | 100 | 0.742049 |
fff9fc8440983caf3be836f890ba77142451a38f | 1,360 | exs | Elixir | test/still/compiler/error_cache_test.exs | tomasz-tomczyk/still | 3f2fdb64c72244b789e14b31d514199f8adeb796 | [
"ISC"
] | 202 | 2021-01-13T15:45:17.000Z | 2022-03-22T01:26:27.000Z | test/still/compiler/error_cache_test.exs | tomasz-tomczyk/still | 3f2fdb64c72244b789e14b31d514199f8adeb796 | [
"ISC"
] | 55 | 2021-01-26T14:11:34.000Z | 2022-03-22T22:34:37.000Z | test/still/compiler/error_cache_test.exs | tomasz-tomczyk/still | 3f2fdb64c72244b789e14b31d514199f8adeb796 | [
"ISC"
] | 10 | 2021-02-04T21:14:41.000Z | 2022-03-20T10:12:59.000Z | defmodule Still.Compiler.ErrorCacheTest do
use Still.Case, async: true
alias Still.Compiler.{ErrorCache, PreprocessorError}
alias Still.SourceFile
describe "set/1" do
test "set an errors for the given" do
error = %PreprocessorError{
payload: :udnef,
kind: :error,
source_file: %SourceFile{
input_file: "_header.slime",
dependency_chain: ["index.eex", "_header.slime"]
}
}
ErrorCache.set({:error, error})
errors = ErrorCache.get_errors()
assert not is_nil(errors["index.eex <- _header.slime"])
end
test "doesn't set an error for the given file" do
source_file = %SourceFile{
input_file: "_header.slime",
dependency_chain: ["index.eex", "_header.slime"]
}
ErrorCache.set({:ok, source_file})
errors = ErrorCache.get_errors()
assert is_nil(errors["index.eex <- _header.slime"])
end
test "removes an error for the given" do
source_file = %SourceFile{
input_file: "_header.slime",
dependency_chain: ["index.eex", "_header.slime"]
}
error = %PreprocessorError{source_file: source_file}
ErrorCache.set({:error, error})
ErrorCache.set({:ok, source_file})
errors = ErrorCache.get_errors()
assert errors["index.html"] == nil
end
end
end
| 24.727273 | 61 | 0.626471 |
fffa2a006f550a993345687d394051436c5aeca8 | 9,102 | ex | Elixir | lib/zaryn/mining/pending_transaction_validation.ex | ambareesha7/node-zaryn | 136e542801bf9b6fa4a015d3464609fdf3dacee8 | [
"Apache-2.0"
] | 1 | 2021-07-06T19:47:14.000Z | 2021-07-06T19:47:14.000Z | lib/zaryn/mining/pending_transaction_validation.ex | ambareesha7/node-zaryn | 136e542801bf9b6fa4a015d3464609fdf3dacee8 | [
"Apache-2.0"
] | null | null | null | lib/zaryn/mining/pending_transaction_validation.ex | ambareesha7/node-zaryn | 136e542801bf9b6fa4a015d3464609fdf3dacee8 | [
"Apache-2.0"
] | null | null | null | defmodule Zaryn.Mining.PendingTransactionValidation do
@moduledoc false
alias Zaryn.Contracts
alias Zaryn.Contracts.Contract
alias Zaryn.Crypto
alias Zaryn.Governance
alias Zaryn.Governance.Code.Proposal, as: CodeProposal
alias Zaryn.OracleChain
alias Zaryn.P2P
alias Zaryn.P2P.Message.FirstPublicKey
alias Zaryn.P2P.Message.GetFirstPublicKey
alias Zaryn.P2P.Node
alias Zaryn.Replication
alias Zaryn.Reward
alias Zaryn.SharedSecrets.NodeRenewal
alias Zaryn.TransactionChain
alias Zaryn.TransactionChain.Transaction
alias Zaryn.TransactionChain.TransactionData
alias Zaryn.TransactionChain.TransactionData.Keys
alias Zaryn.TransactionChain.TransactionData.Ledger
alias Zaryn.TransactionChain.TransactionData.ZARYNLedger
alias Zaryn.Utils
require Logger
@doc """
Determines if the transaction is accepted into the network
"""
@spec validate(Transaction.t()) :: :ok | {:error, any()}
def validate(tx = %Transaction{address: address, type: type}) do
start = System.monotonic_time()
with true <- Transaction.verify_previous_signature?(tx),
:ok <- validate_contract(tx) do
res = do_accept_transaction(tx)
:telemetry.execute(
[:zaryn, :mining, :pending_transaction_validation],
%{duration: System.monotonic_time() - start},
%{transaction_type: type}
)
res
else
false ->
Logger.error("Invalid previous signature",
transaction: "#{type}@#{Base.encode16(address)}"
)
{:error, "Invalid previous signature"}
{:error, _} = e ->
e
end
end
defp validate_contract(%Transaction{data: %TransactionData{code: ""}}), do: :ok
defp validate_contract(%Transaction{
address: address,
type: type,
data: %TransactionData{code: code, keys: keys}
}) do
case Contracts.parse(code) do
{:ok, %Contract{triggers: [_ | _]}} ->
if Crypto.storage_nonce_public_key() in Keys.list_authorized_keys(keys) do
:ok
else
Logger.error("Require storage nonce public key as authorized keys",
transaction: "#{type}@#{Base.encode16(address)}"
)
{:error, "Requires storage nonce public key as authorized keys"}
end
{:ok, %Contract{}} ->
:ok
{:error, reason} ->
Logger.error("Smart contract invalid #{inspect(reason)}",
transaction: "#{type}@#{Base.encode16(address)}"
)
{:error, reason}
end
end
defp do_accept_transaction(%Transaction{
address: address,
type: :node_rewards,
data: %TransactionData{
ledger: %Ledger{
zaryn: %ZARYNLedger{transfers: zaryn_transfers}
}
}
}) do
case Reward.get_transfers_for_in_need_validation_nodes(Reward.last_scheduling_date()) do
^zaryn_transfers ->
:ok
_ ->
Logger.error("Invalid network pool transfers",
transaction: "node_rewards@#{Base.encode16(address)}"
)
{:error, "Invalid network pool transfers"}
end
end
defp do_accept_transaction(%Transaction{
address: address,
type: :node,
data: %TransactionData{
content: content
},
previous_public_key: previous_public_key
}) do
with {:ok, _, _, _, _, key_certificate} <- Node.decode_transaction_content(content),
root_ca_public_key <- Crypto.get_root_ca_public_key(previous_public_key),
true <-
Crypto.verify_key_certificate?(
previous_public_key,
key_certificate,
root_ca_public_key
) do
:ok
else
:error ->
Logger.error("Invalid node transaction content",
transaction: "node@#{Base.encode16(address)}"
)
{:error, "Invalid node transaction"}
false ->
Logger.error("Invalid node key certificate",
transaction: "node@#{Base.encode16(address)}"
)
{:error, "Invalid node transaction"}
end
end
defp do_accept_transaction(%Transaction{
address: address,
type: :node_shared_secrets,
data: %TransactionData{
content: content,
keys: %Keys{secret: secret, authorized_keys: authorized_keys}
}
})
when is_binary(secret) and byte_size(secret) > 0 and map_size(authorized_keys) > 0 do
nodes = P2P.available_nodes()
with {:ok, _, _} <- NodeRenewal.decode_transaction_content(content),
true <- Enum.all?(Map.keys(authorized_keys), &Utils.key_in_node_list?(nodes, &1)) do
:ok
else
:error ->
Logger.error("Node shared secrets has invalid content",
transaction: "node_shared_secrets@#{Base.encode16(address)}"
)
{:error, "Invalid node shared secrets transaction"}
false ->
Logger.error("Node shared secrets can only contains public node list",
transaction: "node_shared_secrets@#{Base.encode16(address)}"
)
{:error, "Invalid node shared secrets transaction"}
end
end
defp do_accept_transaction(%Transaction{type: :node_shared_secrets}) do
{:error, "Invalid node shared secrets transaction"}
end
defp do_accept_transaction(
tx = %Transaction{
address: address,
type: :code_proposal
}
) do
with {:ok, prop} <- CodeProposal.from_transaction(tx),
true <- Governance.valid_code_changes?(prop) do
:ok
else
_ ->
Logger.error("Invalid code proposal",
transaction: "code_proposal@#{Base.encode16(address)}"
)
{:error, "Invalid code proposal"}
end
end
defp do_accept_transaction(
tx = %Transaction{
address: address,
type: :code_approval,
data: %TransactionData{
recipients: [proposal_address]
}
}
) do
first_public_key = get_first_public_key(tx)
with {:member, true} <-
{:member, Governance.pool_member?(first_public_key, :technical_council)},
{:ok, prop} <- Governance.get_code_proposal(proposal_address),
previous_address <- Transaction.previous_address(tx),
{:signed, false} <- {:signed, CodeProposal.signed_by?(prop, previous_address)} do
:ok
else
{:member, false} ->
Logger.error("No technical council member",
transaction: "code_approval@#{Base.encode16(address)}"
)
{:error, "No technical council member"}
{:error, :not_found} ->
Logger.error("Code proposal does not exist",
transaction: "code_approval@#{Base.encode16(address)}"
)
{:error, "Code proposal doest not exist"}
{:signed, true} ->
Logger.error("Code proposal already signed",
transaction: "code_approval@#{Base.encode16(address)}"
)
{:error, "Code proposal already signed"}
end
end
defp do_accept_transaction(%Transaction{
address: address,
type: :nft,
data: %TransactionData{content: content}
}) do
if Regex.match?(~r/(?<=initial supply:).*\d/mi, content) do
:ok
else
Logger.error("Invalid NFT transaction content", transaction: "nft@#{Base.encode16(address)}")
{:error, "Invalid NFT content"}
end
end
defp do_accept_transaction(%Transaction{
address: address,
type: :oracle,
data: %TransactionData{
content: content
}
}) do
if OracleChain.valid_services_content?(content) do
:ok
else
Logger.error("Invalid oracle transaction", transaction: "oracle@#{Base.encode16(address)}")
{:error, "Invalid oracle transaction"}
end
end
defp do_accept_transaction(%Transaction{
address: address,
type: :oracle_summary,
data: %TransactionData{
content: content
},
previous_public_key: previous_public_key
}) do
with previous_address <- Crypto.hash(previous_public_key),
oracle_chain <-
TransactionChain.get(previous_address, data: [:content], validation_stamp: [:timestamp]),
true <- OracleChain.valid_summary?(content, oracle_chain) do
:ok
else
_ ->
Logger.error("Invalid oracle summary transaction",
transaction: "oracle_summary@#{Base.encode16(address)}"
)
{:error, "Invalid oracle summary transaction"}
end
end
defp do_accept_transaction(_), do: :ok
defp get_first_public_key(tx = %Transaction{previous_public_key: previous_public_key}) do
previous_address = Transaction.previous_address(tx)
storage_nodes = Replication.chain_storage_nodes(previous_address)
response_message =
P2P.reply_first(storage_nodes, %GetFirstPublicKey{address: previous_address})
case response_message do
{:ok, %FirstPublicKey{public_key: public_key}} ->
public_key
_ ->
previous_public_key
end
end
end
| 28.44375 | 100 | 0.626895 |
fffa2ba351d4d065ea9873a38eadd9b6b3817ff9 | 4,380 | ex | Elixir | clients/cloud_asset/lib/google_api/cloud_asset/v1/model/software_package.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | 1 | 2021-10-01T09:20:41.000Z | 2021-10-01T09:20:41.000Z | clients/cloud_asset/lib/google_api/cloud_asset/v1/model/software_package.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/cloud_asset/lib/google_api/cloud_asset/v1/model/software_package.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudAsset.V1.Model.SoftwarePackage do
@moduledoc """
Software package information of the operating system.
## Attributes
* `aptPackage` (*type:* `GoogleApi.CloudAsset.V1.Model.VersionedPackage.t`, *default:* `nil`) - Details of an APT package. For details about the apt package manager, see https://wiki.debian.org/Apt.
* `cosPackage` (*type:* `GoogleApi.CloudAsset.V1.Model.VersionedPackage.t`, *default:* `nil`) - Details of a COS package.
* `googetPackage` (*type:* `GoogleApi.CloudAsset.V1.Model.VersionedPackage.t`, *default:* `nil`) - Details of a Googet package. For details about the googet package manager, see https://github.com/google/googet.
* `qfePackage` (*type:* `GoogleApi.CloudAsset.V1.Model.WindowsQuickFixEngineeringPackage.t`, *default:* `nil`) - Details of a Windows Quick Fix engineering package. See https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-quickfixengineering for info in Windows Quick Fix Engineering.
* `wuaPackage` (*type:* `GoogleApi.CloudAsset.V1.Model.WindowsUpdatePackage.t`, *default:* `nil`) - Details of a Windows Update package. See https://docs.microsoft.com/en-us/windows/win32/api/_wua/ for information about Windows Update.
* `yumPackage` (*type:* `GoogleApi.CloudAsset.V1.Model.VersionedPackage.t`, *default:* `nil`) - Yum package info. For details about the yum package manager, see https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/ch-yum.
* `zypperPackage` (*type:* `GoogleApi.CloudAsset.V1.Model.VersionedPackage.t`, *default:* `nil`) - Details of a Zypper package. For details about the Zypper package manager, see https://en.opensuse.org/SDB:Zypper_manual.
* `zypperPatch` (*type:* `GoogleApi.CloudAsset.V1.Model.ZypperPatch.t`, *default:* `nil`) - Details of a Zypper patch. For details about the Zypper package manager, see https://en.opensuse.org/SDB:Zypper_manual.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:aptPackage => GoogleApi.CloudAsset.V1.Model.VersionedPackage.t() | nil,
:cosPackage => GoogleApi.CloudAsset.V1.Model.VersionedPackage.t() | nil,
:googetPackage => GoogleApi.CloudAsset.V1.Model.VersionedPackage.t() | nil,
:qfePackage =>
GoogleApi.CloudAsset.V1.Model.WindowsQuickFixEngineeringPackage.t() | nil,
:wuaPackage => GoogleApi.CloudAsset.V1.Model.WindowsUpdatePackage.t() | nil,
:yumPackage => GoogleApi.CloudAsset.V1.Model.VersionedPackage.t() | nil,
:zypperPackage => GoogleApi.CloudAsset.V1.Model.VersionedPackage.t() | nil,
:zypperPatch => GoogleApi.CloudAsset.V1.Model.ZypperPatch.t() | nil
}
field(:aptPackage, as: GoogleApi.CloudAsset.V1.Model.VersionedPackage)
field(:cosPackage, as: GoogleApi.CloudAsset.V1.Model.VersionedPackage)
field(:googetPackage, as: GoogleApi.CloudAsset.V1.Model.VersionedPackage)
field(:qfePackage, as: GoogleApi.CloudAsset.V1.Model.WindowsQuickFixEngineeringPackage)
field(:wuaPackage, as: GoogleApi.CloudAsset.V1.Model.WindowsUpdatePackage)
field(:yumPackage, as: GoogleApi.CloudAsset.V1.Model.VersionedPackage)
field(:zypperPackage, as: GoogleApi.CloudAsset.V1.Model.VersionedPackage)
field(:zypperPatch, as: GoogleApi.CloudAsset.V1.Model.ZypperPatch)
end
defimpl Poison.Decoder, for: GoogleApi.CloudAsset.V1.Model.SoftwarePackage do
def decode(value, options) do
GoogleApi.CloudAsset.V1.Model.SoftwarePackage.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudAsset.V1.Model.SoftwarePackage do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 63.478261 | 301 | 0.74863 |
fffa2f26ae63a29aedd96ee513d4ac42d2d91808 | 810 | ex | Elixir | lib/hl7/2.4/datatypes/ppn.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.4/datatypes/ppn.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.4/datatypes/ppn.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | defmodule HL7.V2_4.DataTypes.Ppn do
@moduledoc false
alias HL7.V2_4.{DataTypes}
use HL7.DataType,
fields: [
id_number_st: nil,
family_name: DataTypes.Fn,
given_name: nil,
second_and_further_given_names_or_initials_thereof: nil,
suffix_eg_jr_or_iii: nil,
prefix_eg_dr: nil,
degree_eg_md: nil,
source_table: nil,
assigning_authority: DataTypes.Hd,
name_type_code: nil,
identifier_check_digit: nil,
code_identifying_the_check_digit_scheme_employed: nil,
identifier_type_code_is: nil,
assigning_facility: DataTypes.Hd,
datetime_action_performed: DataTypes.Ts,
name_representation_code: nil,
name_context: DataTypes.Ce,
name_validity_range: DataTypes.Dr,
name_assembly_order: nil
]
end
| 28.928571 | 62 | 0.708642 |
fffa3060ea838dfa175fc2f1d56a656b7ef493db | 4,933 | ex | Elixir | clients/slides/lib/google_api/slides/v1/model/presentation.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/slides/lib/google_api/slides/v1/model/presentation.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/slides/lib/google_api/slides/v1/model/presentation.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.Slides.V1.Model.Presentation do
@moduledoc """
A Google Slides presentation.
## Attributes
* `layouts` (*type:* `list(GoogleApi.Slides.V1.Model.Page.t)`, *default:* `nil`) - The layouts in the presentation. A layout is a template that determines how content is arranged and styled on the slides that inherit from that layout.
* `locale` (*type:* `String.t`, *default:* `nil`) - The locale of the presentation, as an IETF BCP 47 language tag.
* `masters` (*type:* `list(GoogleApi.Slides.V1.Model.Page.t)`, *default:* `nil`) - The slide masters in the presentation. A slide master contains all common page elements and the common properties for a set of layouts. They serve three purposes: - Placeholder shapes on a master contain the default text styles and shape properties of all placeholder shapes on pages that use that master. - The master page properties define the common page properties inherited by its layouts. - Any other shapes on the master slide appear on all slides using that master, regardless of their layout.
* `notesMaster` (*type:* `GoogleApi.Slides.V1.Model.Page.t`, *default:* `nil`) - The notes master in the presentation. It serves three purposes: - Placeholder shapes on a notes master contain the default text styles and shape properties of all placeholder shapes on notes pages. Specifically, a `SLIDE_IMAGE` placeholder shape contains the slide thumbnail, and a `BODY` placeholder shape contains the speaker notes. - The notes master page properties define the common page properties inherited by all notes pages. - Any other shapes on the notes master appear on all notes pages. The notes master is read-only.
* `pageSize` (*type:* `GoogleApi.Slides.V1.Model.Size.t`, *default:* `nil`) - The size of pages in the presentation.
* `presentationId` (*type:* `String.t`, *default:* `nil`) - The ID of the presentation.
* `revisionId` (*type:* `String.t`, *default:* `nil`) - The revision ID of the presentation. Can be used in update requests to assert that the presentation revision hasn't changed since the last read operation. Only populated if the user has edit access to the presentation. The format of the revision ID may change over time, so it should be treated opaquely. A returned revision ID is only guaranteed to be valid for 24 hours after it has been returned and cannot be shared across users. If the revision ID is unchanged between calls, then the presentation has not changed. Conversely, a changed ID (for the same presentation and user) usually means the presentation has been updated; however, a changed ID can also be due to internal factors such as ID format changes.
* `slides` (*type:* `list(GoogleApi.Slides.V1.Model.Page.t)`, *default:* `nil`) - The slides in the presentation. A slide inherits properties from a slide layout.
* `title` (*type:* `String.t`, *default:* `nil`) - The title of the presentation.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:layouts => list(GoogleApi.Slides.V1.Model.Page.t()) | nil,
:locale => String.t() | nil,
:masters => list(GoogleApi.Slides.V1.Model.Page.t()) | nil,
:notesMaster => GoogleApi.Slides.V1.Model.Page.t() | nil,
:pageSize => GoogleApi.Slides.V1.Model.Size.t() | nil,
:presentationId => String.t() | nil,
:revisionId => String.t() | nil,
:slides => list(GoogleApi.Slides.V1.Model.Page.t()) | nil,
:title => String.t() | nil
}
field(:layouts, as: GoogleApi.Slides.V1.Model.Page, type: :list)
field(:locale)
field(:masters, as: GoogleApi.Slides.V1.Model.Page, type: :list)
field(:notesMaster, as: GoogleApi.Slides.V1.Model.Page)
field(:pageSize, as: GoogleApi.Slides.V1.Model.Size)
field(:presentationId)
field(:revisionId)
field(:slides, as: GoogleApi.Slides.V1.Model.Page, type: :list)
field(:title)
end
defimpl Poison.Decoder, for: GoogleApi.Slides.V1.Model.Presentation do
def decode(value, options) do
GoogleApi.Slides.V1.Model.Presentation.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Slides.V1.Model.Presentation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 69.478873 | 775 | 0.727144 |
fffa5c183717e26b9a721bdf161a1e1ee71a96d8 | 1,325 | ex | Elixir | test/support/conn_case.ex | nunocf/reason-react-exercise | b6e6920a596fe436b02a602282750456a7edbdea | [
"MIT"
] | null | null | null | test/support/conn_case.ex | nunocf/reason-react-exercise | b6e6920a596fe436b02a602282750456a7edbdea | [
"MIT"
] | null | null | null | test/support/conn_case.ex | nunocf/reason-react-exercise | b6e6920a596fe436b02a602282750456a7edbdea | [
"MIT"
] | null | null | null | defmodule ReasonReactExerciseWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use ReasonReactExerciseWeb.ConnCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
import Plug.Conn
import Phoenix.ConnTest
import ReasonReactExerciseWeb.ConnCase
alias ReasonReactExerciseWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint ReasonReactExerciseWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(ReasonReactExercise.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(ReasonReactExercise.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 30.113636 | 81 | 0.741887 |
fffa6a70a8418d6d5c26fbeb0f136ec37dbe5b6f | 5,352 | ex | Elixir | lib/relay/resources/rds.ex | aclemmensen/relay | 4bce71ed7d8bd4936f96d62ed08d007729c4253d | [
"BSD-3-Clause"
] | 5 | 2018-10-12T13:13:19.000Z | 2020-10-03T17:51:37.000Z | lib/relay/resources/rds.ex | aclemmensen/relay | 4bce71ed7d8bd4936f96d62ed08d007729c4253d | [
"BSD-3-Clause"
] | 207 | 2018-02-09T14:24:14.000Z | 2020-07-25T11:09:19.000Z | lib/relay/resources/rds.ex | aclemmensen/relay | 4bce71ed7d8bd4936f96d62ed08d007729c4253d | [
"BSD-3-Clause"
] | 1 | 2019-08-08T11:30:59.000Z | 2019-08-08T11:30:59.000Z | defmodule Relay.Resources.RDS do
use LogWrapper, as: Log
@moduledoc """
Builds Envoy RouteConfiguration values from cluster resources.
"""
alias Relay.Resources.{AppEndpoint, Config}
alias Envoy.Api.V2.RouteConfiguration
alias Envoy.Api.V2.Route.{RedirectAction, Route, RouteAction, RouteMatch, VirtualHost}
@listeners [:http, :https]
@doc """
Create Clusters for the given app_endpoints.
"""
@spec route_configurations([AppEndpoint.t()]) :: [RouteConfiguration.t()]
def route_configurations(apps) do
{apps, _duplicate_domains} = filter_duplicate_domains(apps)
# TODO: Do something with duplicate domains
Enum.map(@listeners, &route_configuration(&1, apps))
end
@spec filter_duplicate_domains([AppEndpoint.t()]) :: {[AppEndpoint.t()], [String.t()]}
defp filter_duplicate_domains(apps) do
duplicate_domains = find_duplicate_domains(apps)
filtered_apps =
apps
|> Enum.map(&filter_app_domains(&1, duplicate_domains))
|> Enum.filter(&check_app_domains/1)
{filtered_apps, duplicate_domains}
end
defp check_app_domains(%AppEndpoint{name: name, domains: []}) do
Log.warn("App has no routable domains: #{name}")
false
end
defp check_app_domains(%AppEndpoint{}), do: true
defp filter_app_domains(app, duplicate_domains),
do: %AppEndpoint{app | domains: app.domains |> reject_items(duplicate_domains)}
defp reject_items(enum, unwanted), do: Enum.reject(enum, &Enum.member?(unwanted, &1))
defp find_duplicate_domains(apps) do
apps
|> Enum.reduce(%{}, &apps_by_domain/2)
|> Enum.filter(fn {_, apps} -> length(apps) > 1 end)
|> log_duplicate_warnings()
|> Enum.map(fn {dom, _} -> dom end)
end
defp log_duplicate_warnings(duplicates) do
duplicates |> Enum.each(&log_duplicate_warning/1)
duplicates
end
defp log_duplicate_warning({domain, apps}),
do: Log.warn("Domain #{domain} claimed by multiple apps: #{Enum.join(apps, " ")}")
defp apps_by_domain(%AppEndpoint{name: name, domains: domains}, domain_map) do
Enum.reduce(domains, domain_map, fn dom, dom_map ->
Map.update(dom_map, dom, [name], &[name | &1])
end)
end
@spec route_configuration(atom, [AppEndpoint.t()]) :: RouteConfiguration.t()
defp route_configuration(listener, app_endpoints) do
# TODO: Validate that the configured name is less than max_obj_name_length
route_config_name = Config.get_listener_route_config_name(listener)
vhosts = app_endpoints |> Enum.map(&virtual_host(listener, &1))
RouteConfiguration.new(name: route_config_name, virtual_hosts: vhosts)
end
@spec virtual_host(atom, AppEndpoint.t()) :: VirtualHost.t()
defp virtual_host(listener, app_endpoint) do
VirtualHost.new(
[
# TODO: Do VirtualHost names need to be truncated?
name: "#{listener}_#{app_endpoint.name}",
# TODO: Validate domains
domains: app_endpoint.domains,
routes: app_endpoint_routes(listener, app_endpoint)
] ++ app_endpoint.vhost_opts
)
end
@spec app_endpoint_routes(atom, AppEndpoint.t()) :: [Route.t()]
defp app_endpoint_routes(:http, app_endpoint) do
primary_route =
if app_endpoint.redirect_to_https do
https_redirect_route()
else
app_endpoint_route(app_endpoint)
end
case app_endpoint.marathon_acme_domains do
# No marathon-acme domain--don't route to marathon-acme
[] ->
[primary_route]
_ ->
[marathon_acme_route(), primary_route]
end
end
defp app_endpoint_routes(:https, app_endpoint) do
# TODO: Do we want an HTTPS route for apps without certificates?
[app_endpoint_route(app_endpoint)]
end
@spec app_endpoint_route(AppEndpoint.t()) :: Route.t()
defp app_endpoint_route(%AppEndpoint{route_opts: options} = app_endpoint) do
Route.new(
[
action: {:route, app_endpoint_route_action(app_endpoint)},
match: app_endpoint_route_match(app_endpoint)
] ++ options
)
end
@spec app_endpoint_route_action(AppEndpoint.t()) :: RouteAction.t()
defp app_endpoint_route_action(%AppEndpoint{name: name, route_action_opts: options}) do
# TODO: Does the cluster name here need to be truncated?
RouteAction.new([cluster_specifier: {:cluster, name}] ++ options)
end
@spec app_endpoint_route_match(AppEndpoint.t()) :: RouteMatch.t()
defp app_endpoint_route_match(%AppEndpoint{route_match_opts: options}) do
# TODO: Support path-based routing
RouteMatch.new([path_specifier: {:prefix, "/"}] ++ options)
end
@spec https_redirect_route() :: Route.t()
defp https_redirect_route do
# The HTTPS redirect route is simple and can't be customized per-app
Route.new(
action: {:redirect, RedirectAction.new(https_redirect: true)},
match: RouteMatch.new(path_specifier: {:prefix, "/"})
)
end
@spec marathon_acme_route() :: Route.t()
defp marathon_acme_route do
app_id = Config.fetch_marathon_acme!(:app_id)
port_index = Config.fetch_marathon_acme!(:port_index)
# TODO: Does the cluster name here need to be truncated?
cluster = "#{app_id}_#{port_index}"
Route.new(
action: {:route, RouteAction.new(cluster_specifier: {:cluster, cluster})},
match: RouteMatch.new(path_specifier: {:prefix, "/.well-known/acme-challenge/"})
)
end
end
| 33.242236 | 89 | 0.700673 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.