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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
088781e4033f8f33446667ffcbc4ac26a4efa0af | 3,780 | exs | Elixir | test/cocktail/reversibility_test.exs | camelohq/cocktail | 9b25d8f24d148397be6537ab1414abdbdec1ce8d | [
"MIT"
] | 117 | 2017-09-09T00:02:32.000Z | 2022-02-10T15:36:28.000Z | test/cocktail/reversibility_test.exs | camelohq/cocktail | 9b25d8f24d148397be6537ab1414abdbdec1ce8d | [
"MIT"
] | 193 | 2017-09-09T22:49:18.000Z | 2022-03-30T13:05:25.000Z | test/cocktail/reversibility_test.exs | camelohq/cocktail | 9b25d8f24d148397be6537ab1414abdbdec1ce8d | [
"MIT"
] | 20 | 2018-01-04T14:58:42.000Z | 2021-11-25T13:59:10.000Z | defmodule Cocktail.ReversibilityTest do
use ExUnit.Case
alias Cocktail.Schedule
defp assert_reversible(schedule) do
i_calendar_string = Schedule.to_i_calendar(schedule)
{:ok, parsed_schedule} = Schedule.from_i_calendar(i_calendar_string)
assert parsed_schedule == schedule
end
for frequency <- [:secondly, :minutely, :hourly, :daily, :weekly] do
test "#{frequency}" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(unquote(frequency))
|> assert_reversible()
end
test "#{frequency} interval 2" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(unquote(frequency), interval: 2)
|> assert_reversible()
end
test "#{frequency} on Mondays, Wednesdays and Fridays" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(unquote(frequency), days: [:monday, :wednesday, :friday])
|> assert_reversible()
end
test "#{frequency} on the 10th, 12th and 14th hours of the day" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(unquote(frequency), hours: [10, 12, 14])
|> assert_reversible()
end
test "#{frequency} on the 0th and 30th minutes of the hour" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(unquote(frequency), minutes: [0, 30])
|> assert_reversible()
end
test "#{frequency} on the 0th and 30th seconds of the minute" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(unquote(frequency), seconds: [0, 30])
|> assert_reversible()
end
test "#{frequency} until someday" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(unquote(frequency), until: ~N[2017-10-09 09:00:00])
|> assert_reversible()
end
test "#{frequency} 10 times" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(unquote(frequency), count: 10)
|> assert_reversible()
end
end
test "recurrence times" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_time(~N[2017-10-09 09:00:00])
|> assert_reversible()
end
test "exception times" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(:daily)
|> Schedule.add_exception_time(~N[2017-09-10 09:00:00])
|> assert_reversible()
end
test "time of day option" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(:daily, times: [~T[09:00:00], ~T[11:30:00]])
|> assert_reversible()
end
test "time range option" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(
:daily,
time_range: %{start_time: ~T[09:00:00], end_time: ~T[11:00:00], interval_seconds: 1_800}
)
|> assert_reversible()
end
test "empty days" do
~N[2017-09-09 09:00:00] |> Schedule.new() |> Schedule.add_recurrence_rule(:daily, days: []) |> assert_reversible()
end
test "empty hours" do
~N[2017-09-09 09:00:00] |> Schedule.new() |> Schedule.add_recurrence_rule(:daily, hours: []) |> assert_reversible()
end
test "empty minutes" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(:daily, minutes: [])
|> assert_reversible()
end
test "empty seconds" do
~N[2017-09-09 09:00:00]
|> Schedule.new()
|> Schedule.add_recurrence_rule(:daily, seconds: [])
|> assert_reversible()
end
test "empty times" do
~N[2017-09-09 09:00:00] |> Schedule.new() |> Schedule.add_recurrence_rule(:daily, times: []) |> assert_reversible()
end
end
| 29.302326 | 119 | 0.633862 |
088786fe880abfe6163dbbcc312f84bd48069344 | 11,913 | ex | Elixir | lib/commanded/process_managers/process_manager_instance.ex | edwardzhou/commanded | f104cbf5ff3a37a6e9b637bc07ccde1d79c0725d | [
"MIT"
] | 1 | 2018-12-28T20:48:23.000Z | 2018-12-28T20:48:23.000Z | lib/commanded/process_managers/process_manager_instance.ex | edwardzhou/commanded | f104cbf5ff3a37a6e9b637bc07ccde1d79c0725d | [
"MIT"
] | null | null | null | lib/commanded/process_managers/process_manager_instance.ex | edwardzhou/commanded | f104cbf5ff3a37a6e9b637bc07ccde1d79c0725d | [
"MIT"
] | 1 | 2018-12-28T20:48:24.000Z | 2018-12-28T20:48:24.000Z | defmodule Commanded.ProcessManagers.ProcessManagerInstance do
@moduledoc false
use GenServer
require Logger
alias Commanded.ProcessManagers.{ProcessRouter, ProcessManagerInstance, FailureContext}
alias Commanded.EventStore
alias Commanded.EventStore.{RecordedEvent, SnapshotData}
defstruct [
:command_dispatcher,
:process_router,
:process_manager_name,
:process_manager_module,
:process_uuid,
:process_state,
:last_seen_event
]
def start_link(
command_dispatcher,
process_router,
process_manager_name,
process_manager_module,
process_uuid
) do
state = %ProcessManagerInstance{
command_dispatcher: command_dispatcher,
process_router: process_router,
process_manager_name: process_manager_name,
process_manager_module: process_manager_module,
process_uuid: process_uuid,
process_state: struct(process_manager_module)
}
GenServer.start_link(__MODULE__, state)
end
def init(%ProcessManagerInstance{} = state) do
GenServer.cast(self(), :fetch_state)
{:ok, state}
end
@doc """
Checks whether or not the process manager has already processed events
"""
def new?(process_manager) do
GenServer.call(process_manager, :new?)
end
@doc """
Handle the given event by delegating to the process manager module
"""
def process_event(process_manager, %RecordedEvent{} = event) do
GenServer.cast(process_manager, {:process_event, event})
end
@doc """
Stop the given process manager and delete its persisted state.
Typically called when it has reached its final state.
"""
def stop(process_manager) do
GenServer.call(process_manager, :stop)
end
@doc """
Fetch the process state of this instance
"""
def process_state(process_manager) do
GenServer.call(process_manager, :process_state)
end
@doc false
def handle_call(:stop, _from, %ProcessManagerInstance{} = state) do
:ok = delete_state(state)
# Stop the process with a normal reason
{:stop, :normal, :ok, state}
end
@doc false
def handle_call(:process_state, _from, %ProcessManagerInstance{} = state) do
%ProcessManagerInstance{process_state: process_state} = state
{:reply, process_state, state}
end
@doc false
def handle_call(:new?, _from, %ProcessManagerInstance{} = state) do
%ProcessManagerInstance{last_seen_event: last_seen_event} = state
{:reply, is_nil(last_seen_event), state}
end
@doc """
Attempt to fetch intial process state from snapshot storage
"""
def handle_cast(:fetch_state, %ProcessManagerInstance{} = state) do
state =
case EventStore.read_snapshot(process_state_uuid(state)) do
{:ok, snapshot} ->
%ProcessManagerInstance{
state
| process_state: snapshot.data,
last_seen_event: snapshot.source_version
}
{:error, :snapshot_not_found} ->
state
end
{:noreply, state}
end
@doc """
Handle the given event, using the process manager module, against the current process state
"""
def handle_cast({:process_event, event}, %ProcessManagerInstance{} = state) do
case event_already_seen?(event, state) do
true -> process_seen_event(event, state)
false -> process_unseen_event(event, state)
end
end
defp event_already_seen?(%RecordedEvent{}, %ProcessManagerInstance{last_seen_event: nil}),
do: false
defp event_already_seen?(%RecordedEvent{} = event, %ProcessManagerInstance{} = state) do
%RecordedEvent{event_number: event_number} = event
%ProcessManagerInstance{last_seen_event: last_seen_event} = state
event_number <= last_seen_event
end
# Already seen event, so just ack
defp process_seen_event(event, state) do
:ok = ack_event(event, state)
{:noreply, state}
end
defp process_unseen_event(event, state, context \\ %{}) do
%RecordedEvent{
correlation_id: correlation_id,
event_id: event_id,
event_number: event_number
} = event
case handle_event(event, state) do
{:error, error} ->
Logger.error(fn ->
describe(state) <>
" failed to handle event #{inspect(event_number)} due to: #{inspect(error)}"
end)
handle_event_error({:error, error}, event, state, context)
{:stop, _error, _state} = reply ->
reply
commands ->
# Copy event id, as causation id, and correlation id from handled event.
opts = [causation_id: event_id, correlation_id: correlation_id]
with :ok <- commands |> List.wrap() |> dispatch_commands(opts, state, event) do
process_state = mutate_state(event, state)
state = %ProcessManagerInstance{
state
| process_state: process_state,
last_seen_event: event_number
}
:ok = persist_state(event_number, state)
:ok = ack_event(event, state)
{:noreply, state}
else
{:stop, reason} ->
{:stop, reason, state}
end
end
end
# Process instance is given the event and returns applicable commands
# (may be none, one or many).
defp handle_event(%RecordedEvent{} = event, %ProcessManagerInstance{} = state) do
%RecordedEvent{data: data} = event
%ProcessManagerInstance{
process_manager_module: process_manager_module,
process_state: process_state
} = state
try do
process_manager_module.handle(process_state, data)
rescue
e -> {:error, e}
end
end
defp handle_event_error(error, failed_event, state, context) do
%RecordedEvent{data: data} = failed_event
%ProcessManagerInstance{process_manager_module: process_manager_module} = state
failure_context = %FailureContext{
pending_commands: [],
process_manager_state: state,
last_event: failed_event,
context: context
}
case process_manager_module.error(error, data, failure_context) do
{:retry, context} when is_map(context) ->
# Retry the failed event
Logger.info(fn -> describe(state) <> " is retrying failed event" end)
process_unseen_event(failed_event, state, context)
{:retry, delay, context} when is_map(context) and is_integer(delay) and delay >= 0 ->
# Retry the failed event after waiting for the given delay, in milliseconds
Logger.info(fn ->
describe(state) <> " is retrying failed event after #{inspect(delay)}ms"
end)
:timer.sleep(delay)
process_unseen_event(failed_event, state, context)
:skip ->
# Skip the failed event by confirming receipt
Logger.info(fn -> describe(state) <> " is skipping event" end)
:ok = ack_event(failed_event, state)
{:noreply, state}
{:stop, error} ->
# Stop the process manager instance
Logger.warn(fn -> describe(state) <> " has requested to stop: #{inspect(error)}" end)
{:stop, error, state}
invalid ->
Logger.warn(fn ->
describe(state) <> " returned an invalid error response: #{inspect(invalid)}"
end)
# Stop process manager with original error
{:stop, error, state}
end
end
# update the process instance's state by applying the event
defp mutate_state(%RecordedEvent{data: data}, %ProcessManagerInstance{
process_manager_module: process_manager_module,
process_state: process_state
}) do
process_manager_module.apply(process_state, data)
end
defp dispatch_commands(commands, opts, state, last_event, context \\ %{})
defp dispatch_commands([], _opts, _state, _last_event, _context), do: :ok
defp dispatch_commands([command | pending_commands], opts, state, last_event, context) do
Logger.debug(fn ->
describe(state) <> " attempting to dispatch command: #{inspect(command)}"
end)
case state.command_dispatcher.dispatch(command, opts) do
:ok ->
dispatch_commands(pending_commands, opts, state, last_event)
# when include_execution_result is set to true, the dispatcher returns an :ok tuple
{:ok, _} ->
dispatch_commands(pending_commands, opts, state, last_event)
error ->
Logger.warn(fn ->
describe(state) <>
" failed to dispatch command #{inspect(command)} due to: #{inspect(error)}"
end)
failure_context = %FailureContext{
pending_commands: pending_commands,
process_manager_state: mutate_state(last_event, state),
last_event: last_event,
context: context
}
dispatch_failure(error, command, opts, state, failure_context)
end
end
defp dispatch_failure(error, failed_command, opts, state, failure_context) do
%ProcessManagerInstance{process_manager_module: process_manager_module} = state
%FailureContext{pending_commands: pending_commands, last_event: last_event} = failure_context
case process_manager_module.error(error, failed_command, failure_context) do
{:continue, commands, context} when is_list(commands) ->
# continue dispatching the given commands
Logger.info(fn -> describe(state) <> " is continuing with modified command(s)" end)
dispatch_commands(commands, opts, state, last_event, context)
{:retry, context} ->
# retry the failed command immediately
Logger.info(fn -> describe(state) <> " is retrying failed command" end)
dispatch_commands([failed_command | pending_commands], opts, state, last_event, context)
{:retry, delay, context} when is_integer(delay) ->
# retry the failed command after waiting for the given delay, in milliseconds
Logger.info(fn ->
describe(state) <> " is retrying failed command after #{inspect(delay)}ms"
end)
:timer.sleep(delay)
dispatch_commands([failed_command | pending_commands], opts, state, last_event, context)
{:skip, :discard_pending} ->
# skip the failed command and discard any pending commands
Logger.info(fn ->
describe(state) <>
" is skipping event and #{length(pending_commands)} pending command(s)"
end)
:ok
{:skip, :continue_pending} ->
# skip the failed command, but continue dispatching any pending commands
Logger.info(fn -> describe(state) <> " is ignoring error dispatching command" end)
dispatch_commands(pending_commands, opts, state, last_event)
{:stop, reason} = reply ->
# stop process manager
Logger.warn(fn -> describe(state) <> " has requested to stop: #{inspect(reason)}" end)
reply
end
end
defp describe(%ProcessManagerInstance{process_manager_module: process_manager_module}),
do: inspect(process_manager_module)
defp persist_state(source_version, %ProcessManagerInstance{} = state) do
%ProcessManagerInstance{
process_manager_module: process_manager_module,
process_state: process_state
} = state
EventStore.record_snapshot(%SnapshotData{
source_uuid: process_state_uuid(state),
source_version: source_version,
source_type: Atom.to_string(process_manager_module),
data: process_state
})
end
defp delete_state(%ProcessManagerInstance{} = state) do
EventStore.delete_snapshot(process_state_uuid(state))
end
defp ack_event(%RecordedEvent{} = event, %ProcessManagerInstance{} = state) do
%ProcessManagerInstance{process_router: process_router} = state
ProcessRouter.ack_event(process_router, event, self())
end
defp process_state_uuid(%ProcessManagerInstance{} = state) do
%ProcessManagerInstance{
process_manager_name: process_manager_name,
process_uuid: process_uuid
} = state
"#{process_manager_name}-#{process_uuid}"
end
end
| 30.942857 | 97 | 0.676992 |
0887ad95e09cda4b72d478191827b7817a3018d7 | 1,214 | exs | Elixir | test/couchdb_connector/reader_test.exs | PinheiroRodrigo/couchdb_connector | 464136ebe47049c5b3143bbd5f74977c82c9c621 | [
"Apache-2.0"
] | 64 | 2016-01-20T17:48:05.000Z | 2017-05-24T18:00:14.000Z | test/couchdb_connector/reader_test.exs | PinheiroRodrigo/couchdb_connector | 464136ebe47049c5b3143bbd5f74977c82c9c621 | [
"Apache-2.0"
] | 40 | 2016-01-16T18:39:46.000Z | 2017-06-03T10:02:54.000Z | test/couchdb_connector/reader_test.exs | PinheiroRodrigo/couchdb_connector | 464136ebe47049c5b3143bbd5f74977c82c9c621 | [
"Apache-2.0"
] | 22 | 2015-12-28T00:23:20.000Z | 2017-05-28T21:58:21.000Z | defmodule Couchdb.Connector.ReaderTest do
use ExUnit.Case
use Couchdb.Connector.TestSupport.Macros
alias Couchdb.Connector.Reader
alias Couchdb.Connector.TestConfig
alias Couchdb.Connector.TestPrep
setup context do
TestPrep.ensure_database
TestPrep.ensure_document "{\"test_key\": \"test_value\"}", "foo"
on_exit context, fn ->
TestPrep.delete_database
end
end
# Test cases for unsecured database
test "get/2: ensure that document exists" do
{:ok, json} = retry_on_error(
fn() -> Reader.get(TestConfig.database_properties, "foo") end)
{:ok, json_map} = Poison.decode json
assert json_map["test_key"] == "test_value"
end
test "get/2: ensure an error is returned for missing document" do
{:error, json} = retry_on_error(
fn() -> Reader.get(TestConfig.database_properties, "unicorn") end)
{:ok, json_map} = Poison.decode json
assert json_map["reason"] == "missing"
end
test "fetch_uuid/1: get a single uuid from database server" do
{:ok, json} = retry_on_error(
fn() -> Reader.fetch_uuid(TestConfig.database_properties) end)
uuid = hd(Poison.decode!(json)["uuids"])
assert String.length(uuid) == 32
end
end
| 30.35 | 72 | 0.696046 |
0887df14b4dcb13fa6e568dd0f281158270020fb | 569 | exs | Elixir | Primer/7_enumerables.exs | joelbandi/elixir-start-here | 65722377d455a4b4678658eee56713681c6f16ce | [
"MIT"
] | null | null | null | Primer/7_enumerables.exs | joelbandi/elixir-start-here | 65722377d455a4b4678658eee56713681c6f16ce | [
"MIT"
] | null | null | null | Primer/7_enumerables.exs | joelbandi/elixir-start-here | 65722377d455a4b4678658eee56713681c6f16ce | [
"MIT"
] | null | null | null | # Lets use the default Enum function to use firstclass function
defmodule Sample.Utils do
def square(n) do
n*n
end
def sum(a,b) do
a+b
end
# anonymous function test
def anon_test(a,f) do
f.(a)
end
end
# '&' is the reference to squaring function and pass in the arity too
IO.puts Enum.map([1,2,3,4,5], &Sample.Utils.square/1)
# using anonymous functions
IO.puts Enum.map([1,2,3,4,5], fn(x) -> x*x end)
Sample.Utils.anon_test("test string", fn(x) -> IO.puts x end)
# Use f.(arg) if you want to call an anonymous function from a fucniton! | 21.074074 | 72 | 0.676626 |
088818b39c52e793317261a5d5749c2963fb1f99 | 219 | exs | Elixir | apps/gitgud/config/dev.exs | chulkilee/gitgud | 7a9b1023ff986ca08fb821a5e7658904a6061ba3 | [
"MIT"
] | null | null | null | apps/gitgud/config/dev.exs | chulkilee/gitgud | 7a9b1023ff986ca08fb821a5e7658904a6061ba3 | [
"MIT"
] | null | null | null | apps/gitgud/config/dev.exs | chulkilee/gitgud | 7a9b1023ff986ca08fb821a5e7658904a6061ba3 | [
"MIT"
] | null | null | null | use Mix.Config
# Configure your database
config :gitgud, GitGud.DB,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
database: "gitgud_dev",
hostname: "localhost",
pool_size: 10
| 19.909091 | 34 | 0.721461 |
08881f24a255d02d3a17887e99a6352370ed8405 | 2,468 | ex | Elixir | clients/reseller/lib/google_api/reseller/v1/model/subscription_transfer_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/reseller/lib/google_api/reseller/v1/model/subscription_transfer_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/reseller/lib/google_api/reseller/v1/model/subscription_transfer_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Reseller.V1.Model.SubscriptionTransferInfo do
@moduledoc """
Read-only transfer related information for the subscription. For more information, see retrieve transferable subscriptions for a customer.
## Attributes
* `currentLegacySkuId` (*type:* `String.t`, *default:* `nil`) - The `skuId` of the current resold subscription. This is populated only when the customer has a subscription with a legacy SKU and the subscription resource is populated with the `skuId` of the SKU recommended for the transfer.
* `minimumTransferableSeats` (*type:* `integer()`, *default:* `nil`) - When inserting a subscription, this is the minimum number of seats listed in the transfer order for this product. For example, if the customer has 20 users, the reseller cannot place a transfer order of 15 seats. The minimum is 20 seats.
* `transferabilityExpirationTime` (*type:* `String.t`, *default:* `nil`) - The time when transfer token or intent to transfer will expire. The time is in milliseconds using UNIX Epoch format.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:currentLegacySkuId => String.t() | nil,
:minimumTransferableSeats => integer() | nil,
:transferabilityExpirationTime => String.t() | nil
}
field(:currentLegacySkuId)
field(:minimumTransferableSeats)
field(:transferabilityExpirationTime)
end
defimpl Poison.Decoder, for: GoogleApi.Reseller.V1.Model.SubscriptionTransferInfo do
def decode(value, options) do
GoogleApi.Reseller.V1.Model.SubscriptionTransferInfo.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Reseller.V1.Model.SubscriptionTransferInfo do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 46.566038 | 312 | 0.752836 |
0888201f28cd4f8bf8575819bd5a613154423e9a | 3,213 | ex | Elixir | lib/reactive_commons/runtime/message_context.ex | bancolombia/reactive-commons-elixir | eaf740d596cadbe44a6914de1783fe9aba2001b9 | [
"Apache-2.0"
] | 4 | 2021-06-01T20:39:34.000Z | 2021-08-06T14:51:57.000Z | lib/reactive_commons/runtime/message_context.ex | bancolombia/reactive-commons-elixir | eaf740d596cadbe44a6914de1783fe9aba2001b9 | [
"Apache-2.0"
] | 5 | 2022-03-04T19:15:47.000Z | 2022-03-04T21:57:23.000Z | lib/reactive_commons/runtime/message_context.ex | bancolombia/reactive-commons-elixir | eaf740d596cadbe44a6914de1783fe9aba2001b9 | [
"Apache-2.0"
] | null | null | null | defmodule MessageContext do
@moduledoc """
This module maintain the required settings to achieve communication with the message broker, it also provides default semantic settings
"""
use GenServer
require Logger
@table_name :msg_ctx
@default_values %{
reply_exchange: "globalReply",
direct_exchange: "directMessages",
events_exchange: "domainEvents",
connection_props: "amqp://guest:guest@localhost",
connection_assignation: %{
ReplyListener: ListenerConn,
QueryListener: ListenerConn,
CommandListener: ListenerConn,
EventListener: ListenerConn,
MessageExtractor: ListenerConn,
MessageSender: SenderConn,
ListenerController: SenderConn,
},
with_dlq_retry: false,
retry_delay: 500,
max_retries: 10,
prefetch_count: 250,
}
def start_link(config = %AsyncConfig{}) do
GenServer.start_link(__MODULE__, config, name: __MODULE__)
end
@impl
def init(config = %AsyncConfig{}) do
config
|> put_default_values()
|> put_route_info()
|> save_in_ets()
{:ok, nil}
end
def save_handlers_config(config = %HandlersConfig{}) do
GenServer.call(__MODULE__, {:save_handlers_config, config})
end
defp put_route_info(config = %AsyncConfig{application_name: app_name}) do
%AsyncConfig{
config |
reply_routing_key: NameGenerator.generate(),
reply_queue: NameGenerator.generate(app_name),
query_queue: "#{app_name}.query",
event_queue: "#{app_name}.subsEvents",
command_queue: "#{app_name}",
}
end
defp put_default_values(config = %AsyncConfig{}) do
@default_values
|> Enum.reduce(config, fn {key, value}, conf -> put_if_nil(conf, key, value) end)
end
defp put_if_nil(map, key, value) do
case Map.get(map, key) do
nil -> Map.put(map, key, value)
_ -> map
end
end
defp save_in_ets(config) do
:ets.new(@table_name, [:named_table, read_concurrency: true])
:ets.insert(@table_name, {:conf, config})
end
def reply_queue_name(), do: config().reply_queue
def query_queue_name(), do: config().query_queue
def command_queue_name(), do: config().command_queue
def event_queue_name(), do: config().event_queue
def reply_routing_key(), do: config().reply_routing_key
def reply_exchange_name(), do: config().reply_exchange
def direct_exchange_name(), do: config().direct_exchange
def events_exchange_name(), do: config().events_exchange
def with_dlq_retry(), do: config().with_dlq_retry
def retry_delay(), do: config().retry_delay
def max_retries(), do: config().max_retries
def prefetch_count(), do: config().prefetch_count
def application_name(), do: config().application_name
def config() do
[{:conf, config}] = :ets.lookup(@table_name, :conf)
config
end
def handlers() do
case :ets.lookup(@table_name, :handlers) do
[{:handlers, config}] -> config
[] -> []
end
end
@impl true
def handle_call({:save_handlers_config, config}, _from, state) do
Logger.info "Saving handlers config!"
true = :ets.insert(@table_name, {:handlers, config})
{:reply, :ok, state}
end
def table() do
:ets.tab2list(@table_name)
end
end
| 28.433628 | 139 | 0.688142 |
088831939118a95ea23ddcd8b3a77d4d66590ec9 | 4,064 | ex | Elixir | apps/definition_presto/lib/presto/table/destination.ex | jdenen/hindsight | ef69b4c1a74c94729dd838a9a0849a48c9b6e04c | [
"Apache-2.0"
] | 12 | 2020-01-27T19:43:02.000Z | 2021-07-28T19:46:29.000Z | apps/definition_presto/lib/presto/table/destination.ex | jdenen/hindsight | ef69b4c1a74c94729dd838a9a0849a48c9b6e04c | [
"Apache-2.0"
] | 81 | 2020-01-28T18:07:23.000Z | 2021-11-22T02:12:13.000Z | apps/definition_presto/lib/presto/table/destination.ex | jdenen/hindsight | ef69b4c1a74c94729dd838a9a0849a48c9b6e04c | [
"Apache-2.0"
] | 10 | 2020-02-13T21:24:09.000Z | 2020-05-21T18:39:35.000Z | defmodule Presto.Table.Destination do
@moduledoc false
use GenServer
use Properties, otp_app: :definition_presto
require Logger
alias Presto.Table.{DataFile, DataStorage, Manager}
getter(:catalog, required: true)
getter(:user, required: true)
getter(:write_timeout, default: 25_000)
getter(:no_activity_timeout, default: 10_000)
getter(:staged_batches_count, default: 50)
def start_link(table, context) do
GenServer.start_link(__MODULE__, {table, context})
end
def write(_table, server, messages) do
GenServer.call(server, {:write, messages}, write_timeout())
end
def stop(_table, server) do
GenServer.call(server, :stop, write_timeout())
end
def delete(table) do
session = new_session(table)
Manager.delete(session, table.name)
staging_table = "#{table.name}__staging"
Manager.delete(session, staging_table)
:ok
end
def init({table, context}) do
Logger.debug(fn -> "#{__MODULE__}: init with #{inspect(table)} - #{inspect(context)}" end)
state = %{
table: table,
context: context,
session: new_session(table),
staging_table: "#{table.name}__staging",
staged: 0
}
{:ok, state, {:continue, :init}}
end
def handle_continue(:init, state) do
with :ok <- Manager.create(state.session, state.table.name, state.context.dictionary, :orc),
{:ok, _} <-
Manager.create_from(state.session, state.staging_table, state.table.name,
format: DataFile.format()
) do
{:noreply, state}
else
{:error, reason} ->
Logger.error(fn -> "#{__MODULE__}: handle_continue failed - #{inspect(reason)}" end)
{:stop, reason, state}
end
catch
_, reason ->
Logger.error(fn ->
"#{__MODULE__}: unexpected error - #{inspect(reason)} - #{inspect(__STACKTRACE__)}"
end)
{:stop, reason, state}
end
def handle_call({:write, messages}, from, state) do
:ok = write_data(messages, state)
new_staged = state.staged + 1
case new_staged >= staged_batches_count() do
true ->
GenServer.reply(from, :ok)
copy_to_production(state)
{:noreply, %{state | staged: 0}}
false ->
{:reply, :ok, %{state | staged: new_staged}, no_activity_timeout()}
end
catch
_, reason ->
Logger.error(fn ->
"#{__MODULE__}: unexpected error - #{inspect(reason)} - #{inspect(__STACKTRACE__)}"
end)
{:stop, reason, state}
end
def handle_call(:stop, _from, state) do
Logger.info(fn -> "#{__MODULE__}: asked to terminate" end)
{:stop, :normal, :ok, state}
end
def handle_info(:timeout, %{staged: staged} = state) when staged > 0 do
copy_to_production(state)
{:noreply, %{state | staged: 0}}
end
def handle_info(:timeout, state) do
{:noreply, state}
end
defp write_data(messages, state) do
with {:ok, data_file} <-
Presto.Table.DataFile.open(state.staging_table, state.context.dictionary),
{:ok, _size} <- Presto.Table.DataFile.write(data_file, messages),
file_path <- Presto.Table.DataFile.close(data_file),
{:ok, _} <- upload_file(file_path, state.staging_table) do
File.rm(file_path)
:ok
end
end
defp upload_file(file_path, table_name) do
extension = Path.extname(file_path)
DataStorage.upload(
file_path,
"#{table_name}/#{:erlang.system_time(:nanosecond)}#{extension}"
)
end
defp copy_to_production(state) do
Logger.debug(fn ->
"#{__MODULE__}: Copying from #{state.staging_table} to #{state.table.name}"
end)
{:ok, _} = Presto.Table.Manager.copy(state.session, state.staging_table, state.table.name)
:ok = DataStorage.delete(state.staging_table)
Logger.debug(fn ->
"#{__MODULE__}: DONE Copying from #{state.staging_table} to #{state.table.name}"
end)
end
defp new_session(table) do
Prestige.new_session(
url: table.url,
catalog: catalog(),
schema: table.schema,
user: user()
)
end
end
| 27.275168 | 96 | 0.639518 |
088841e215ffa129f20241d5a3ec72829a9e9043 | 1,682 | ex | Elixir | clients/service_management/lib/google_api/service_management/v1/model/list_service_rollouts_response.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/service_management/lib/google_api/service_management/v1/model/list_service_rollouts_response.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/service_management/lib/google_api/service_management/v1/model/list_service_rollouts_response.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.ServiceManagement.V1.Model.ListServiceRolloutsResponse do
@moduledoc """
Response message for ListServiceRollouts method.
## Attributes
- nextPageToken (String): The token of the next page of results. Defaults to: `null`.
- rollouts (List[Rollout]): The list of rollout resources. Defaults to: `null`.
"""
defstruct [
:"nextPageToken",
:"rollouts"
]
end
defimpl Poison.Decoder, for: GoogleApi.ServiceManagement.V1.Model.ListServiceRolloutsResponse do
import GoogleApi.ServiceManagement.V1.Deserializer
def decode(value, options) do
value
|> deserialize(:"rollouts", :list, GoogleApi.ServiceManagement.V1.Model.Rollout, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceManagement.V1.Model.ListServiceRolloutsResponse do
def encode(value, options) do
GoogleApi.ServiceManagement.V1.Deserializer.serialize_non_nil(value, options)
end
end
| 33.64 | 96 | 0.763971 |
088854fd43f47d3e141d41e07dd9f383de273d6f | 929 | ex | Elixir | test/support/channel_case.ex | eahanson/corex | 550020c5cbfc7dc828bc74e1edf0223c1cbffef1 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | eahanson/corex | 550020c5cbfc7dc828bc74e1edf0223c1cbffef1 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | eahanson/corex | 550020c5cbfc7dc828bc74e1edf0223c1cbffef1 | [
"MIT"
] | null | null | null | defmodule CorexWeb.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build common datastructures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
use Phoenix.ChannelTest
# The default endpoint for testing
@endpoint CorexWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Corex.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Corex.Repo, {:shared, self()})
end
:ok
end
end
| 24.447368 | 67 | 0.713671 |
08886fc1bf9b62ff6b9a830fbdce7797fe01334a | 7,883 | exs | Elixir | test/mix/tasks/phoenix.gen.model_test.exs | seejee/phoenix | 3f7bed87d74be9e3100492545e3750e80765c271 | [
"MIT"
] | 1 | 2019-06-11T20:22:21.000Z | 2019-06-11T20:22:21.000Z | test/mix/tasks/phoenix.gen.model_test.exs | DavidAlphaFox/phoenix | 560131ab3b48c6b6cf864a3d20b7667e40990237 | [
"MIT"
] | null | null | null | test/mix/tasks/phoenix.gen.model_test.exs | DavidAlphaFox/phoenix | 560131ab3b48c6b6cf864a3d20b7667e40990237 | [
"MIT"
] | null | null | null | Code.require_file "../../../installer/test/mix_helper.exs", __DIR__
defmodule Phoenix.Dup do
end
defmodule Phoenix.Article do
def __schema__(:source), do: "articles"
end
defmodule Mix.Tasks.Phoenix.Gen.ModelTest do
use ExUnit.Case
import MixHelper
setup do
Mix.Task.clear
:ok
end
test "generates model" do
in_tmp "generates model", fn ->
Mix.Tasks.Phoenix.Gen.Model.run ["user", "users", "name", "age:integer", "nicks:array:text",
"famous:boolean", "born_at:datetime", "secret:uuid", "desc:text"]
assert [migration] = Path.wildcard("priv/repo/migrations/*_create_user.exs")
assert_file migration, fn file ->
assert file =~ "defmodule Phoenix.Repo.Migrations.CreateUser do"
assert file =~ "create table(:users) do"
assert file =~ "add :name, :string"
assert file =~ "add :age, :integer"
assert file =~ "add :nicks, {:array, :text}"
assert file =~ "add :famous, :boolean, default: false"
assert file =~ "add :born_at, :datetime"
assert file =~ "add :secret, :uuid"
assert file =~ "add :desc, :text"
assert file =~ "timestamps"
end
assert_file "web/models/user.ex", fn file ->
assert file =~ "defmodule Phoenix.User do"
assert file =~ "use Phoenix.Web, :model"
assert file =~ "schema \"users\" do"
assert file =~ "field :name, :string"
assert file =~ "field :age, :integer"
assert file =~ "field :nicks, {:array, :string}"
assert file =~ "field :famous, :boolean, default: false"
assert file =~ "field :born_at, Ecto.DateTime"
assert file =~ "field :secret, Ecto.UUID"
assert file =~ "field :desc, :string"
assert file =~ "timestamps"
assert file =~ "def changeset"
assert file =~ "~w(name age nicks famous born_at secret desc)"
end
assert_file "test/models/user_test.exs", fn file ->
assert file =~ "defmodule Phoenix.UserTest"
assert file =~ "use Phoenix.ModelCase"
assert file =~ ~S|@valid_attrs %{age: 42|
assert file =~ ~S|changeset(%User{}, @valid_attrs)|
assert file =~ ~S|assert changeset.valid?|
assert file =~ ~S|@invalid_attrs %{}|
assert file =~ ~S|changeset(%User{}, @invalid_attrs)|
assert file =~ ~S|refute changeset.valid?|
end
end
end
test "generates nested model" do
in_tmp "generates nested model", fn ->
Mix.Tasks.Phoenix.Gen.Model.run ["Admin.User", "users", "name:string"]
assert [migration] = Path.wildcard("priv/repo/migrations/*_create_admin_user.exs")
assert_file migration, fn file ->
assert file =~ "defmodule Phoenix.Repo.Migrations.CreateAdmin.User do"
assert file =~ "create table(:users) do"
end
assert_file "web/models/admin/user.ex", fn file ->
assert file =~ "defmodule Phoenix.Admin.User do"
assert file =~ "use Phoenix.Web, :model"
assert file =~ "schema \"users\" do"
end
end
end
test "generates belongs_to associations with association table provided by user" do
in_tmp "generates belongs_to associations", fn ->
Mix.Tasks.Phoenix.Gen.Model.run ["Post", "posts", "title", "user_id:references:users"]
assert [migration] = Path.wildcard("priv/repo/migrations/*_create_post.exs")
assert_file migration, fn file ->
assert file =~ "defmodule Phoenix.Repo.Migrations.CreatePost do"
assert file =~ "create table(:posts) do"
assert file =~ "add :title, :string"
assert file =~ "add :user_id, references(:users, on_delete: :nothing)"
end
assert_file "web/models/post.ex", fn file ->
assert file =~ "defmodule Phoenix.Post do"
assert file =~ "use Phoenix.Web, :model"
assert file =~ "schema \"posts\" do"
assert file =~ "field :title, :string"
assert file =~ "belongs_to :user, Phoenix.User"
end
end
end
test "generates unique_index" do
in_tmp "generates unique_index", fn ->
Mix.Tasks.Phoenix.Gen.Model.run ["Post", "posts", "title:unique", "unique_int:integer:unique", "unique_float:float:unique"]
assert [migration] = Path.wildcard("priv/repo/migrations/*_create_post.exs")
assert_file migration, fn file ->
assert file =~ "defmodule Phoenix.Repo.Migrations.CreatePost do"
assert file =~ "create table(:posts) do"
assert file =~ "add :title, :string"
assert file =~ "add :unique_int, :integer"
assert file =~ "add :unique_float, :float"
assert file =~ "create unique_index(:posts, [:title])"
assert file =~ "create unique_index(:posts, [:unique_int])"
assert file =~ "create unique_index(:posts, [:unique_float])"
end
assert_file "web/models/post.ex", fn file ->
assert file =~ "defmodule Phoenix.Post do"
assert file =~ "use Phoenix.Web, :model"
assert file =~ "schema \"posts\" do"
assert file =~ "field :title, :string"
assert file =~ "field :unique_int, :integer"
assert file =~ "|> unique_constraint(:title)"
assert file =~ "|> unique_constraint(:unique_int)"
end
end
end
test "generates migration with binary_id" do
in_tmp "generates migration with binary_id", fn ->
Mix.Tasks.Phoenix.Gen.Model.run ["Post", "posts", "title", "user_id:references:users", "--binary-id"]
assert [migration] = Path.wildcard("priv/repo/migrations/*_create_post.exs")
assert_file migration, fn file ->
assert file =~ "create table(:posts, primary_key: false) do"
assert file =~ "add :id, :binary_id, primary_key: true"
assert file =~ "add :user_id, references(:users, on_delete: :nothing, type: :binary_id)"
end
end
end
test "skips migration with --no-migration option" do
in_tmp "skips migration with -no-migration option", fn ->
Mix.Tasks.Phoenix.Gen.Model.run ["Post", "posts", "--no-migration"]
assert [] = Path.wildcard("priv/repo/migrations/*_create_post.exs")
end
end
test "uses defaults from :generators configuration" do
in_tmp "uses defaults from generators configuration (migration)", fn ->
with_generators_config [migration: false], fn ->
Mix.Tasks.Phoenix.Gen.Model.run ["Post", "posts"]
assert [] = Path.wildcard("priv/repo/migrations/*_create_post.exs")
end
end
in_tmp "uses defaults from generators configuration (binary_id)", fn ->
with_generators_config [binary_id: true], fn ->
Mix.Tasks.Phoenix.Gen.Model.run ["Post", "posts"]
assert [migration] = Path.wildcard("priv/repo/migrations/*_create_post.exs")
assert_file migration, fn file ->
assert file =~ "create table(:posts, primary_key: false) do"
assert file =~ "add :id, :binary_id, primary_key: true"
end
end
end
end
test "plural can't contain a colon" do
assert_raise Mix.Error, fn ->
Mix.Tasks.Phoenix.Gen.Model.run ["Admin.User", "name:string", "foo:string"]
end
end
test "plural can't have uppercased characters or camelized format" do
assert_raise Mix.Error, fn ->
Mix.Tasks.Phoenix.Gen.Html.run ["Admin.User", "Users", "foo:string"]
end
assert_raise Mix.Error, fn ->
Mix.Tasks.Phoenix.Gen.Html.run ["Admin.User", "AdminUsers", "foo:string"]
end
end
test "name is already defined" do
assert_raise Mix.Error, fn ->
Mix.Tasks.Phoenix.Gen.Model.run ["Dup", "dups"]
end
end
defp with_generators_config(config, fun) do
old_value = Application.get_env(:phoenix, :generators, [])
try do
Application.put_env(:phoenix, :generators, config)
fun.()
after
Application.put_env(:phoenix, :generators, old_value)
end
end
end
| 36.16055 | 129 | 0.629583 |
08887a03e416665faf68ed3c229e8644eb13bde0 | 686 | exs | Elixir | exercises/bowling/bowling.exs | Triangle-Elixir/xelixir | 08d23bf47f57799f286567cb26f635291de2fde5 | [
"MIT"
] | 1 | 2021-08-16T20:24:14.000Z | 2021-08-16T20:24:14.000Z | exercises/bowling/bowling.exs | Triangle-Elixir/xelixir | 08d23bf47f57799f286567cb26f635291de2fde5 | [
"MIT"
] | null | null | null | exercises/bowling/bowling.exs | Triangle-Elixir/xelixir | 08d23bf47f57799f286567cb26f635291de2fde5 | [
"MIT"
] | null | null | null | defmodule Bowling do
@doc """
Creates a new game of bowling that can be used to store the results of
the game
"""
@spec start() :: any
def start do
end
@doc """
Records the number of pins knocked down on a single roll. Returns `:ok`
unless there is something wrong with the given number of pins, in which
case it returns a helpful message.
"""
@spec roll(any, integer) :: any | String.t
def roll(game, roll) do
end
@doc """
Returns the score of a given game of bowling if the game is complete.
If the game isn't complete, it returns a helpful message.
"""
@spec score(any) :: integer | String.t
def score(game) do
end
end
| 22.129032 | 75 | 0.655977 |
0888c743a38b5d5d816a175d02758eb4397c4559 | 1,984 | ex | Elixir | clients/genomics/lib/google_api/genomics/v2alpha1/model/existing_disk.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/genomics/lib/google_api/genomics/v2alpha1/model/existing_disk.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/genomics/lib/google_api/genomics/v2alpha1/model/existing_disk.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Genomics.V2alpha1.Model.ExistingDisk do
@moduledoc """
Configuration for an existing disk to be attached to the VM.
## Attributes
* `disk` (*type:* `String.t`, *default:* `nil`) - If `disk` contains slashes, the Cloud Life Sciences API assumes that it is a complete URL for the disk. If `disk` does not contain slashes, the Cloud Life Sciences API assumes that the disk is a zonal disk and a URL will be generated of the form `zones//disks/`, where `` is the zone in which the instance is allocated. The disk must be ext4 formatted. If all `Mount` references to this disk have the `read_only` flag set to true, the disk will be attached in `read-only` mode and can be shared with other instances. Otherwise, the disk will be available for writing but cannot be shared.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:disk => String.t() | nil
}
field(:disk)
end
defimpl Poison.Decoder, for: GoogleApi.Genomics.V2alpha1.Model.ExistingDisk do
def decode(value, options) do
GoogleApi.Genomics.V2alpha1.Model.ExistingDisk.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Genomics.V2alpha1.Model.ExistingDisk do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 42.212766 | 642 | 0.74496 |
0888dccc8283b7982b2bd3afe15fb6ffd30903cb | 2,462 | exs | Elixir | server/config/dev.exs | BlueHotDog/buff | 0403f68867e950945a47cce2d7442974d12583b2 | [
"MIT"
] | 1 | 2020-03-18T17:29:32.000Z | 2020-03-18T17:29:32.000Z | server/config/dev.exs | BlueHotDog/buff | 0403f68867e950945a47cce2d7442974d12583b2 | [
"MIT"
] | 26 | 2019-06-09T18:35:45.000Z | 2020-07-30T17:05:58.000Z | server/config/dev.exs | BlueHotDog/buff | 0403f68867e950945a47cce2d7442974d12583b2 | [
"MIT"
] | null | null | null | use Mix.Config
config :ex_aws,
region: "local",
access_key_id: "minio",
secret_access_key: "minio123"
config :ex_aws, :s3,
host: "minio",
region: "local",
scheme: "http://",
port: 9000
config :buff_server,
s3_bucket_name: "buff-packages-development"
# Configure your database
config :buff_server, BuffServer.Repo,
username: "postgres",
password: "postgres",
database: "buff_server_dev",
hostname: "postgres",
show_sensitive_data_on_connection_error: true,
pool_size: 10
config :joken, default_signer: "secret"
# 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 webpack to recompile .js and .css sources.
config :buff_server, BuffServerWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--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
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.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 :buff_server, BuffServerWeb.Endpoint,
live_reload: [
patterns: [
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/buff_server_web/{live,views}/.*(ex)$",
~r"lib/buff_server_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
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
| 26.76087 | 68 | 0.694557 |
0888eaab8c20ae7d4ed3f1491825a492907519c0 | 797 | ex | Elixir | lib/verk_web.ex | apodlaski/verk_web | 91c544b1f792f929e06f18e26b964e23a5771a8a | [
"MIT"
] | null | null | null | lib/verk_web.ex | apodlaski/verk_web | 91c544b1f792f929e06f18e26b964e23a5771a8a | [
"MIT"
] | null | null | null | lib/verk_web.ex | apodlaski/verk_web | 91c544b1f792f929e06f18e26b964e23a5771a8a | [
"MIT"
] | null | null | null | defmodule VerkWeb do
use Application
@doc false
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
{VerkWeb.Endpoint, [type: :supervisor]},
# pub sub
{Phoenix.PubSub, [name: VerkWeb.PubSub, adapter: Phoenix.PubSub.PG2]}
]
children =
if Application.get_env(:verk_web, :link_verk_supervisor, false) do
[{Verk.Supervisor, [type: :supervisor]} | children]
else
children
end
:ets.new(:verk_web_session, [:named_table, :public, read_concurrency: true])
opts = [strategy: :one_for_one, name: VerkWeb.Supervisor]
Supervisor.start_link(children, opts)
end
@doc false
def config_change(changed, _new, removed) do
VerkWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 24.151515 | 80 | 0.666248 |
0889021b06e4ebd89c2ad91f848a6c947a2a6168 | 4,901 | exs | Elixir | test/epicenter/accounts/admin_test.exs | geometricservices/epi-viewpoin | ecb5316ea0f3f7299d5ff63e2de588539005ac1c | [
"Apache-2.0"
] | 5 | 2021-02-25T18:43:09.000Z | 2021-02-27T06:00:35.000Z | test/epicenter/accounts/admin_test.exs | geometricservices/epi-viewpoint | ecb5316ea0f3f7299d5ff63e2de588539005ac1c | [
"Apache-2.0"
] | 3 | 2021-12-13T17:52:47.000Z | 2021-12-17T01:35:31.000Z | test/epicenter/accounts/admin_test.exs | geometricservices/epi-viewpoint | ecb5316ea0f3f7299d5ff63e2de588539005ac1c | [
"Apache-2.0"
] | 1 | 2022-01-27T23:26:38.000Z | 2022-01-27T23:26:38.000Z | defmodule Epicenter.Accounts.AdminTest do
use Epicenter.DataCase, async: true
alias Epicenter.Accounts
alias Epicenter.Accounts.Admin
alias Epicenter.Accounts.User
alias Epicenter.Cases
alias Epicenter.Cases.Person
alias Epicenter.Repo
alias Epicenter.Test
setup do
{:ok, persisted_admin} = Test.Fixtures.admin() |> Accounts.change_user(%{}) |> Repo.insert()
unpersisted_admin = %User{id: Application.get_env(:epicenter, :unpersisted_admin_id)}
{:ok, not_admin} = Test.Fixtures.user_attrs(unpersisted_admin, "not-admin") |> Accounts.register_user()
{person_attrs, audit_meta} = Test.Fixtures.person_attrs(persisted_admin, "person")
%{
audit_meta: audit_meta,
person_attrs: person_attrs,
not_admin: not_admin,
persisted_admin: persisted_admin,
unpersisted_admin: unpersisted_admin
}
end
describe "persisted_admin? and unpersisted_admin?" do
test "for persisted admin", %{audit_meta: audit_meta, persisted_admin: persisted_admin} do
audit_meta = %{audit_meta | author_id: persisted_admin.id}
assert Admin.persisted_admin?(audit_meta)
refute Admin.unpersisted_admin?(audit_meta)
end
test "for unpersisted admin", %{audit_meta: audit_meta, unpersisted_admin: unpersisted_admin} do
audit_meta = %{audit_meta | author_id: unpersisted_admin.id}
refute Admin.persisted_admin?(audit_meta)
assert Admin.unpersisted_admin?(audit_meta)
end
test "for non-admin", %{audit_meta: audit_meta, not_admin: not_admin} do
audit_meta = %{audit_meta | author_id: not_admin.id}
refute Admin.persisted_admin?(audit_meta)
refute Admin.unpersisted_admin?(audit_meta)
end
end
describe "insert_by_admin and insert_by_admin!" do
test "succeeds when the author is a persisted admin",
%{persisted_admin: persisted_admin, person_attrs: person_attrs, audit_meta: audit_meta} do
audit_meta = %{audit_meta | author_id: persisted_admin.id}
{:ok, inserted1} = Cases.change_person(%Person{}, person_attrs) |> Admin.insert_by_admin(audit_meta)
assert inserted1.tid == "person"
assert_revision_count(inserted1, 1)
inserted2 = Cases.change_person(%Person{}, person_attrs) |> Admin.insert_by_admin!(audit_meta)
assert inserted2.tid == "person"
assert_revision_count(inserted2, 1)
end
test "succeeds when the author is an unpersisted admin",
%{unpersisted_admin: unpersisted_admin, person_attrs: person_attrs, audit_meta: audit_meta} do
audit_meta = %{audit_meta | author_id: unpersisted_admin.id}
{:ok, inserted1} = Cases.change_person(%Person{}, person_attrs) |> Admin.insert_by_admin(audit_meta)
assert inserted1.tid == "person"
assert_revision_count(inserted1, 1)
inserted2 = Cases.change_person(%Person{}, person_attrs) |> Admin.insert_by_admin!(audit_meta)
assert inserted2.tid == "person"
assert_revision_count(inserted2, 1)
end
test "fails when the author is not an admin",
%{not_admin: not_admin, person_attrs: person_attrs, audit_meta: audit_meta} do
audit_meta = %{audit_meta | author_id: not_admin.id}
{:error, :admin_privileges_required} = Cases.change_person(%Person{}, person_attrs) |> Admin.insert_by_admin(audit_meta)
assert_raise Epicenter.AdminRequiredError, "Action can only be performed by administrators", fn ->
Cases.change_person(%Person{}, person_attrs) |> Admin.insert_by_admin!(audit_meta)
end
end
end
describe "update_by_admin" do
test "succeeds when the author is a persisted admin",
%{persisted_admin: persisted_admin, person_attrs: person_attrs, audit_meta: audit_meta} do
audit_meta = %{audit_meta | author_id: persisted_admin.id}
{:ok, person} = Cases.create_person({person_attrs, audit_meta})
{:ok, updated} = Cases.change_person(person, %{tid: "updated"}) |> Admin.update_by_admin(audit_meta)
assert updated.tid == "updated"
assert_revision_count(updated, 2)
end
test "fails when the author is an unpersisted admin",
%{unpersisted_admin: unpersisted_admin, person_attrs: person_attrs, audit_meta: audit_meta} do
audit_meta = %{audit_meta | author_id: unpersisted_admin.id}
{:ok, person} = Cases.create_person({person_attrs, audit_meta})
{:error, :admin_privileges_required} = Cases.change_person(person, %{tid: "updated"}) |> Admin.update_by_admin(audit_meta)
end
test "fails when the author is not an admin",
%{not_admin: not_admin, person_attrs: person_attrs, audit_meta: audit_meta} do
audit_meta = %{audit_meta | author_id: not_admin.id}
{:ok, person} = Cases.create_person({person_attrs, audit_meta})
{:error, :admin_privileges_required} = Cases.change_person(person, %{tid: "updated"}) |> Admin.update_by_admin(audit_meta)
end
end
end
| 42.991228 | 128 | 0.719241 |
08890429972d51de76cb28f0a42647115b2b20c1 | 1,750 | exs | Elixir | test/mix/tasks/gen_test.exs | basmoura/cpf | a3c37daa7598358b7e15a5ce4b342ed551df79d3 | [
"MIT"
] | 34 | 2019-04-14T22:57:21.000Z | 2022-01-06T01:26:25.000Z | test/mix/tasks/gen_test.exs | basmoura/cpf | a3c37daa7598358b7e15a5ce4b342ed551df79d3 | [
"MIT"
] | 4 | 2019-06-09T15:48:53.000Z | 2022-01-29T13:13:57.000Z | test/mix/tasks/gen_test.exs | basmoura/cpf | a3c37daa7598358b7e15a5ce4b342ed551df79d3 | [
"MIT"
] | 10 | 2019-04-16T04:26:56.000Z | 2020-10-08T18:00:47.000Z | defmodule Mix.Tasks.Cpf.GenTest do
use CPF.MixCase, async: false
describe "run/1" do
import Mix.Tasks.Cpf.Gen, only: [run: 1]
test "generates valid random CPFs" do
run([])
assert_received {:mix_shell, :info, [cpf]}
assert CPF.valid?(cpf)
end
test "accepts the count option" do
count = Enum.random(1..100)
run(["--count=#{count}"])
{:messages, messages} = :erlang.process_info(self(), :messages)
cpfs = for {:mix_shell, :info, [cpf]} <- messages, do: cpf
assert length(cpfs) == count
assert Enum.all?(cpfs, &CPF.valid?/1)
end
test "accepts the standard format" do
run(["--format=standard"])
assert_received {:mix_shell, :info, [cpf]}
assert String.match?(cpf, ~r/[0-9]{3}\.[0-9]{3}\.[0-9]{3}-[0-9]{2}/)
end
test "accepts the digits format" do
run(["--format=digits"])
assert_received {:mix_shell, :info, [cpf]}
assert String.match?(cpf, ~r/[0-9]{11}/)
end
test "accepts the integer format" do
run(["--format=integer"])
assert_received {:mix_shell, :info, [cpf]}
assert String.match?(cpf, ~r/[1-9]{1}[0-9]{1,10}/)
end
test "fails with negative count" do
assert catch_exit(run(["--count=-10"])) == {:shutdown, 1}
{:mix_shell, :error, ["Invalid value `-10` for option --count"]}
end
test "fails with invalid count" do
assert catch_exit(run(["--count=invalid"])) == {:shutdown, 1}
{:mix_shell, :error, ["Invalid value for `--count`"]}
end
test "fails with invalid format" do
assert catch_exit(run(["--format=invalid"])) == {:shutdown, 1}
{:mix_shell, :error, ["Invalid value `invalid` for option --format"]}
end
end
end
| 27.34375 | 75 | 0.589143 |
088931ada10e3d9d72f4e704248938971e722f75 | 1,493 | exs | Elixir | lib/mix/test/mix/tasks/clean_test.exs | enokd/elixir | e39b32f235082b8a29fcb22d250c822cca98609f | [
"Apache-2.0"
] | 1 | 2015-11-12T19:23:45.000Z | 2015-11-12T19:23:45.000Z | lib/mix/test/mix/tasks/clean_test.exs | enokd/elixir | e39b32f235082b8a29fcb22d250c822cca98609f | [
"Apache-2.0"
] | null | null | null | lib/mix/test/mix/tasks/clean_test.exs | enokd/elixir | e39b32f235082b8a29fcb22d250c822cca98609f | [
"Apache-2.0"
] | null | null | null | Code.require_file "../../test_helper.exs", __DIR__
defmodule Mix.Tasks.CleanTest do
use MixTest.Case
defmodule Sample do
def project do
[
app: :sample,
version: "0.1.0",
deps: [
{ :ok, "0.1.0", path: "deps/ok" },
{ :unknown, "0.1.0", git: "deps/unknown" }
]
]
end
end
setup do
Mix.Project.push Sample
:ok
end
test "removes the build application" do
in_fixture "deps_status", fn ->
Mix.Tasks.Compile.run ["--no-deps"]
assert File.exists?("_build/dev/lib/sample")
Mix.Tasks.Clean.run []
refute File.exists?("_build/dev/lib/sample")
end
end
test "cleans deps" do
in_fixture "deps_status", fn ->
assert File.exists?("_build/dev/lib/ok")
Mix.Tasks.Deps.Clean.run ["--all"]
assert File.exists?("_build/dev")
refute File.exists?("_build/dev/lib/ok")
assert_received { :mix_shell, :info, ["* Cleaning ok"] }
# Assert we don't choke on unfetched deps
assert_received { :mix_shell, :info, ["* Cleaning unknown"] }
end
end
test "cleans all deps and builds" do
in_fixture "deps_status", fn ->
assert File.exists?("_build/dev/lib/ok")
Mix.Tasks.Clean.run ["--all"]
assert File.exists?("_build/dev")
refute File.exists?("_build/dev/lib")
assert_received { :mix_shell, :info, ["* Cleaning ok"] }
assert_received { :mix_shell, :info, ["* Cleaning unknown"] }
end
end
end
| 24.883333 | 67 | 0.593436 |
08895d2678f2328ee619450ae76ce9fe3269353d | 11,499 | ex | Elixir | lib/onnx.pb.ex | jeffreyksmithjr/onnxs | 91a0c13a785db19bcd76c9e0d3f26089aadcf106 | [
"MIT"
] | 4 | 2018-05-19T17:00:14.000Z | 2021-04-12T05:29:20.000Z | lib/onnx.pb.ex | jeffreyksmithjr/onnxs | 91a0c13a785db19bcd76c9e0d3f26089aadcf106 | [
"MIT"
] | null | null | null | lib/onnx.pb.ex | jeffreyksmithjr/onnxs | 91a0c13a785db19bcd76c9e0d3f26089aadcf106 | [
"MIT"
] | 1 | 2021-04-12T05:29:35.000Z | 2021-04-12T05:29:35.000Z | defmodule Onnx.AttributeProto do
@moduledoc """
A named attribute containing either singular float, integer, string
and tensor values, or repeated float, integer, string and tensor values.
An AttributeProto MUST contain the name field, and *only one* of the
following content fields, effectively enforcing a C/C++ union equivalent.
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
name: String.t(),
doc_string: String.t(),
type: integer,
f: float,
i: integer,
s: String.t(),
t: Onnx.TensorProto.t(),
g: Onnx.GraphProto.t(),
floats: [float],
ints: [integer],
strings: [String.t()],
tensors: [Onnx.TensorProto.t()],
graphs: [Onnx.GraphProto.t()]
}
defstruct [
:name,
:doc_string,
:type,
:f,
:i,
:s,
:t,
:g,
:floats,
:ints,
:strings,
:tensors,
:graphs
]
field(:name, 1, optional: true, type: :string)
field(:doc_string, 13, optional: true, type: :string)
field(:type, 20, optional: true, type: Onnx.AttributeProto.AttributeType, enum: true)
field(:f, 2, optional: true, type: :float)
field(:i, 3, optional: true, type: :int64)
field(:s, 4, optional: true, type: :bytes)
field(:t, 5, optional: true, type: Onnx.TensorProto)
field(:g, 6, optional: true, type: Onnx.GraphProto)
field(:floats, 7, repeated: true, type: :float)
field(:ints, 8, repeated: true, type: :int64)
field(:strings, 9, repeated: true, type: :bytes)
field(:tensors, 10, repeated: true, type: Onnx.TensorProto)
field(:graphs, 11, repeated: true, type: Onnx.GraphProto)
end
defmodule Onnx.AttributeProto.AttributeType do
@moduledoc """
Note: this enum is structurally identical to the OpSchema::AttrType
enum defined in schema.h. If you rev one, you likely need to rev the other.
"""
use Protobuf, enum: true, syntax: :proto2
field(:UNDEFINED, 0)
field(:FLOAT, 1)
field(:INT, 2)
field(:STRING, 3)
field(:TENSOR, 4)
field(:GRAPH, 5)
field(:FLOATS, 6)
field(:INTS, 7)
field(:STRINGS, 8)
field(:TENSORS, 9)
field(:GRAPHS, 10)
end
defmodule Onnx.ValueInfoProto do
@moduledoc """
Defines information on value, including the name, the type, and
the shape of the value.
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
name: String.t(),
type: Onnx.TypeProto.t(),
doc_string: String.t()
}
defstruct [:name, :type, :doc_string]
field(:name, 1, optional: true, type: :string)
field(:type, 2, optional: true, type: Onnx.TypeProto)
field(:doc_string, 3, optional: true, type: :string)
end
defmodule Onnx.NodeProto do
@moduledoc """
NodeProto stores a node that is similar to the notion of "layer"
or "operator" in many deep learning frameworks. For example, it can be a
node of type "Conv" that takes in an image, a filter tensor and a bias
tensor, and produces the convolved output.
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
input: [String.t()],
output: [String.t()],
name: String.t(),
op_type: String.t(),
domain: String.t(),
attribute: [Onnx.AttributeProto.t()],
doc_string: String.t()
}
defstruct [:input, :output, :name, :op_type, :domain, :attribute, :doc_string]
field(:input, 1, repeated: true, type: :string)
field(:output, 2, repeated: true, type: :string)
field(:name, 3, optional: true, type: :string)
field(:op_type, 4, optional: true, type: :string)
field(:domain, 7, optional: true, type: :string)
field(:attribute, 5, repeated: true, type: Onnx.AttributeProto)
field(:doc_string, 6, optional: true, type: :string)
end
defmodule Onnx.ModelProto do
@moduledoc """
ModelProto is a top-level file/container format for bundling a ML model.
The semantics of the model are described by the GraphProto that represents
a parameterized computation graph against a set of named operators that are
defined independently from the graph.
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
ir_version: integer,
opset_import: [Onnx.OperatorSetIdProto.t()],
producer_name: String.t(),
producer_version: String.t(),
domain: String.t(),
model_version: integer,
doc_string: String.t(),
graph: Onnx.GraphProto.t(),
metadata_props: [Onnx.StringStringEntryProto.t()]
}
defstruct [
:ir_version,
:opset_import,
:producer_name,
:producer_version,
:domain,
:model_version,
:doc_string,
:graph,
:metadata_props
]
field(:ir_version, 1, optional: true, type: :int64)
field(:opset_import, 8, repeated: true, type: Onnx.OperatorSetIdProto)
field(:producer_name, 2, optional: true, type: :string)
field(:producer_version, 3, optional: true, type: :string)
field(:domain, 4, optional: true, type: :string)
field(:model_version, 5, optional: true, type: :int64)
field(:doc_string, 6, optional: true, type: :string)
field(:graph, 7, optional: true, type: Onnx.GraphProto)
field(:metadata_props, 14, repeated: true, type: Onnx.StringStringEntryProto)
end
defmodule Onnx.StringStringEntryProto do
@moduledoc """
StringStringEntryProto follows the pattern for cross-proto-version maps.
See https://developers.google.com/protocol-buffers/docs/proto3#maps
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
key: String.t(),
value: String.t()
}
defstruct [:key, :value]
field(:key, 1, optional: true, type: :string)
field(:value, 2, optional: true, type: :string)
end
defmodule Onnx.GraphProto do
@moduledoc """
GraphProto defines a parameterized series of nodes to form a directed acyclic graph.
This is the equivalent of the "network" and "graph" in many deep learning
frameworks.
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
node: [Onnx.NodeProto.t()],
name: String.t(),
initializer: [Onnx.TensorProto.t()],
doc_string: String.t(),
input: [Onnx.ValueInfoProto.t()],
output: [Onnx.ValueInfoProto.t()],
value_info: [Onnx.ValueInfoProto.t()]
}
defstruct [:node, :name, :initializer, :doc_string, :input, :output, :value_info]
field(:node, 1, repeated: true, type: Onnx.NodeProto)
field(:name, 2, optional: true, type: :string)
field(:initializer, 5, repeated: true, type: Onnx.TensorProto)
field(:doc_string, 10, optional: true, type: :string)
field(:input, 11, repeated: true, type: Onnx.ValueInfoProto)
field(:output, 12, repeated: true, type: Onnx.ValueInfoProto)
field(:value_info, 13, repeated: true, type: Onnx.ValueInfoProto)
end
defmodule Onnx.TensorProto do
@moduledoc """
A message defined to store a tensor in its serialized format.
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
dims: [integer],
data_type: integer,
segment: Onnx.TensorProto.Segment.t(),
float_data: [float],
int32_data: [integer],
string_data: [String.t()],
int64_data: [integer],
name: String.t(),
doc_string: String.t(),
raw_data: String.t(),
double_data: [float],
uint64_data: [non_neg_integer]
}
defstruct [
:dims,
:data_type,
:segment,
:float_data,
:int32_data,
:string_data,
:int64_data,
:name,
:doc_string,
:raw_data,
:double_data,
:uint64_data
]
field(:dims, 1, repeated: true, type: :int64)
field(:data_type, 2, optional: true, type: Onnx.TensorProto.DataType, enum: true)
field(:segment, 3, optional: true, type: Onnx.TensorProto.Segment)
field(:float_data, 4, repeated: true, type: :float, packed: true)
field(:int32_data, 5, repeated: true, type: :int32, packed: true)
field(:string_data, 6, repeated: true, type: :bytes)
field(:int64_data, 7, repeated: true, type: :int64, packed: true)
field(:name, 8, optional: true, type: :string)
field(:doc_string, 12, optional: true, type: :string)
field(:raw_data, 9, optional: true, type: :bytes)
field(:double_data, 10, repeated: true, type: :double, packed: true)
field(:uint64_data, 11, repeated: true, type: :uint64, packed: true)
end
defmodule Onnx.TensorProto.Segment do
@moduledoc """
For very large tensors, we may want to store them in chunks, in which
case the following fields will specify the segment that is stored in
the current TensorProto.
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
begin: integer,
end: integer
}
defstruct [:begin, :end]
field(:begin, 1, optional: true, type: :int64)
field(:end, 2, optional: true, type: :int64)
end
defmodule Onnx.TensorProto.DataType do
@moduledoc false
use Protobuf, enum: true, syntax: :proto2
field(:UNDEFINED, 0)
field(:FLOAT, 1)
field(:UINT8, 2)
field(:INT8, 3)
field(:UINT16, 4)
field(:INT16, 5)
field(:INT32, 6)
field(:INT64, 7)
field(:STRING, 8)
field(:BOOL, 9)
field(:FLOAT16, 10)
field(:DOUBLE, 11)
field(:UINT32, 12)
field(:UINT64, 13)
field(:COMPLEX64, 14)
field(:COMPLEX128, 15)
end
defmodule Onnx.TensorShapeProto do
@moduledoc """
Defines a tensor shape.
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
dim: [Onnx.TensorShapeProto.Dimension.t()]
}
defstruct [:dim]
field(:dim, 1, repeated: true, type: Onnx.TensorShapeProto.Dimension)
end
defmodule Onnx.TensorShapeProto.Dimension do
@moduledoc """
A dimension can be either an integer value
or a symbolic variable. A symbolic variable represents an unknown
dimension.
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
value: {atom, any}
}
defstruct [:value]
oneof(:value, 0)
field(:dim_value, 1, optional: true, type: :int64, oneof: 0)
field(:dim_param, 2, optional: true, type: :string, oneof: 0)
end
defmodule Onnx.TypeProto do
@moduledoc """
Define the types.
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
value: {atom, any}
}
defstruct [:value]
oneof(:value, 0)
field(:tensor_type, 1, optional: true, type: Onnx.TypeProto.Tensor, oneof: 0)
end
defmodule Onnx.TypeProto.Tensor do
@moduledoc false
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
elem_type: integer,
shape: Onnx.TensorShapeProto.t()
}
defstruct [:elem_type, :shape]
field(:elem_type, 1, optional: true, type: Onnx.TensorProto.DataType, enum: true)
field(:shape, 2, optional: true, type: Onnx.TensorShapeProto)
end
defmodule Onnx.OperatorSetIdProto do
@moduledoc """
OperatorSets are uniquely identified by a (domain, opset_version) pair.
"""
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
domain: String.t(),
version: integer
}
defstruct [:domain, :version]
field(:domain, 1, optional: true, type: :string)
field(:version, 2, optional: true, type: :int64)
end
defmodule Onnx.Version do
@moduledoc """
To be compatible with both proto2 and proto3, we will use a version number
that is not defined by the default value but an explicit enum number.
"""
use Protobuf, enum: true, syntax: :proto2
field(:_START_VERSION, 0)
field(:IR_VERSION_2017_10_10, 1)
field(:IR_VERSION_2017_10_30, 2)
field(:IR_VERSION, 3)
end
| 29.484615 | 87 | 0.649274 |
088963d612613d85245c672eae7ccf924cae4467 | 882 | ex | Elixir | broker/test/support/conn_case.ex | mikehelmick/broker-prototype | 68082f753d3a7ea29399706504419e495287b35f | [
"Apache-2.0"
] | 1 | 2019-02-04T21:09:16.000Z | 2019-02-04T21:09:16.000Z | broker/test/support/conn_case.ex | mikehelmick/broker-prototype | 68082f753d3a7ea29399706504419e495287b35f | [
"Apache-2.0"
] | null | null | null | broker/test/support/conn_case.ex | mikehelmick/broker-prototype | 68082f753d3a7ea29399706504419e495287b35f | [
"Apache-2.0"
] | null | null | null | defmodule BrokerWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
alias BrokerWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint BrokerWeb.Endpoint
end
end
setup _tags do
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 26.727273 | 59 | 0.727891 |
08896b34c64d8a9fd55b6fa241b84f21263ea5ac | 1,024 | exs | Elixir | kousa/test/broth/user/unfollow_test.exs | AhmetEsad/dogehouse | ba8c757bc0419ac07bd9bf062c67a39ab74cdfa6 | [
"MIT"
] | 1 | 2021-04-22T08:37:55.000Z | 2021-04-22T08:37:55.000Z | kousa/test/broth/user/unfollow_test.exs | mateuszklysz/dogehouse | ba8c757bc0419ac07bd9bf062c67a39ab74cdfa6 | [
"MIT"
] | null | null | null | kousa/test/broth/user/unfollow_test.exs | mateuszklysz/dogehouse | ba8c757bc0419ac07bd9bf062c67a39ab74cdfa6 | [
"MIT"
] | null | null | null | defmodule BrothTest.User.UnfollowTest do
use ExUnit.Case, async: true
use KousaTest.Support.EctoSandbox
alias Beef.Schemas.User
alias BrothTest.WsClient
alias BrothTest.WsClientFactory
alias KousaTest.Support.Factory
require WsClient
setup do
user = Factory.create(User)
client_ws = WsClientFactory.create_client_for(user)
{:ok, user: user, client_ws: client_ws}
end
describe "the user:unfollow operation" do
test "causes you to to unfollow", t do
followed = Factory.create(User)
Beef.Follows.insert(%{
userId: followed.id,
followerId: t.user.id
})
assert Beef.Follows.following_me?(followed.id, t.user.id)
WsClient.send_msg(t.client_ws, "user:unfollow", %{
"userId" => followed.id
})
# this is kind of terrible, we should make this a call operation.
Process.sleep(100)
refute Beef.Follows.following_me?(followed.id, t.user.id)
end
@tag :skip
test "you can't follow yourself?"
end
end
| 23.272727 | 71 | 0.678711 |
088973d37bcf46e8c5c7e87827856acfc4139fe0 | 6,816 | exs | Elixir | test/atom_tweaks_web/controllers/admin/release_note_controller_test.exs | lee-dohm/atom-style-tweaks | c1f5afa76fd2c3363dfa760bd44637397b0f3fd6 | [
"MIT"
] | 14 | 2017-01-08T14:51:25.000Z | 2022-03-14T09:23:17.000Z | test/atom_tweaks_web/controllers/admin/release_note_controller_test.exs | lee-dohm/atom-style-tweaks | c1f5afa76fd2c3363dfa760bd44637397b0f3fd6 | [
"MIT"
] | 654 | 2017-05-23T22:55:21.000Z | 2022-03-30T09:02:25.000Z | test/atom_tweaks_web/controllers/admin/release_note_controller_test.exs | lee-dohm/atom-style-tweaks | c1f5afa76fd2c3363dfa760bd44637397b0f3fd6 | [
"MIT"
] | 4 | 2019-07-10T23:09:25.000Z | 2020-02-09T12:14:00.000Z | defmodule AtomTweaksWeb.Admin.ReleaseNoteControllerTest do
use AtomTweaksWeb.ConnCase
alias AtomTweaksWeb.ForbiddenUserError
alias AtomTweaksWeb.NotLoggedInError
describe "index when not logged in" do
test "returns unauthorized", context do
assert_raise NotLoggedInError, fn ->
request_admin_release_note_index(context)
end
end
end
describe "index when logged in as non-admin user" do
setup [:insert_user, :log_in]
test "returns forbidden", context do
assert_raise ForbiddenUserError, fn ->
request_admin_release_note_index(context)
end
end
end
describe "index when logged in as an admin with no notes" do
setup [:insert_site_admin, :log_in, :request_admin_release_note_index]
test "displays a blankslate element", context do
blankslate =
context.conn
|> html_response(:ok)
|> find(".blankslate")
assert text(blankslate) == "No release notes for you to see here"
end
end
describe "index when logged in as an admin and there are notes" do
setup [:insert_site_admin, :log_in, :insert_release_note, :request_admin_release_note_index]
test "displays the link to the release note record", context do
link =
context.conn
|> html_response(:ok)
|> find("a.title")
assert text(link) == context.note.title
assert Routes.admin_release_note_path(context.conn, :show, context.note) in attribute(
link,
"href"
)
end
test "displays when the release note was created", context do
created =
context.conn
|> html_response(:ok)
|> find(".release-info")
assert text(created) == "Released about now"
end
end
describe "show when not logged in" do
setup [:insert_release_note]
test "returns unauthorized", context do
assert_raise NotLoggedInError, fn ->
request_admin_release_note_show(context)
end
end
end
describe "show when logged in as a normal user" do
setup [:insert_user, :log_in, :insert_release_note]
test "returns forbidden", context do
assert_raise ForbiddenUserError, fn ->
request_admin_release_note_show(context)
end
end
end
describe "show when logged in as an admin user" do
setup [:insert_site_admin, :log_in, :insert_release_note, :request_admin_release_note_show]
test "displays the note's title", context do
title =
context.conn
|> html_response(:ok)
|> find(".release-note-title")
assert text(title) == context.note.title
end
test "displays an edit button", context do
button =
context.conn
|> html_response(:ok)
|> find("a#edit-button")
path = Routes.admin_release_note_path(context.conn, :edit, context.note)
assert path in attribute(button, "href")
end
test "displays the note's description", context do
description =
context.conn
|> html_response(:ok)
|> find(".markdown-body")
assert inner_html(description) == String.trim(html(context.note.description))
end
end
describe "edit when not logged in" do
setup [:insert_release_note]
test "returns unauthorized", context do
assert_raise NotLoggedInError, fn ->
request_admin_release_note_edit(context)
end
end
end
describe "edit when logged in as a normal user" do
setup [:insert_user, :log_in, :insert_release_note]
test "returns forbidden", context do
assert_raise ForbiddenUserError, fn ->
request_admin_release_note_edit(context)
end
end
end
describe "edit when logged in as a site admin" do
setup [:insert_site_admin, :log_in, :insert_release_note, :request_admin_release_note_edit]
test "displays the title edit box", context do
edit =
context.conn
|> html_response(:ok)
|> find("#note_title")
assert attribute(edit, "placeholder") == ["Title"]
assert attribute(edit, "value") == [context.note.title]
end
test "displays the detail url edit box", context do
edit =
context.conn
|> html_response(:ok)
|> find("#note_detail_url")
assert attribute(edit, "placeholder") == [
"https://github.com/lee-dohm/atom-style-tweaks/pull/1234"
]
assert attribute(edit, "value") == [context.note.detail_url]
end
test "displays the description text area", context do
text_area =
context.conn
|> html_response(:ok)
|> find("#note_description")
assert attribute(text_area, "placeholder") == ["Release notes"]
assert String.trim(text(text_area)) == md(context.note.description)
end
test "displays the submit button", context do
button =
context.conn
|> html_response(:ok)
|> find("button[type=\"submit\"].btn.btn-primary")
assert text(button) == "Update release note"
end
test "displays the cancel button", context do
button =
context.conn
|> html_response(:ok)
|> find(".btn.btn-danger")
assert text(button) =~ "Cancel"
end
end
describe "new when not logged in" do
test "returns unauthorized", context do
assert_raise NotLoggedInError, fn ->
request_admin_release_note_new(context)
end
end
end
describe "new when logged in as a normal user" do
setup [:insert_user, :log_in]
test "returns forbidden", context do
assert_raise ForbiddenUserError, fn ->
request_admin_release_note_new(context)
end
end
end
describe "new when logged in as a site admin" do
setup [:insert_site_admin, :log_in, :request_admin_release_note_new]
test "displays the title edit box", context do
edit =
context.conn
|> html_response(:ok)
|> find("#note_title")
assert attribute(edit, "placeholder") == ["Title"]
end
test "displays the detail url edit box", context do
edit =
context.conn
|> html_response(:ok)
|> find("#note_detail_url")
assert attribute(edit, "placeholder") == [
"https://github.com/lee-dohm/atom-style-tweaks/pull/1234"
]
end
test "displays the description text area", context do
text_area =
context.conn
|> html_response(:ok)
|> find("#note_description")
assert attribute(text_area, "placeholder") == ["Release notes"]
end
test "displays the submit button", context do
button =
context.conn
|> html_response(:ok)
|> find("button[type=\"submit\"].btn.btn-primary")
assert text(button) == "Save new release note"
end
end
end
| 26.940711 | 96 | 0.639818 |
088981d2fc9af8b351aa17d9d19dc35ee47ff95b | 1,565 | ex | Elixir | lib/hhex_web.ex | arvidkahl/hhex_elixir_auth0 | 2ec6a91a8d48afe036a39fe40b685335078dcfd5 | [
"MIT"
] | 1 | 2017-10-25T09:56:17.000Z | 2017-10-25T09:56:17.000Z | lib/hhex_web.ex | arvidkahl/hhex_elixir_auth0 | 2ec6a91a8d48afe036a39fe40b685335078dcfd5 | [
"MIT"
] | null | null | null | lib/hhex_web.ex | arvidkahl/hhex_elixir_auth0 | 2ec6a91a8d48afe036a39fe40b685335078dcfd5 | [
"MIT"
] | null | null | null | defmodule HhexWeb do
@moduledoc """
The entrypoint for defining your web interface, such
as controllers, views, channels and so on.
This can be used in your application as:
use HhexWeb, :controller
use HhexWeb, :view
The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below. Instead, define any helper function in modules
and import those modules here.
"""
def controller do
quote do
use Phoenix.Controller, namespace: HhexWeb
import Plug.Conn
import HhexWeb.Router.Helpers
import HhexWeb.Gettext
end
end
def view do
quote do
use Phoenix.View, root: "lib/hhex_web/templates",
namespace: HhexWeb
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_flash: 2, view_module: 1]
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
import HhexWeb.Router.Helpers
import HhexWeb.ErrorHelpers
import HhexWeb.Gettext
end
end
def router do
quote do
use Phoenix.Router
import Plug.Conn
import Phoenix.Controller
end
end
def channel do
quote do
use Phoenix.Channel
import HhexWeb.Gettext
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
| 23.014706 | 69 | 0.679233 |
0889a31f3b51020d2dab0ddbbd85fedef0850233 | 2,118 | ex | Elixir | elixir/lib/homework_web/schemas/transactions_schema.ex | gosimitz/web-homework | df72cdd4f341c4ea96beeb8164c4029928dffa50 | [
"MIT"
] | null | null | null | elixir/lib/homework_web/schemas/transactions_schema.ex | gosimitz/web-homework | df72cdd4f341c4ea96beeb8164c4029928dffa50 | [
"MIT"
] | null | null | null | elixir/lib/homework_web/schemas/transactions_schema.ex | gosimitz/web-homework | df72cdd4f341c4ea96beeb8164c4029928dffa50 | [
"MIT"
] | null | null | null | defmodule HomeworkWeb.Schemas.TransactionsSchema do
@moduledoc """
Defines the graphql schema for transactions.
"""
use Absinthe.Schema.Notation
alias HomeworkWeb.Resolvers.TransactionsResolver
alias HomeworkWeb.Resolvers.TransactionsResolver
alias HomeworkWeb.Resolvers.TransactionsResolver
object :transaction do
field(:id, non_null(:id))
field(:user_id, non_null(:id))
field(:amount, :integer)
field(:credit, :boolean)
field(:debit, :boolean)
field(:description, :string)
field(:merchant_id, non_null(:id))
field(:company_id, non_null(:id))
field(:inserted_at, :naive_datetime)
field(:updated_at, :naive_datetime)
field(:user, :user) do
resolve(&TransactionsResolver.user/3)
end
field(:merchant, :merchant) do
resolve(&TransactionsResolver.merchant/3)
end
field(:company, :company) do
resolve(&TransactionsResolver.company/3)
end
end
object :transaction_mutations do
@desc "Create a new transaction"
field :create_transaction, :transaction do
arg(:user_id, non_null(:id))
arg(:merchant_id, non_null(:id))
arg(:company_id, non_null(:id))
@desc "amount is in cents"
arg(:amount, non_null(:integer))
arg(:credit, non_null(:boolean))
arg(:debit, non_null(:boolean))
arg(:description, non_null(:string))
resolve(&TransactionsResolver.create_transaction/3)
end
@desc "Update a new transaction"
field :update_transaction, :transaction do
arg(:id, non_null(:id))
arg(:user_id, non_null(:id))
arg(:company_id, non_null(:id))
arg(:merchant_id, non_null(:id))
@desc "amount is in cents"
arg(:amount, non_null(:integer))
arg(:credit, non_null(:boolean))
arg(:debit, non_null(:boolean))
arg(:description, non_null(:string))
resolve(&TransactionsResolver.update_transaction/3)
end
@desc "delete an existing transaction"
field :delete_transaction, :transaction do
arg(:id, non_null(:id))
resolve(&TransactionsResolver.delete_transaction/3)
end
end
end
| 28.24 | 57 | 0.680831 |
0889aa9dd3e7741222c784b41322579d3014ac98 | 2,108 | exs | Elixir | test/pow/extension/phoenix/router_test.exs | matthewford/pow | 82c3359ec757a139fe38f4a745c3da176425f901 | [
"MIT"
] | null | null | null | test/pow/extension/phoenix/router_test.exs | matthewford/pow | 82c3359ec757a139fe38f4a745c3da176425f901 | [
"MIT"
] | null | null | null | test/pow/extension/phoenix/router_test.exs | matthewford/pow | 82c3359ec757a139fe38f4a745c3da176425f901 | [
"MIT"
] | 1 | 2020-07-13T01:11:17.000Z | 2020-07-13T01:11:17.000Z | defmodule Pow.Test.Extension.Phoenix.Router.Phoenix.Router do
use Pow.Extension.Phoenix.Router.Base
alias Pow.Phoenix.Router
defmacro routes(_config) do
quote location: :keep do
Router.pow_resources "/test", TestController, only: [:new, :create, :edit, :update]
end
end
end
defmodule Pow.Test.Extension.Phoenix.Router do
use Phoenix.Router
use Pow.Phoenix.Router
use Pow.Extension.Phoenix.Router,
extensions: [Pow.Test.Extension.Phoenix.Router]
scope "/", as: "pow_test_extension_phoenix_router" do
get "/test/:id/overidden", TestController, :edit
end
scope "/" do
pow_routes()
pow_extension_routes()
end
def phoenix_routes(), do: @phoenix_routes
end
module_raised_with =
try do
defmodule Pow.Test.Extension.Phoenix.RouterAliasScope do
@moduledoc false
use Phoenix.Router
use Pow.Phoenix.Router
use Pow.Extension.Phoenix.Router,
extensions: [Pow.Test.Extension.Phoenix.Router]
scope "/", Test do
pow_extension_routes()
end
end
rescue
e in ArgumentError -> e.message
else
_ -> raise "Scope with alias didn't throw any error"
end
defmodule Pow.Extension.Phoenix.RouterTest do
use Pow.Test.Ecto.TestCase
doctest Pow.Extension.Phoenix.Router
alias Pow.Test.Extension.Phoenix.Router.Helpers, as: Routes
alias Phoenix.ConnTest
@conn ConnTest.build_conn()
test "has routes" do
assert unquote(Routes.pow_session_path(@conn, :new)) == "/session/new"
assert unquote(Routes.pow_test_extension_phoenix_router_test_path(@conn, :new)) == "/test/new"
end
test "validates no aliases" do
assert unquote(module_raised_with) =~ "Pow routes should not be defined inside scopes with aliases: Test"
assert unquote(module_raised_with) =~ "scope \"/\", Test do"
end
test "can override routes" do
assert unquote(Routes.pow_test_extension_phoenix_router_test_path(@conn, :edit, 1)) == "/test/1/overidden"
assert Enum.count(Pow.Test.Extension.Phoenix.Router.phoenix_routes(), &(&1.plug == TestController && &1.plug_opts == :edit)) == 1
end
end
| 28.106667 | 133 | 0.71537 |
0889d8ae4a935ea9820e9bea9b36c11a0dafc21d | 223 | exs | Elixir | config/config.exs | mfb2/logger_stackdriver_backend | 8e5481e0dc679c0f81f11b3f9b1985d787927ec7 | [
"Apache-2.0"
] | null | null | null | config/config.exs | mfb2/logger_stackdriver_backend | 8e5481e0dc679c0f81f11b3f9b1985d787927ec7 | [
"Apache-2.0"
] | null | null | null | config/config.exs | mfb2/logger_stackdriver_backend | 8e5481e0dc679c0f81f11b3f9b1985d787927ec7 | [
"Apache-2.0"
] | 1 | 2019-07-02T14:07:11.000Z | 2019-07-02T14:07:11.000Z | use Mix.Config
config :goth,
json:
System.get_env()
|> Map.get(
"GOOGLE_APPLICATION_CREDENTIALS",
"#{System.user_home()}/.config/gcloud/application_default_credentials.json"
)
|> File.read!()
| 20.272727 | 81 | 0.650224 |
0889f3a6c30393f3dd0a3b49fe074e59caf5ba1d | 7,619 | ex | Elixir | lib/ex_admin/table.ex | jaxyeh/ex_admin | 7b269fd90f2314e27633dd75e4570e53656f3625 | [
"MIT"
] | null | null | null | lib/ex_admin/table.ex | jaxyeh/ex_admin | 7b269fd90f2314e27633dd75e4570e53656f3625 | [
"MIT"
] | null | null | null | lib/ex_admin/table.ex | jaxyeh/ex_admin | 7b269fd90f2314e27633dd75e4570e53656f3625 | [
"MIT"
] | null | null | null | Code.ensure_compiled(ExAdmin.Utils)
defmodule ExAdmin.Table do
@moduledoc false
require Integer
use Xain
import ExAdmin.Helpers
import ExAdmin.Utils
import ExAdmin.Render
import ExAdmin.Theme.Helpers
import Kernel, except: [to_string: 1]
alias ExAdmin.Schema
def attributes_table(conn, resource, schema) do
theme_module(conn, Table).theme_attributes_table conn, resource,
schema, model_name(resource)
end
def attributes_table_for(conn, resource, schema) do
theme_module(conn, Table).theme_attributes_table_for conn, resource,
schema, model_name(resource)
end
def do_attributes_table_for(conn, resource, resource_model, schema, table_opts) do
primary_key = Schema.get_id(resource)
div(".panel_contents") do
id = "attributes_table_#{resource_model}_#{primary_key}"
div(".attributes_table.#{resource_model}#{id}") do
table(table_opts) do
tbody do
for field_name <- Map.get(schema, :rows, []) do
build_field(resource, conn, field_name, fn
_contents, {:map, f_name} ->
for {k,v} <- Map.get(resource, f_name) do
tr do
field_header "#{f_name} #{k}"
td ".td-#{parameterize k} #{v}"
end
end
contents, f_name ->
tr do
field_header field_name
handle_contents(contents, f_name)
end
end)
end
end
end
end
end
end
def field_header({_, %{label: label}}), do: th(humanize label)
def field_header({{_, field_name}, opts}), do: field_header({field_name, opts})
def field_header({_, field_name}) when is_atom(field_name), do: field_header(field_name)
def field_header({field_name, _opts}), do: field_header(field_name)
def field_header(field_name), do: th(humanize field_name)
def panel(conn, schema, _opts \\ []) do
theme_module(conn, Table).theme_panel(conn, schema)
end
defp do_panel_resource(conn, %{__struct__: _} = resource, inx, model_name, columns) do
odd_even = if Integer.is_even(inx), do: "even", else: "odd"
tr_id = if Map.has_key?(resource, :id), do: resource.id, else: inx
tr(".#{odd_even}##{model_name}_#{tr_id}") do
for field <- columns do
case field do
{f_name, fun} when is_function(fun) ->
td ".td-#{parameterize f_name} #{fun.(resource)}"
{f_name, opts} ->
build_field(resource, conn, {f_name, Enum.into(opts, %{})}, fn(contents, f_name) ->
td ".td-#{parameterize f_name} #{contents}"
end)
end
end
end
end
defp do_panel_resource(conn, %{} = resource, inx, model_name, columns) do
odd_even = if Integer.is_even(inx), do: "even", else: "odd"
tr(".#{odd_even}##{model_name}_#{inx}") do
for field <- columns do
case field do
{f_name, fun} when is_function(fun) ->
td ".td-#{parameterize f_name} #{fun.(resource)}"
{f_name, opts} ->
build_field(resource, conn, {f_name, Enum.into(opts, %{})}, fn(contents, f_name) ->
td ".td-#{parameterize f_name} #{contents}"
end)
end
end
end
end
def do_panel(conn, columns \\ [], table_opts \\ [], output \\ [])
def do_panel(_conn, [], _table_opts, output), do: Enum.join(Enum.reverse(output))
def do_panel(conn, [{:table_for, %{resources: resources, columns: columns, opts: opts}} | tail], table_opts, output) do
output = [table(Keyword.merge(table_opts, opts)) do
table_head(columns)
tbody do
model_name = get_resource_model resources
Enum.with_index(resources)
|> Enum.map(fn({resource, inx}) ->
do_panel_resource(conn, resource, inx, model_name, columns)
end)
end
end | output]
do_panel(conn, tail, table_opts, output)
end
def do_panel(conn, [{:contents, %{contents: content}} | tail], table_opts, output) do
output = [
case content do
{:safe, _} -> Phoenix.HTML.safe_to_string(content)
content -> content
end
|> Xain.raw | output]
do_panel(conn, tail, table_opts, output)
end
# skip unknown blocks
def do_panel(conn, [_head|tail], table_opts, output) do
do_panel(conn, tail, table_opts, output)
end
def table_head(columns, opts \\ %{}) do
selectable = Map.get opts, :selectable_column
thead do
tr do
if selectable do
th(".selectable") do
div(".resource_selection_toggle_cell") do
input("#collection_selection_toggle_all.toggle_all", type: "checkbox", name: "collection_selection_toggle_all")
end
end
end
for field <- columns do
build_th field, opts
end
end
end
end
def build_th({field_name, opts}, table_opts) do
build_th(to_string(field_name), opts, table_opts)
end
def build_th(field_name, _),
do: th(".th-#{parameterize field_name} #{humanize field_name}")
def build_th(field_name, opts, %{fields: fields} = table_opts) do
if String.to_atom(field_name) in fields and opts in [%{}, %{link: true}] do
_build_th(field_name, opts, table_opts)
else
th(".th-#{parameterize field_name} #{humanize Map.get(opts, :label, to_string(field_name))}")
end
end
def build_th(field_name, _, _), do: build_th(field_name, nil)
def _build_th(field_name, _opts, %{path_prefix: path_prefix, order: {name, sort},
fields: _fields} = table_opts) when field_name == name do
link_order = if sort == "desc", do: "asc", else: "desc"
page_segment = case Map.get table_opts, :page, nil do
nil -> ""
page -> "&page=#{page.page_number}"
end
scope_segment = case table_opts[:scope] do
nil -> ""
scope -> "&scope=#{scope}"
end
th(".sortable.sorted-#{sort}.th-#{field_name}") do
a("#{humanize field_name}", href: path_prefix <>
field_name <> "_#{link_order}#{page_segment}" <> scope_segment <>
Map.get(table_opts, :filter, ""))
end
end
def _build_th(field_name, opts, %{path_prefix: path_prefix} = table_opts) do
sort = Map.get(table_opts, :sort, "asc")
page_segment = case Map.get table_opts, :page, nil do
nil -> ""
page -> "&page=#{page.page_number}"
end
scope_segment = case table_opts[:scope] do
nil -> ""
scope -> "&scope=#{scope}"
end
th(".sortable.th-#{field_name}") do
a("#{humanize Map.get(opts, :label, to_string(field_name))}", href: path_prefix <>
field_name <> "_#{sort}#{page_segment}" <> scope_segment <>
Map.get(table_opts, :filter, ""))
end
end
def handle_contents(%Ecto.DateTime{} = dt, field_name) do
td class: to_class("td-", field_name) do
text to_string(dt)
end
end
def handle_contents(%Ecto.Time{} = dt, field_name) do
td class: to_class("td-", field_name) do
text to_string(dt)
end
end
def handle_contents(%Ecto.Date{} = dt, field_name) do
td class: to_class("td-", field_name) do
text to_string(dt)
end
end
def handle_contents(%{}, _field_name), do: []
def handle_contents(contents, field_name) when is_binary(contents) do
td(to_class(".td-", field_name)) do
text contents
end
end
def handle_contents({:safe, contents}, field_name) do
handle_contents contents, field_name
end
def handle_contents(contents, field_name) do
td(to_class(".td-", field_name), contents)
end
end
| 34.949541 | 125 | 0.617666 |
0889f686f98afa7c8189d4ce80d966d4bef46494 | 1,954 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/accounts_list_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/accounts_list_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/accounts_list_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V34.Model.AccountsListResponse do
@moduledoc """
Account List Response
## Attributes
* `accounts` (*type:* `list(GoogleApi.DFAReporting.V34.Model.Account.t)`, *default:* `nil`) - Account collection.
* `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountsListResponse".
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Pagination token to be used for the next list operation.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:accounts => list(GoogleApi.DFAReporting.V34.Model.Account.t()) | nil,
:kind => String.t() | nil,
:nextPageToken => String.t() | nil
}
field(:accounts, as: GoogleApi.DFAReporting.V34.Model.Account, type: :list)
field(:kind)
field(:nextPageToken)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.AccountsListResponse do
def decode(value, options) do
GoogleApi.DFAReporting.V34.Model.AccountsListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.AccountsListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.867925 | 156 | 0.725691 |
0889fa4a76dc84392312cb282d9768f893f5fc5a | 1,232 | ex | Elixir | lib/hl7/2.4/segments/om7.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.4/segments/om7.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.4/segments/om7.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | defmodule HL7.V2_4.Segments.OM7 do
@moduledoc false
require Logger
alias HL7.V2_4.{DataTypes}
use HL7.Segment,
fields: [
segment: nil,
sequence_number_test_observation_master_file: nil,
universal_service_identifier: DataTypes.Ce,
category_identifier: DataTypes.Ce,
category_description: nil,
category_synonym: nil,
effective_test_service_start_date_time: DataTypes.Ts,
effective_test_service_end_date_time: DataTypes.Ts,
test_service_default_duration_quantity: nil,
test_service_default_duration_units: DataTypes.Ce,
test_service_default_frequency: nil,
consent_indicator: nil,
consent_identifier: DataTypes.Ce,
consent_effective_start_date_time: DataTypes.Ts,
consent_effective_end_date_time: DataTypes.Ts,
consent_interval_quantity: nil,
consent_interval_units: DataTypes.Ce,
consent_waiting_period_quantity: nil,
consent_waiting_period_units: DataTypes.Ce,
effective_date_time_of_change: DataTypes.Ts,
entered_by: DataTypes.Xcn,
orderable_at_location: DataTypes.Pl,
formulary_status: nil,
special_order_indicator: nil,
primary_key_value_cdm: DataTypes.Ce
]
end
| 34.222222 | 59 | 0.749188 |
088a1748a7d45851d0d998d720bdd8d18bab8018 | 114 | ex | Elixir | lib/ex_dns/message/additional.ex | kipcole9/dns | f32448954f5c8f13ba714099f47e0e80e1091cf5 | [
"Apache-2.0"
] | 3 | 2019-08-09T05:24:23.000Z | 2021-11-16T18:44:00.000Z | lib/ex_dns/message/additional.ex | kipcole9/dns | f32448954f5c8f13ba714099f47e0e80e1091cf5 | [
"Apache-2.0"
] | null | null | null | lib/ex_dns/message/additional.ex | kipcole9/dns | f32448954f5c8f13ba714099f47e0e80e1091cf5 | [
"Apache-2.0"
] | null | null | null | defmodule ExDns.Message.Additional do
def decode(header, section, message) do
{:ok, nil, message}
end
end
| 19 | 41 | 0.719298 |
088a25333372e5f57eae2348c6b8906f5226e75e | 972 | ex | Elixir | apps/banking_account_manager_web/lib/banking_account_manager_web/application.ex | danielscosta/banking_account_manager | 8acec8f4fa774c85401e67b4aa39c97a0ca9d149 | [
"MIT"
] | null | null | null | apps/banking_account_manager_web/lib/banking_account_manager_web/application.ex | danielscosta/banking_account_manager | 8acec8f4fa774c85401e67b4aa39c97a0ca9d149 | [
"MIT"
] | null | null | null | apps/banking_account_manager_web/lib/banking_account_manager_web/application.ex | danielscosta/banking_account_manager | 8acec8f4fa774c85401e67b4aa39c97a0ca9d149 | [
"MIT"
] | null | null | null | defmodule BankingAccountManagerWeb.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
# Start the endpoint when the application starts
BankingAccountManagerWeb.Endpoint
# Starts a worker by calling: BankingAccountManagerWeb.Worker.start_link(arg)
# {BankingAccountManagerWeb.Worker, arg},
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: BankingAccountManagerWeb.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
BankingAccountManagerWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 32.4 | 83 | 0.747942 |
088a2c2a31247fcb27e46ca4ccde7abdbff4ed20 | 2,031 | ex | Elixir | apps/nerves_hub_web_core/lib/nerves_hub_web_core/devices/device.ex | Gazler/nerves_hub_web | 9a636a17310382819eaa6cee590e053cb47f0dcc | [
"Apache-2.0"
] | 1 | 2020-08-04T14:13:24.000Z | 2020-08-04T14:13:24.000Z | apps/nerves_hub_web_core/lib/nerves_hub_web_core/devices/device.ex | Eaftos/nerves_hub_web | ac03bd044b97265bf3ba3edd8da249d300fa3668 | [
"Apache-2.0"
] | 1 | 2020-09-08T15:15:50.000Z | 2020-09-08T16:13:28.000Z | apps/nerves_hub_web_core/lib/nerves_hub_web_core/devices/device.ex | Eaftos/nerves_hub_web | ac03bd044b97265bf3ba3edd8da249d300fa3668 | [
"Apache-2.0"
] | null | null | null | defmodule NervesHubWebCore.Devices.Device do
use Ecto.Schema
import Ecto.Changeset
import Ecto.Query
alias NervesHubWebCore.Repo
alias NervesHubWebCore.Accounts
alias NervesHubWebCore.Accounts.Org
alias NervesHubWebCore.Products.Product
alias NervesHubWebCore.Firmwares.FirmwareMetadata
alias NervesHubWebCore.Devices.DeviceCertificate
alias __MODULE__
@type t :: %__MODULE__{}
@optional_params [
:last_communication,
:description,
:healthy,
:tags
]
@required_params [:org_id, :product_id, :identifier]
schema "devices" do
belongs_to(:org, Org)
belongs_to(:product, Product)
embeds_one(:firmware_metadata, FirmwareMetadata, on_replace: :update)
has_many(:device_certificates, DeviceCertificate, on_delete: :delete_all)
field(:identifier, :string)
field(:description, :string)
field(:last_communication, :utc_datetime)
field(:healthy, :boolean, default: true)
field(:tags, NervesHubWebCore.Types.Tag)
field(:status, :string, default: "offline", virtual: true)
timestamps()
end
def changeset(%Device{} = device, params) do
device
|> cast(params, @required_params ++ @optional_params)
|> cast_embed(:firmware_metadata)
|> validate_required(@required_params)
|> validate_length(:tags, min: 1)
|> validate_device_limit()
|> unique_constraint(:identifier, name: :devices_org_id_identifier_index)
end
defp validate_device_limit(%Ecto.Changeset{changes: %{org_id: org_id}} = cs) do
if too_many_devices?(org_id) do
cs |> add_error(:org, "device limit reached")
else
cs
end
end
defp validate_device_limit(%Ecto.Changeset{} = cs) do
cs
end
defp too_many_devices?(org_id) do
device_count =
from(d in Device, where: d.org_id == ^org_id, select: count(d.id))
|> Repo.one()
%{devices: limit} = Accounts.get_org_limit_by_org_id(org_id)
device_count + 1 > limit
end
def with_org(device_query) do
device_query
|> preload(:org)
end
end
| 26.038462 | 81 | 0.708026 |
088a2eef37f50075bd0225b4015a9d59f18375e2 | 872 | ex | Elixir | clients/iam/lib/google_api/iam/v1/metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/iam/lib/google_api/iam/v1/metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/iam/lib/google_api/iam/v1/metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.IAM.V1 do
@moduledoc """
API client metadata for GoogleApi.IAM.V1.
"""
@discovery_revision "20211104"
def discovery_revision(), do: @discovery_revision
end
| 32.296296 | 74 | 0.755734 |
088a3550d8a34ee4367d21563bdc7a8ee673a963 | 600 | ex | Elixir | lib/excerpt/connection_manager.ex | clone1018/excerpt | eef37f7c144bd4c477444b809da73c821b754c2b | [
"MIT"
] | 1 | 2021-08-12T20:37:44.000Z | 2021-08-12T20:37:44.000Z | lib/excerpt/connection_manager.ex | clone1018/excerpt | eef37f7c144bd4c477444b809da73c821b754c2b | [
"MIT"
] | null | null | null | lib/excerpt/connection_manager.ex | clone1018/excerpt | eef37f7c144bd4c477444b809da73c821b754c2b | [
"MIT"
] | null | null | null | defmodule Excerpt.ConnectionManager do
alias Excerpt.Connection
require Logger
def accept(port) do
{:ok, socket} =
:gen_tcp.listen(port, [:binary, packet: :line, reuseaddr: true, active: false])
Logger.info("Listening for IRC connections on #{port}")
loop_acceptor(socket)
end
def loop_acceptor(acceptor_socket) do
{:ok, socket} = :gen_tcp.accept(acceptor_socket)
:inet.setopts(socket, active: true)
{:ok, pid} = GenServer.start(Connection, socket: socket)
:ok = :gen_tcp.controlling_process(socket, pid)
loop_acceptor(acceptor_socket)
end
end
| 25 | 85 | 0.703333 |
088a6f75d14f8664bb2f4a0c10de7ac5a1bf6e21 | 810 | exs | Elixir | apps/ewallet_db/priv/repo/migrations/20180511045020_add_max_consumptions_per_user_to_transaction_requests.exs | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | apps/ewallet_db/priv/repo/migrations/20180511045020_add_max_consumptions_per_user_to_transaction_requests.exs | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | apps/ewallet_db/priv/repo/migrations/20180511045020_add_max_consumptions_per_user_to_transaction_requests.exs | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule EWalletDB.Repo.Migrations.AddMaxConsumptionsPerUserToTransactionRequests do
use Ecto.Migration
def change do
alter table(:transaction_request) do
add :max_consumptions_per_user, :integer
end
end
end
| 33.75 | 85 | 0.77037 |
088a9d16711967f064b52c2b571dc3bd47fd858c | 24,992 | ex | Elixir | clients/content/lib/google_api/content/v2/api/accounts.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/api/accounts.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/api/accounts.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.Content.V2.Api.Accounts do
@moduledoc """
API calls for all endpoints tagged `Accounts`.
"""
alias GoogleApi.Content.V2.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Returns information about the authenticated user.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.AccountsAuthInfoResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_accounts_authinfo(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.AccountsAuthInfoResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def content_accounts_authinfo(connection, 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("/accounts/authinfo", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.AccountsAuthInfoResponse{}])
end
@doc """
Claims the website of a Merchant Center sub-account.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and accountId must be the ID of a sub-account of this account.
* `account_id` (*type:* `String.t`) - The ID of the account whose website is claimed.
* `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.
* `:overwrite` (*type:* `boolean()`) - Only available to selected merchants. When set to True, this flag removes any existing claim on the requested website by another account and replaces it with a claim from this account.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.AccountsClaimWebsiteResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_accounts_claimwebsite(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.AccountsClaimWebsiteResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def content_accounts_claimwebsite(
connection,
merchant_id,
account_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:overwrite => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/accounts/{accountId}/claimwebsite", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"accountId" => URI.encode(account_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.AccountsClaimWebsiteResponse{}]
)
end
@doc """
Retrieves, inserts, updates, and deletes multiple Merchant Center (sub-)accounts in a single request.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:dryRun` (*type:* `boolean()`) - Flag to simulate a request like in a live environment. If set to true, dry-run mode checks the validity of the request and returns errors (if any).
* `:body` (*type:* `GoogleApi.Content.V2.Model.AccountsCustomBatchRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.AccountsCustomBatchResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_accounts_custombatch(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.AccountsCustomBatchResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def content_accounts_custombatch(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:dryRun => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/accounts/batch", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.AccountsCustomBatchResponse{}]
)
end
@doc """
Deletes a Merchant Center sub-account.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the managing account. This must be a multi-client account, and accountId must be the ID of a sub-account of this account.
* `account_id` (*type:* `String.t`) - The ID of the account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:dryRun` (*type:* `boolean()`) - Flag to simulate a request like in a live environment. If set to true, dry-run mode checks the validity of the request and returns errors (if any).
* `:force` (*type:* `boolean()`) - Flag to delete sub-accounts with products. The default value is false.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %{}}` on success
* `{:error, info}` on failure
"""
@spec content_accounts_delete(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, nil} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()}
def content_accounts_delete(
connection,
merchant_id,
account_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:dryRun => :query,
:force => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/{merchantId}/accounts/{accountId}", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"accountId" => URI.encode(account_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
@doc """
Retrieves a Merchant Center account.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and accountId must be the ID of a sub-account of this account.
* `account_id` (*type:* `String.t`) - The ID of the account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.Account{}}` on success
* `{:error, info}` on failure
"""
@spec content_accounts_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.Account.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def content_accounts_get(connection, merchant_id, account_id, 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("/{merchantId}/accounts/{accountId}", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"accountId" => URI.encode(account_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.Account{}])
end
@doc """
Creates a Merchant Center sub-account.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the managing account. This must be a multi-client account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:dryRun` (*type:* `boolean()`) - Flag to simulate a request like in a live environment. If set to true, dry-run mode checks the validity of the request and returns errors (if any).
* `:body` (*type:* `GoogleApi.Content.V2.Model.Account.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.Account{}}` on success
* `{:error, info}` on failure
"""
@spec content_accounts_insert(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.Account.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def content_accounts_insert(connection, merchant_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:dryRun => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/accounts", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.Account{}])
end
@doc """
Performs an action on a link between two Merchant Center accounts, namely accountId and linkedAccountId.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and accountId must be the ID of a sub-account of this account.
* `account_id` (*type:* `String.t`) - The ID of the account that should be linked.
* `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.
* `:body` (*type:* `GoogleApi.Content.V2.Model.AccountsLinkRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.AccountsLinkResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_accounts_link(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.AccountsLinkResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def content_accounts_link(
connection,
merchant_id,
account_id,
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("/{merchantId}/accounts/{accountId}/link", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"accountId" => URI.encode(account_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.AccountsLinkResponse{}])
end
@doc """
Lists the sub-accounts in your Merchant Center account.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the managing account. This must be a multi-client account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:maxResults` (*type:* `integer()`) - The maximum number of accounts to return in the response, used for paging.
* `:pageToken` (*type:* `String.t`) - The token returned by the previous request.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.AccountsListResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_accounts_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.AccountsListResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def content_accounts_list(connection, merchant_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:maxResults => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{merchantId}/accounts", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.AccountsListResponse{}])
end
@doc """
Updates a Merchant Center account.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the managing account. If this parameter is not the same as accountId, then this account must be a multi-client account and accountId must be the ID of a sub-account of this account.
* `account_id` (*type:* `String.t`) - The ID of the account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:dryRun` (*type:* `boolean()`) - Flag to simulate a request like in a live environment. If set to true, dry-run mode checks the validity of the request and returns errors (if any).
* `:body` (*type:* `GoogleApi.Content.V2.Model.Account.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.Account{}}` on success
* `{:error, info}` on failure
"""
@spec content_accounts_update(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.Account.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def content_accounts_update(
connection,
merchant_id,
account_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:dryRun => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/{merchantId}/accounts/{accountId}", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"accountId" => URI.encode(account_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.Account{}])
end
end
| 45.689214 | 234 | 0.631962 |
088aacf493912c1a9a270400142d5071f5b37a47 | 67 | ex | Elixir | apps/admin_app/lib/admin_app_web/views/property_view.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 456 | 2018-09-20T02:40:59.000Z | 2022-03-07T08:53:48.000Z | apps/admin_app/lib/admin_app_web/views/property_view.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 273 | 2018-09-19T06:43:43.000Z | 2021-08-07T12:58:26.000Z | apps/admin_app/lib/admin_app_web/views/property_view.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 122 | 2018-09-26T16:32:46.000Z | 2022-03-13T11:44:19.000Z | defmodule AdminAppWeb.PropertyView do
use AdminAppWeb, :view
end
| 16.75 | 37 | 0.820896 |
088aaffb7efbc462788d19e4629047aee381ab83 | 377 | exs | Elixir | priv/repo/seeds.exs | CTMoney/phoenix-postgres-react | b51c298fdcef339324a601dd874a82e1e0cc8e6e | [
"MIT"
] | null | null | null | priv/repo/seeds.exs | CTMoney/phoenix-postgres-react | b51c298fdcef339324a601dd874a82e1e0cc8e6e | [
"MIT"
] | 1 | 2021-03-09T11:33:04.000Z | 2021-03-09T11:33:04.000Z | priv/repo/seeds.exs | CTMoney/phoenix_ | b51c298fdcef339324a601dd874a82e1e0cc8e6e | [
"MIT"
] | null | null | null | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# PhoenixPostgresReact.Repo.insert!(%PhoenixPostgresReact.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 31.416667 | 75 | 0.72679 |
088acd4b8731f7d109a2c6c282733a2c4ea1c838 | 374 | ex | Elixir | server/lib/server_web/views/error_view.ex | wasd171/primitive-scanner | c0b911204b680f936d1c98e7bf72ebeb77ae87b1 | [
"MIT"
] | null | null | null | server/lib/server_web/views/error_view.ex | wasd171/primitive-scanner | c0b911204b680f936d1c98e7bf72ebeb77ae87b1 | [
"MIT"
] | null | null | null | server/lib/server_web/views/error_view.ex | wasd171/primitive-scanner | c0b911204b680f936d1c98e7bf72ebeb77ae87b1 | [
"MIT"
] | null | null | null | defmodule ServerWeb.ErrorView do
use ServerWeb, :view
def render("404.html", _assigns) do
"Page not found"
end
def render("500.html", _assigns) do
"Internal server error"
end
# In case no render clause matches or no
# template is found, let's render it as 500
def template_not_found(_template, assigns) do
render "500.html", assigns
end
end
| 20.777778 | 47 | 0.700535 |
088adf0c6a978ecdf31ca9f63b07ce2c32028eec | 54 | ex | Elixir | RAEM/raem/lib/raem_web/views/igc_view.ex | pedromcorreia/Rumo-ao-ensino-superior | be0b9bf417604bdf8a349fde8a8a1c0aaf4c4cdb | [
"MIT"
] | null | null | null | RAEM/raem/lib/raem_web/views/igc_view.ex | pedromcorreia/Rumo-ao-ensino-superior | be0b9bf417604bdf8a349fde8a8a1c0aaf4c4cdb | [
"MIT"
] | null | null | null | RAEM/raem/lib/raem_web/views/igc_view.ex | pedromcorreia/Rumo-ao-ensino-superior | be0b9bf417604bdf8a349fde8a8a1c0aaf4c4cdb | [
"MIT"
] | 2 | 2018-02-24T19:56:21.000Z | 2018-02-26T00:16:41.000Z | defmodule RaemWeb.IgcView do
use RaemWeb, :view
end
| 13.5 | 28 | 0.777778 |
088aee7a16ddb6304b5d3392b911e21b37d7f7b1 | 19,674 | ex | Elixir | lib/mint/core/transport/ssl.ex | liamwhite/mint | 9b19e09994d85b9c3af05279340cefc6c440ea67 | [
"Apache-2.0"
] | null | null | null | lib/mint/core/transport/ssl.ex | liamwhite/mint | 9b19e09994d85b9c3af05279340cefc6c440ea67 | [
"Apache-2.0"
] | null | null | null | lib/mint/core/transport/ssl.ex | liamwhite/mint | 9b19e09994d85b9c3af05279340cefc6c440ea67 | [
"Apache-2.0"
] | null | null | null | defmodule Mint.Core.Transport.SSL do
@moduledoc false
require Logger
require Record
@behaviour Mint.Core.Transport
# From RFC7540 appendix A
@blacklisted_ciphers [
{:null, :null, :null},
{:rsa, :null, :md5},
{:rsa, :null, :sha},
{:rsa_export, :rc4_40, :md5},
{:rsa, :rc4_128, :md5},
{:rsa, :rc4_128, :sha},
{:rsa_export, :rc2_cbc_40, :md5},
{:rsa, :idea_cbc, :sha},
{:rsa_export, :des40_cbc, :sha},
{:rsa, :des_cbc, :sha},
{:rsa, :"3des_ede_cbc", :sha},
{:dh_dss_export, :des40_cbc, :sha},
{:dh_dss, :des_cbc, :sha},
{:dh_dss, :"3des_ede_cbc", :sha},
{:dh_rsa_export, :des40_cbc, :sha},
{:dh_rsa, :des_cbc, :sha},
{:dh_rsa, :"3des_ede_cbc", :sha},
{:dhe_dss_export, :des40_cbc, :sha},
{:dhe_dss, :des_cbc, :sha},
{:dhe_dss, :"3des_ede_cbc", :sha},
{:dhe_rsa_export, :des40_cbc, :sha},
{:dhe_rsa, :des_cbc, :sha},
{:dhe_rsa, :"3des_ede_cbc", :sha},
{:dh_anon_export, :rc4_40, :md5},
{:dh_anon, :rc4_128, :md5},
{:dh_anon_export, :des40_cbc, :sha},
{:dh_anon, :des_cbc, :sha},
{:dh_anon, :"3des_ede_cbc", :sha},
{:krb5, :des_cbc, :sha},
{:krb5, :"3des_ede_cbc", :sha},
{:krb5, :rc4_128, :sha},
{:krb5, :idea_cbc, :sha},
{:krb5, :des_cbc, :md5},
{:krb5, :"3des_ede_cbc", :md5},
{:krb5, :rc4_128, :md5},
{:krb5, :idea_cbc, :md5},
{:krb5_export, :des_cbc_40, :sha},
{:krb5_export, :rc2_cbc_40, :sha},
{:krb5_export, :rc4_40, :sha},
{:krb5_export, :des_cbc_40, :md5},
{:krb5_export, :rc2_cbc_40, :md5},
{:krb5_export, :rc4_40, :md5},
{:psk, :null, :sha},
{:dhe_psk, :null, :sha},
{:rsa_psk, :null, :sha},
{:rsa, :aes_128_cbc, :sha},
{:dh_dss, :aes_128_cbc, :sha},
{:dh_rsa, :aes_128_cbc, :sha},
{:dhe_dss, :aes_128_cbc, :sha},
{:dhe_rsa, :aes_128_cbc, :sha},
{:dh_anon, :aes_128_cbc, :sha},
{:rsa, :aes_256_cbc, :sha},
{:dh_dss, :aes_256_cbc, :sha},
{:dh_rsa, :aes_256_cbc, :sha},
{:dhe_dss, :aes_256_cbc, :sha},
{:dhe_rsa, :aes_256_cbc, :sha},
{:dh_anon, :aes_256_cbc, :sha},
{:rsa, :null, :sha256},
{:rsa, :aes_128_cbc, :sha256},
{:rsa, :aes_256_cbc, :sha256},
{:dh_dss, :aes_128_cbc, :sha256},
{:dh_rsa, :aes_128_cbc, :sha256},
{:dhe_dss, :aes_128_cbc, :sha256},
{:rsa, :camellia_128_cbc, :sha},
{:dh_dss, :camellia_128_cbc, :sha},
{:dh_rsa, :camellia_128_cbc, :sha},
{:dhe_dss, :camellia_128_cbc, :sha},
{:dhe_rsa, :camellia_128_cbc, :sha},
{:dh_anon, :camellia_128_cbc, :sha},
{:dhe_rsa, :aes_128_cbc, :sha256},
{:dh_dss, :aes_256_cbc, :sha256},
{:dh_rsa, :aes_256_cbc, :sha256},
{:dhe_dss, :aes_256_cbc, :sha256},
{:dhe_rsa, :aes_256_cbc, :sha256},
{:dh_anon, :aes_128_cbc, :sha256},
{:dh_anon, :aes_256_cbc, :sha256},
{:rsa, :camellia_256_cbc, :sha},
{:dh_dss, :camellia_256_cbc, :sha},
{:dh_rsa, :camellia_256_cbc, :sha},
{:dhe_dss, :camellia_256_cbc, :sha},
{:dhe_rsa, :camellia_256_cbc, :sha},
{:dh_anon, :camellia_256_cbc, :sha},
{:psk, :rc4_128, :sha},
{:psk, :"3des_ede_cbc", :sha},
{:psk, :aes_128_cbc, :sha},
{:psk, :aes_256_cbc, :sha},
{:dhe_psk, :rc4_128, :sha},
{:dhe_psk, :"3des_ede_cbc", :sha},
{:dhe_psk, :aes_128_cbc, :sha},
{:dhe_psk, :aes_256_cbc, :sha},
{:rsa_psk, :rc4_128, :sha},
{:rsa_psk, :"3des_ede_cbc", :sha},
{:rsa_psk, :aes_128_cbc, :sha},
{:rsa_psk, :aes_256_cbc, :sha},
{:rsa, :seed_cbc, :sha},
{:dh_dss, :seed_cbc, :sha},
{:dh_rsa, :seed_cbc, :sha},
{:dhe_dss, :seed_cbc, :sha},
{:dhe_rsa, :seed_cbc, :sha},
{:dh_anon, :seed_cbc, :sha},
{:rsa, :aes_128_gcm, :sha256},
{:rsa, :aes_256_gcm, :sha384},
{:dh_rsa, :aes_128_gcm, :sha256},
{:dh_rsa, :aes_256_gcm, :sha384},
{:dh_dss, :aes_128_gcm, :sha256},
{:dh_dss, :aes_256_gcm, :sha384},
{:dh_anon, :aes_128_gcm, :sha256},
{:dh_anon, :aes_256_gcm, :sha384},
{:psk, :aes_128_gcm, :sha256},
{:psk, :aes_256_gcm, :sha384},
{:rsa_psk, :aes_128_gcm, :sha256},
{:rsa_psk, :aes_256_gcm, :sha384},
{:psk, :aes_128_cbc, :sha256},
{:psk, :aes_256_cbc, :sha384},
{:psk, :null, :sha256},
{:psk, :null, :sha384},
{:dhe_psk, :aes_128_cbc, :sha256},
{:dhe_psk, :aes_256_cbc, :sha384},
{:dhe_psk, :null, :sha256},
{:dhe_psk, :null, :sha384},
{:rsa_psk, :aes_128_cbc, :sha256},
{:rsa_psk, :aes_256_cbc, :sha384},
{:rsa_psk, :null, :sha256},
{:rsa_psk, :null, :sha384},
{:rsa, :camellia_128_cbc, :sha256},
{:dh_dss, :camellia_128_cbc, :sha256},
{:dh_rsa, :camellia_128_cbc, :sha256},
{:dhe_dss, :camellia_128_cbc, :sha256},
{:dhe_rsa, :camellia_128_cbc, :sha256},
{:dh_anon, :camellia_128_cbc, :sha256},
{:rsa, :camellia_256_cbc, :sha256},
{:dh_dss, :camellia_256_cbc, :sha256},
{:dh_rsa, :camellia_256_cbc, :sha256},
{:dhe_dss, :camellia_256_cbc, :sha256},
{:dhe_rsa, :camellia_256_cbc, :sha256},
{:dh_anon, :camellia_256_cbc, :sha256},
{:ecdh_ecdsa, :null, :sha},
{:ecdh_ecdsa, :rc4_128, :sha},
{:ecdh_ecdsa, :"3des_ede_cbc", :sha},
{:ecdh_ecdsa, :aes_128_cbc, :sha},
{:ecdh_ecdsa, :aes_256_cbc, :sha},
{:ecdhe_ecdsa, :null, :sha},
{:ecdhe_ecdsa, :rc4_128, :sha},
{:ecdhe_ecdsa, :"3des_ede_cbc", :sha},
{:ecdhe_ecdsa, :aes_128_cbc, :sha},
{:ecdhe_ecdsa, :aes_256_cbc, :sha},
{:ecdh_rsa, :null, :sha},
{:ecdh_rsa, :rc4_128, :sha},
{:ecdh_rsa, :"3des_ede_cbc", :sha},
{:ecdh_rsa, :aes_128_cbc, :sha},
{:ecdh_rsa, :aes_256_cbc, :sha},
{:ecdhe_rsa, :null, :sha},
{:ecdhe_rsa, :rc4_128, :sha},
{:ecdhe_rsa, :"3des_ede_cbc", :sha},
{:ecdhe_rsa, :aes_128_cbc, :sha},
{:ecdhe_rsa, :aes_256_cbc, :sha},
{:ecdh_anon, :null, :sha},
{:ecdh_anon, :rc4_128, :sha},
{:ecdh_anon, :"3des_ede_cbc", :sha},
{:ecdh_anon, :aes_128_cbc, :sha},
{:ecdh_anon, :aes_256_cbc, :sha},
{:srp_sha, :"3des_ede_cbc", :sha},
{:srp_sha_rsa, :"3des_ede_cbc", :sha},
{:srp_sha_dss, :"3des_ede_cbc", :sha},
{:srp_sha, :aes_128_cbc, :sha},
{:srp_sha_rsa, :aes_128_cbc, :sha},
{:srp_sha_dss, :aes_128_cbc, :sha},
{:srp_sha, :aes_256_cbc, :sha},
{:srp_sha_rsa, :aes_256_cbc, :sha},
{:srp_sha_dss, :aes_256_cbc, :sha},
{:ecdhe_ecdsa, :aes_128_cbc, :sha256},
{:ecdhe_ecdsa, :aes_256_cbc, :sha384},
{:ecdh_ecdsa, :aes_128_cbc, :sha256},
{:ecdh_ecdsa, :aes_256_cbc, :sha384},
{:ecdhe_rsa, :aes_128_cbc, :sha256},
{:ecdhe_rsa, :aes_256_cbc, :sha384},
{:ecdh_rsa, :aes_128_cbc, :sha256},
{:ecdh_rsa, :aes_256_cbc, :sha384},
{:ecdh_ecdsa, :aes_128_gcm, :sha256},
{:ecdh_ecdsa, :aes_256_gcm, :sha384},
{:ecdh_rsa, :aes_128_gcm, :sha256},
{:ecdh_rsa, :aes_256_gcm, :sha384},
{:ecdhe_psk, :rc4_128, :sha},
{:ecdhe_psk, :"3des_ede_cbc", :sha},
{:ecdhe_psk, :aes_128_cbc, :sha},
{:ecdhe_psk, :aes_256_cbc, :sha},
{:ecdhe_psk, :aes_128_cbc, :sha256},
{:ecdhe_psk, :aes_256_cbc, :sha384},
{:ecdhe_psk, :null, :sha},
{:ecdhe_psk, :null, :sha256},
{:ecdhe_psk, :null, :sha384},
{:rsa, :aria_128_cbc, :sha256},
{:rsa, :aria_256_cbc, :sha384},
{:dh_dss, :aria_128_cbc, :sha256},
{:dh_dss, :aria_256_cbc, :sha384},
{:dh_rsa, :aria_128_cbc, :sha256},
{:dh_rsa, :aria_256_cbc, :sha384},
{:dhe_dss, :aria_128_cbc, :sha256},
{:dhe_dss, :aria_256_cbc, :sha384},
{:dhe_rsa, :aria_128_cbc, :sha256},
{:dhe_rsa, :aria_256_cbc, :sha384},
{:dh_anon, :aria_128_cbc, :sha256},
{:dh_anon, :aria_256_cbc, :sha384},
{:ecdhe_ecdsa, :aria_128_cbc, :sha256},
{:ecdhe_ecdsa, :aria_256_cbc, :sha384},
{:ecdh_ecdsa, :aria_128_cbc, :sha256},
{:ecdh_ecdsa, :aria_256_cbc, :sha384},
{:ecdhe_rsa, :aria_128_cbc, :sha256},
{:ecdhe_rsa, :aria_256_cbc, :sha384},
{:ecdh_rsa, :aria_128_cbc, :sha256},
{:ecdh_rsa, :aria_256_cbc, :sha384},
{:rsa, :aria_128_gcm, :sha256},
{:rsa, :aria_256_gcm, :sha384},
{:dh_rsa, :aria_128_gcm, :sha256},
{:dh_rsa, :aria_256_gcm, :sha384},
{:dh_dss, :aria_128_gcm, :sha256},
{:dh_dss, :aria_256_gcm, :sha384},
{:dh_anon, :aria_128_gcm, :sha256},
{:dh_anon, :aria_256_gcm, :sha384},
{:ecdh_ecdsa, :aria_128_gcm, :sha256},
{:ecdh_ecdsa, :aria_256_gcm, :sha384},
{:ecdh_rsa, :aria_128_gcm, :sha256},
{:ecdh_rsa, :aria_256_gcm, :sha384},
{:psk, :aria_128_cbc, :sha256},
{:psk, :aria_256_cbc, :sha384},
{:dhe_psk, :aria_128_cbc, :sha256},
{:dhe_psk, :aria_256_cbc, :sha384},
{:rsa_psk, :aria_128_cbc, :sha256},
{:rsa_psk, :aria_256_cbc, :sha384},
{:psk, :aria_128_gcm, :sha256},
{:psk, :aria_256_gcm, :sha384},
{:rsa_psk, :aria_128_gcm, :sha256},
{:rsa_psk, :aria_256_gcm, :sha384},
{:ecdhe_psk, :aria_128_cbc, :sha256},
{:ecdhe_psk, :aria_256_cbc, :sha384},
{:ecdhe_ecdsa, :camellia_128_cbc, :sha256},
{:ecdhe_ecdsa, :camellia_256_cbc, :sha384},
{:ecdh_ecdsa, :camellia_128_cbc, :sha256},
{:ecdh_ecdsa, :camellia_256_cbc, :sha384},
{:ecdhe_rsa, :camellia_128_cbc, :sha256},
{:ecdhe_rsa, :camellia_256_cbc, :sha384},
{:ecdh_rsa, :camellia_128_cbc, :sha256},
{:ecdh_rsa, :camellia_256_cbc, :sha384},
{:rsa, :camellia_128_gcm, :sha256},
{:rsa, :camellia_256_gcm, :sha384},
{:dh_rsa, :camellia_128_gcm, :sha256},
{:dh_rsa, :camellia_256_gcm, :sha384},
{:dh_dss, :camellia_128_gcm, :sha256},
{:dh_dss, :camellia_256_gcm, :sha384},
{:dh_anon, :camellia_128_gcm, :sha256},
{:dh_anon, :camellia_256_gcm, :sha384},
{:ecdh_ecdsa, :camellia_128_gcm, :sha256},
{:ecdh_ecdsa, :camellia_256_gcm, :sha384},
{:ecdh_rsa, :camellia_128_gcm, :sha256},
{:ecdh_rsa, :camellia_256_gcm, :sha384},
{:psk, :camellia_128_gcm, :sha256},
{:psk, :camellia_256_gcm, :sha384},
{:rsa_psk, :camellia_128_gcm, :sha256},
{:rsa_psk, :camellia_256_gcm, :sha384},
{:psk, :camellia_128_cbc, :sha256},
{:psk, :camellia_256_cbc, :sha384},
{:dhe_psk, :camellia_128_cbc, :sha256},
{:dhe_psk, :camellia_256_cbc, :sha384},
{:rsa_psk, :camellia_128_cbc, :sha256},
{:rsa_psk, :camellia_256_cbc, :sha384},
{:ecdhe_psk, :camellia_128_cbc, :sha256},
{:ecdhe_psk, :camellia_256_cbc, :sha384},
{:rsa, :aes_128, :ccm},
{:rsa, :aes_256, :ccm},
{:rsa, :aes_128, :ccm_8},
{:rsa, :aes_256, :ccm_8},
{:psk, :aes_128, :ccm},
{:psk, :aes_256, :ccm},
{:psk, :aes_128, :ccm_8},
{:psk, :aes_256, :ccm_8}
]
@transport_opts [
packet: :raw,
mode: :binary,
active: false
]
@default_versions [:"tlsv1.2"]
@default_timeout 30_000
Record.defrecordp(
:certificate,
:Certificate,
Record.extract(:Certificate, from_lib: "public_key/include/OTP-PUB-KEY.hrl")
)
Record.defrecordp(
:tbs_certificate,
:OTPTBSCertificate,
Record.extract(:OTPTBSCertificate, from_lib: "public_key/include/OTP-PUB-KEY.hrl")
)
# TODO: Document how to enable revocation checking:
# crl_check: true
# crl_cache: {:ssl_crl_cache, {:internal, [http: 30_000]}}
@impl true
def connect(hostname, port, opts) do
hostname = String.to_charlist(hostname)
timeout = Keyword.get(opts, :timeout, @default_timeout)
wrap_err(:ssl.connect(hostname, port, ssl_opts(hostname, opts), timeout))
end
@impl true
def upgrade(socket, :http, hostname, _port, opts) do
hostname = String.to_charlist(hostname)
timeout = Keyword.get(opts, :timeout, @default_timeout)
# Seems like this is not set in :ssl.connect/2 correctly, so set it explicitly
Mint.Core.Transport.TCP.setopts(socket, active: false)
wrap_err(:ssl.connect(socket, ssl_opts(hostname, opts), timeout))
end
def upgrade(_socket, :https, _hostname, _port, _opts) do
raise "nested SSL sessions are not supported"
end
@impl true
def negotiated_protocol(socket) do
wrap_err(:ssl.negotiated_protocol(socket))
end
@impl true
def send(socket, payload) do
wrap_err(:ssl.send(socket, payload))
end
@impl true
def close(socket) do
wrap_err(:ssl.close(socket))
end
@impl true
def recv(socket, bytes, timeout) do
wrap_err(:ssl.recv(socket, bytes, timeout))
end
@impl true
def controlling_process(socket, pid) do
# We do this dance because it's what gen_tcp does in Erlang. However, ssl
# doesn't do this so we need to do it ourselves. Implementation roughly
# taken from this:
# https://github.com/erlang/otp/blob/fc1f0444e32b039194189af97fb3d5358a2b91e3/lib/kernel/src/inet.erl#L1696-L1754
with {:ok, active: active} <- getopts(socket, [:active]),
:ok <- setopts(socket, active: false),
:ok <- forward_messages_to_new_controlling_process(socket, pid),
:ok <- wrap_err(:ssl.controlling_process(socket, pid)) do
if(active == :once, do: setopts(socket, active: :once), else: :ok)
end
end
defp forward_messages_to_new_controlling_process(socket, pid) do
receive do
{:ssl, ^socket, _data} = message ->
Kernel.send(pid, message)
forward_messages_to_new_controlling_process(socket, pid)
{:ssl_error, ^socket, error} ->
{:error, error}
{:ssl_closed, ^socket} ->
{:error, :closed}
after
0 ->
:ok
end
end
@impl true
def setopts(socket, opts) do
wrap_err(:ssl.setopts(socket, opts))
end
@impl true
def getopts(socket, opts) do
wrap_err(:ssl.getopts(socket, opts))
end
@impl true
def wrap_error(reason) do
%Mint.TransportError{reason: reason}
end
defp ssl_opts(hostname, opts) do
default_ssl_opts(hostname)
|> Keyword.merge(opts)
|> Keyword.merge(@transport_opts)
|> Keyword.delete(:timeout)
|> add_verify_opts(hostname)
end
defp add_verify_opts(opts, hostname) do
verify = Keyword.get(opts, :verify)
if verify == :verify_peer do
opts
|> add_cacerts()
|> add_partial_chain_fun()
|> customize_hostname_check(hostname)
else
opts
end
end
defp customize_hostname_check(opts, host_or_ip) do
if ssl_major_version() >= 9 do
# From OTP 20.0 use built-in support for custom hostname checks
add_customize_hostname_check(opts)
else
# Before OTP 20.0 use mint_shims for hostname check, from a custom
# verify_fun
add_verify_fun(opts, host_or_ip)
end
end
defp add_customize_hostname_check(opts) do
customize_hostname_check_present? = Keyword.has_key?(opts, :customize_hostname_check)
if not customize_hostname_check_present? do
Keyword.put(opts, :customize_hostname_check, match_fun: &match_fun/2)
else
opts
end
end
defp add_verify_fun(opts, host_or_ip) do
verify_fun_present? = Keyword.has_key?(opts, :verify_fun)
if not verify_fun_present? do
reference_ids = [dns_id: host_or_ip, ip: host_or_ip]
Keyword.put(opts, :verify_fun, {&verify_fun/3, reference_ids})
else
opts
end
end
def verify_fun(_, {:bad_cert, _} = reason, _), do: {:fail, reason}
def verify_fun(_, {:extension, _}, state), do: {:unknown, state}
def verify_fun(_, :valid, state), do: {:valid, state}
def verify_fun(cert, :valid_peer, state) do
if :mint_shims.pkix_verify_hostname(cert, state, match_fun: &match_fun/2) do
{:valid, state}
else
{:fail, {:bad_cert, :hostname_check_failed}}
end
end
# Wildcard domain handling for DNS ID entries in the subjectAltName X.509
# extension. Note that this is a subset of the wildcard patterns implemented
# by OTP when matching against the subject CN attribute, but this is the only
# wildcard usage defined by the CA/Browser Forum's Baseline Requirements, and
# therefore the only pattern used in commercially issued certificates.
defp match_fun({:dns_id, reference}, {:dNSName, [?*, ?. | presented]}) do
case domain_without_host(reference) do
'' ->
:default
domain ->
# TODO: replace with `:string.casefold/1` eventually
:string.to_lower(domain) == :string.to_lower(presented)
end
end
defp match_fun(_reference, _presented), do: :default
defp domain_without_host([]), do: []
defp domain_without_host([?. | domain]), do: domain
defp domain_without_host([_ | more]), do: domain_without_host(more)
defp default_ssl_opts(hostname) do
# TODO: Add revocation check
[
ciphers: default_ciphers(),
server_name_indication: hostname,
versions: @default_versions,
verify: :verify_peer,
depth: 4,
secure_renegotiate: true,
reuse_sessions: true
]
end
defp add_cacerts(opts) do
if Keyword.has_key?(opts, :cacertfile) || Keyword.has_key?(opts, :cacerts) do
opts
else
raise_on_missing_castore!()
Keyword.put(opts, :cacertfile, CAStore.file_path())
end
end
defp add_partial_chain_fun(opts) do
if Keyword.has_key?(opts, :partial_chain) do
opts
else
case Keyword.fetch(opts, :cacerts) do
{:ok, cacerts} ->
cacerts = decode_cacerts(cacerts)
fun = &partial_chain(cacerts, &1)
Keyword.put(opts, :partial_chain, fun)
:error ->
path = Keyword.fetch!(opts, :cacertfile)
cacerts = decode_cacertfile(path)
fun = &partial_chain(cacerts, &1)
Keyword.put(opts, :partial_chain, fun)
end
end
end
defp decode_cacertfile(path) do
# TODO: Cache this?
path
|> File.read!()
|> :public_key.pem_decode()
|> Enum.filter(&match?({:Certificate, _, :not_encrypted}, &1))
|> Enum.map(&:public_key.pem_entry_decode/1)
end
defp decode_cacerts(certs) do
# TODO: Cache this?
Enum.map(certs, &:public_key.pkix_decode_cert(&1, :plain))
end
def partial_chain(cacerts, certs) do
# TODO: Shim this with OTP 21.1 implementation?
certs = Enum.map(certs, &{&1, :public_key.pkix_decode_cert(&1, :plain)})
trusted =
Enum.find_value(certs, fn {der, cert} ->
trusted? =
Enum.find(cacerts, fn cacert ->
extract_public_key_info(cacert) == extract_public_key_info(cert)
end)
if trusted?, do: der
end)
if trusted do
{:trusted_ca, trusted}
else
:unknown_ca
end
end
defp extract_public_key_info(cert) do
cert
|> certificate(:tbsCertificate)
|> tbs_certificate(:subjectPublicKeyInfo)
end
# NOTE: Should this be private and moved to a different module?
@doc false
def default_ciphers(), do: get_valid_suites(:ssl.cipher_suites(), [])
@dialyzer {:no_match, get_valid_suites: 2}
for {kex, cipher, mac} <- @blacklisted_ciphers do
defp get_valid_suites([{unquote(kex), unquote(cipher), _mac, unquote(mac)} | rest], valid) do
get_valid_suites(rest, valid)
end
defp get_valid_suites([{unquote(kex), unquote(cipher), unquote(mac)} | rest], valid) do
get_valid_suites(rest, valid)
end
end
defp get_valid_suites([suit | rest], valid), do: get_valid_suites(rest, [suit | valid])
defp get_valid_suites([], valid), do: valid
defp raise_on_missing_castore! do
Code.ensure_loaded?(CAStore) ||
raise "default CA trust store not available; " <>
"please add `:castore` to your project's dependencies or " <>
"specify the trust store using the `:cacertfile`/`:cacerts` option"
end
defp wrap_err({:error, reason}), do: {:error, wrap_error(reason)}
defp wrap_err(other), do: other
defp ssl_major_version do
Application.spec(:ssl, :vsn)
|> :string.to_integer()
|> elem(0)
end
end
| 32.252459 | 117 | 0.631341 |
088b2de9002a3422f2367c9d729b1c0d5678e926 | 564 | exs | Elixir | test/protocols/count_test.exs | lowks/atlas | e01cefa088fe1174d9162f5834156611f1caa594 | [
"MIT"
] | 94 | 2015-01-01T16:17:40.000Z | 2021-12-16T02:53:01.000Z | test/protocols/count_test.exs | IdoBn/atlas | e01cefa088fe1174d9162f5834156611f1caa594 | [
"MIT"
] | 2 | 2015-09-22T14:45:26.000Z | 2017-08-29T18:16:04.000Z | test/protocols/count_test.exs | IdoBn/atlas | e01cefa088fe1174d9162f5834156611f1caa594 | [
"MIT"
] | 11 | 2015-01-06T02:25:00.000Z | 2021-12-16T03:10:11.000Z | Code.require_file "../test_helper.exs", __DIR__
defmodule Atlas.CountTest do
use ExUnit.Case, async: true
import Atlas.Count
test "it implements count for List" do
assert count([1, 2, 3]) == 3
assert count([]) == 0
end
test "it implements count for BitString" do
assert count("") == 0
assert count("test") == 4
end
test "it implements count for Atom" do
assert count(nil) == 0
assert count(:atom) == 4
end
test "it implements count for Map" do
assert count(%{}) == 0
assert count(%{foo: :bar}) == 1
end
end
| 20.888889 | 47 | 0.629433 |
088b547e3a6d3103480763a00676795ab4ceb118 | 61 | ex | Elixir | lib/ketbin_web/views/layout_view.ex | ATechnoHazard/katbin | 20a0b45954cf7819cd9d51c401db06be0f47666b | [
"MIT"
] | 4 | 2020-08-05T20:05:34.000Z | 2020-10-01T10:01:56.000Z | lib/ketbin_web/views/layout_view.ex | ATechnoHazard/katbin | 20a0b45954cf7819cd9d51c401db06be0f47666b | [
"MIT"
] | 1 | 2020-07-08T05:02:12.000Z | 2020-09-25T10:05:11.000Z | lib/ketbin_web/views/layout_view.ex | ATechnoHazard/katbin | 20a0b45954cf7819cd9d51c401db06be0f47666b | [
"MIT"
] | 1 | 2020-08-30T12:59:49.000Z | 2020-08-30T12:59:49.000Z | defmodule KetbinWeb.LayoutView do
use KetbinWeb, :view
end
| 15.25 | 33 | 0.803279 |
088b842eb8cdc156435689b0b1082397602f65f9 | 906 | ex | Elixir | clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/metadata.ex | corp-momenti/elixir-google-api | fe1580e305789ab2ca0741791b8ffe924bd3240c | [
"Apache-2.0"
] | null | null | null | clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/metadata.ex | corp-momenti/elixir-google-api | fe1580e305789ab2ca0741791b8ffe924bd3240c | [
"Apache-2.0"
] | null | null | null | clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/metadata.ex | corp-momenti/elixir-google-api | fe1580e305789ab2ca0741791b8ffe924bd3240c | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 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.CloudResourceManager.V1 do
@moduledoc """
API client metadata for GoogleApi.CloudResourceManager.V1.
"""
@discovery_revision "20211017"
def discovery_revision(), do: @discovery_revision
end
| 33.555556 | 74 | 0.764901 |
088b98129b743bccc9611058c3f147e330bac228 | 474 | exs | Elixir | web/api/test/app/auth/router_test.exs | felixwolter/idai-field | 146ab8dbdedb23035a4ba19eac95f02a1fa2329f | [
"Apache-2.0"
] | null | null | null | web/api/test/app/auth/router_test.exs | felixwolter/idai-field | 146ab8dbdedb23035a4ba19eac95f02a1fa2329f | [
"Apache-2.0"
] | null | null | null | web/api/test/app/auth/router_test.exs | felixwolter/idai-field | 146ab8dbdedb23035a4ba19eac95f02a1fa2329f | [
"Apache-2.0"
] | null | null | null | defmodule Api.AppTest.Auth.RouterTest do
use ExUnit.Case, async: true
use Plug.Test
alias Api.AppTest.Support.AppTestHelper
@auth_info_path AppTestHelper.auth_path <> "/info"
@user5 {"user-5", "pass-5"}
setup context do
AppTestHelper.perform_query context
end
@tag path: @auth_info_path, login: @user5
test "show readable_projects - anonymous", context do
assert context.body.readable_projects == ["a", "b"]
end
end
| 24.947368 | 57 | 0.683544 |
088bcd08bf214dd787bbab229d10dabac47d5594 | 78 | ex | Elixir | lib/squarestore_web/views/product_view.ex | NinjaAnge/forksquare | ee9ea91e45e50b9f1ba4a8261ebdd99b7fe3333d | [
"MIT"
] | null | null | null | lib/squarestore_web/views/product_view.ex | NinjaAnge/forksquare | ee9ea91e45e50b9f1ba4a8261ebdd99b7fe3333d | [
"MIT"
] | null | null | null | lib/squarestore_web/views/product_view.ex | NinjaAnge/forksquare | ee9ea91e45e50b9f1ba4a8261ebdd99b7fe3333d | [
"MIT"
] | null | null | null | defmodule SquarestoreWeb.ProductView do
use SquarestoreWeb, :view
end
| 19.5 | 39 | 0.769231 |
088c0af55d4e58a67d260c12d8d769c743d3ece6 | 778 | exs | Elixir | 2021/ERI-MT/language_list/test/language_list_test.exs | adolfont/pensandoemelixir | 10a639c6451b8ec181116a0531a77815fde04f3f | [
"CC0-1.0"
] | 5 | 2021-09-02T20:07:04.000Z | 2021-12-14T21:24:38.000Z | 2021/ERI-MT/language_list/test/language_list_test.exs | adolfont/pensandoemelixir | 10a639c6451b8ec181116a0531a77815fde04f3f | [
"CC0-1.0"
] | null | null | null | 2021/ERI-MT/language_list/test/language_list_test.exs | adolfont/pensandoemelixir | 10a639c6451b8ec181116a0531a77815fde04f3f | [
"CC0-1.0"
] | null | null | null | defmodule LanguageListTest do
use ExUnit.Case
import LanguageList
test "Adiciona Elixir à lista de linguagens" do
assert LanguageList.adiciona([], "Elixir") == ["Elixir"]
end
test "Adiciona C e Elixir à lista de linguagens" do
lista =
adiciona([], "C")
|> adiciona("Elixir")
assert lista == ["Elixir", "C"]
end
test "Adiciona C, Java e Elixir à lista de linguagens" do
lista =
adiciona([], "C")
|> adiciona("Java")
|> adiciona("Elixir")
assert lista == ["Elixir", "Java", "C"]
end
test "Elixir está na lista de linguagens contendo C, Java e Elixir" do
lista =
adiciona([], "C")
|> adiciona("Java")
|> adiciona("Elixir")
assert LanguageList.esta_na?("Elixir", lista)
end
end
| 21.611111 | 72 | 0.606684 |
088c20d9b76e656f770afd1ceae7ec2939a07544 | 401 | exs | Elixir | priv/repo/migrations/20190206161902_create_ip_pools.exs | runhyve/webapp | 434b074f98c1ebac657b56062c1c1a54e683dea1 | [
"BSD-2-Clause"
] | 12 | 2019-07-02T14:30:06.000Z | 2022-03-12T08:22:18.000Z | priv/repo/migrations/20190206161902_create_ip_pools.exs | runhyve/webapp | 434b074f98c1ebac657b56062c1c1a54e683dea1 | [
"BSD-2-Clause"
] | 9 | 2020-03-16T20:10:50.000Z | 2021-06-17T17:45:44.000Z | priv/repo/migrations/20190206161902_create_ip_pools.exs | runhyve/webapp | 434b074f98c1ebac657b56062c1c1a54e683dea1 | [
"BSD-2-Clause"
] | null | null | null | defmodule Webapp.Repo.Migrations.CreateIpPools do
use Ecto.Migration
def change do
create table(:ip_pools) do
add(:name, :string)
add(:ip_range, :string)
add(:netmask, :inet)
add(:gateway, :inet)
add(:network_id, references(:networks, on_delete: :delete_all))
timestamps(type: :utc_datetime)
end
create(index(:ip_pools, [:network_id]))
end
end
| 22.277778 | 69 | 0.658354 |
088c2aac64319fac6680c999f58b4b47abe9999a | 651 | ex | Elixir | lib/embed_chat_web/controllers/page_controller.ex | guofei/embedchat | 6562108acd1d488dde457f28cf01d82b4c5a9bf8 | [
"MIT"
] | 27 | 2016-10-15T12:13:22.000Z | 2021-02-07T20:31:41.000Z | lib/embed_chat_web/controllers/page_controller.ex | guofei/embedchat | 6562108acd1d488dde457f28cf01d82b4c5a9bf8 | [
"MIT"
] | null | null | null | lib/embed_chat_web/controllers/page_controller.ex | guofei/embedchat | 6562108acd1d488dde457f28cf01d82b4c5a9bf8 | [
"MIT"
] | 4 | 2016-08-21T15:03:29.000Z | 2019-11-22T13:15:29.000Z | defmodule EmbedChatWeb.PageController do
use EmbedChatWeb, :controller
alias EmbedChat.Attempt
plug Guardian.Plug.EnsureAuthenticated, [handler: EmbedChatWeb.AuthErrorHandler] when action in [:welcome]
def index(conn, _params) do
user = Guardian.Plug.current_resource(conn)
if user do
room = Repo.one(user_rooms conn)
render conn, "index.html", room: room
else
changeset = Attempt.changeset(%Attempt{})
render conn, "index.html", attempt: changeset
end
end
def price(conn, _params) do
render conn, "price.html"
end
def welcome(conn, _params) do
render conn, "welcome.html"
end
end
| 25.038462 | 108 | 0.705069 |
088c44f348e6a2ed6024c26accfd0d412a4b787e | 143 | exs | Elixir | test/parsers/binary_test.exs | kianmeng/combine | f3a16b56efab388abe2608188d519291549b7eb5 | [
"MIT"
] | 199 | 2015-07-27T11:42:38.000Z | 2022-01-16T13:42:32.000Z | test/parsers/binary_test.exs | kianmeng/combine | f3a16b56efab388abe2608188d519291549b7eb5 | [
"MIT"
] | 45 | 2015-07-27T00:16:26.000Z | 2018-03-02T23:27:04.000Z | test/parsers/binary_test.exs | kianmeng/combine | f3a16b56efab388abe2608188d519291549b7eb5 | [
"MIT"
] | 24 | 2015-07-26T23:52:14.000Z | 2021-09-12T01:35:14.000Z | defmodule Combine.Parsers.Binary.Test do
use ExUnit.Case, async: true
doctest Combine.Parsers.Binary
import Combine.Parsers.Binary
end
| 17.875 | 40 | 0.79021 |
088caa2f643c6721046788eedd122f3c0e05a4f7 | 1,010 | ex | Elixir | test/support/conn_case.ex | mfunaro/handiman-api | 66357caa55c2b1fb696471c04e602b5546879cf4 | [
"Unlicense",
"MIT"
] | null | null | null | test/support/conn_case.ex | mfunaro/handiman-api | 66357caa55c2b1fb696471c04e602b5546879cf4 | [
"Unlicense",
"MIT"
] | null | null | null | test/support/conn_case.ex | mfunaro/handiman-api | 66357caa55c2b1fb696471c04e602b5546879cf4 | [
"Unlicense",
"MIT"
] | null | null | null | defmodule HandimanApi.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
imports other functionality to make it easier
to build and query models.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
alias HandimanApi.Repo
import Ecto.Model
import Ecto.Query, only: [from: 2]
import HandimanApi.Router.Helpers
# The default endpoint for testing
@endpoint HandimanApi.Endpoint
end
end
setup tags do
unless tags[:async] do
Ecto.Adapters.SQL.restart_test_transaction(HandimanApi.Repo, [])
end
:ok
end
end
| 24.047619 | 70 | 0.711881 |
088cef7cf7214dd54f1f2c6925b21d062b9166a1 | 304 | ex | Elixir | lib/mangopay_ex/resources/users/natural.ex | StephaneRob/mangopay_ex | d05dab35f431c2f18f6ae95aedf68dede6731402 | [
"MIT"
] | 1 | 2018-02-01T11:10:09.000Z | 2018-02-01T11:10:09.000Z | lib/mangopay_ex/resources/users/natural.ex | StephaneRob/mangopay_ex | d05dab35f431c2f18f6ae95aedf68dede6731402 | [
"MIT"
] | null | null | null | lib/mangopay_ex/resources/users/natural.ex | StephaneRob/mangopay_ex | d05dab35f431c2f18f6ae95aedf68dede6731402 | [
"MIT"
] | null | null | null | defmodule MangopayEx.Users.Natural do
@moduledoc """
A Natural User is a person whereas a legal user represents a business or an organisation. This natural user is able to:
"""
@endpoint "users/natural"
@resource_name "natural user"
use MangopayEx.Resource, import: [:create, :update]
end
| 25.333333 | 121 | 0.736842 |
088d24ddedaffa1dce58ff1f0273963c13c8655e | 11,295 | ex | Elixir | lib/eden/lexer.ex | mindreframer/Eden | 071018819530e07ed6b2e000c20383a98c716f07 | [
"Apache-2.0"
] | null | null | null | lib/eden/lexer.ex | mindreframer/Eden | 071018819530e07ed6b2e000c20383a98c716f07 | [
"Apache-2.0"
] | null | null | null | lib/eden/lexer.ex | mindreframer/Eden | 071018819530e07ed6b2e000c20383a98c716f07 | [
"Apache-2.0"
] | null | null | null | defmodule Eden.Lexer do
alias Eden.Exception, as: Ex
@moduledoc """
A module that implements a lexer for the edn format through its
only function `tokenize/1`.
"""
defmodule Token do
defstruct type: nil, value: nil
end
##############################################################################
## API
##############################################################################
@doc """
Takes a string and returns a list of tokens.
Options:
- `:location` - a `boolean` that determines wether the location information
should be included with each token. Lines are one-based and columns are
zero-based. The default value for `:location` is `false`.
## Examples
iex> Eden.Lexer.tokenize("nil")
[%Eden.Lexer.Token{type: nil, value: "nil"}]
iex> Eden.Lexer.tokenize("nil", location: true)
[%Eden.Lexer.Token{location: %{col: 0, line: 1}, type: nil, value: "nil"}]
"""
def tokenize(input, opts \\ [location: false]) do
initial_state = %{
state: :new,
tokens: [],
current: nil,
opts: opts,
location: %{line: 1, col: 0}
}
_tokenize(initial_state, input)
end
##############################################################################
## Private functions
##############################################################################
# End of input
defp _tokenize(state, <<>>) do
state
|> valid?
|> add_token(state.current)
|> Map.get(:tokens)
|> Enum.reverse()
end
# Comment
defp _tokenize(state = %{state: :new}, <<";"::utf8, rest::binary>>) do
token = token(:comment, "")
start_token(state, :comment, token, ";", rest)
end
defp _tokenize(state = %{state: :comment}, <<char::utf8, rest::binary>>)
when <<char::utf8>> in ["\n", "\r"] do
end_token(state, <<char::utf8>>, rest)
end
defp _tokenize(state = %{state: :comment}, <<";"::utf8, rest::binary>>) do
skip_char(state, ";", rest)
end
defp _tokenize(state = %{state: :comment}, <<char::utf8, rest::binary>>) do
consume_char(state, <<char::utf8>>, rest)
end
# Literals
defp _tokenize(state = %{state: :new}, <<"nil"::utf8, rest::binary>>) do
token = token(nil, "nil")
start_token(state, :check_literal, token, "nil", rest)
end
defp _tokenize(state = %{state: :new}, <<"true"::utf8, rest::binary>>) do
token = token(true, "true")
start_token(state, :check_literal, token, "true", rest)
end
defp _tokenize(state = %{state: :new}, <<"false"::utf8, rest::binary>>) do
token = token(false, "false")
start_token(state, :check_literal, token, "false", rest)
end
defp _tokenize(state = %{state: :check_literal}, <<char::utf8, _::binary>> = input) do
if separator?(<<char::utf8>>) do
end_token(state, "", input)
else
token = token(:symbol, state.current.value)
start_token(state, :symbol, token, "", input)
end
end
# String
defp _tokenize(state = %{state: :new}, <<"\""::utf8, rest::binary>>) do
token = token(:string, "")
start_token(state, :string, token, "\"", rest)
end
defp _tokenize(state = %{state: :string}, <<"\\"::utf8, char::utf8, rest::binary>>) do
# TODO: this will cause the line count to get corrupted,
# either use the original or send the real content as
# an optional argument.
consume_char(state, escaped_char(<<char::utf8>>), rest, <<"\\"::utf8, char::utf8>>)
end
defp _tokenize(state = %{state: :string}, <<"\""::utf8, rest::binary>>) do
end_token(state, "\"", rest)
end
defp _tokenize(state = %{state: :string}, <<char::utf8, rest::binary>>) do
consume_char(state, <<char::utf8>>, rest)
end
# Character
defp _tokenize(state = %{state: :new}, <<"\\"::utf8, char::utf8, rest::binary>>) do
token = token(:character, <<char::utf8>>)
end_token(state, token, "\\" <> <<char::utf8>>, rest)
end
# Keyword and Symbol
defp _tokenize(state = %{state: :new}, <<":"::utf8, rest::binary>>) do
token = token(:keyword, "")
start_token(state, :symbol, token, ":", rest)
end
defp _tokenize(state = %{state: :symbol}, <<"/"::utf8, rest::binary>>) do
if not String.contains?(state.current.value, "/") do
consume_char(state, <<"/"::utf8>>, rest)
else
raise Ex.UnexpectedInputError, "/"
end
end
defp _tokenize(state = %{state: :symbol}, <<c::utf8, rest::binary>> = input) do
if symbol_char?(<<c::utf8>>) do
consume_char(state, <<c::utf8>>, rest)
else
end_token(state, "", input)
end
end
# Integers & Float
defp _tokenize(state = %{state: :new}, <<sign::utf8, rest::binary>>)
when <<sign>> in ["-", "+"] do
token = token(:integer, <<sign>>)
start_token(state, :number, token, <<sign>>, rest)
end
defp _tokenize(state = %{state: :exponent}, <<sign::utf8, rest::binary>>)
when <<sign>> in ["-", "+"] do
consume_char(state, <<sign::utf8>>, rest)
end
defp _tokenize(state = %{state: :number}, <<"N"::utf8, rest::binary>>) do
state = append_to_current(state, "N")
end_token(state, "N", rest)
end
defp _tokenize(state = %{state: :number}, <<"M"::utf8, rest::binary>>) do
state = append_to_current(state, "M")
token = token(:float, state.current.value)
end_token(state, token, "M", rest)
end
defp _tokenize(state = %{state: :number}, <<"."::utf8, rest::binary>>) do
state = append_to_current(state, ".")
token = token(:float, state.current.value)
start_token(state, :fraction, token, ".", rest)
end
defp _tokenize(state = %{state: :number}, <<char::utf8, rest::binary>>)
when <<char::utf8>> in ["e", "E"] do
state = append_to_current(state, <<char::utf8>>)
token = token(:float, state.current.value)
start_token(state, :exponent, token, <<char::utf8>>, rest)
end
defp _tokenize(state = %{state: s}, <<char::utf8, rest::binary>> = input)
when s in [:number, :exponent, :fraction] do
cond do
digit?(<<char::utf8>>) ->
state
|> set_state(:number)
|> consume_char(<<char::utf8>>, rest)
s in [:exponent, :fraction] and separator?(<<char::utf8>>) ->
raise Ex.UnfinishedTokenError, state.current
separator?(<<char::utf8>>) ->
end_token(state, "", input)
true ->
raise Ex.UnexpectedInputError, <<char::utf8>>
end
end
# Delimiters
defp _tokenize(state = %{state: :new}, <<delim::utf8, rest::binary>>)
when <<delim>> in ["{", "}", "[", "]", "(", ")"] do
delim = <<delim>>
token = token(delim_type(delim), delim)
end_token(state, token, delim, rest)
end
defp _tokenize(state = %{state: :new}, <<"#\{"::utf8, rest::binary>>) do
token = token(:set_open, "#\{")
end_token(state, token, "#\{", rest)
end
# Whitespace
defp _tokenize(state = %{state: :new}, <<whitespace::utf8, rest::binary>>)
when <<whitespace>> in [" ", "\t", "\r", "\n", ","] do
skip_char(state, <<whitespace>>, rest)
end
# Discard
defp _tokenize(state = %{state: :new}, <<"#_"::utf8, rest::binary>>) do
token = token(:discard, "#_")
end_token(state, token, "#_", rest)
end
# Tags
defp _tokenize(state = %{state: :new}, <<"#"::utf8, rest::binary>>) do
token = token(:tag, "")
start_token(state, :symbol, token, "#", rest)
end
# Symbol, Integer or Invalid input
defp _tokenize(state = %{state: :new}, <<char::utf8, rest::binary>>) do
cond do
alpha?(<<char::utf8>>) ->
token = token(:symbol, <<char::utf8>>)
start_token(state, :symbol, token, <<char::utf8>>, rest)
digit?(<<char::utf8>>) ->
token = token(:integer, <<char::utf8>>)
start_token(state, :number, token, <<char::utf8>>, rest)
true ->
raise Ex.UnexpectedInputError, <<char::utf8>>
end
end
# Unexpected Input
defp _tokenize(_, <<char::utf8, _::binary>>) do
raise Ex.UnexpectedInputError, <<char::utf8>>
end
##############################################################################
## Helper functions
##############################################################################
defp start_token(state, name, token, char, rest) do
state
|> set_state(name)
|> set_token(token)
|> update_location(char)
|> _tokenize(rest)
end
defp consume_char(state, char, rest, real_char \\ nil) when is_binary(char) do
state
|> update_location(real_char || char)
|> append_to_current(char)
|> _tokenize(rest)
end
defp skip_char(state, char, rest) when is_binary(char) do
state
|> update_location(char)
|> _tokenize(rest)
end
defp end_token(state, char, rest) do
state
|> update_location(char)
|> add_token(state.current)
|> reset
|> _tokenize(rest)
end
defp end_token(state, token, char, rest) do
state
|> set_token(token)
|> end_token(char, rest)
end
defp update_location(state, "") do
state
end
defp update_location(state, <<"\n"::utf8, rest::binary>>) do
state
|> put_in([:location, :line], state.location.line + 1)
|> put_in([:location, :col], 0)
|> update_location(rest)
end
defp update_location(state, <<"\r"::utf8, rest::binary>>) do
update_location(state, rest)
end
defp update_location(state, <<_::utf8, rest::binary>>) do
state
|> put_in([:location, :col], state.location.col + 1)
|> update_location(rest)
end
defp token(type, value) do
%Token{type: type, value: value}
end
defp set_token(state, token) do
token =
if state.opts[:location] do
Map.put(token, :location, state.location)
else
token
end
Map.put(state, :current, token)
end
defp set_state(state, name) do
Map.put(state, :state, name)
end
defp append_to_current(%{current: current} = state, c) do
current = %{current | value: current.value <> c}
%{state | current: current}
end
defp reset(state) do
%{state | state: :new, current: nil}
end
defp valid?(%{state: state, current: current})
when state in [:string, :exponent, :character, :fraction] do
raise Ex.UnfinishedTokenError, current
end
defp valid?(state) do
state
end
defp add_token(state, nil) do
state
end
defp add_token(state, token) do
if token.type == :keyword and token.value == "" do
raise Ex.UnfinishedTokenError, token
end
%{state | tokens: [token | state.tokens]}
end
defp delim_type("{"), do: :curly_open
defp delim_type("}"), do: :curly_close
defp delim_type("["), do: :bracket_open
defp delim_type("]"), do: :bracket_close
defp delim_type("("), do: :paren_open
defp delim_type(")"), do: :paren_close
defp escaped_char("\""), do: "\""
defp escaped_char("t"), do: "\t"
defp escaped_char("r"), do: "\r"
defp escaped_char("n"), do: "\n"
defp escaped_char("\\"), do: "\\"
defp alpha?(char), do: String.match?(char, ~r/[a-zA-Z]/)
defp digit?(char), do: String.match?(char, ~r/[0-9]/)
defp symbol_char?(char), do: String.match?(char, ~r/[_?a-zA-Z0-9.*+!\-$%&=<>\#:]/)
defp whitespace?(char), do: String.match?(char, ~r/[\s,]/)
defp delim?(char), do: String.match?(char, ~r/[\{\}\[\]\(\)]/)
defp separator?(char), do: whitespace?(char) or delim?(char)
end
| 28.740458 | 88 | 0.572377 |
088d3df122437d55c3d0a5eaf125dfe987419916 | 598 | exs | Elixir | test/koans/functions_koans_test.exs | flowerett/elixir-koans | 174f4610e846f59cc34b41a36b813f5d684fd510 | [
"MIT"
] | 1 | 2017-10-12T15:57:40.000Z | 2017-10-12T15:57:40.000Z | test/koans/functions_koans_test.exs | flowerett/elixir-koans | 174f4610e846f59cc34b41a36b813f5d684fd510 | [
"MIT"
] | null | null | null | test/koans/functions_koans_test.exs | flowerett/elixir-koans | 174f4610e846f59cc34b41a36b813f5d684fd510 | [
"MIT"
] | null | null | null | defmodule FunctionsTests do
use ExUnit.Case
import TestHarness
test "Functions" do
answers = [
"Hello, World!",
3,
{:multiple, ["One and Two", "Only One"]},
{:multiple, ["Hello Hello Hello Hello Hello ","Hello Hello "]},
{:multiple, [:entire_list, :single_thing]},
{:multiple, ["10 is bigger than 5", "4 is not bigger than 27"]},
{:multiple, ["The number was zero", "The number was 5"]},
6,
6,
"Hi, Foo!",
["foo", "foo", "foo"],
100,
1000,
"Full Name",
]
test_all(Functions, answers)
end
end
| 23 | 70 | 0.543478 |
088d7b6f01ec3d326a80bfbfab2eac23b04386d7 | 820 | ex | Elixir | lib/kitchen_sink/schema/changeset.ex | noizu/KitchenSink | 34f51fb93dfa913ba7be411475d02520d537e676 | [
"MIT"
] | 2 | 2019-04-15T22:17:59.000Z | 2022-01-03T15:35:36.000Z | lib/kitchen_sink/schema/changeset.ex | noizu/KitchenSink | 34f51fb93dfa913ba7be411475d02520d537e676 | [
"MIT"
] | null | null | null | lib/kitchen_sink/schema/changeset.ex | noizu/KitchenSink | 34f51fb93dfa913ba7be411475d02520d537e676 | [
"MIT"
] | null | null | null | #-------------------------------------------------------------------------------
# Author: Keith Brings
# Copyright (C) 2018 Noizu Labs, Inc. All rights reserved.
#-------------------------------------------------------------------------------
defmodule Noizu.KitchenSink.ChangeSet do
#alias Noizu.MnesiaVersioning.ChangeSet
use Amnesia
use Noizu.KitchenSink.Database
use Noizu.MnesiaVersioning.SchemaBehaviour
def neighbors() do
topology_provider = Application.get_env(:noizu_mnesia_versioning, :topology_provider)
{:ok, nodes} = topology_provider.mnesia_nodes();
nodes
end
#-----------------------------------------------------------------------------
# ChangeSets
#-----------------------------------------------------------------------------
def change_sets do
[
]
end
end | 34.166667 | 89 | 0.453659 |
088d92acc75831ca71de3f0a8c1a9ddddf456a26 | 1,523 | ex | Elixir | server/test/support/data_case.ex | Nymrinae/TimeManager | 5048280da7c497909bca7faf7d2256c07438d442 | [
"MIT"
] | null | null | null | server/test/support/data_case.ex | Nymrinae/TimeManager | 5048280da7c497909bca7faf7d2256c07438d442 | [
"MIT"
] | null | null | null | server/test/support/data_case.ex | Nymrinae/TimeManager | 5048280da7c497909bca7faf7d2256c07438d442 | [
"MIT"
] | null | null | null | defmodule Server.DataCase do
@moduledoc """
This module defines the setup for tests requiring
access to the application's data layer.
You may define functions here to be used as helpers in
your tests.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use Server.DataCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
alias Server.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Server.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Server.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Server.Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transforms changeset errors into a map of messages.
assert {:error, changeset} = Users.create_user(%{password: "short"})
assert "password is too short" in errors_on(changeset).password
assert %{password: ["password is too short"]} = errors_on(changeset)
"""
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
| 27.196429 | 77 | 0.686802 |
088d97f3aa1aad5e8f99317c4e70d7a3ad306126 | 501 | ex | Elixir | day11/dumbo_octopus/lib/dumbo_octopus_web/views/error_view.ex | alopezz/advent_of_code-2021 | 90f0d7e3290a5c8ba5d18b2a5d9240ea6b1682bd | [
"MIT"
] | null | null | null | day11/dumbo_octopus/lib/dumbo_octopus_web/views/error_view.ex | alopezz/advent_of_code-2021 | 90f0d7e3290a5c8ba5d18b2a5d9240ea6b1682bd | [
"MIT"
] | null | null | null | day11/dumbo_octopus/lib/dumbo_octopus_web/views/error_view.ex | alopezz/advent_of_code-2021 | 90f0d7e3290a5c8ba5d18b2a5d9240ea6b1682bd | [
"MIT"
] | null | null | null | defmodule DumboOctopusWeb.ErrorView do
use DumboOctopusWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.html", _assigns) do
# "Internal Server Error"
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| 29.470588 | 61 | 0.740519 |
088dae1071f9bb1505ad7bbdb540beb9e49eea05 | 2,242 | ex | Elixir | clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1p3beta1__text_frame.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1p3beta1__text_frame.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1p3beta1__text_frame.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.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p3beta1_TextFrame do
@moduledoc """
Video frame level annotation results for text annotation (OCR).
Contains information regarding timestamp and bounding box locations for the
frames containing detected OCR text snippets.
## Attributes
* `rotatedBoundingBox` (*type:* `GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly.t`, *default:* `nil`) - Bounding polygon of the detected text for this frame.
* `timeOffset` (*type:* `String.t`, *default:* `nil`) - Timestamp of this frame.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:rotatedBoundingBox =>
GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly.t(),
:timeOffset => String.t()
}
field(:rotatedBoundingBox,
as:
GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly
)
field(:timeOffset)
end
defimpl Poison.Decoder,
for: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p3beta1_TextFrame do
def decode(value, options) do
GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p3beta1_TextFrame.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p3beta1_TextFrame do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.16129 | 212 | 0.76628 |
088dd12706bac25420ac87b25639a0c8e12c7432 | 2,543 | ex | Elixir | clients/service_management/lib/google_api/service_management/v1/model/type.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/service_management/lib/google_api/service_management/v1/model/type.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/service_management/lib/google_api/service_management/v1/model/type.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ServiceManagement.V1.Model.Type do
@moduledoc """
A protocol buffer message type.
## Attributes
* `fields` (*type:* `list(GoogleApi.ServiceManagement.V1.Model.Field.t)`, *default:* `nil`) - The list of fields.
* `name` (*type:* `String.t`, *default:* `nil`) - The fully qualified message name.
* `oneofs` (*type:* `list(String.t)`, *default:* `nil`) - The list of types appearing in `oneof` definitions in this type.
* `options` (*type:* `list(GoogleApi.ServiceManagement.V1.Model.Option.t)`, *default:* `nil`) - The protocol buffer options.
* `sourceContext` (*type:* `GoogleApi.ServiceManagement.V1.Model.SourceContext.t`, *default:* `nil`) - The source context.
* `syntax` (*type:* `String.t`, *default:* `nil`) - The source syntax.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:fields => list(GoogleApi.ServiceManagement.V1.Model.Field.t()),
:name => String.t(),
:oneofs => list(String.t()),
:options => list(GoogleApi.ServiceManagement.V1.Model.Option.t()),
:sourceContext => GoogleApi.ServiceManagement.V1.Model.SourceContext.t(),
:syntax => String.t()
}
field(:fields, as: GoogleApi.ServiceManagement.V1.Model.Field, type: :list)
field(:name)
field(:oneofs, type: :list)
field(:options, as: GoogleApi.ServiceManagement.V1.Model.Option, type: :list)
field(:sourceContext, as: GoogleApi.ServiceManagement.V1.Model.SourceContext)
field(:syntax)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceManagement.V1.Model.Type do
def decode(value, options) do
GoogleApi.ServiceManagement.V1.Model.Type.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceManagement.V1.Model.Type do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.016129 | 128 | 0.70468 |
088dfa7acca461758aeb64b05646bc7fbf21a101 | 1,725 | ex | Elixir | clients/service_networking/lib/google_api/service_networking/v1/model/list_peered_dns_domains_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/service_networking/lib/google_api/service_networking/v1/model/list_peered_dns_domains_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/service_networking/lib/google_api/service_networking/v1/model/list_peered_dns_domains_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ServiceNetworking.V1.Model.ListPeeredDnsDomainsResponse do
@moduledoc """
Response to list peered DNS domains for a given connection.
## Attributes
* `peeredDnsDomains` (*type:* `list(GoogleApi.ServiceNetworking.V1.Model.PeeredDnsDomain.t)`, *default:* `nil`) - The list of peered DNS domains.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:peeredDnsDomains =>
list(GoogleApi.ServiceNetworking.V1.Model.PeeredDnsDomain.t()) | nil
}
field(:peeredDnsDomains, as: GoogleApi.ServiceNetworking.V1.Model.PeeredDnsDomain, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceNetworking.V1.Model.ListPeeredDnsDomainsResponse do
def decode(value, options) do
GoogleApi.ServiceNetworking.V1.Model.ListPeeredDnsDomainsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceNetworking.V1.Model.ListPeeredDnsDomainsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.9375 | 149 | 0.75942 |
088e341c3e88a16425497799ea295fb6f03ff395 | 3,018 | exs | Elixir | test/surface/components/form/color_input_test.exs | thorsten-de/surface | 67ebc2eadec22a22e043394f37d0d8d0e0e81b77 | [
"MIT"
] | null | null | null | test/surface/components/form/color_input_test.exs | thorsten-de/surface | 67ebc2eadec22a22e043394f37d0d8d0e0e81b77 | [
"MIT"
] | null | null | null | test/surface/components/form/color_input_test.exs | thorsten-de/surface | 67ebc2eadec22a22e043394f37d0d8d0e0e81b77 | [
"MIT"
] | null | null | null | defmodule Surface.Components.Form.ColorInputTest do
use Surface.ConnCase, async: true
alias Surface.Components.Form.ColorInput
test "empty input" do
html =
render_surface do
~F"""
<ColorInput form="user" field="color" />
"""
end
assert html =~ """
<input id="user_color" name="user[color]" type="color">
"""
end
test "input with atom field" do
html =
render_surface do
~F"""
<ColorInput form="user" field={:color} />
"""
end
assert html =~ """
<input id="user_color" name="user[color]" type="color">
"""
end
test "setting the value" do
html =
render_surface do
~F"""
<ColorInput form="user" field="color" value="mycolor" />
"""
end
assert html =~ """
<input id="user_color" name="user[color]" type="color" value="mycolor">
"""
end
test "setting the class" do
html =
render_surface do
~F"""
<ColorInput form="user" field="color" class="input"/>
"""
end
assert html =~ ~r/class="input"/
end
test "setting multiple classes" do
html =
render_surface do
~F"""
<ColorInput form="user" field="color" class="input primary"/>
"""
end
assert html =~ ~r/class="input primary"/
end
test "passing other options" do
html =
render_surface do
~F"""
<ColorInput form="user" field="color" opts={autofocus: "autofocus"} />
"""
end
assert html =~ """
<input autofocus="autofocus" id="user_color" name="user[color]" type="color">
"""
end
test "events with parent live view as target" do
html =
render_surface do
~F"""
<ColorInput form="user" field="color" value="mycolor" click="my_click" />
"""
end
assert html =~ ~s(phx-click="my_click")
end
test "setting id and name through props" do
html =
render_surface do
~F"""
<ColorInput form="user" field="color" id="color" name="color" />
"""
end
assert html =~ """
<input id="color" name="color" type="color">
"""
end
test "setting the phx-value-* values" do
html =
render_surface do
~F"""
<ColorInput form="user" field="color" values={a: "one", b: :two, c: 3} />
"""
end
assert html =~ """
<input id="user_color" name="user[color]" phx-value-a="one" phx-value-b="two" phx-value-c="3" type="color">
"""
end
end
defmodule Surface.Components.Form.ColorInputConfigTest do
use Surface.ConnCase
alias Surface.Components.Form.ColorInput
test ":default_class config" do
using_config ColorInput, default_class: "default_class" do
html =
render_surface do
~F"""
<ColorInput/>
"""
end
assert html =~ ~r/class="default_class"/
end
end
end
| 22.191176 | 118 | 0.543406 |
088e36fd782deb9f9ab3e7e342dc0082cde37992 | 3,517 | ex | Elixir | deps/plug/lib/plug/session.ex | dmitrinesterenko/sample_phoenix_ecs | d6b94f35680163302e372cf30c70d3e409b0c9b1 | [
"MIT"
] | 1 | 2019-05-07T15:05:52.000Z | 2019-05-07T15:05:52.000Z | lib/plug/session.ex | DavidAlphaFox/Plug | 3a98e7667d76ba8d2eb629e518bcb7ac83a1a188 | [
"Apache-2.0"
] | null | null | null | lib/plug/session.ex | DavidAlphaFox/Plug | 3a98e7667d76ba8d2eb629e518bcb7ac83a1a188 | [
"Apache-2.0"
] | null | null | null | defmodule Plug.Session do
@moduledoc """
A plug to handle session cookies and session stores.
The session is accessed via functions on `Plug.Conn`. Cookies and
session have to be fetched with `Plug.Conn.fetch_session/1` before the
session can be accessed.
Consider using `Plug.CSRFProtection` when using `Plug.Session`.
## Session stores
See `Plug.Session.Store` for the specification session stores are required to
implement.
Plug ships with the following session stores:
* `Plug.Session.ETS`
* `Plug.Session.COOKIE`
## Options
* `:store` - session store module (required);
* `:key` - session cookie key (required);
* `:domain` - see `Plug.Conn.put_resp_cookie/4`;
* `:max_age` - see `Plug.Conn.put_resp_cookie/4`;
* `:path` - see `Plug.Conn.put_resp_cookie/4`;
* `:secure` - see `Plug.Conn.put_resp_cookie/4`;
Additional options can be given to the session store, see the store's
documentation for the options it accepts.
## Examples
plug Plug.Session, store: :ets, key: "_my_app_session", table: :session
"""
alias Plug.Conn
@behaviour Plug
@cookie_opts [:domain, :max_age, :path, :secure]
def init(opts) do
store = Keyword.fetch!(opts, :store) |> convert_store
key = Keyword.fetch!(opts, :key)
cookie_opts = Keyword.take(opts, @cookie_opts)
store_opts = Keyword.drop(opts, [:store, :key] ++ @cookie_opts)
store_config = store.init(store_opts)
%{store: store,
store_config: store_config,
key: key,
cookie_opts: cookie_opts}
end
def call(conn, config) do
Conn.put_private(conn, :plug_session_fetch, fetch_session(config))
end
defp convert_store(store) do
case Atom.to_string(store) do
"Elixir." <> _ -> store
reference -> Module.concat(Plug.Session, String.upcase(reference))
end
end
defp fetch_session(config) do
%{store: store, store_config: store_config, key: key} = config
fn conn ->
{sid, session} =
if cookie = conn.cookies[key] do
store.get(conn, cookie, store_config)
else
{nil, %{}}
end
conn
|> Conn.put_private(:plug_session, session)
|> Conn.put_private(:plug_session_fetch, :done)
|> Conn.register_before_send(before_send(sid, config))
end
end
defp before_send(sid, config) do
fn conn ->
case Map.get(conn.private, :plug_session_info) do
:write ->
value = put_session(sid, conn, config)
put_cookie(value, conn, config)
:drop ->
if sid do
delete_session(sid, conn, config)
delete_cookie(conn, config)
else
conn
end
:renew ->
if sid, do: delete_session(sid, conn, config)
value = put_session(nil, conn, config)
put_cookie(value, conn, config)
:ignore ->
conn
nil ->
conn
end
end
end
defp put_session(sid, conn, %{store: store, store_config: store_config}),
do: store.put(conn, sid, conn.private[:plug_session], store_config)
defp delete_session(sid, conn, %{store: store, store_config: store_config}),
do: store.delete(conn, sid, store_config)
defp put_cookie(value, conn, %{cookie_opts: cookie_opts, key: key}),
do: Conn.put_resp_cookie(conn, key, value, cookie_opts)
defp delete_cookie(conn, %{cookie_opts: cookie_opts, key: key}),
do: Conn.delete_resp_cookie(conn, key, cookie_opts)
end
| 28.827869 | 79 | 0.640034 |
088e3b38f7e21995cb6968a75274183dab109a12 | 3,590 | exs | Elixir | mix.exs | fhunleth/nerves_system_rpi3a | 5fe2d2c1adc8b2697dc32a76dbf1bf43b7af3eb7 | [
"Apache-2.0"
] | null | null | null | mix.exs | fhunleth/nerves_system_rpi3a | 5fe2d2c1adc8b2697dc32a76dbf1bf43b7af3eb7 | [
"Apache-2.0"
] | null | null | null | mix.exs | fhunleth/nerves_system_rpi3a | 5fe2d2c1adc8b2697dc32a76dbf1bf43b7af3eb7 | [
"Apache-2.0"
] | null | null | null | defmodule NervesSystemRpi3a.MixProject do
use Mix.Project
@github_organization "nerves-project"
@app :nerves_system_rpi3a
@source_url "https://github.com/#{@github_organization}/#{@app}"
@version Path.join(__DIR__, "VERSION")
|> File.read!()
|> String.trim()
def project do
[
app: @app,
version: @version,
elixir: "~> 1.6",
compilers: Mix.compilers() ++ [:nerves_package],
nerves_package: nerves_package(),
description: description(),
package: package(),
deps: deps(),
aliases: [loadconfig: [&bootstrap/1]],
docs: docs(),
preferred_cli_env: %{
docs: :docs,
"hex.build": :docs,
"hex.publish": :docs
}
]
end
def application do
[]
end
defp bootstrap(args) do
set_target()
Application.start(:nerves_bootstrap)
Mix.Task.run("loadconfig", args)
end
defp nerves_package do
[
type: :system,
artifact_sites: [
{:github_releases, "#{@github_organization}/#{@app}"}
],
build_runner_opts: build_runner_opts(),
platform: Nerves.System.BR,
platform_config: [
defconfig: "nerves_defconfig"
],
# The :env key is an optional experimental feature for adding environment
# variables to the crosscompile environment. These are intended for
# llvm-based tooling that may need more precise processor information.
env: [
{"TARGET_ARCH", "arm"},
{"TARGET_CPU", "cortex_a53"},
{"TARGET_OS", "linux"},
{"TARGET_ABI", "gnueabihf"},
{"TARGET_GCC_FLAGS",
"-mabi=aapcs-linux -mfpu=neon-vfpv4 -marm -fstack-protector-strong -mfloat-abi=hard -mcpu=cortex-a53 -fPIE -pie -Wl,-z,now -Wl,-z,relro"}
],
checksum: package_files()
]
end
defp deps do
[
{:nerves, "~> 1.5.4 or ~> 1.6.0 or ~> 1.7.15", runtime: false},
{:nerves_system_br, "1.18.6", runtime: false},
{:nerves_toolchain_armv7_nerves_linux_gnueabihf, "~> 1.5.0", runtime: false},
{:nerves_system_linter, "~> 0.4", only: [:dev, :test], runtime: false},
{:ex_doc, "~> 0.22", only: :docs, runtime: false}
]
end
defp description do
"""
Nerves System - Raspberry Pi 3 A+ and Zero 2 W
"""
end
defp docs do
[
extras: ["README.md", "CHANGELOG.md"],
main: "readme",
assets: "assets",
source_ref: "v#{@version}",
source_url: @source_url,
skip_undefined_reference_warnings_on: ["CHANGELOG.md"]
]
end
defp package do
[
files: package_files(),
licenses: ["Apache-2.0"],
links: %{"GitHub" => @source_url}
]
end
defp package_files do
[
"fwup_include",
"rootfs_overlay",
"CHANGELOG.md",
"cmdline.txt",
"config.txt",
"fwup-revert.conf",
"fwup.conf",
"LICENSE",
"linux-5.10.defconfig",
"mix.exs",
"nerves_defconfig",
"post-build.sh",
"post-createfs.sh",
"ramoops.dts",
"README.md",
"VERSION"
]
end
defp build_runner_opts() do
# Download source files first to get download errors right away.
[make_args: primary_site() ++ ["source", "all", "legal-info"]]
end
defp primary_site() do
case System.get_env("BR2_PRIMARY_SITE") do
nil -> []
primary_site -> ["BR2_PRIMARY_SITE=#{primary_site}"]
end
end
defp set_target() do
if function_exported?(Mix, :target, 1) do
apply(Mix, :target, [:target])
else
System.put_env("MIX_TARGET", "target")
end
end
end
| 25.104895 | 146 | 0.58663 |
088e4df75885bfc3d145d709efec0bb3cf445e41 | 82 | exs | Elixir | test/bit_helper_test.exs | poanetwork/blockchain | 408287adeab1b7dbb7d55fd7398dd9320e37b30f | [
"MIT"
] | null | null | null | test/bit_helper_test.exs | poanetwork/blockchain | 408287adeab1b7dbb7d55fd7398dd9320e37b30f | [
"MIT"
] | null | null | null | test/bit_helper_test.exs | poanetwork/blockchain | 408287adeab1b7dbb7d55fd7398dd9320e37b30f | [
"MIT"
] | null | null | null | defmodule BitHelperTest do
use ExUnit.Case, async: true
doctest BitHelper
end | 16.4 | 30 | 0.792683 |
088e572afcd71d58a3095496999bf863fdf50b39 | 1,993 | exs | Elixir | test/mix/tasks/phx.gen.embedded_test.exs | faheempatel/phoenix | a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9 | [
"MIT"
] | 18,092 | 2015-01-01T01:51:04.000Z | 2022-03-31T19:37:14.000Z | test/mix/tasks/phx.gen.embedded_test.exs | faheempatel/phoenix | a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9 | [
"MIT"
] | 3,905 | 2015-01-01T00:22:47.000Z | 2022-03-31T17:06:21.000Z | test/mix/tasks/phx.gen.embedded_test.exs | faheempatel/phoenix | a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9 | [
"MIT"
] | 3,205 | 2015-01-03T10:58:22.000Z | 2022-03-30T14:55:57.000Z | Code.require_file "../../../installer/test/mix_helper.exs", __DIR__
defmodule Mix.Tasks.Phx.Gen.EmbeddedTest do
use ExUnit.Case
import MixHelper
alias Mix.Tasks.Phx.Gen
alias Mix.Phoenix.Schema
setup do
Mix.Task.clear()
:ok
end
test "build" do
in_tmp_project "embedded build", fn ->
schema = Gen.Embedded.build(~w(Blog.Post title:string))
assert %Schema{
alias: Post,
module: Phoenix.Blog.Post,
repo: Phoenix.Repo,
migration?: false,
migration_defaults: %{title: ""},
plural: nil,
singular: "post",
human_plural: "Nil",
human_singular: "Post",
attrs: [title: :string],
types: %{title: :string},
embedded?: true,
defaults: %{title: ""},
} = schema
assert String.ends_with?(schema.file, "lib/phoenix/blog/post.ex")
end
end
test "generates embedded schema", config do
in_tmp_project config.test, fn ->
Gen.Embedded.run(~w(Blog.Post title:string))
assert_file "lib/phoenix/blog/post.ex", fn file ->
assert file =~ "embedded_schema do"
end
end
end
test "generates nested embedded schema", config do
in_tmp_project config.test, fn ->
Gen.Embedded.run(~w(Blog.Admin.User name:string))
assert_file "lib/phoenix/blog/admin/user.ex", fn file ->
assert file =~ "defmodule Phoenix.Blog.Admin.User do"
assert file =~ "embedded_schema do"
end
end
end
test "generates embedded schema with proper datetime types", config do
in_tmp_project config.test, fn ->
Gen.Embedded.run(~w(Blog.Comment title:string drafted_at:datetime published_at:naive_datetime edited_at:utc_datetime))
assert_file "lib/phoenix/blog/comment.ex", fn file ->
assert file =~ "field :drafted_at, :naive_datetime"
assert file =~ "field :published_at, :naive_datetime"
assert file =~ "field :edited_at, :utc_datetime"
end
end
end
end
| 28.884058 | 124 | 0.639237 |
088e5b5b96edae8386ca761ab919c72aff4be72c | 1,291 | ex | Elixir | installer/templates/phx_web/views/error_helpers.ex | blunckr/fenix | aeccae9658ed3d85d8af8f28ce2584d407b43d6b | [
"MIT"
] | null | null | null | installer/templates/phx_web/views/error_helpers.ex | blunckr/fenix | aeccae9658ed3d85d8af8f28ce2584d407b43d6b | [
"MIT"
] | null | null | null | installer/templates/phx_web/views/error_helpers.ex | blunckr/fenix | aeccae9658ed3d85d8af8f28ce2584d407b43d6b | [
"MIT"
] | 1 | 2020-02-08T16:23:00.000Z | 2020-02-08T16:23:00.000Z | defmodule <%= web_namespace %>.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
<%= if html do %>
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
if error = form.errors[field] do
content_tag :span, translate_error(error), class: "help-block"
end
end
<% end %>
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# Because error messages were defined within Ecto, we must
# call the Gettext module passing our Gettext backend. We
# also use the "errors" domain as translations are placed
# in the errors.po file.
# Ecto will pass the :count keyword if the error message is
# meant to be pluralized.
# On your own code and templates, depending on whether you
# need the message to be pluralized or not, this could be
# written simply as:
#
# dngettext "errors", "1 file", "%{count} files", count
# dgettext "errors", "is invalid"
#
if count = opts[:count] do
Gettext.dngettext(<%= web_namespace %>.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(<%= web_namespace %>.Gettext, "errors", msg, opts)
end
end
end
| 31.487805 | 86 | 0.656081 |
088e68b0cc78031ecccd8e88b977feee4d0e11d1 | 4,426 | ex | Elixir | lib/asciinema_web/router.ex | AnotherKamila/asciinema-server | cafdba3c0461eb77ca0d1b66de07aa943b91f700 | [
"Apache-2.0"
] | null | null | null | lib/asciinema_web/router.ex | AnotherKamila/asciinema-server | cafdba3c0461eb77ca0d1b66de07aa943b91f700 | [
"Apache-2.0"
] | null | null | null | lib/asciinema_web/router.ex | AnotherKamila/asciinema-server | cafdba3c0461eb77ca0d1b66de07aa943b91f700 | [
"Apache-2.0"
] | null | null | null | defmodule AsciinemaWeb.Router do
use AsciinemaWeb, :router
use Plug.ErrorHandler
defp handle_errors(_conn, %{reason: %Ecto.NoResultsError{}}), do: nil
defp handle_errors(_conn, %{reason: %Phoenix.NotAcceptableError{}}), do: nil
use Sentry.Plug
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
plug AsciinemaWeb.Auth
end
pipeline :asciicast do
plug :accepts, ["html", "js", "json", "cast", "svg", "png", "gif"]
plug :format_specific_plugs
plug :put_secure_browser_headers
end
defp format_specific_plugs(conn, []) do
format_specific_plugs(conn, Phoenix.Controller.get_format(conn))
end
defp format_specific_plugs(conn, "html") do
conn
|> fetch_session([])
|> fetch_flash([])
|> protect_from_forgery([])
|> AsciinemaWeb.Auth.call([])
end
defp format_specific_plugs(conn, _other), do: conn
pipeline :oembed do
plug :accepts, ["json", "xml"]
plug :put_secure_browser_headers
end
scope "/", AsciinemaWeb do
pipe_through :asciicast
resources "/a", AsciicastController, only: [:show, :edit, :update, :delete]
end
scope "/", AsciinemaWeb do
pipe_through :oembed
get "/oembed", OembedController, :show
end
scope "/", AsciinemaWeb do
pipe_through :browser # Use the default browser stack
get "/", HomeController, :show
get "/explore", AsciicastController, :index
get "/explore/:category", AsciicastController, :category
get "/a/:id/iframe", AsciicastController, :iframe
get "/a/:id/embed", AsciicastController, :embed
get "/a/:id/example", AsciicastController, :example
get "/docs", DocController, :index
get "/docs/:topic", DocController, :show
resources "/login", LoginController, only: [:new, :create], singleton: true
get "/login/sent", LoginController, :sent, as: :login
resources "/user", UserController, as: :user, only: [:edit, :update], singleton: true
resources "/users", UserController, as: :users, only: [:new, :create]
get "/u/:id", UserController, :show
get "/~:username", UserController, :show
resources "/username", UsernameController, only: [:new, :create], singleton: true
get "/username/skip", UsernameController, :skip, as: :username
resources "/session", SessionController, only: [:new, :create, :delete], singleton: true
get "/connect/:api_token", ApiTokenController, :show, as: :connect
resources "/api_tokens", ApiTokenController, only: [:delete]
get "/about", PageController, :about
get "/privacy", PageController, :privacy
get "/tos", PageController, :tos
get "/contact", PageController, :contact
get "/contributing", PageController, :contributing
end
scope "/api", AsciinemaWeb.Api, as: :api do
post "/asciicasts", AsciicastController, :create
end
# Other scopes may use custom stacks.
# scope "/api", Asciinema do
# pipe_through :api
# end
end
defmodule AsciinemaWeb.Router.Helpers.Extra do
alias AsciinemaWeb.Router.Helpers, as: H
alias AsciinemaWeb.Endpoint
def profile_path(_conn, user) do
profile_path(user)
end
def profile_path(%Plug.Conn{} = conn) do
profile_path(conn.assigns.current_user)
end
def profile_path(%{id: id, username: username}) do
if username do
"/~#{username}"
else
"/u/#{id}"
end
end
def profile_url(user) do
Endpoint.url() <> profile_path(user)
end
def asciicast_file_path(conn, asciicast) do
H.asciicast_path(conn, :show, asciicast) <> "." <> ext(asciicast)
end
def asciicast_file_url(asciicast) do
asciicast_file_url(AsciinemaWeb.Endpoint, asciicast)
end
def asciicast_file_url(conn, asciicast) do
H.asciicast_url(conn, :show, asciicast) <> "." <> ext(asciicast)
end
defp ext(asciicast) do
case asciicast.version do
0 -> "json"
1 -> "json"
_ -> "cast"
end
end
def asciicast_image_path(conn, asciicast) do
H.asciicast_path(conn, :show, asciicast) <> ".png"
end
def asciicast_image_url(conn, asciicast) do
H.asciicast_url(conn, :show, asciicast) <> ".png"
end
def asciicast_animation_path(conn, asciicast) do
H.asciicast_path(conn, :show, asciicast) <> ".gif"
end
def asciicast_script_url(conn, asciicast) do
H.asciicast_url(conn, :show, asciicast) <> ".js"
end
end
| 27.153374 | 92 | 0.67962 |
088e9c019d4e19e076853a01e32308bc12b57d65 | 607 | ex | Elixir | lib/mix/tasks/vnu.validate.css.ex | angelikatyborska/vnu-elixir | c12676e41b7fba3b8acf98812f0e3a054c298458 | [
"MIT"
] | 51 | 2020-04-11T22:30:43.000Z | 2022-01-14T13:24:56.000Z | lib/mix/tasks/vnu.validate.css.ex | angelikatyborska/vnu-elixir | c12676e41b7fba3b8acf98812f0e3a054c298458 | [
"MIT"
] | 20 | 2020-04-13T12:20:49.000Z | 2022-03-29T18:32:41.000Z | lib/mix/tasks/vnu.validate.css.ex | angelikatyborska/vnu-elixir | c12676e41b7fba3b8acf98812f0e3a054c298458 | [
"MIT"
] | null | null | null | defmodule Mix.Tasks.Vnu.Validate.Css do
use Mix.Task
alias Vnu.CLI
@shortdoc "Validates CSS files"
@moduledoc """
Validates CSS files.
It expects a file or a list of files as an argument.
```bash
mix vnu.validate.css [OPTIONS] FILE [FILE2 FILE3...]
```
See `mix vnu.validate.html` for the list of options and other details.
Examples
```bash
mix vnu.validate.css screen.css print.css
mix vnu.validate.css --server-url localhost:8888 priv/static/**/*.css
```
"""
@doc false
@spec run(list()) :: no_return()
def run(argv) do
CLI.validate(argv, :css)
end
end
| 20.233333 | 72 | 0.665568 |
088ec95f16fd6379c0c00082e89e7f9b0a6d636a | 564 | exs | Elixir | unsilo/test/unsilo/accounts/accounts_test.exs | TehSnappy/unsilo_elixir | d0dd592dee71ed5b994ac08cd347aa357d5845f4 | [
"MIT"
] | 1 | 2019-03-21T02:43:06.000Z | 2019-03-21T02:43:06.000Z | unsilo/test/unsilo/accounts/accounts_test.exs | TehSnappy/unsilo_elixir | d0dd592dee71ed5b994ac08cd347aa357d5845f4 | [
"MIT"
] | 3 | 2021-03-09T01:43:16.000Z | 2022-02-10T17:04:55.000Z | unsilo/test/unsilo/accounts/accounts_test.exs | TehSnappy/unsilo_elixir | d0dd592dee71ed5b994ac08cd347aa357d5845f4 | [
"MIT"
] | null | null | null | defmodule Unsilo.AccountsTest do
use Unsilo.DataCase
alias Unsilo.Accounts
describe "users" do
alias Unsilo.Accounts.User
@valid_attrs %{password: "some encrypted_password", email: "some email"}
def user_fixture(attrs \\ %{}) do
{:ok, user} =
attrs
|> Enum.into(@valid_attrs)
|> Accounts.create_user()
user
end
test "create_user/1 with valid data creates a user" do
assert {:ok, %User{} = user} = Accounts.create_user(@valid_attrs)
assert user.email == "some email"
end
end
end
| 21.692308 | 76 | 0.634752 |
088ee7c848443c17d854d3b1a6a2a6daa6ed8308 | 16,124 | exs | Elixir | test/teslamate/vehicles/vehicle/driving_test.exs | AlwindB/teslamate | 59295ce8cf5c737ff26be4ea999206eb131ba38a | [
"MIT"
] | null | null | null | test/teslamate/vehicles/vehicle/driving_test.exs | AlwindB/teslamate | 59295ce8cf5c737ff26be4ea999206eb131ba38a | [
"MIT"
] | null | null | null | test/teslamate/vehicles/vehicle/driving_test.exs | AlwindB/teslamate | 59295ce8cf5c737ff26be4ea999206eb131ba38a | [
"MIT"
] | 1 | 2019-10-24T13:17:57.000Z | 2019-10-24T13:17:57.000Z | defmodule TeslaMate.Vehicles.Vehicle.DrivingTest do
use TeslaMate.VehicleCase, async: true
alias TeslaMate.Log.{Drive, Car}
test "logs a full drive", %{test: name} do
now = DateTime.utc_now()
now_ts = DateTime.to_unix(now, :millisecond)
events = [
{:ok, online_event()},
{:ok, drive_event(now_ts + 1, "D", 60)},
{:ok, drive_event(now_ts + 2, "N", 30)},
{:ok, drive_event(now_ts + 3, "R", -5)},
{:ok, online_event(drive_state: %{timestamp: now_ts + 4, latitude: 0.2, longitude: 0.2})}
]
:ok = start_vehicle(name, events)
start_date = DateTime.from_unix!(now_ts + 1, :millisecond)
assert_receive {:start_state, car, :online, date: ^start_date}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online, since: s0}}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving, since: s1}}}
assert DateTime.diff(s0, s1, :nanosecond) < 0
assert_receive {:start_drive, ^car}
assert_receive {:insert_position, drive, %{longitude: 0.1, speed: 97}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving, since: ^s1}}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: 48}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving, since: ^s1}}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: -8}}
assert_receive {:close_drive, ^drive, lookup_address: true}
start_date = DateTime.from_unix!(now_ts + 4, :millisecond)
assert_receive {:start_state, ^car, :online, date: ^start_date}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online, since: s2}}}
assert DateTime.diff(s1, s2, :nanosecond) < 0
refute_receive _
end
@tag :capture_log
test "handles a connection loss when driving", %{test: name} do
now = DateTime.utc_now()
now_ts = DateTime.to_unix(now, :millisecond)
events = [
{:ok, online_event()},
{:ok, online_event(drive_state: %{timestamp: now_ts, latitude: 0.0, longitude: 0.0})},
{:ok, drive_event(now_ts + 1, "D", 50)},
{:error, :vehicle_unavailable},
{:ok, %TeslaApi.Vehicle{state: "offline"}},
{:error, :vehicle_unavailable},
{:ok, %TeslaApi.Vehicle{state: "unknown"}},
{:ok, drive_event(now_ts + 2, "D", 55)},
{:ok, drive_event(now_ts + 3, "D", 40)},
{:ok, online_event(drive_state: %{timestamp: now_ts + 4, latitude: 0.2, longitude: 0.2})}
]
:ok = start_vehicle(name, events)
start_date = DateTime.from_unix!(now_ts, :millisecond)
assert_receive {:start_state, car, :online, date: ^start_date}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:start_drive, ^car}
assert_receive {:insert_position, drive, %{longitude: 0.1, speed: 80}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: 89}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: 64}}
assert_receive {:close_drive, ^drive, lookup_address: true}
start_date = DateTime.from_unix!(now_ts + 4, :millisecond)
assert_receive {:start_state, ^car, :online, date: ^start_date}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
refute_receive _
end
test "transitions directly into driving state", %{test: name} do
now = DateTime.utc_now()
now_ts = DateTime.to_unix(now, :millisecond)
events = [
{:ok, online_event()},
{:ok, drive_event(now_ts, "N", 0)}
]
:ok = start_vehicle(name, events)
start_date = DateTime.from_unix!(now_ts, :millisecond)
assert_receive {:start_state, car, :online, date: ^start_date}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:start_drive, ^car}
assert_receive {:insert_position, drive, %{longitude: 0.1, speed: 0}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: 0}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: 0}}
# ...
refute_received _
end
test "shift state P does not trigger driving state", %{test: name} do
now = DateTime.utc_now()
now_ts = DateTime.to_unix(now, :millisecond)
events = [
{:ok, online_event()},
{:ok, drive_event(now_ts, "P", 0)}
]
:ok = start_vehicle(name, events)
date = DateTime.from_unix!(now_ts, :millisecond)
assert_receive {:start_state, car, :online, date: ^date}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
refute_receive _
end
test "shift_state P ends the drive", %{test: name} do
now = DateTime.utc_now()
now_ts = DateTime.to_unix(now, :millisecond)
events = [
{:ok, online_event()},
{:ok, drive_event(now_ts, "D", 5)},
{:ok, drive_event(now_ts + 1, "D", 15)},
{:ok, drive_event(now_ts + 2, "P", 0)}
]
:ok = start_vehicle(name, events)
start_date = DateTime.from_unix!(now_ts, :millisecond)
assert_receive {:start_state, car, :online, date: ^start_date}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:start_drive, ^car}
assert_receive {:insert_position, %Drive{id: 111} = drive, %{longitude: 0.1, speed: 8}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: 24}}
assert_receive {:close_drive, ^drive, lookup_address: true}
start_date = DateTime.from_unix!(now_ts + 2, :millisecond)
assert_receive {:start_state, ^car, :online, date: ^start_date}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
refute_receive _
end
describe "when offline" do
defp drive_event(ts, pos, speed, lvl, range, added) do
{:ok,
online_event(
drive_state: %{
timestamp: ts,
latitude: pos,
longitude: pos,
shift_state: "D",
speed: speed
},
charge_state: %{
battery_level: lvl,
ideal_battery_range: range,
timestamp: ts,
charge_energy_added: added
}
)}
end
@tag :capture_log
test "interprets a significant offline period while driving with SOC gains as charge session",
%{test: name} do
now = DateTime.utc_now()
now_ts = DateTime.to_unix(now, :millisecond)
events =
[
{:ok, online_event()},
drive_event(now_ts, 0.1, 30, 20, 200, 0),
drive_event(now_ts + 1, 0.1, 30, 20, 200, 0)
] ++
List.duplicate({:ok, %TeslaApi.Vehicle{state: "offline"}}, 20) ++
[
drive_event(now_ts + :timer.minutes(5), 0.2, 20, 80, 300, 45),
{:ok, online_event(drive_state: %{timestamp: now_ts + :timer.minutes(5) + 1})}
]
:ok = start_vehicle(name, events)
date = DateTime.from_unix!(now_ts, :millisecond)
assert_receive {:start_state, car, :online, date: ^date}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:start_drive, ^car}
assert_receive {:insert_position, drive, %{longitude: 0.1, speed: 48}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: 48}}
refute_receive _, 50
# Logs previous drive because of timeout
assert_receive {:close_drive, ^drive, lookup_address: true}, 300
# Logs a charge session based on the available data
start_date =
now
|> DateTime.add(1, :millisecond)
|> DateTime.truncate(:millisecond)
end_date =
now
|> DateTime.add(5 * 60, :second)
|> DateTime.truncate(:millisecond)
assert_receive {:start_charging_process, ^car, %{latitude: 0.1, longitude: 0.1},
lookup_address: true}
assert_receive {:insert_charge, charging_id,
%{date: ^start_date, charge_energy_added: 0, charger_power: 0}}
assert_receive {:insert_charge, ^charging_id,
%{date: ^end_date, charge_energy_added: 45, charger_power: 0}}
assert_receive {:complete_charging_process, ^charging_id}
d1 = DateTime.from_unix!(now_ts + :timer.minutes(5), :millisecond)
assert_receive {:start_state, ^car, :online, date: ^d1}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert_receive {:start_drive, ^car}
assert_receive {:insert_position, drive, %{longitude: 0.2, speed: 32}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:close_drive, ^drive, lookup_address: true}
d2 = DateTime.from_unix!(now_ts + :timer.minutes(5) + 1, :millisecond)
assert_receive {:start_state, ^car, :online, date: ^d2}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
refute_receive _
end
@tag :capture_log
test "times out a drive when being offline for to long",
%{test: name} do
now_ts = DateTime.utc_now() |> DateTime.to_unix(:millisecond)
events = [
{:ok, online_event()},
drive_event(now_ts, 0.1, 30, 20, 200, nil),
drive_event(now_ts, 0.1, 30, 20, 200, nil),
{:ok, %TeslaApi.Vehicle{state: "offline"}}
]
:ok = start_vehicle(name, events)
date = DateTime.from_unix!(now_ts, :millisecond)
assert_receive {:start_state, car, :online, date: ^date}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:start_drive, ^car}
assert_receive {:insert_position, drive, %{longitude: 0.1, speed: 48}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: 48}}
# Timeout
assert_receive {:close_drive, ^drive, lookup_address: true}, 1200
refute_receive _
end
test "times out a drive when rececing sleep event", %{test: name} do
now_ts = DateTime.utc_now() |> DateTime.to_unix(:millisecond)
events = [
{:ok, online_event()},
drive_event(now_ts, 0.1, 30, 20, 200, nil),
drive_event(now_ts + 1, 0.1, 30, 20, 200, nil),
{:ok, %TeslaApi.Vehicle{state: "asleep"}}
]
:ok = start_vehicle(name, events)
date = DateTime.from_unix!(now_ts, :millisecond)
assert_receive {:start_state, car, :online, date: ^date}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:start_drive, ^car}
assert_receive {:insert_position, drive, %{longitude: 0.1, speed: 48}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: 48}}
# Timeout
assert_receive {:close_drive, ^drive, lookup_address: true}, 1200
assert_receive {:start_state, car, :asleep, []}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :asleep}}}
refute_receive _
end
@tag :capture_log
test "logs a drive after a significant offline period while driving",
%{test: name} do
now = DateTime.utc_now()
now_ts = DateTime.to_unix(now, :millisecond)
events =
[
{:ok, online_event()},
drive_event(now_ts, 0.1, 30, 20, 200, nil),
drive_event(now_ts + 1, 0.1, 30, 20, 200, nil)
] ++
List.duplicate({:ok, %TeslaApi.Vehicle{state: "offline"}}, 20) ++
[
drive_event(now_ts + :timer.minutes(15), 0.2, 20, 19, 190, nil),
{:ok, online_event(drive_state: %{timestamp: now_ts + :timer.minutes(15) + 1})}
]
:ok = start_vehicle(name, events)
d0 = DateTime.from_unix!(now_ts, :millisecond)
assert_receive {:start_state, car, :online, date: ^d0}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:start_drive, ^car}
assert_receive {:insert_position, drive, %{longitude: 0.1, speed: 48}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: 48}}
refute_receive _, 100
# Logs previous drive
assert_receive {:close_drive, ^drive, lookup_address: true}, 250
d1 = DateTime.from_unix!(now_ts + :timer.minutes(15), :millisecond)
assert_receive {:start_state, ^car, :online, date: ^d1}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert_receive {:start_drive, ^car}
assert_receive {:insert_position, drive, %{longitude: 0.2, speed: 32}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:close_drive, ^drive, lookup_address: true}
d2 = DateTime.from_unix!(now_ts + :timer.minutes(15) + 1, :millisecond)
assert_receive {:start_state, ^car, :online, date: ^d2}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
refute_receive _
end
@tag :capture_log
test "continues a drive after a short offline period while driving",
%{test: name} do
now = DateTime.utc_now()
now_ts = DateTime.to_unix(now, :millisecond)
events =
[
{:ok, online_event()},
drive_event(now_ts, 0.1, 30, 20, 200, nil),
drive_event(now_ts + 1, 0.1, 30, 20, 200, nil)
] ++
List.duplicate({:ok, %TeslaApi.Vehicle{state: "offline"}}, 16) ++
[
drive_event(now_ts + :timer.minutes(4), 0.2, 20, 19, 190, nil),
{:ok, online_event(drive_state: %{timestamp: now_ts + :timer.minutes(4) + 1})}
]
:ok = start_vehicle(name, events)
d0 = DateTime.from_unix!(now_ts, :millisecond)
assert_receive {:start_state, car, :online, date: ^d0}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:start_drive, ^car}
assert_receive {:insert_position, drive, %{longitude: 0.1, speed: 48}}
assert_receive {:insert_position, ^drive, %{longitude: 0.1, speed: 48}}
refute_receive _, 50
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :driving}}}
assert_receive {:insert_position, drive, %{longitude: 0.2, speed: 32}}
assert_receive {:close_drive, ^drive, lookup_address: true}
d1 = DateTime.from_unix!(now_ts + :timer.minutes(4) + 1, :millisecond)
assert_receive {:start_state, ^car, :online, date: ^d1}
assert_receive {:insert_position, ^car, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
refute_receive _
end
end
end
| 38.390476 | 98 | 0.625961 |
088f08e11ff84cb2cc4b5976898fd269aa5c0119 | 713 | exs | Elixir | spec/parallel_spec.exs | antonmi/flowex | 7597e2ae1bf53033679ba65e0be13a50ad6f1e5e | [
"Apache-2.0"
] | 422 | 2017-01-20T13:38:13.000Z | 2022-02-08T14:07:11.000Z | spec/parallel_spec.exs | antonmi/flowex | 7597e2ae1bf53033679ba65e0be13a50ad6f1e5e | [
"Apache-2.0"
] | 11 | 2017-01-26T15:40:36.000Z | 2020-07-02T21:02:18.000Z | spec/parallel_spec.exs | antonmi/flowex | 7597e2ae1bf53033679ba65e0be13a50ad6f1e5e | [
"Apache-2.0"
] | 20 | 2017-01-25T07:56:00.000Z | 2021-11-29T16:19:34.000Z | defmodule PerallelSpec do
use ESpec, async: true
let :pipeline, do: ParallelPipeline.start
def result(p) do
ParallelPipeline.call(p, %ParallelPipeline{n: 1})
end
it "takes ~0.5 sec for 1 call" do
func = fn -> result(pipeline()) end
time = :timer.tc(func) |> elem(0)
expect(time) |> to(be :>, 500_000)
end
context "4 parallel calls" do
def func do
p = pipeline()
fn ->
(1..4)
|> Enum.map(fn(_i) -> Task.async(fn -> result(p) end) end)
|> Enum.map(&Task.await/1)
end
end
it "takes ~0.5 sec for 4 parallel calls" do
time = :timer.tc(func()) |> elem(0)
time |> should(be_between(500_000, 600_000))
end
end
end
| 22.28125 | 66 | 0.580645 |
088f376dc9b863c8ebefb1ec1febcf0bd24e6e67 | 201 | ex | Elixir | lib/sanbase_web/admin/comments/notification.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | 81 | 2017-11-20T01:20:22.000Z | 2022-03-05T12:04:25.000Z | lib/sanbase_web/admin/comments/notification.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 359 | 2017-10-15T14:40:53.000Z | 2022-01-25T13:34:20.000Z | lib/sanbase_web/admin/comments/notification.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | 16 | 2017-11-19T13:57:40.000Z | 2022-02-07T08:13:02.000Z | defmodule SanbaseWeb.ExAdmin.Comments.Notification do
use ExAdmin.Register
register_resource Sanbase.Comments.Notification do
show notif do
attributes_table(all: true)
end
end
end
| 20.1 | 53 | 0.771144 |
088f7c54aacfa48188fc07f4789c90fe4af75ee4 | 1,186 | exs | Elixir | apps/gobstopper_service/config/test.exs | ZURASTA/gobstopper | f8d231c4459af6fa44273c3ef80857348410c70b | [
"BSD-2-Clause"
] | null | null | null | apps/gobstopper_service/config/test.exs | ZURASTA/gobstopper | f8d231c4459af6fa44273c3ef80857348410c70b | [
"BSD-2-Clause"
] | 12 | 2017-07-24T12:29:51.000Z | 2018-04-05T03:58:10.000Z | apps/gobstopper_service/config/test.exs | ZURASTA/gobstopper | f8d231c4459af6fa44273c3ef80857348410c70b | [
"BSD-2-Clause"
] | 4 | 2017-07-24T12:19:23.000Z | 2019-02-19T06:34:46.000Z | use Mix.Config
# Print only warnings and errors during test
config :logger, level: :warn
# Configure database
config :gobstopper_service, Gobstopper.Service.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
database: "gobstopper_service_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
config :gobstopper_service, Gobstopper.Service.Token,
allowed_algos: ["HS512"],
token_verify_module: Guardian.Token.Jwt.Verify,
issuer: "Gobstopper.Service",
ttl: { 30, :days },
allowed_drift: 2000,
verify_issuer: true,
secret_key: "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.e30.6bK5p0FPG1KY68mstRXiUjWtti5EbPmDg0QxP702j3WTEcI16GXZAU0NlXMQFnyPsrDyqCv9p6KRqMg7LcswMg"
config :sherbet_service,
ecto_repos: [Sherbet.Service.Repo]
config :sherbet_service, Sherbet.Service.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
database: "sherbet_service_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
config :cake_service, Cake.Service.Mailer.Dispatch,
adapter: Swoosh.Adapters.Logger,
log_full_email: true,
level: :debug
| 30.410256 | 145 | 0.747049 |
088f818fd8f1cd1172dada18e34922e2acf47e70 | 324 | ex | Elixir | lib/day02/part01.ex | eldemonstro/AdventOfCode2019Elixir | a047a5085a906b7d78ce4f3c8a26904415616f2c | [
"MIT"
] | null | null | null | lib/day02/part01.ex | eldemonstro/AdventOfCode2019Elixir | a047a5085a906b7d78ce4f3c8a26904415616f2c | [
"MIT"
] | null | null | null | lib/day02/part01.ex | eldemonstro/AdventOfCode2019Elixir | a047a5085a906b7d78ce4f3c8a26904415616f2c | [
"MIT"
] | null | null | null | Code.require_file "../intcode.ex", __DIR__
{ :ok, contents } = File.read("#{__DIR__}/input.txt")
intcode = contents
|>IntCode.parse_program()
|>Map.put(1, 12)
|>Map.put(2, 2)
{:ok, first_op} = Map.fetch(intcode, 0)
{value, _, _, _} = IntCode.execute(intcode, first_op, 0)
IO.puts value[0]
| 21.6 | 56 | 0.595679 |
088fad6a72fc0c404b79199b515f2b4f544694e9 | 1,058 | ex | Elixir | lib/student_list/directory/formatter.ex | jwarwick/student_list | d35a2fcef2025d3de9b7915682965c48481c1d15 | [
"MIT"
] | 1 | 2021-06-27T20:02:11.000Z | 2021-06-27T20:02:11.000Z | lib/student_list/directory/formatter.ex | jwarwick/student_list | d35a2fcef2025d3de9b7915682965c48481c1d15 | [
"MIT"
] | null | null | null | lib/student_list/directory/formatter.ex | jwarwick/student_list | d35a2fcef2025d3de9b7915682965c48481c1d15 | [
"MIT"
] | null | null | null | defmodule StudentList.Directory.Formatter do
@moduledoc """
Output the directory in an RTF format
"""
require EEx
alias StudentList.Directory
EEx.function_from_file(:def, :directory,
Path.expand("templates/directory.rtf.eex", :code.priv_dir(:student_list)),
[:assigns])
EEx.function_from_file(:def, :class,
Path.expand("templates/class.rtf.eex", :code.priv_dir(:student_list)),
[:assigns])
EEx.function_from_file(:def, :student,
Path.expand("templates/student.rtf.eex", :code.priv_dir(:student_list)),
[:assigns])
@doc """
Generate the RTF string
"""
def create do
directory(classes: Directory.get_listing())
end
@doc """
Generate RTF file
"""
def write do
tmp_file = "directory.rtf"
tmp_dir = System.tmp_dir!
tmp_path = Path.join(tmp_dir, tmp_file)
result = create()
:ok = File.write(Path.expand(tmp_path), result)
{:ok, tmp_path}
end
end
| 27.842105 | 99 | 0.597353 |
088fc28dadfe73968171158cf3fba32e2d785fa5 | 595 | ex | Elixir | lib/contracts_api_web/views/changeset_view.ex | gissandrogama/contracts_api | 13bcd292637d0e2bc4d2a6c05f5b3266e8bf28e1 | [
"MIT"
] | null | null | null | lib/contracts_api_web/views/changeset_view.ex | gissandrogama/contracts_api | 13bcd292637d0e2bc4d2a6c05f5b3266e8bf28e1 | [
"MIT"
] | 2 | 2021-03-16T06:43:04.000Z | 2021-03-16T06:54:55.000Z | lib/contracts_api_web/views/changeset_view.ex | gissandrogama/contracts_api | 13bcd292637d0e2bc4d2a6c05f5b3266e8bf28e1 | [
"MIT"
] | null | null | null | defmodule ContractsApiWeb.ChangesetView do
use ContractsApiWeb, :view
@doc """
Está função percorre e traduz os erros do changeset.
Veja `Ecto.Changeset.traverse_errors/2` e
`EventsApiWeb.ErrorHelpers.translate_error/1` para mais detalhes.
"""
def translate_errors(changeset) do
Ecto.Changeset.traverse_errors(changeset, &translate_error/1)
end
def render("error.json", %{changeset: changeset}) do
# Quando codificado, o changeset retorna seus erros
# como um objeto JSON. Então, nós apenas passamos adiante.
%{errors: translate_errors(changeset)}
end
end
| 29.75 | 67 | 0.747899 |
088fcb634187d2c30dead715abf335aae9558acd | 738 | ex | Elixir | lib/ja_spex/plug.ex | ReelCoaches/ja_spex | 9ad3bdb8525f7eee005724305fb579d9d7a1bb8a | [
"Apache-2.0"
] | 1 | 2021-05-10T22:38:00.000Z | 2021-05-10T22:38:00.000Z | lib/ja_spex/plug.ex | ReelCoaches/ja_spex | 9ad3bdb8525f7eee005724305fb579d9d7a1bb8a | [
"Apache-2.0"
] | null | null | null | lib/ja_spex/plug.ex | ReelCoaches/ja_spex | 9ad3bdb8525f7eee005724305fb579d9d7a1bb8a | [
"Apache-2.0"
] | null | null | null | defmodule JaSpex.Plug do
@moduledoc """
A Plug to validate and deserialize OpenAPI requests in JSON-API format.
"""
alias OpenApiSpex.Plug.CastAndValidate
alias JaSpex.{Deserializer, RenderError}
@behaviour Plug
@spec init(Plug.opts()) :: Plug.opts()
def init(opts) do
render_error = Keyword.get(opts, :render_error, RenderError)
validator_opts = CastAndValidate.init(render_error: render_error)
deserializer_opts = Deserializer.init(opts)
[validator: validator_opts, deserializer: deserializer_opts]
end
@spec call(Plug.Conn.t(), Plug.opts()) :: Plug.Conn.t()
def call(conn, opts) do
conn
|> CastAndValidate.call(opts[:validator])
|> Deserializer.call(opts[:deserializer])
end
end
| 28.384615 | 73 | 0.719512 |
088fd476d9dcb173aa20361e6ea81bc688749101 | 598 | exs | Elixir | apps/definition_load_broadcast/mix.exs | kennyatpillar/hindsight | e90e2150a14218e5d6fdf5874f57eb055fd2dd07 | [
"Apache-2.0"
] | null | null | null | apps/definition_load_broadcast/mix.exs | kennyatpillar/hindsight | e90e2150a14218e5d6fdf5874f57eb055fd2dd07 | [
"Apache-2.0"
] | null | null | null | apps/definition_load_broadcast/mix.exs | kennyatpillar/hindsight | e90e2150a14218e5d6fdf5874f57eb055fd2dd07 | [
"Apache-2.0"
] | null | null | null | defmodule DefinitionLoadBroadcast.MixProject do
use Mix.Project
def project do
[
app: :definition_load_broadcast,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.9",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
def application do
[
extra_applications: [:logger]
]
end
defp deps do
[
{:definition, in_umbrella: true},
{:checkov, "~> 1.0", only: [:dev, :test]}
]
end
end
| 19.290323 | 47 | 0.543478 |
088fd4c2e2561d94065188546f67e58737401a43 | 916 | ex | Elixir | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/metadata.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/metadata.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/metadata.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 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.ServiceConsumerManagement.V1 do
@moduledoc """
API client metadata for GoogleApi.ServiceConsumerManagement.V1.
"""
@discovery_revision "20210217"
def discovery_revision(), do: @discovery_revision
end
| 33.925926 | 74 | 0.767467 |
088fd758cd63ce865dd40c83d0ea6b1d732e0de6 | 1,749 | ex | Elixir | test/support/data_case.ex | szajbus/elasticsearch-elixir | 4ce751b4b5379ccc168a8930bca9c3ad99ffbc55 | [
"MIT"
] | 215 | 2019-01-28T23:31:14.000Z | 2022-03-31T16:03:30.000Z | test/support/data_case.ex | szajbus/elasticsearch-elixir | 4ce751b4b5379ccc168a8930bca9c3ad99ffbc55 | [
"MIT"
] | 56 | 2018-01-02T17:52:54.000Z | 2019-01-19T16:05:47.000Z | test/support/data_case.ex | szajbus/elasticsearch-elixir | 4ce751b4b5379ccc168a8930bca9c3ad99ffbc55 | [
"MIT"
] | 39 | 2019-03-12T20:35:03.000Z | 2022-03-11T16:49:45.000Z | defmodule Elasticsearch.DataCase do
@moduledoc false
# This module defines the setup for tests requiring
# access to the application's data layer.
#
# You may define functions here to be used as helpers in
# your tests.
#
# Finally, if the test case interacts with the database,
# it cannot be async. For this reason, every test runs
# inside a transaction which is reset at the beginning
# of the test unless the test case is marked as async.
use ExUnit.CaseTemplate
import Ecto.Query
using do
quote do
alias Elasticsearch.Test.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Elasticsearch.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Elasticsearch.Test.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Elasticsearch.Test.Repo, {:shared, self()})
end
Logger.configure(level: :warn)
:ok
end
def populate_posts_table(quantity \\ 10_000) do
posts =
[%{title: "Example Post", author: "John Smith"}]
|> Stream.cycle()
|> Enum.take(quantity)
Elasticsearch.Test.Repo.insert_all("posts", posts)
end
def random_post_id do
case Elasticsearch.Test.Repo.one(
from(
p in Post,
order_by: fragment("RANDOM()"),
limit: 1
)
) do
nil -> nil
post -> post.id
end
end
def populate_comments_table(quantity \\ 10) do
comments =
0..quantity
|> Enum.map(fn _ ->
%{
body: "Example Comment",
author: "Jane Doe",
post_id: random_post_id()
}
end)
Elasticsearch.Test.Repo.insert_all("comments", comments)
end
end
| 22.714286 | 80 | 0.626072 |
08900786f84917c09af83a5b9d9d09a1df73d4fd | 7,249 | ex | Elixir | lib/super_issuer/account.ex | WeLightProject/WeLight-Portal | 6e701469423e3a62affdc415c4e8c186d603d324 | [
"MIT"
] | 2 | 2021-02-12T09:21:56.000Z | 2021-02-22T08:52:20.000Z | lib/super_issuer/account.ex | WeLightProject/WeLight-Portal | 6e701469423e3a62affdc415c4e8c186d603d324 | [
"MIT"
] | 4 | 2021-02-22T08:53:43.000Z | 2021-06-09T09:24:46.000Z | lib/super_issuer/account.ex | WeLightProject/WeLight-Portal | 6e701469423e3a62affdc415c4e8c186d603d324 | [
"MIT"
] | null | null | null | defmodule SuperIssuer.Account do
use Ecto.Schema
import Ecto.{Changeset, Query}
alias SuperIssuer.{Contract, WeIdentity}
alias SuperIssuer.Contracts.{Erc20Handler, Erc721Handler}
alias SuperIssuer.Repo
alias SuperIssuer.Account, as: Ele
require Logger
schema "account" do
field :addr, :string
field :ft_balance, :map
field :nft_balance, :map
field :type, :string
belongs_to :weidentity, WeIdentity
timestamps()
end
def fetch_addr_by_weid(weid) do
weid
|> String.split(":")
|> Enum.fetch!(-1)
end
# +---------------+
# | Account Funcs |
# +---------------+
# PS: get_ft_info: call the get_contract_info in Contract
def get_ft_balance(chain, %{addr: erc_20_addr} = erc_20_contract, caller_addr, query_addr) do
{:ok, [ft_new_balance]} =
Erc20Handler.get_balance(chain, erc_20_addr, caller_addr, query_addr)
{:ok, _ele} = sync_to_local(erc_20_contract, query_addr, ft_new_balance)
{:ok, ft_new_balance}
end
def sync_to_local(erc_20_contract, query_addr, ft_new_balance) do
acct = Ele.get_by_addr(query_addr)
do_sync_to_local(erc_20_contract, query_addr, acct, ft_new_balance)
end
defp do_sync_to_local(_erc_20_contract, query_addr, acct, _ft_new_balance)
when is_nil(acct) do
Logger.info("#{query_addr} is not in our Account List")
{:ok, :pass}
end
defp do_sync_to_local(%{addr: erc_20_addr}, _query_addr, acct, ft_new_balance) do
update_ft_balance(erc_20_addr, acct, ft_new_balance)
end
def update_ft_balance(
erc20_addr,
%{ft_balance: ft_balance_local} = acct,
ft_new_balance)
when is_nil(ft_balance_local) do
do_update_ft_balance(erc20_addr, acct, %{}, ft_new_balance)
end
def update_ft_balance(
erc20_addr,
%{ft_balance: ft_balance_local} = acct,
ft_new_balance) do
do_update_ft_balance(erc20_addr, acct, ft_balance_local, ft_new_balance)
end
def do_update_ft_balance(erc20_addr, acct, ft_balance_local, ft_new_balance) do
payload = Map.put(ft_balance_local, erc20_addr, ft_new_balance)
Ele.change(acct, %{ft_balance: payload})
end
def update_nft_balnace(_erc721_addr, acct, token_id, _token_uri)
when is_nil(acct) do
Logger.info("#{token_id}'s owner is not in our Account List")
{:ok, :pass}
end
def update_nft_balnace(erc721_addr, %{nft_balance: nft_balance} = acct, token_id, token_uri)
when is_nil(nft_balance) do
do_update_nft_balance(erc721_addr, %{}, acct, token_id, token_uri)
end
def update_nft_balnace(erc721_addr, %{nft_balance: nft_balance} = acct, token_id, token_uri) do
do_update_nft_balance(erc721_addr, nft_balance, acct, token_id, token_uri)
end
def do_update_nft_balance(erc721_addr, nft_balance, acct, token_id, token_uri) do
balance_of_the_token = Map.get(nft_balance, erc721_addr)
balance_of_the_token =
if is_nil(balance_of_the_token) do
%{}
else
balance_of_the_token
end
balance_of_the_token_newest = Map.put(balance_of_the_token, token_id, token_uri)
payload = Map.put(nft_balance, erc721_addr, balance_of_the_token_newest)
Ele.change(acct, %{nft_balance: payload})
end
def transfer_ft(chain, %{addr: erc_20_addr} = contract, from, to, amount) do
{:ok, ft_balance} = get_ft_balance(chain, %{addr: erc_20_addr}, from, from)
with {:ok, :pos} <- check_amount_pos(amount),
{:ok, :balance_enough} <- checkout_balance_enough(ft_balance, amount) do
# Ensure Transfer is Ok
{:ok,
%{
"statusOK" => true,
"transactionHash" => tx_id
}} = Erc20Handler.transfer(chain, erc_20_addr, from, to, amount)
# Update the balance
Task.async(fn ->
# eazy way suit now!
:timer.sleep(3000)
{:ok, from_balance} = get_ft_balance(chain, contract, from, from)
{:ok, to_balance} = get_ft_balance(chain, contract, to, to)
Logger.info("#{from} balance is #{from_balance} now")
Logger.info("#{to} balance is #{to_balance} now")
end)
# {:ok, %Account{}} = sync_to_local(contract, from, ft_balance - amount)
# sync_to_local(contract, to, ft_balance + amount)
{:ok, tx_id}
else
error_info ->
error_info
end
end
def get_nft_balance(chain, %{addr: contract_addr, erc721_total_num: local_supply} = erc_721_contract, caller_addr, query_addr) do
{:ok, [total_supply]} = Erc721Handler.get(:total_supply, chain, contract_addr, caller_addr)
sync_nfts(chain, local_supply, total_supply, contract_addr, caller_addr)
# update total_supply
Contract.change(erc_721_contract, %{erc721_total_num: total_supply})
# get_addr's all nft
query_addr
|> get_by_addr()
|> handle_nil()
|> case do
%{nft_balance: nil} ->
{:ok, []}
%{nft_balance: nft_balance} ->
{:ok, nft_balance}
{:error, error_info} ->
{:error, error_info}
end
end
def handle_nil(payload) when is_nil(payload) do
Logger.info("query addr owner is not in our Account List")
{:error, "query addr is not in our Account List"}
end
def handle_nil(payload), do: payload
def sync_nfts(_chain, local_supply, total_supply, _contract_addr, _caller_addr) when local_supply == total_supply, do: :pass
def sync_nfts(chain, local_supply, total_supply, contract_addr, caller_addr) when is_nil(local_supply) do
sync_nfts(chain, 0, total_supply, contract_addr, caller_addr)
end
def sync_nfts(chain, local_supply, total_supply, contract_addr, caller_addr) do
Enum.map((local_supply + 1)..total_supply, fn token_id ->
{:ok, %{owner_addr: owner_addr, token_uri: token_uri}} =
sync_nft(chain, token_id, contract_addr, caller_addr)
acct = get_by_addr(owner_addr)
{:ok, _ele} = update_nft_balnace(contract_addr, acct, token_id, token_uri)
end)
end
def sync_nft(chain, token_id, contract_addr, caller_addr) do
{:ok, [owner_addr]} = Erc721Handler.get_token_owner(chain, contract_addr, caller_addr, token_id)
{:ok, [token_uri]} = Erc721Handler.get_token_uri(chain, contract_addr, caller_addr, token_id)
{:ok, %{owner_addr: owner_addr, token_uri: token_uri}}
end
def check_amount_pos(amount) do
if amount > 0 do
{:ok, :pos}
else
{:error, :neg_amount}
end
end
def checkout_balance_enough(ft_balance, amount) do
if ft_balance >= amount do
{:ok, :balance_enough}
else
{:erro, :balance_not_enough}
end
end
# +----------------+
# | Database Funcs |
# +----------------+
def count() do
Ele
|> select(count("*"))
|> Repo.one()
end
def preload(ele) do
Repo.preload(ele, :weidentity)
end
def get_all() do
Repo.all(Ele)
end
def get_by_addr(addr) do
Repo.get_by(Ele, addr: addr)
end
def create(attrs \\ %{}) do
%Ele{}
|> changeset(attrs)
|> Repo.insert()
end
def change(%Ele{} = ele, attrs) do
ele
|> changeset(attrs)
|> Repo.update()
end
def changeset(%Ele{} = ele) do
Ele.changeset(ele, %{})
end
def changeset(%Ele{} = ele, attrs) do
ele
|> cast(attrs, [:addr, :weidentity_id, :ft_balance, :nft_balance, :type])
end
end
| 29.831276 | 131 | 0.6743 |
08901b09505153a10f250c48778fbc423f84caab | 884 | exs | Elixir | test/mix/tasks/brando/brando.gen.blueprint_test.exs | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 4 | 2020-10-30T08:40:38.000Z | 2022-01-07T22:21:37.000Z | test/mix/tasks/brando/brando.gen.blueprint_test.exs | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 1,162 | 2020-07-05T11:20:15.000Z | 2022-03-31T06:01:49.000Z | test/mix/tasks/brando/brando.gen.blueprint_test.exs | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | null | null | null | Code.require_file("../../../support/mix_helper.exs", __DIR__)
defmodule Mix.Tasks.Brando.Gen.BlueprintTest do
use ExUnit.Case
import MixHelper
setup do
Mix.Task.clear()
:ok
end
test "generates html resource" do
in_tmp("brando.gen.blueprint", fn ->
send(self(), {:mix_shell_input, :prompt, "MyDomain"})
send(self(), {:mix_shell_input, :prompt, "MySchema"})
Mix.Tasks.Brando.Gen.Blueprint.run([])
# test gallery
assert_file("lib/brando/my_domain/my_schema.ex", fn file ->
assert file =~
"defmodule BrandoIntegration.MyDomain.MySchema do\n @moduledoc \"\"\"\n Blueprint for MySchema\n \"\"\"\n\n use Brando.Blueprint,\n application: \"BrandoIntegration\",\n domain: \"MyDomain\",\n schema: \"MySchema\",\n singular: \"my_schema\",\n plural: \"my_schemas\""
end)
end)
end
end
| 34 | 304 | 0.634615 |
089031d4f5583a12db71207f6ec54fe8638059b1 | 320 | ex | Elixir | lib/codes/codes_g35.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_g35.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_g35.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_G35 do
alias IcdCode.ICDCode
def _G35 do
%ICDCode{full_code: "G35",
category_code: "G35",
short_code: "",
full_name: "Multiple sclerosis",
short_name: "Multiple sclerosis",
category_name: "Multiple sclerosis"
}
end
end
| 20 | 45 | 0.6125 |
089059e612e54d5aaf45237da83bfae2b7747610 | 540 | ex | Elixir | lib/colorify_web/controllers/dashboard_controller.ex | ashkan18/colorify | e4da2bc54a60199c411afc696086689d825b7a13 | [
"MIT"
] | 1 | 2020-03-12T18:44:10.000Z | 2020-03-12T18:44:10.000Z | lib/colorify_web/controllers/dashboard_controller.ex | ashkan18/colorify | e4da2bc54a60199c411afc696086689d825b7a13 | [
"MIT"
] | 1 | 2021-03-10T10:22:38.000Z | 2021-03-10T10:22:38.000Z | lib/colorify_web/controllers/dashboard_controller.ex | ashkan18/colorify | e4da2bc54a60199c411afc696086689d825b7a13 | [
"MIT"
] | 1 | 2020-03-12T18:41:42.000Z | 2020-03-12T18:41:42.000Z | defmodule ColorifyWeb.DashboardController do
use ColorifyWeb, :controller
def index(conn, _) do
user_id = get_session(conn, :user_id)
conn
|> get_session(:access_token)
|> Spotify.client()
|> Spotify.user_playlists(user_id)
|> case do
{:ok, response} ->
case response.status do
200 -> render(conn, "index.html", playlists: response.body["items"], user_id: user_id)
_ -> redirect(conn, to: "/auth")
end
_ ->
redirect(conn, to: "/auth")
end
end
end
| 23.478261 | 96 | 0.601852 |
0890a91c80e07886b54b5f86933e0ce09efb1409 | 71 | exs | Elixir | test/input_event_test.exs | hez/input_event | e831a1053d7d837ccadfb75d9e70c70b56895eab | [
"Apache-2.0"
] | 20 | 2018-09-23T18:12:14.000Z | 2020-04-18T12:37:34.000Z | test/input_event_test.exs | hez/input_event | e831a1053d7d837ccadfb75d9e70c70b56895eab | [
"Apache-2.0"
] | 7 | 2018-09-17T05:40:23.000Z | 2020-06-06T20:17:53.000Z | test/input_event_test.exs | hez/input_event | e831a1053d7d837ccadfb75d9e70c70b56895eab | [
"Apache-2.0"
] | 6 | 2020-12-04T21:20:39.000Z | 2022-03-16T19:26:24.000Z | defmodule InputEventTest do
use ExUnit.Case
doctest InputEvent
end
| 14.2 | 27 | 0.816901 |
0891067d5c94e5ed61f877155b7e278d0d68587c | 1,542 | ex | Elixir | lib/flamelex/gui/components/layout/layoutable.ex | JediLuke/franklin | 8eb77a342547de3eb43d28dcf9f835ff443ad489 | [
"Apache-2.0"
] | 1 | 2020-02-09T23:04:33.000Z | 2020-02-09T23:04:33.000Z | lib/flamelex/gui/components/layout/layoutable.ex | JediLuke/franklin | 8eb77a342547de3eb43d28dcf9f835ff443ad489 | [
"Apache-2.0"
] | null | null | null | lib/flamelex/gui/components/layout/layoutable.ex | JediLuke/franklin | 8eb77a342547de3eb43d28dcf9f835ff443ad489 | [
"Apache-2.0"
] | null | null | null | defmodule Flamelex.GUI.Component.Layoutable do
@defmodule """
A high-order component which wraps around a list of other components,
allows them to be dynamically sized, and re-arranges it's child-components
based on some pre-defined rules.
One example is how we use the Layout to handle the placement of
tags inside HyperCard.TagsBox
"""
use Scenic.Component
require Logger
alias ScenicWidgets.Core.Structs.Frame
#NOTE: components is a list of functions
# todo - dunno why but we cant pattern match on a %Frame{} here
# def validate(%{frame: %Frame{} = _f, components: _c, layout: _l} = data), do: data
# def validate(%{frame: _f, components: _c, layout: _l} = data) do
def validate(%{id: _id} = data) do
{:ok, data}
end
def init(scene, args, opts) do
#TODO render the graph, put a clear rectangle the size of the frame on the bottom to ensure it has full bounds
init_scene = scene
|> assign(id: args.id)
# |> assign(frame: args.frame)
# |> assign(graph: args.graph)
# |> push_graph(args.graph)
{:ok, init_scene, {:continue, :publish_bounds}}
end
def handle_continue(:publish_bounds, scene) do
bounds = Scenic.Graph.bounds(scene.assigns.graph)
send_parent_event(scene, {:update_bounds, %{id: "j", bounds: bounds}})
|> GenServer.cast({:new_component_bounds, {scene.assigns.state.uuid, bounds}})
{:noreply, scene, {:continue, :render_next_hyper_card}}
end
end | 35.860465 | 118 | 0.656291 |
08911b8ae9cfa12f8c31c503b2722a0cc53f49ea | 1,631 | ex | Elixir | clients/cloud_search/lib/google_api/cloud_search/v1/model/get_customer_index_stats_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-10-01T09:20:41.000Z | 2021-10-01T09:20:41.000Z | clients/cloud_search/lib/google_api/cloud_search/v1/model/get_customer_index_stats_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | clients/cloud_search/lib/google_api/cloud_search/v1/model/get_customer_index_stats_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudSearch.V1.Model.GetCustomerIndexStatsResponse do
@moduledoc """
## Attributes
* `stats` (*type:* `list(GoogleApi.CloudSearch.V1.Model.CustomerIndexStats.t)`, *default:* `nil`) - Summary of indexed item counts, one for each day in the requested range.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:stats => list(GoogleApi.CloudSearch.V1.Model.CustomerIndexStats.t()) | nil
}
field(:stats, as: GoogleApi.CloudSearch.V1.Model.CustomerIndexStats, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.CloudSearch.V1.Model.GetCustomerIndexStatsResponse do
def decode(value, options) do
GoogleApi.CloudSearch.V1.Model.GetCustomerIndexStatsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudSearch.V1.Model.GetCustomerIndexStatsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.702128 | 176 | 0.755365 |
08913d7fde0a621ec368e4ade71061a1177481ea | 6,252 | exs | Elixir | test/membrane/integration/child_crash_test.exs | vKxni/membrane_core | d14a67304b63706d6df520fa306dd2fda147c07c | [
"Apache-2.0"
] | null | null | null | test/membrane/integration/child_crash_test.exs | vKxni/membrane_core | d14a67304b63706d6df520fa306dd2fda147c07c | [
"Apache-2.0"
] | null | null | null | test/membrane/integration/child_crash_test.exs | vKxni/membrane_core | d14a67304b63706d6df520fa306dd2fda147c07c | [
"Apache-2.0"
] | null | null | null | defmodule Membrane.Integration.ChildCrashTest do
use ExUnit.Case, async: false
import Membrane.Testing.Assertions
alias Membrane.Testing
alias Membrane.Support.ChildCrashTest
alias Membrane.Pipeline
test "Element that is not member of any crash group crashed when pipeline is in playing state" do
Process.flag(:trap_exit, true)
assert {:ok, pipeline_pid} =
Testing.Pipeline.start_link(%Testing.Pipeline.Options{
module: ChildCrashTest.Pipeline,
custom_args: %{
sink: Testing.Sink
}
})
:ok = Pipeline.play(pipeline_pid)
ChildCrashTest.Pipeline.add_path(pipeline_pid, [:filter_1_1, :filter_2_1], :source_1)
[sink_pid, center_filter_pid, filter_1_1_pid, filter_1_2_pid, source_1_pid] =
[:sink, :center_filter, :filter_1_1, :filter_2_1, :source_1]
|> Enum.map(&get_pid_and_link(&1, pipeline_pid))
assert_pipeline_playback_changed(pipeline_pid, _, :playing)
ChildCrashTest.Pipeline.crash_child(filter_1_1_pid)
# assert all members of pipeline and pipeline itself down
assert_pid_dead(source_1_pid)
assert_pid_dead(filter_1_1_pid)
assert_pid_dead(filter_1_2_pid)
assert_pid_dead(center_filter_pid)
assert_pid_dead(sink_pid)
assert_pid_dead(pipeline_pid)
end
test "small pipeline with one crash group test" do
Process.flag(:trap_exit, true)
assert {:ok, pipeline_pid} =
Testing.Pipeline.start_link(%Testing.Pipeline.Options{
module: ChildCrashTest.Pipeline
})
:ok = Pipeline.play(pipeline_pid)
ChildCrashTest.Pipeline.add_path(pipeline_pid, [], :source, {1, :temporary})
[source_pid, center_filter_pid, sink_pid] =
[:source, :center_filter, :sink]
|> Enum.map(&get_pid_and_link(&1, pipeline_pid))
assert_pipeline_playback_changed(pipeline_pid, _, :playing)
Process.exit(source_pid, :crash)
# member of group is dead
assert_pid_dead(source_pid)
# other parts of pipeline are alive
assert_pid_alive(source_pid)
assert_pid_alive(center_filter_pid)
assert_pid_alive(sink_pid)
assert_pid_alive(pipeline_pid)
assert_pipeline_crash_group_down(pipeline_pid, 1)
end
test "Crash group consisting of bin crashes" do
Process.flag(:trap_exit, true)
assert {:ok, pipeline_pid} =
Testing.Pipeline.start_link(%Testing.Pipeline.Options{
module: ChildCrashTest.Pipeline
})
:ok = Pipeline.play(pipeline_pid)
ChildCrashTest.Pipeline.add_bin(pipeline_pid, :bin_1, :source_1, {1, :temporary})
ChildCrashTest.Pipeline.add_bin(pipeline_pid, :bin_2, :source_2, {2, :temporary})
ChildCrashTest.Pipeline.add_bin(pipeline_pid, :bin_3, :source_3, {3, :temporary})
[
sink_pid,
center_filter_pid,
bin_1_pid,
bin_2_pid,
bin_3_pid,
source_1_pid,
source_2_pid,
source_3_pid
] =
[
:sink,
:center_filter,
:bin_1,
:bin_2,
:bin_3,
:source_1,
:source_2,
:source_3
]
|> Enum.map(&get_pid_and_link(&1, pipeline_pid))
assert_pipeline_playback_changed(pipeline_pid, _, :playing)
filter_1_pid = get_pid(:filter, bin_1_pid)
ChildCrashTest.Filter.crash(filter_1_pid)
# assert source 1, bin_1 and filter that is inside of it are dead
assert_pid_dead(source_1_pid)
assert_pid_dead(bin_1_pid)
assert_pid_alive(sink_pid)
assert_pid_alive(center_filter_pid)
assert_pid_alive(bin_2_pid)
assert_pid_alive(bin_3_pid)
assert_pid_alive(source_2_pid)
assert_pid_alive(source_3_pid)
assert_pid_alive(pipeline_pid)
end
test "Crash two groups one after another" do
Process.flag(:trap_exit, true)
assert {:ok, pipeline_pid} =
Testing.Pipeline.start_link(%Testing.Pipeline.Options{
module: ChildCrashTest.Pipeline
})
:ok = Pipeline.play(pipeline_pid)
ChildCrashTest.Pipeline.add_path(
pipeline_pid,
[:filter_1_1, :filter_2_1],
:source_1,
{1, :temporary}
)
ChildCrashTest.Pipeline.add_path(
pipeline_pid,
[:filter_1_2, :filter_2_2],
:source_2,
{2, :temporary}
)
[
sink_pid,
center_filter_pid,
filter_1_1_pid,
filter_2_1_pid,
source_1_pid,
filter_1_2_pid,
filter_2_2_pid,
source_2_pid
] =
[
:sink,
:center_filter,
:filter_1_1,
:filter_2_1,
:source_1,
:filter_1_2,
:filter_2_2,
:source_2
]
|> Enum.map(&get_pid_and_link(&1, pipeline_pid))
assert_pipeline_playback_changed(pipeline_pid, _, :playing)
ChildCrashTest.Pipeline.crash_child(filter_1_1_pid)
# assert all members of group are dead
assert_pid_dead(filter_1_1_pid)
assert_pid_dead(filter_2_1_pid)
assert_pid_dead(source_1_pid)
# assert all other members of pipeline and pipeline itself are alive
assert_pid_alive(sink_pid)
assert_pid_alive(center_filter_pid)
assert_pid_alive(filter_1_2_pid)
assert_pid_alive(filter_2_2_pid)
assert_pid_alive(source_2_pid)
assert_pid_alive(pipeline_pid)
assert_pipeline_crash_group_down(pipeline_pid, 1)
refute_pipeline_crash_group_down(pipeline_pid, 2)
ChildCrashTest.Pipeline.crash_child(filter_1_2_pid)
# assert all members of group are dead
assert_pid_dead(filter_1_2_pid)
assert_pid_dead(filter_2_2_pid)
assert_pid_dead(source_2_pid)
# assert all other members of pipeline and pipeline itself are alive
assert_pid_alive(sink_pid)
assert_pid_alive(center_filter_pid)
assert_pid_alive(pipeline_pid)
assert_pipeline_crash_group_down(pipeline_pid, 2)
end
defp assert_pid_alive(pid) do
refute_receive {:EXIT, ^pid, _}
end
defp assert_pid_dead(pid) do
assert_receive {:EXIT, ^pid, _}, 2000
end
defp get_pid_and_link(ref, pipeline_pid) do
state = :sys.get_state(pipeline_pid)
pid = state.children[ref].pid
:erlang.link(pid)
pid
end
defp get_pid(ref, parent_pid) do
state = :sys.get_state(parent_pid)
state.children[ref].pid
end
end
| 26.948276 | 99 | 0.68762 |
0891681ba09fef827b061e39f2fe166ec276bf65 | 1,758 | ex | Elixir | clients/ad_sense/lib/google_api/ad_sense/v14/model/ad_unit_content_ads_settings.ex | ericrwolfe/elixir-google-api | 3dc0f17edd5e2d6843580c16ddae3bf84b664ffd | [
"Apache-2.0"
] | null | null | null | clients/ad_sense/lib/google_api/ad_sense/v14/model/ad_unit_content_ads_settings.ex | ericrwolfe/elixir-google-api | 3dc0f17edd5e2d6843580c16ddae3bf84b664ffd | [
"Apache-2.0"
] | null | null | null | clients/ad_sense/lib/google_api/ad_sense/v14/model/ad_unit_content_ads_settings.ex | ericrwolfe/elixir-google-api | 3dc0f17edd5e2d6843580c16ddae3bf84b664ffd | [
"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.AdSense.V14.Model.AdUnitContentAdsSettings do
@moduledoc """
Settings specific to content ads (AFC) and highend mobile content ads (AFMC - deprecated).
## Attributes
- backupOption (AdUnitContentAdsSettingsBackupOption): Defaults to: `null`.
- size (String): Size of this ad unit. Defaults to: `null`.
- type (String): Type of this ad unit. Defaults to: `null`.
"""
defstruct [
:backupOption,
:size,
:type
]
end
defimpl Poison.Decoder, for: GoogleApi.AdSense.V14.Model.AdUnitContentAdsSettings do
import GoogleApi.AdSense.V14.Deserializer
def decode(value, options) do
value
|> deserialize(
:backupOption,
:struct,
GoogleApi.AdSense.V14.Model.AdUnitContentAdsSettingsBackupOption,
options
)
end
end
defimpl Poison.Encoder, for: GoogleApi.AdSense.V14.Model.AdUnitContentAdsSettings do
def encode(value, options) do
GoogleApi.AdSense.V14.Deserializer.serialize_non_nil(value, options)
end
end
| 31.392857 | 92 | 0.742321 |
0891a754b5d932f7c7817496f297a80eaf851a72 | 92 | ex | Elixir | lib/delugex/message_store/mnesia/expected_version_error.ex | Fire-Dragon-DoL/esp_ex | 0cd95de570ed7963744b298ad403fe4e1947dd2b | [
"MIT"
] | null | null | null | lib/delugex/message_store/mnesia/expected_version_error.ex | Fire-Dragon-DoL/esp_ex | 0cd95de570ed7963744b298ad403fe4e1947dd2b | [
"MIT"
] | null | null | null | lib/delugex/message_store/mnesia/expected_version_error.ex | Fire-Dragon-DoL/esp_ex | 0cd95de570ed7963744b298ad403fe4e1947dd2b | [
"MIT"
] | null | null | null | defmodule Delugex.MessageStore.Mnesia.ExpectedVersionError do
defexception [:message]
end
| 23 | 61 | 0.847826 |
0891ceae89688852440d7ec9770a4271cdf5f484 | 7,250 | exs | Elixir | test/epi_contacts/commcare/client_test.exs | RatioPBC/epi-contacts | 6c43eea52cbfe2097f48b02e3d0c8fce3b46f1ee | [
"Apache-2.0"
] | null | null | null | test/epi_contacts/commcare/client_test.exs | RatioPBC/epi-contacts | 6c43eea52cbfe2097f48b02e3d0c8fce3b46f1ee | [
"Apache-2.0"
] | 13 | 2021-06-29T04:35:41.000Z | 2022-02-09T04:25:39.000Z | test/epi_contacts/commcare/client_test.exs | RatioPBC/epi-contacts | 6c43eea52cbfe2097f48b02e3d0c8fce3b46f1ee | [
"Apache-2.0"
] | null | null | null | defmodule EpiContacts.Commcare.ClientTest do
use EpiContacts.DataCase, async: true
alias EpiContacts.Commcare.Client, as: CommcareClient
alias EpiContacts.Parsers
alias EpiContacts.Test
import Mox
setup :verify_on_exit!
@test_domain "test domain"
@test_case_id "test case id"
test "update_properties!" do
envelope_id = Ecto.UUID.generate()
envelope_timestamp = DateTime.utc_now()
opts = [envelope_id: envelope_id, envelope_timestamp: envelope_timestamp]
Mox.expect(EpiContacts.HTTPoisonMock, :post, 1, fn url, body, _headers, _opt ->
assert url == "https://www.commcarehq.org/a/#{@test_domain}/receiver/"
assert body == CommcareClient.build_update(@test_case_id, %{some: "property"}, opts)
{:ok, %{status_code: 201, body: ""}}
end)
CommcareClient.update_properties!(@test_domain, @test_case_id, %{some: "property"}, opts)
end
test "build_update" do
envelope_id = Ecto.UUID.generate()
envelope_timestamp = DateTime.utc_now()
opts = [envelope_id: envelope_id, envelope_timestamp: envelope_timestamp]
assert CommcareClient.build_update(@test_case_id, %{some: "property", other: "value"}, opts) == """
<?xml version="1.0" encoding="UTF-8"?>\
<data xmlns="http://ratiopbc.com/epi-contacts">\
<case case_id="test case id" user_id="abc123" xmlns="http://commcarehq.org/case/transaction/v2">\
<update>\
<other>value</other>\
<some>property</some>\
</update>\
</case>\
<n1:meta xmlns:n1=\"http://openrosa.org/jr/xforms\"><n1:deviceID>Formplayer</n1:deviceID><n1:timeStart>#{
envelope_timestamp
}</n1:timeStart><n1:timeEnd>#{envelope_timestamp}</n1:timeEnd><n1:username>geometer_user_1</n1:username><n1:userID>abc123</n1:userID><n1:instanceID>#{
envelope_id
}</n1:instanceID></n1:meta>\
</data>\
"""
assert CommcareClient.build_update(@test_case_id, [kwlist: "also works"], opts) == """
<?xml version="1.0" encoding="UTF-8"?>\
<data xmlns="http://ratiopbc.com/epi-contacts">\
<case case_id="test case id" user_id="abc123" xmlns="http://commcarehq.org/case/transaction/v2">\
<update>\
<kwlist>also works</kwlist>\
</update>\
</case>\
<n1:meta xmlns:n1=\"http://openrosa.org/jr/xforms\"><n1:deviceID>Formplayer</n1:deviceID><n1:timeStart>#{
envelope_timestamp
}</n1:timeStart><n1:timeEnd>#{envelope_timestamp}</n1:timeEnd><n1:username>geometer_user_1</n1:username><n1:userID>abc123</n1:userID><n1:instanceID>#{
envelope_id
}</n1:instanceID></n1:meta>\
</data>\
"""
end
describe "build_contact" do
setup context do
{:ok, true} = FunWithFlags.enable(:feb_17_commcare_release, [])
now_as_string = "2021-08-16 01:02:03Z"
{:ok, now, _} = DateTime.from_iso8601(now_as_string)
patient_case = %{
"domain" => "ny-state-covid19",
"case_id" => "case-123",
"properties" => %{
"owner_id" => "owner-id",
"doh_mpi_id" => "patient-doh-mpi-id",
"smc_trigger_reason" => "pre_ci"
}
}
contact = %{
first_name: "Joe",
last_name: "Smith",
email: "joe@example.com",
phone: "123-456-7890",
exposed_on: ~D[2020-11-03],
contact_id: "1111",
is_minor: false,
relationship: "family",
contact_location: "household",
primary_language: "en"
}
envelope_id = Ecto.UUID.generate()
xml =
CommcareClient.build_contact(patient_case, contact,
case_id: context[:case_id],
envelope_id: envelope_id,
envelope_timestamp: now
)
doc = xml |> Floki.parse_document!()
[xml: xml, doc: doc, now: now_as_string, envelope_id: envelope_id]
end
test "xml has <?xml> element", %{xml: xml} do
assert xml |> String.starts_with?(~s|<?xml version=\"1.0\" encoding=\"UTF-8\"?>|)
end
test "xml contains base data", %{doc: doc} do
assert Test.Xml.attr(doc, "data", "xmlns") == "http://ratiopbc.com/epi-contacts"
assert Test.Xml.attr(doc, "case:nth-of-type(1)", "xmlns") == "http://commcarehq.org/case/transaction/v2"
assert Test.Xml.attr(doc, "case:nth-of-type(1)", "case_id") |> Parsers.valid_uuid?()
# expected value of user_id comes from COMMCARE_USER_ID from .env.test
assert Test.Xml.attr(doc, "case:nth-of-type(1)", "user_id") == "abc123"
assert Test.Xml.text(doc, "case:nth-of-type(1) create case_name") == "Joe Smith"
assert Test.Xml.text(doc, "case:nth-of-type(1) create case_type") == "contact"
end
@tag case_id: "our-case_id"
test "xml contains our case_id", %{case_id: case_id, doc: doc} do
assert Test.Xml.attr(doc, "case:nth-of-type(1)", "case_id") == case_id
end
test "xml index field contains info about the parent case", %{doc: doc} do
assert Test.Xml.attr(doc, "case:nth-of-type(1) index parent", "case_type") == "patient"
assert Test.Xml.attr(doc, "case:nth-of-type(1) index parent", "relationship") == "extension"
end
test "xml contains metadata", %{doc: doc, now: now, envelope_id: envelope_id} do
assert Test.Xml.attr(doc, "meta", "xmlns:n1") == "http://openrosa.org/jr/xforms"
assert Test.Xml.text(doc, "meta timeStart") == now
assert Test.Xml.text(doc, "meta timeEnd") == now
assert Test.Xml.text(doc, "meta username") == "geometer_user_1"
assert Test.Xml.text(doc, "meta userID") == "abc123"
assert Test.Xml.text(doc, "meta instanceID") == envelope_id
end
test "xml update field contains contact data", %{doc: doc} do
expected_fields = %{
"commcare_email_address" => "joe@example.com",
"contact_id" => "1111",
"contact_is_a_minor" => "no",
"contact_status" => "pending_first_contact",
"contact_type" => "household",
"elicited_from_smc" => "yes",
"exposure_date" => "2020-11-3",
"first_name" => "Joe",
"full_name" => "Joe Smith",
"fup_end_date" => "2020-11-17",
"fup_next_method" => "call",
"fup_next_type" => "initial_interview",
"fup_start_date" => "2020-11-3",
"has_index_case" => "yes",
"has_phone_number" => "yes",
"initials" => "J.S.",
"investigation" => "",
"investigation_case_id" => "",
"investigation_id" => "",
"investigation_name" => "",
"index_case_id" => "patient-doh-mpi-id",
"last_name" => "Smith",
"name" => "Joe Smith",
"owner_id" => "owner-id",
"phone_home" => "123-456-7890",
"primary_language" => "en",
"relation_to_case" => "family",
"smc_trigger_reason" => "pre_ci"
}
Floki.find(doc, "case:nth-of-type(1) update *")
|> Enum.map(fn
{element, _attrs, [value]} -> {element, value}
{element, _attrs, []} -> {element, ""}
end)
|> Map.new()
|> assert_eq(
expected_fields,
only: expected_fields |> Map.keys()
)
end
end
end
| 38.56383 | 161 | 0.596966 |
0891d270576670e723d1f8a079fd0c816e7cd9e2 | 739 | ex | Elixir | lib/auth0_ex/application.ex | nazarsh/auth0_ex | 21f5b2cb88679368c938d2bbd193eca0ee54620d | [
"Apache-2.0"
] | 38 | 2016-08-31T12:44:19.000Z | 2021-06-17T18:23:21.000Z | lib/auth0_ex/application.ex | nazarsh/auth0_ex | 21f5b2cb88679368c938d2bbd193eca0ee54620d | [
"Apache-2.0"
] | 24 | 2017-01-12T17:53:10.000Z | 2022-03-14T13:43:12.000Z | lib/auth0_ex/application.ex | nazarsh/auth0_ex | 21f5b2cb88679368c938d2bbd193eca0ee54620d | [
"Apache-2.0"
] | 24 | 2017-01-27T20:51:57.000Z | 2022-03-11T19:58:40.000Z | defmodule Auth0Ex.Application do
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
import Supervisor.Spec, warn: false
# Define workers and child supervisors to be supervised
children = [
# Starts a worker by calling: Auth0Ex.Worker.start_link(arg1, arg2, arg3)
# worker(Auth0Ex.Worker, [arg1, arg2, arg3]),
worker(Auth0Ex.TokenState, [])
]
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Auth0Ex.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 29.56 | 79 | 0.711773 |
08921ad5549560f3a7108ca47028ce5a1e065cae | 9,688 | ex | Elixir | lib/akd/dsl/form_hook.ex | corroded/akd | ed15b8929b6d110552a19522f8a17edf75452e87 | [
"MIT"
] | null | null | null | lib/akd/dsl/form_hook.ex | corroded/akd | ed15b8929b6d110552a19522f8a17edf75452e87 | [
"MIT"
] | null | null | null | lib/akd/dsl/form_hook.ex | corroded/akd | ed15b8929b6d110552a19522f8a17edf75452e87 | [
"MIT"
] | null | null | null | defmodule Akd.Dsl.FormHook do
@moduledoc """
Defines a Hook.
This modules provides a DSL to define hooks (`Akd.Hook.t` structs) in a
readable and organized manner.
This module provides a set of macros for generating hooks using operations
specified by `main`, `ensure` and `rollback` macros.
## Form Hook and Operations
Once form_hook is called, it is goes through all the operations defined within
the `do - end` block, using the `main`, `ensure`, and `rollback` macros, with their
specific options. Once the block ends, it resolves all those operations into
an `Akd.Hook.t` struct, which it then returns.
Once this hook is defined it can be used in a pipeline or an `Akd.Hook` module
that returns a hook.
## For Example:
Use within an `Akd.Hook` module
```
defmodule DeployApp.CustomHook.Hook do
use Akd.Hook
def get_hooks(deployment, opts \\ []) do
my_hook = form_hook opts do
main "run this", deployment.build_at
main "run this too", deployment.publish_to
ensure "ensure this command runs", deployment.build_at
rollback "call this only if the hook fails", deployment.publish_to
end
[my_hook]
end
end
```
Please refer to `Nomenclature` for more information about the terms used.
"""
@doc """
Forms a hook with a given block.
This is the entry point to this DSL.
Same as `form_hook/2` but without `opts`
## Examples
```elixir
form_hook do
main "echo hello", Akd.Destination.local()
end
```
iex> import Akd.Dsl.FormHook
iex> form_hook do
...> main "echo hello", Akd.Destination.local()
...> main "run this cmd", Akd.Destination.local()
...> ensure "run this too", Akd.Destination.local()
...> rollback "roll this back", Akd.Destination.local()
...> end
%Akd.Hook{ensure: [%Akd.Operation{cmd: "run this too", cmd_envs: [],
destination: %Akd.Destination{host: :local, path: ".",
user: :current}}], ignore_failure: false,
main: [%Akd.Operation{cmd: "echo hello", cmd_envs: [],
destination: %Akd.Destination{host: :local, path: ".",
user: :current}},
%Akd.Operation{cmd: "run this cmd", cmd_envs: [],
destination: %Akd.Destination{host: :local, path: ".",
user: :current}}],
rollback: [%Akd.Operation{cmd: "roll this back", cmd_envs: [],
destination: %Akd.Destination{host: :local, path: ".",
user: :current}}], run_ensure: true}
"""
defmacro form_hook(do: block) do
quote do
{:ok, var!(ops, unquote(__MODULE__))} = start_ops_acc()
unquote(block)
val = ops
|> var!(unquote(__MODULE__))
|> get_ops_acc()
|> struct_hook([])
stop_ops_acc(var!(ops, unquote(__MODULE__)))
val
end
end
@doc """
Forms a hook with a given block.
This is the entry point to this DSL.
## Examples
```elixir
form_hook opts, do
main "echo hello", Akd.Destination.local()
end
```
iex> import Akd.Dsl.FormHook
iex> form_hook ignore_failure: true, run_ensure: false do
...> main "echo hello", Akd.Destination.local()
...> main "run this cmd", Akd.Destination.local()
...> ensure "run this too", Akd.Destination.local()
...> rollback "roll this back", Akd.Destination.local()
...> end
%Akd.Hook{ensure: [%Akd.Operation{cmd: "run this too", cmd_envs: [],
destination: %Akd.Destination{host: :local, path: ".",
user: :current}}], ignore_failure: true,
main: [%Akd.Operation{cmd: "echo hello", cmd_envs: [],
destination: %Akd.Destination{host: :local, path: ".",
user: :current}},
%Akd.Operation{cmd: "run this cmd", cmd_envs: [],
destination: %Akd.Destination{host: :local, path: ".",
user: :current}}],
rollback: [%Akd.Operation{cmd: "roll this back", cmd_envs: [],
destination: %Akd.Destination{host: :local, path: ".",
user: :current}}], run_ensure: false}
"""
defmacro form_hook(opts, do: block) do
quote do
{:ok, var!(ops, unquote(__MODULE__))} = start_ops_acc()
unquote(block)
val = ops
|> var!(unquote(__MODULE__))
|> get_ops_acc()
|> struct_hook(unquote(opts))
stop_ops_acc(var!(ops, unquote(__MODULE__)))
val
end
end
@doc """
Adds an operation to the `main` category of a hook
These commands are the main commands that are ran when a hook is first
executed.
Same as `main/2` but without `cmd_envs`
## Examples
```elixir
main "echo hello", Akd.Destination.local()
```
"""
defmacro main(cmd, dest) do
quote do
put_ops_acc(var!(ops, unquote(__MODULE__)),
{:main, {unquote(cmd), unquote(dest), []}})
end
end
@doc """
Adds an operation to the `main` category of a hook
These commands are the main commands that are ran when a hook is first
executed.
Takes a set of `cmd_envs`, which is a list of tuples
which represent the environment (system) variables
that will be given before the operation is executed.
## Examples
```elixir
main "echo $GREET", Akd.Destination.local(), cmd_envs: [{"GREET", "hello"}]
```
"""
defmacro main(cmd, dest, cmd_envs: cmd_envs) do
quote do
put_ops_acc(var!(ops, unquote(__MODULE__)),
{:main, {unquote(cmd), unquote(dest), unquote(cmd_envs)}})
end
end
@doc """
Adds an operation to the `ensure` category of a hook
These commands are the commands that are ran after all the hooks are
executed. Think of these commands as cleanup commands
Same as `ensure/2` but without `cmd_envs`
## Examples
```elixir
ensure "echo $GREET", Akd.Destination.local()
```
"""
defmacro ensure(cmd, dest) do
quote do
put_ops_acc(var!(ops, unquote(__MODULE__)),
{:ensure, {unquote(cmd), unquote(dest), []}})
end
end
@doc """
Adds an operation to the `ensure` category of a hook
These commands are the commands that are ran after all the hooks are
executed. Think of these commands as cleanup commands
Takes a set of `cmd_envs`, which is a list of tuples
which represent the environment (system) variables
that will be given before the operation is executed.
## Examples
```elixir
ensure "echo $GREET", Akd.Destination.local(), cmd_envs: [{"GREET", "hello"}]
```
"""
defmacro ensure(cmd, dest, cmd_envs: cmd_envs) do
quote do
put_ops_acc(var!(ops, unquote(__MODULE__)),
{:ensure, {unquote(cmd), unquote(dest), unquote(cmd_envs)}})
end
end
@doc """
Adds an operation to the `rollback` category of a hook
These commands are the commands that are ran after all the hooks are
executed and if there is a failure.
Same as `rollback/2` but without `cmd_envs`
## Examples
```elixir
rollback "echo $GREET", Akd.Destination.local()
```
"""
defmacro rollback(cmd, dest) do
quote do
put_ops_acc(var!(ops, unquote(__MODULE__)),
{:rollback, {unquote(cmd), unquote(dest), []}})
end
end
@doc """
Adds an operation to the `rollback` category of a hook
These commands are the commands that are ran after all the hooks are
executed and if there is a failure.
Takes a set of `cmd_envs`, which is a list of tuples
which represent the environment (system) variables
that will be given before the operation is executed.
## Examples
```elixir
rollback "echo $GREET", Akd.Destination.local(), cmd_envs: [{"GREET", "hello"}]
```
"""
defmacro rollback(cmd, dest, cmd_envs: cmd_envs) do
quote do
put_ops_acc(var!(ops, unquote(__MODULE__)),
{:rollback, {unquote(cmd), unquote(dest), unquote(cmd_envs)}})
end
end
@doc """
This starts an Agent that keeps track of added operations while using
the FormHook DSL
"""
def start_ops_acc(ops \\ []), do: Agent.start_link(fn -> ops end)
@doc """
This stops the Agent that keeps track of added operations while using
the FormHook DSL
"""
def stop_ops_acc(ops), do: Agent.stop(ops)
@doc """
This adds an operation to the Agent that keeps track of operations while using
the FormHook DSL
"""
def put_ops_acc(ops, op), do: Agent.update(ops, &[op | &1])
@doc """
Gets list of operations from the Agent that keeps track of operations while using
the FormHook DSL
"""
def get_ops_acc(ops), do: ops |> Agent.get(& &1) |> Enum.reverse()
@doc """
Converts a list of operations with options to an `Akd.Hook.t` struct
"""
def struct_hook(ops, opts) do
%Akd.Hook{
ensure: translate(ops, :ensure),
ignore_failure: !!opts[:ignore_failure],
main: translate(ops, :main),
rollback: translate(ops, :rollback),
run_ensure: Keyword.get(opts, :run_ensure, true),
}
end
# Translates a keyword of options with types to a list of `Akd.Opertion.t`
defp translate(keyword, type) do
keyword
|> Keyword.get_values(type)
|> Enum.map(&struct_op/1)
end
# This function takes in a command, a destination and list of environment
# variables and returns an `Akd.Operation.t` struct which can be used
# while executing a hook
defp struct_op({cmd, dst, cmd_envs}) when is_binary(dst) do
struct_op({cmd, Akd.Destination.parse(dst), cmd_envs})
end
defp struct_op({cmd, dst, cmd_envs}) do
%Akd.Operation{cmd: cmd, destination: dst, cmd_envs: cmd_envs}
end
end
| 29.901235 | 85 | 0.629129 |
08923552c3d8c9ec54e6072fdcaee145f9f7db0e | 9,883 | ex | Elixir | lib/text_delta/operation.ex | document-delta/text_delta | a37ccbcabf83c845a1040dd4fb4de9f45382aaf0 | [
"MIT"
] | 48 | 2017-05-29T19:39:42.000Z | 2022-03-28T15:53:29.000Z | lib/text_delta/operation.ex | document-delta/text_delta | a37ccbcabf83c845a1040dd4fb4de9f45382aaf0 | [
"MIT"
] | 1 | 2017-05-26T15:03:30.000Z | 2017-05-26T15:37:16.000Z | lib/text_delta/operation.ex | document-delta/text_delta | a37ccbcabf83c845a1040dd4fb4de9f45382aaf0 | [
"MIT"
] | 6 | 2017-11-30T16:54:27.000Z | 2021-05-19T10:27:12.000Z | defmodule TextDelta.Operation do
@moduledoc """
Operations represent a smallest possible change applicable to a text.
In case of text, there are exactly 3 possible operations we might want to
perform:
- `t:TextDelta.Operation.insert/0`: insert a new piece of text or an embedded
element
- `t:TextDelta.Operation.retain/0`: preserve given number of characters in
sequence
- `t:TextDelta.Operation.delete/0`: delete given number of characters in
sequence
`insert` and `retain` operations can also have optional
`t:TextDelta.Attributes.t/0` attached to them. This is how Delta manages rich
text formatting without breaking the [Operational Transformation][ot]
paradigm.
[ot]: https://en.wikipedia.org/wiki/Operational_transformation
"""
alias TextDelta.{Attributes, ConfigurableString}
@typedoc """
Insert operation represents an intention to add a text or an embedded element
to a text state. Text additions are represented with binary strings and
embedded elements are represented with either an integer or an object.
Insert also allows us to attach attributes to the element being inserted.
"""
@type insert ::
%{insert: element}
| %{insert: element, attributes: Attributes.t()}
@typedoc """
Retain operation represents an intention to keep a sequence of characters
unchanged in the text. It is always a number and it is always positive.
In addition to indicating preservation of existing text, retain also allows us
to change formatting of retained text or element via optional attributes.
"""
@type retain ::
%{retain: non_neg_integer}
| %{retain: non_neg_integer, attributes: Attributes.t()}
@typedoc """
Delete operation represents an intention to delete a sequence of characters
from the text. It is always a number and it is always positive.
"""
@type delete :: %{delete: non_neg_integer}
@typedoc """
An operation. Either `insert`, `retain` or `delete`.
"""
@type t :: insert | retain | delete
@typedoc """
Atom representing type of operation.
"""
@type type :: :insert | :retain | :delete
@typedoc """
The result of comparison operation.
"""
@type comparison :: :eq | :gt | :lt
@typedoc """
An insertable rich text element. Either a piece of text, a number or an embed.
"""
@type element :: String.t() | integer | map
@doc """
Creates a new insert operation.
Attributes are optional and are ignored if empty map or `nil` is provided.
## Examples
To indicate that we need to insert a text "hello" into the text, we can
use following insert:
iex> TextDelta.Operation.insert("hello")
%{insert: "hello"}
In addition, we can indicate that "hello" should be inserted with specific
attributes:
iex> TextDelta.Operation.insert("hello", %{bold: true, color: "magenta"})
%{insert: "hello", attributes: %{bold: true, color: "magenta"}}
We can also insert non-text objects, such as an image:
iex> TextDelta.Operation.insert(%{img: "me.png"}, %{alt: "My photo"})
%{insert: %{img: "me.png"}, attributes: %{alt: "My photo"}}
"""
@spec insert(element, Attributes.t()) :: insert
def insert(el, attrs \\ %{})
def insert(el, nil), do: %{insert: el}
def insert(el, attrs) when map_size(attrs) == 0, do: %{insert: el}
def insert(el, attrs), do: %{insert: el, attributes: attrs}
@doc """
Creates a new retain operation.
Attributes are optional and are ignored if empty map or `nil` is provided.
## Examples
To keep 5 next characters inside the text, we can use the following retain:
iex> TextDelta.Operation.retain(5)
%{retain: 5}
To make those exact 5 characters bold, while keeping them, we can use
attributes:
iex> TextDelta.Operation.retain(5, %{bold: true})
%{retain: 5, attributes: %{bold: true}}
"""
@spec retain(non_neg_integer, Attributes.t()) :: retain
def retain(len, attrs \\ %{})
def retain(len, nil), do: %{retain: len}
def retain(len, attrs) when map_size(attrs) == 0, do: %{retain: len}
def retain(len, attrs), do: %{retain: len, attributes: attrs}
@doc """
Creates a new delete operation.
## Example
To delete 3 next characters from the text, we can create a following
operation:
iex> TextDelta.Operation.delete(3)
%{delete: 3}
"""
@spec delete(non_neg_integer) :: delete
def delete(len)
def delete(len), do: %{delete: len}
@doc """
Returns atom representing type of the given operation.
## Example
iex> TextDelta.Operation.type(%{retain: 5, attributes: %{bold: true}})
:retain
"""
@spec type(t) :: type
def type(op)
def type(%{insert: _}), do: :insert
def type(%{retain: _}), do: :retain
def type(%{delete: _}), do: :delete
@doc """
Returns length of text affected by a given operation.
Length for `insert` operations is calculated by counting the length of text
itself being inserted, length for `retain` or `delete` operations is a length
of sequence itself. Attributes have no effect over the length.
## Examples
For text inserts it is a length of text itself:
iex> TextDelta.Operation.length(%{insert: "hello!"})
6
For embed inserts, however, length is always 1:
iex> TextDelta.Operation.length(%{insert: 3})
1
For retain and deletes, the number itself is the length:
iex> TextDelta.Operation.length(%{retain: 4})
4
"""
@spec length(t) :: non_neg_integer
def length(op)
def length(%{insert: el}) when not is_bitstring(el), do: 1
def length(%{insert: str}), do: ConfigurableString.length(str)
def length(%{retain: len}), do: len
def length(%{delete: len}), do: len
@doc """
Compares the length of two operations.
## Example
iex> TextDelta.Operation.compare(%{insert: "hello!"}, %{delete: 3})
:gt
"""
@spec compare(t, t) :: comparison
def compare(op_a, op_b) do
len_a = __MODULE__.length(op_a)
len_b = __MODULE__.length(op_b)
cond do
len_a > len_b -> :gt
len_a < len_b -> :lt
true -> :eq
end
end
@doc """
Splits operations into two halves around the given index.
Text `insert` is split via slicing the text itself, `retain` or `delete` is
split by subtracting the sequence number. Attributes are preserved during
splitting. This is mostly used for normalisation of deltas during iteration.
## Examples
Text `inserts` are split via slicing the text itself:
iex> TextDelta.Operation.slice(%{insert: "hello"}, 3)
{%{insert: "hel"}, %{insert: "lo"}}
`retain` and `delete` are split by subtracting the sequence number:
iex> TextDelta.Operation.slice(%{retain: 5}, 2)
{%{retain: 2}, %{retain: 3}}
"""
@spec slice(t, non_neg_integer) :: {t, t}
def slice(op, idx)
def slice(%{insert: str} = op, idx) when is_bitstring(str) do
{part_one, part_two} = ConfigurableString.split_at(str, idx)
{Map.put(op, :insert, part_one), Map.put(op, :insert, part_two)}
end
def slice(%{insert: _} = op, _) do
{op, %{insert: ""}}
end
def slice(%{retain: op_len} = op, idx) do
{Map.put(op, :retain, idx), Map.put(op, :retain, op_len - idx)}
end
def slice(%{delete: op_len} = op, idx) do
{Map.put(op, :delete, idx), Map.put(op, :delete, op_len - idx)}
end
@doc """
Attempts to compact two given operations into one.
If successful, will return a list with just a single, compacted operation. In
any other case both operations will be returned back unchanged.
Compacting works by combining same operations with the same attributes
together. Easiest way to think about this function is that it produces an
exact opposite effect of `TextDelta.Operation.slice/2`.
Text `insert` is compacted by concatenating strings, `retain` or `delete` is
compacted by adding the sequence numbers. Only operations with the same
attribute set are compacted. This is mostly used to keep deltas short and
canonical.
## Examples
Text inserts are compacted into a single insert:
iex> TextDelta.Operation.compact(%{insert: "hel"}, %{insert: "lo"})
[%{insert: "hello"}]
Retains and deletes are compacted by adding their sequence numbers:
iex> TextDelta.Operation.compact(%{retain: 2}, %{retain: 3})
[%{retain: 5}]
"""
@spec compact(t, t) :: [t]
def compact(op_a, op_b)
def compact(%{retain: len_a, attributes: attrs_a}, %{
retain: len_b,
attributes: attrs_b
})
when attrs_a == attrs_b do
[retain(len_a + len_b, attrs_a)]
end
def compact(%{retain: len_a} = a, %{retain: len_b} = b)
when map_size(a) == 1 and map_size(b) == 1 do
[retain(len_a + len_b)]
end
def compact(%{insert: el_a} = op_a, %{insert: _} = op_b)
when not is_bitstring(el_a) do
[op_a, op_b]
end
def compact(%{insert: _} = op_a, %{insert: el_b} = op_b)
when not is_bitstring(el_b) do
[op_a, op_b]
end
def compact(%{insert: str_a, attributes: attrs_a}, %{
insert: str_b,
attributes: attrs_b
})
when attrs_a == attrs_b do
[insert(str_a <> str_b, attrs_a)]
end
def compact(%{insert: str_a} = op_a, %{insert: str_b} = op_b)
when map_size(op_a) == 1 and map_size(op_b) == 1 do
[insert(str_a <> str_b)]
end
def compact(%{delete: len_a}, %{delete: len_b}) do
[delete(len_a + len_b)]
end
def compact(op_a, op_b), do: [op_a, op_b]
@doc """
Checks if given operation is trimmable.
Technically only `retain` operations are trimmable, but the creator of this
library didn't feel comfortable exposing that knowledge outside of this
module.
## Example
iex> TextDelta.Operation.trimmable?(%{retain: 3})
true
"""
@spec trimmable?(t) :: boolean
def trimmable?(op) do
Map.has_key?(op, :retain) and !Map.has_key?(op, :attributes)
end
end
| 29.501493 | 80 | 0.66407 |
08924b34f81b3de356228da2c57097820e4a0de9 | 143 | ex | Elixir | debian/adapterbase.cron.d.ex | isis-project/AdapterBase | 5b8e6086950f6e3938691e6fe0d591fb5e675575 | [
"Apache-2.0"
] | 1 | 2015-07-19T20:11:07.000Z | 2015-07-19T20:11:07.000Z | debian/adapterbase.cron.d.ex | isis-project/AdapterBase | 5b8e6086950f6e3938691e6fe0d591fb5e675575 | [
"Apache-2.0"
] | null | null | null | debian/adapterbase.cron.d.ex | isis-project/AdapterBase | 5b8e6086950f6e3938691e6fe0d591fb5e675575 | [
"Apache-2.0"
] | null | null | null | #
# Regular cron jobs for the adapterbase package
#
0 4 * * * root [ -x /usr/bin/adapterbase_maintenance ] && /usr/bin/adapterbase_maintenance
| 28.6 | 90 | 0.727273 |
08926210a5e96d003ad5f9dac29c8571093bfdac | 1,014 | exs | Elixir | test/test_helper.exs | milendd/xslt_parser | 91f870d86184180a8c05d2e85aa1138f46e0606d | [
"MIT"
] | null | null | null | test/test_helper.exs | milendd/xslt_parser | 91f870d86184180a8c05d2e85aa1138f46e0606d | [
"MIT"
] | null | null | null | test/test_helper.exs | milendd/xslt_parser | 91f870d86184180a8c05d2e85aa1138f46e0606d | [
"MIT"
] | null | null | null | ExUnit.start()
defmodule XmlTestContainer do
def get_books_xml do
"""
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="web">
<title lang="bg">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book empty="yes">
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
"""
end
end
| 26 | 54 | 0.511834 |
0892aa0b1b16548a4ffc774a882998f1d225fe29 | 2,074 | ex | Elixir | lib/web/controllers/bulletin_controller.ex | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | 9 | 2020-02-26T20:24:38.000Z | 2022-03-22T21:14:52.000Z | lib/web/controllers/bulletin_controller.ex | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | 15 | 2020-04-22T19:33:24.000Z | 2022-03-26T15:11:17.000Z | lib/web/controllers/bulletin_controller.ex | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | 4 | 2020-04-27T22:58:57.000Z | 2022-01-14T13:42:09.000Z | defmodule Web.BulletinController do
use Web, :controller
alias ChallengeGov.Challenges
alias ChallengeGov.Challenges.Bulletin
alias ChallengeGov.GovDelivery
def new(conn, %{"challenge_id" => id}) do
%{current_user: user} = conn.assigns
with {:ok, challenge} <- Challenges.get(id),
{:ok, challenge} <- Challenges.can_send_bulletin(user, challenge) do
conn
|> assign(:changeset, Bulletin.create_changeset(%Bulletin{}, %{}))
|> assign(:path, Routes.challenge_bulletin_path(conn, :create, challenge.id))
|> assign(:challenge, challenge)
|> render("new.html")
else
{:error, :not_permitted} ->
conn
|> put_flash(:error, "You are not allowed to send a bulletin for this challenge")
|> redirect(to: Routes.challenge_path(conn, :index))
{:error, :not_found} ->
conn
|> put_flash(:error, "Challenge not found")
|> redirect(to: Routes.challenge_path(conn, :index))
end
end
def create(conn, %{"challenge_id" => id, "bulletin" => bulletin_params}) do
%{current_user: user} = conn.assigns
subject = "Challenge.Gov Bulletin: #{bulletin_params["subject"]}"
with {:ok, challenge} <- Challenges.get(id),
{:ok, challenge} <- Challenges.can_send_bulletin(user, challenge),
{:ok, :sent} <- GovDelivery.send_bulletin(challenge, subject, bulletin_params["body"]) do
conn
|> put_flash(:info, "Bulletin scheduled to send")
|> redirect(to: Routes.challenge_path(conn, :index))
else
{:send_error, _e} ->
conn
|> put_flash(:error, "Error sending bulletin")
|> redirect(to: Routes.challenge_path(conn, :index))
{:error, :not_permitted} ->
conn
|> put_flash(:error, "You are not allowed to send a bulletin for this challenge")
|> redirect(to: Routes.challenge_path(conn, :index))
{:error, :not_found} ->
conn
|> put_flash(:error, "Challenge not found")
|> redirect(to: Routes.challenge_path(conn, :index))
end
end
end
| 34.566667 | 98 | 0.631148 |
0892b44c96c3d991142f05d71bf8eb8453e729bc | 5,609 | exs | Elixir | test/composers/ota_hotel_booking_rule_notif/request_test.exs | ChannexIO/ex_open_travel | 51a1101f55bc2d12a093237bb9ef64ef8a4d3091 | [
"Apache-2.0"
] | null | null | null | test/composers/ota_hotel_booking_rule_notif/request_test.exs | ChannexIO/ex_open_travel | 51a1101f55bc2d12a093237bb9ef64ef8a4d3091 | [
"Apache-2.0"
] | null | null | null | test/composers/ota_hotel_booking_rule_notif/request_test.exs | ChannexIO/ex_open_travel | 51a1101f55bc2d12a093237bb9ef64ef8a4d3091 | [
"Apache-2.0"
] | null | null | null | defmodule ExOpenTravel.Composers.OtaHotelBookingRuleNotif.RequestTest do
use ExUnit.Case
doctest ExOpenTravel.Composers.OtaHotelBookingRuleNotif.Request
@moduletag :ex_open_travel_ota_hotel_booking_rule_notif_request
alias ExOpenTravel.Composers.OtaHotelBookingRuleNotif.Request
@hotel_code "00000"
@meta %{
request: nil,
response: nil,
method: nil,
started_at: DateTime.utc_now(),
finished_at: nil,
success: true,
errors: []
}
test "build_hotel_booking_rule_notif/2" do
{element, _meta} =
Request.build_hotel_booking_rule_notif(
%{
hotel_code: @hotel_code,
rule_messages: [
%{
status_application_control: %{
start: "2010-06-19",
end: "2010-06-20",
inv_type_code: "DBL",
rate_plan_code: "BAR",
destination_system_codes: [1, 2, 3]
},
booking_rules: [
%{
lengths_of_stay: [
%{time: "2", time_unit: "Day", min_max_message_type: "SetMinLOS"}
],
restriction_status: nil
},
%{
lengths_of_stay: nil,
restriction_status: %{restriction: "Master", status: "Close"}
},
%{
lengths_of_stay: nil,
restriction_status: %{restriction: "Arrival", status: "Open"}
},
%{
lengths_of_stay: nil,
restriction_status: %{restriction: "Departure", status: "Close"}
}
]
}
]
},
@meta
)
assert XmlBuilder.generate(element)
assert element ==
{:"ns1:RuleMessages", %{HotelCode: "00000"},
[
{:"ns1:RuleMessage", nil,
[
{:"ns1:StatusApplicationControl",
%{
End: "2010-06-20",
InvTypeCode: "DBL",
RatePlanCode: "BAR",
Start: "2010-06-19"
},
[
{:"ns1:DestinationSystemCodes", nil,
[
{:"ns1:DestinationSystemCode", nil, 1},
{:"ns1:DestinationSystemCode", nil, 2},
{:"ns1:DestinationSystemCode", nil, 3}
]}
]},
{:"ns1:BookingRules", nil,
[
{:"ns1:BookingRule", nil,
[
{:"ns1:LengthsOfStay", nil,
[
{:"ns1:LengthOfStay",
%{MinMaxMessageType: "SetMinLOS", Time: "2", TimeUnit: "Day"}, nil}
]}
]},
{:"ns1:BookingRule", nil,
[
{:"ns1:RestrictionStatus", %{Restriction: "Master", Status: "Close"},
nil}
]},
{:"ns1:BookingRule", nil,
[
{:"ns1:RestrictionStatus", %{Restriction: "Arrival", Status: "Open"},
nil}
]},
{:"ns1:BookingRule", nil,
[
{:"ns1:RestrictionStatus", %{Restriction: "Departure", Status: "Close"},
nil}
]}
]}
]}
]}
end
test "build_hotel_booking_rule_notif_fail" do
assert {:error, _, %{success: false, errors: [:empty_payload]}} =
Request.build_hotel_booking_rule_notif(
%{hotel_code: @hotel_code, rule_messages: []},
@meta
)
end
test "build_booking_rules/1" do
element =
Request.build_booking_rules([
%{
lengths_of_stay: [
%{time: "2", time_unit: "Day", min_max_message_type: "SetMinLOS"}
],
restriction_status: nil
},
%{
lengths_of_stay: nil,
restriction_status: %{restriction: "Master", status: "Close"}
},
%{
lengths_of_stay: nil,
restriction_status: %{restriction: "Arrival", status: "Open"}
},
%{
lengths_of_stay: nil,
restriction_status: %{restriction: "Departure", status: "Close"}
}
])
assert XmlBuilder.generate(element)
end
test "build_booking_rule/1" do
element =
Request.build_booking_rule(%{
lengths_of_stay: [
%{time: "2", time_unit: "Day", min_max_message_type: "SetMinLOS"}
],
restriction_status: nil
})
assert XmlBuilder.generate(element)
end
test "build_lengths_of_stay/1" do
element =
Request.build_lengths_of_stay([
%{
time: "2",
time_unit: "Day",
min_max_message_type: "SetMinLOS"
}
])
assert XmlBuilder.generate(element)
end
test "build_restriction_status/1" do
element =
Request.build_restriction_status(%{
restriction: "Departure",
status: "Close"
})
assert XmlBuilder.generate(element)
end
test "destination_system_codes/1" do
element = Request.destination_system_codes([1, 2, 3])
assert XmlBuilder.generate(element)
end
end
| 29.994652 | 97 | 0.459975 |
0892b85bb66a662deefd36f18496b29d18015c0f | 716 | ex | Elixir | lib/dns/server.ex | jveiga/elixir-dns | 59d00bcad3f1c84217b28822657b203584cddd38 | [
"BSD-3-Clause"
] | null | null | null | lib/dns/server.ex | jveiga/elixir-dns | 59d00bcad3f1c84217b28822657b203584cddd38 | [
"BSD-3-Clause"
] | null | null | null | lib/dns/server.ex | jveiga/elixir-dns | 59d00bcad3f1c84217b28822657b203584cddd38 | [
"BSD-3-Clause"
] | null | null | null | defmodule DNS.Server do
@moduledoc """
TODO: docs
TODO: convert this to a `GenServer` and do proper cleanup
"""
@callback handle(DNS.Record.t, {:inet.ip, :inet.port}) :: DNS.Record.t
@doc """
TODO: docs
"""
@spec accept(:inet.port, DNS.Server) :: no_return
def accept(port, handler) do
socket = Socket.UDP.open!(port)
IO.puts "Server listening at #{port}"
accept_loop(socket, handler)
end
defp accept_loop(socket, handler) do
{data, client} = Socket.Datagram.recv!(socket)
record = DNS.Record.decode(data)
response = handler.handle(record, client)
Socket.Datagram.send!(socket, DNS.Record.encode(response), client)
accept_loop(socket, handler)
end
end
| 23.866667 | 72 | 0.671788 |
0892c198b2595d6d43ede2cb543b7338156d41cb | 5,212 | ex | Elixir | lib/essence/document.ex | nicbet/essence | f3371c33839d4db00020181c9ec980d449d2a00b | [
"MIT"
] | 68 | 2016-09-10T20:04:37.000Z | 2022-03-16T14:53:27.000Z | lib/essence/document.ex | nicbet/essence | f3371c33839d4db00020181c9ec980d449d2a00b | [
"MIT"
] | 1 | 2018-02-14T20:22:45.000Z | 2018-02-14T20:22:45.000Z | lib/essence/document.ex | nicbet/essence | f3371c33839d4db00020181c9ec980d449d2a00b | [
"MIT"
] | 8 | 2017-02-11T19:28:56.000Z | 2021-04-13T08:07:55.000Z | defmodule Essence.Document do
defstruct type: "", uri: "", text: "", nested_tokens: [], meta: %{}
@moduledoc """
This module defines the struct type `Essence.Document`, as well as a
variety of convenience methods for access the document's text, paragraphs,
sentences and tokens.
"""
@doc """
Read the `text` represented by a `String` and create an `Essence.Document`.
"""
@spec from_text(text :: String.t) :: %Essence.Document{}
def from_text(text) when is_bitstring(text) do
paragraphs = Essence.Chunker.paragraphs(text)
sentences = paragraphs
|> Enum.map( fn(x) -> Essence.Chunker.sentences(x) end )
tokens = sentences
|> Enum.map(fn(x) -> x |> Enum.map(fn(y) -> Essence.Tokenizer.tokenize(y) end) end)
%Essence.Document{
type: :plain_text,
uri: "",
text: text,
nested_tokens: tokens
}
end
@doc """
Retrieve the tokenized paragraphs from the given `Essence.Document`.
"""
@spec paragraphs(document :: %Essence.Document{}) :: List.t
def paragraphs(%Essence.Document{nested_tokens: tokens}) do
tokens
end
@doc """
Retrieve a the `n`-th tokenized paragraph from the given `Essence.Document`
"""
@spec paragraph(document :: %Essence.Document{}, n :: integer) :: List.t
def paragraph(%Essence.Document{nested_tokens: tokens}, n) do
tokens |> Enum.at(n)
end
@doc """
Retrieve the tokenized sentences from the given `Essence.Document`.
"""
@spec sentences(document :: %Essence.Document{}) :: List.t
def sentences(%Essence.Document{nested_tokens: tokens}) do
tokens |> List.foldl([], fn(x, acc) -> acc ++ x end)
end
@doc """
Retrieve the `n`-th tokenized sentence from the given `Essence.Document`
"""
@spec sentence(document :: %Essence.Document{}, n :: integer) :: List.t
def sentence(doc = %Essence.Document{}, n) do
doc
|> sentences
|> Enum.at(n)
end
@doc """
Retrieve the list of all tokens contained in the given `Essence.Document`
"""
@spec enumerate_tokens(document :: %Essence.Document{}) :: List.t
def enumerate_tokens(%Essence.Document{nested_tokens: tokens}) do
tokens
|> List.flatten()
|> Enum.map(fn word -> String.downcase word end)
end
@doc """
Retrieve the list of all words in the given `Essence.Document`, ignoring all tokens that are punctuation.
"""
@spec words(document :: %Essence.Document{}) :: List.t
def words(doc = %Essence.Document{}) do
doc
|> enumerate_tokens
|> Enum.filter(&Essence.Token.is_word?/1)
end
@doc """
Find all occurrences of `token` in the given `Essence.Document`. Returns a
list of [token: index] tuples.
"""
@spec find_token(doc :: %Essence.Document{}, token :: String.t) :: List.t
def find_token(doc = %Essence.Document{}, token) do
doc
|> Essence.Document.enumerate_tokens
|> Enum.with_index
|> Enum.filter( fn({tok, _idx}) -> String.upcase(tok) == String.upcase(token) end )
end
@doc """
For each occurrence of `token` in the given `Essence.Document`, `doc`,
returns a list containing the token as well as `n` (default=5) tokens to the left and
right of the occurrence.
"""
@spec context_of(doc :: %Essence.Document{}, token :: String.t, n :: number) :: List.t
def context_of(doc = %Essence.Document{}, token, n \\ 5) do
indices = doc |> find_token(token)
tokens = doc |> enumerate_tokens
indices |> Enum.map( fn({tok, idx}) -> context_left(tokens, idx-1, n) ++ [tok] ++ context_right(tokens, idx+1, n) end)
end
@doc """
Pretty prints all occurrences of `token` in the given `Essence.Document`,
`doc`. Prints `n` (default=20) characters of context.
"""
@spec concordance(doc :: %Essence.Document{}, token :: String.t, n :: number) :: :ok
def concordance(doc = %Essence.Document{}, token, n \\ 20) do
doc
|> context_of(token, round(n / 5)+2)
|> Enum.each(¢er(&1, n))
end
defp context_left(token_list, idx, len) do
token_list |> Enum.slice( (max(0, idx-len))..(idx) )
end
defp context_right(token_list, idx, len) do
token_list |> Enum.slice( (idx)..(min(Enum.count(token_list), idx+len)) )
end
defp center(token_list, len) do
mid = round(Enum.count(token_list) / 2) -1
l = token_list
|> Enum.slice(0..mid-1)
|> Enum.join(" ")
lx = l
|> String.slice(-(min(len, String.length(l)))..-1)
|> String.pad_leading(len, " ")
mx = Enum.at(token_list, mid)
r = token_list
|> Enum.slice(mid+1..Enum.count(token_list))
|> Enum.join(" ")
rx = r
|> String.slice(0..min(len, String.length(r)))
|> String.pad_trailing(len, " ")
IO.puts("#{lx} #{mx} #{rx}")
end
@doc """
Returns a list of all the 1-contexts (1 token to the left, 1 token to the right) of the
given `token` in the given `document`, excluding the token itself.
"""
@spec one_contexts_of(doc :: %Essence.Document{}, token :: String.t) :: List.t
def one_contexts_of(doc = %Essence.Document{}, token) do
indices = doc |> find_token(token)
tokens = doc |> enumerate_tokens
indices |> Enum.map( fn({_tok, idx}) -> context_left(tokens, idx-1, 0) ++ context_right(tokens, idx+1, 0) end)
end
end
| 31.780488 | 122 | 0.639678 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.